void UdpSearcher::search() { try{ LOG_DEBUG("UdpSearcher::search start search"); //¹ã²¥µØÖ· //LOG_DEBUG("UdpSearcher::search send msg to %s", addr_broadcast.to_string().c_str()); udp::endpoint destination(address::from_string("255.255.255.255"), NET_BROADCAST_PORT); boost::array<char, 1> send_buf = { 0 }; socket_.send_to(boost::asio::buffer(send_buf), destination); socket_.async_receive_from(boost::asio::buffer(recvBuf),senderEndpoint,0 ,boost::bind(&UdpSearcher::reciveHandle, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); timer_.expires_from_now(boost::posix_time::seconds(5)); timer_.async_wait(boost::bind(&UdpSearcher::timeoutHandle, this, boost::asio::placeholders::error)); ioServicePool_.start(); } catch(std::exception& e) { LOG_ERROR("UdpSearcher::search error : %s ", e.what()); } }
void QUtilityData::saveColorImage(const std::string& fileName, const glm::uvec2& scale) { QImage source(fileName.c_str()); source = source.scaled(source.width() / scale.x, source.height() / scale.y); int width = source.width(); int height = source.height(); std::vector<cl_uchar4> destination(width * height); cl_uchar4* ptrDestination = destination.data(); for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) { QRgb label = source.pixel(x, y); ptrDestination->s[0] = qRed(label); ptrDestination->s[1] = qGreen(label); ptrDestination->s[2] = qBlue(label); ptrDestination->s[3] = qAlpha(label); ptrDestination++; }; QIO::saveFileData(fileName + QGCSetting::extColor, destination.data(), destination.size() * sizeof(cl_uchar4)); }
bool SharePlugin::receivePackage(const NetworkPackage& np) { /* //TODO: Write a test like this if (np.type() == PACKAGE_TYPE_PING) { qCDebug(KDECONNECT_PLUGIN_SHARE) << "sending file" << (QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc"); NetworkPackage out(PACKAGE_TYPE_SHARE); out.set("filename", mDestinationDir + "itworks.txt"); AutoClosingQFile* file = new AutoClosingQFile(QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc"); //Test file to transfer out.setPayload(file, file->size()); device()->sendPackage(out); return true; } */ qCDebug(KDECONNECT_PLUGIN_SHARE) << "File transfer"; if (np.hasPayload()) { //qCDebug(KDECONNECT_PLUGIN_SHARE) << "receiving file"; const QString filename = np.get<QString>("filename", QString::number(QDateTime::currentMSecsSinceEpoch())); const QUrl dir = destinationDir().adjusted(QUrl::StripTrailingSlash); QUrl destination(dir.toString() + '/' + filename); if (destination.isLocalFile() && QFile::exists(destination.toLocalFile())) { destination = QUrl(dir.toString() + '/' + KIO::suggestName(dir, filename)); } FileTransferJob* job = np.createPayloadTransferJob(destination); job->setDeviceName(device()->name()); connect(job, SIGNAL(result(KJob*)), this, SLOT(finished(KJob*))); KIO::getJobTracker()->registerJob(job); job->start(); } else if (np.has("text")) {
ServiceJob *Service::startOperationCall(const KConfigGroup &description, QObject *parent) { // TODO: nested groups? ServiceJob *job = 0; const QString op = description.isValid() ? description.name() : QString(); RemoteService *rs = qobject_cast<RemoteService *>(this); if (!op.isEmpty() && rs && !rs->isReady()) { // if we have an operation, but a non-ready remote service, just let it through kDebug() << "Remote service is not ready; queueing operation"; QMap<QString, QVariant> params; job = createJob(op, params); RemoteServiceJob *rsj = qobject_cast<RemoteServiceJob *>(job); if (rsj) { rsj->setDelayedDescription(description); } } else if (!d->config) { kDebug() << "No valid operations scheme has been registered"; } else if (!op.isEmpty() && d->config->hasGroup(op)) { if (d->disabledOperations.contains(op)) { kDebug() << "Operation" << op << "is disabled"; } else { QMap<QString, QVariant> params = parametersFromDescription(description); job = createJob(op, params); } } else { kDebug() << op << "is not a valid group; valid groups are:" << d->config->groupList(); } if (!job) { job = new NullServiceJob(destination(), op, this); } job->setParent(parent ? parent : this); connect(job, SIGNAL(finished(KJob*)), this, SLOT(jobFinished(KJob*))); QTimer::singleShot(0, job, SLOT(autoStart())); return job; }
ScriptPromise AudioContext::suspendContext(ScriptState* scriptState) { ASSERT(isMainThread()); AutoLocker locker(this); ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); if (contextState() == Closed) { resolver->reject( DOMException::create(InvalidStateError, "Cannot suspend a context that has been closed")); } else { // Stop rendering now. if (destination()) stopRendering(); // Since we don't have any way of knowing when the hardware actually stops, we'll just // resolve the promise now. resolver->resolve(); } return promise; }
void BlendBench::unalignedBlendArgb32() { const int dimension = 1024; uchar *dstMemory = static_cast<uchar*>(::malloc(dimension * dimension * sizeof(quint32))); QImage destination(dstMemory, dimension, dimension, QImage::Format_ARGB32_Premultiplied); destination.fill(0x12345678); // avoid special cases of alpha uchar *srcMemory = static_cast<uchar*>(::malloc((dimension * dimension * sizeof(quint32)) + 16)); QFETCH(int, offset); uchar *imageSrcMemory = srcMemory + (offset * sizeof(quint32)); QImage src(imageSrcMemory, dimension, dimension, QImage::Format_ARGB32_Premultiplied); src.fill(0x87654321); QPainter painter(&destination); QBENCHMARK { painter.drawImage(QPoint(), src); } ::free(srcMemory); ::free(dstMemory); }
// --------------------------------------------------------------------------- // CStunTurnTests::TestSetSendingStatusUDPL // --------------------------------------------------------------------------- // void CStunTurnTests::TestSetSendingStatusUDPL() { TInetAddr inetAddr; iWrapper->OutgoingAddr( inetAddr ); iWrapper->SetIncomingAddrL( inetAddr ); TInetAddr destination( KTestAddress, KTestServerPort ); RDebug::Print( _L( "\nTEST CASE: Set Sending Status Active" ) ); iNat.SetSendingStateL( iIfStub.LocalCandidateL(), EStreamingStateActive, destination ); iIfStub.StartActiveSchedulerL( KRunningTime ); RDebug::Print( _L( "\nTEST CASE: Set Sending Status Passive" ) ); iNat.SetSendingStateL( iIfStub.LocalCandidateL(), EStreamingStatePassive, destination ); iIfStub.StartActiveSchedulerL( KRunningTime ); }
void CCell::UpdateView() { Helper * help = Helper::Instance(); if( isVisible && unit != s_original ) { QImage source( ":/" + help->GetItemNameByState( hextype ) ); QImage destination( ":/" + help->GetItemNameByState( unit ) ); //destination = destination.scaled( button->width(), button->height() ); QPainter resultPainter(&source); resultPainter.setCompositionMode( QPainter::CompositionMode_SourceOver ); resultPainter.drawImage( 0, 0, destination ); resultPainter.end(); button->setIcon( QIcon( QPixmap::fromImage( source ) ) ); } else { button->setIcon( QIcon(":/" + help->GetItemNameByVisible( isVisible, hextype ) ) ); //button->setText( "1" ); } }
void jumpTableEntry::print() { if (is_unused()) { std->print_cr("Unused {next = %d}", (int) destination()); return; } if (is_nmethod_stub()) { std->print("Nmethod stub "); Disassembler::decode(jump_inst_addr(), state_addr()); nmethod* nm = method(); if (nm) { nm->key.print(); } else { std->print_cr("{not pointing to nmethod}"); } return; } if (is_block_closure_stub()) { std->print("Block closure stub"); Disassembler::decode(jump_inst_addr(), state_addr()); nmethod* nm = block_nmethod(); if (nm) { nm->key.print(); } else { std->print_cr("{not compiled yet}"); } return; } if (is_link()) { std->print_cr("Link for:"); jumpTable::jump_entry_for_at(link(), 0)->print(); return; } fatal("unknown jump table entry"); }
/// Graphical validations for Exponential variate generator. /// @note Important! For this to work and files to be generated, this test must be run *outside* of VS 2013 Gtest plugin. This plugin redirects outputs. TEST_F(ExponentialTrafficGeneratorTest, ExponentialGraphsGenerators) { std::shared_ptr<Message> source(new Message("This is a dummy entity for source.")); std::shared_ptr<Message> destination(new Message("This is a dummy entity for destination.")); std::shared_ptr<Message> tokenContents(new Message("This is a dummy Token contents.")); unsigned int seed = 1; std::shared_ptr<Token> token(nullptr); std::ofstream outputFile; // Output file handle. int numberOfSamples = 300000; // Number of samples to generate for variate. Generate about 300,000 here such that the lambda = 0.5 approximates better the pdf equation. std::map<std::string, ExponentialTrafficGenerator> exponentialGeneratorMap; // Map to control exponential generator instances and their output filenames. (String comes first because the key must be constant.) // Set the fixed seed. simulatorGlobals.seedRandomNumberGenerator(seed); // Create exponential generators and populate maps with their references and output files. exponentialGeneratorMap.insert(std::pair<std::string, ExponentialTrafficGenerator>("exponential_Lambda0.5.csv", ExponentialTrafficGenerator(simulatorGlobals, scheduler, EventType::TRAFFIC_GENERATOR_ARRIVAL, tokenContents, source, destination, 1, 1.0/0.5))); exponentialGeneratorMap.insert(std::pair<std::string, ExponentialTrafficGenerator>("exponential_Lambda1.0.csv", ExponentialTrafficGenerator(simulatorGlobals, scheduler, EventType::TRAFFIC_GENERATOR_ARRIVAL, tokenContents, source, destination, 1, 1.0))); exponentialGeneratorMap.insert(std::pair<std::string, ExponentialTrafficGenerator>("exponential_Lambda1.5.csv", ExponentialTrafficGenerator(simulatorGlobals, scheduler, EventType::TRAFFIC_GENERATOR_ARRIVAL, tokenContents, source, destination, 1, 1/1.5))); exponentialGeneratorMap.insert(std::pair<std::string, ExponentialTrafficGenerator>("exponential_Lambda3.0.csv", ExponentialTrafficGenerator(simulatorGlobals, scheduler, EventType::TRAFFIC_GENERATOR_ARRIVAL, tokenContents, source, destination, 1, 1/3.0))); // Now generate all exponential samples for each generator. for (auto &exponentialGeneratorMapIterator : exponentialGeneratorMap) { // Turn on generator. exponentialGeneratorMapIterator.second.turnOn(); // Open file for output. outputFile.open(exponentialGeneratorMapIterator.first); // Generate samples. for (int i = 0; i < numberOfSamples; ++i) { exponentialGeneratorMapIterator.second.createInstanceTrafficEvent(); outputFile << scheduler.cause().occurAfterTime << std::endl; } outputFile.close(); } }
void MaskFilterBase::Process( cv::Mat& srcImage, cv::Mat& destImage ) { CV_Assert( srcImage.depth() != sizeof(uchar) ); CV_Assert( srcImage.rows == destImage.rows ); CV_Assert( srcImage.cols == destImage.cols ); switch( srcImage.channels() ) { case 1: CV_Assert(false); case 3: cv::Mat_<cv::Vec3b> source = srcImage; cv::Mat_<cv::Vec3b> destination = destImage; for ( int j = 1; j < srcImage.cols - 1; ++j ) { for (int i = 1; i < srcImage.rows - 1; ++i ) destination( i, j ) = Filter( source, i, j, m_mask ); } break; } }
static Character const* __cdecl strip_quotes(Character const* const source) throw() { // Count the number of quotation marks in the string, and compute the length // of the string, in case we need to allocate a new string: size_t quote_count = 0; size_t source_length = 0; for (Character const* it = source; *it; ++it) { if (*it == '\"') ++quote_count; ++source_length; } // No quotes? No problem! if (quote_count == 0) return nullptr; size_t const destination_length = source_length - quote_count + 1; __crt_unique_heap_ptr<Character> destination(_calloc_crt_t(Character, destination_length)); if (destination.get() == nullptr) return nullptr; // Copy the string, stripping quotation marks: Character* destination_it = destination.get(); for (Character const* source_it = source; *source_it; ++source_it) { if (*source_it == '\"') continue; *destination_it++ = *source_it; } *destination_it = '\0'; return destination.detach(); }
static String CGImageToDataURL(CGImageRef image, const String& mimeType, const double* quality) { if (!image) return "data:,"; RetainPtr<CFMutableDataRef> data(AdoptCF, CFDataCreateMutable(kCFAllocatorDefault, 0)); if (!data) return "data:,"; RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType); ASSERT(uti); RetainPtr<CGImageDestinationRef> destination(AdoptCF, CGImageDestinationCreateWithData(data.get(), uti.get(), 1, 0)); if (!destination) return "data:,"; RetainPtr<CFDictionaryRef> imageProperties = 0; if (CFEqual(uti.get(), jpegUTI()) && quality && *quality >= 0.0 && *quality <= 1.0) { // Apply the compression quality to the JPEG image destination. RetainPtr<CFNumberRef> compressionQuality(AdoptCF, CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, quality)); const void* key = kCGImageDestinationLossyCompressionQuality; const void* value = compressionQuality.get(); imageProperties.adoptCF(CFDictionaryCreate(0, &key, &value, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); } // Setting kCGImageDestinationBackgroundColor to black for JPEG images in imageProperties would save some math // in the calling functions, but it doesn't seem to work. CGImageDestinationAddImage(destination.get(), image, imageProperties.get()); CGImageDestinationFinalize(destination.get()); Vector<char> base64Data; base64Encode(reinterpret_cast<const char*>(CFDataGetBytePtr(data.get())), CFDataGetLength(data.get()), base64Data); return "data:" + mimeType + ";base64," + base64Data; }
void HelloWorld::drawPath(const std::vector<TileData*>& path) { this->removeChildByName(DrawNodeStr); DrawNode* drawNode = DrawNode::create(); Size mapSize = m_gamemap->getMapSize(); Size tilesize = m_gamemap->getTileSize(); int mapheight = mapSize.height * tilesize.height; int origin_x = path[0]->position().first * tilesize.width + tilesize.width / 2; int origin_y = path[0]->position().second * tilesize.height + tilesize.height / 2; Vec2 origin(origin_x, mapheight - origin_y); for (int index = 1; index < path.size(); ++index) { int destination_x = path[index]->position().first * tilesize.width + tilesize.width / 2; int destination_y = path[index]->position().second * tilesize.height + tilesize.height / 2; Vec2 destination(destination_x, mapheight - destination_y); drawNode->drawLine(origin, destination, Color4F(0.0, 1.0, 0.0, 1.0)); origin = destination; } this->addChild(drawNode, 0, DrawNodeStr); }
void MPG321::goEvent( SProcessEvent *event ) { if( !event->address().isEmpty() ) setDestination( event->address() ); QStringList arguments; arguments << "-v"; arguments << "--rate"; arguments << "44100"; arguments << "--stereo"; arguments << "--buffer"; arguments << "3072"; arguments << "--resync"; arguments << "-w"; arguments << destination(); arguments << source(); p->used_command.clear(); p->used_command = application() + " "; for( int i=0 ; i<arguments.count() ; i++ ) { QString str = arguments.at(i); if( str.contains(" ") ) str = "\"" + str + "\""; p->used_command = p->used_command + str + " "; } p->log_str = p->used_command; emit itemicLogAdded( MPG321::Information , p->used_command ); p->process->start( application() , arguments ); p->timer->start( 25 ); p->clock->start( 1000 ); }
void _VertexBuffer::Update() { if(m_Buffer) { m_Buffer->Release(); m_Buffer=NULL; } // First we need to know the bufferSize m_BufferSizeInBytes=m_VertexSizeInBytes * m_Count; // Unique_ptr will free the pointer unique_ptr<char> destination(new char[m_BufferSizeInBytes]); int ByteWidth=m_VertexSizeInBytes; int offsetInBytes=0; if(m_Position) { char *destBase=destination.get(); for(int i=0;i<m_Count;i++) { float *dest=(float *)destBase; *dest++=*m_Position++; *dest++=*m_Position++; *dest++=*m_Position++; destBase+=ByteWidth; } } if(m_Color) { char *destBase=destination.get(); destBase+=m_OffsetForColor; for(int i=0;i<m_Count;i++) { float *dest=(float *)destBase; *dest++=*m_Color++; *dest++=*m_Color++; *dest++=*m_Color++; *dest++=*m_Color++; destBase+=ByteWidth; } } if(m_Normal) { char *destBase=destination.get(); destBase+=m_OffsetForNormal; for(int i=0;i<m_Count;i++) { float *dest=(float *)destBase; *dest++=*m_Normal++; *dest++=*m_Normal++; *dest++=*m_Normal++; destBase+=ByteWidth; } } if(m_Tangent) { char *destBase=destination.get(); destBase+=m_OffsetForTangent; for(int i=0;i<m_Count;i++) { float *dest=(float *)destBase; *dest++=*m_Tangent++; destBase+=ByteWidth; } } if(m_TexCoord) { char *destBase=destination.get(); destBase+=m_OffsetForTexCoord; int numChannels=m_NumChannels; for(int channel=0;channel<numChannels;channel++) { for(int i=0;i<m_Count;i++) { float *dest=(float *)destBase; *dest++=*m_TexCoord++; *dest++=*m_TexCoord++; destBase+=ByteWidth; } } } Create(destination.get(),D3D11_BIND_VERTEX_BUFFER); }
// Update: draw background update_status ModuleSceneIntro::Update() { // KEYBOARD if (!App->input->GetKey(SDL_SCANCODE_4) == KEY_DOWN) App->renderer->Blit(background, 0, 0, NULL, 0, 0); if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN) { circles.add(App->physics->CreateObj(App->input->GetMouseX(), App->input->GetMouseY(), 0, 0, 25, 0, 0, 0, false, b_dynamic)); circles.getLast()->data->listener = this; } if (time <= 50) { App->renderer->Blit(green, 274, 216, NULL); App->renderer->Blit(green, 193, 528, NULL); App->renderer->Blit(green, 505, 611, NULL); App->renderer->Blit(arrow_pink, 153, 799, NULL); } else if (time <= 100 && time > 50) { App->renderer->Blit(purple, 238, 215, NULL); App->renderer->Blit(purple, 185, 549, NULL); App->renderer->Blit(purple, 490, 591, NULL); App->renderer->Blit(arrow_pink, 117, 786, NULL); } else if (time <= 150 && time > 100) { App->renderer->Blit(blue, 201, 215, NULL); App->renderer->Blit(blue, 476, 570, NULL); App->renderer->Blit(blue, 177, 572, NULL); } else if (time > 150) { time = 0; App->player->score += 10; } // Prepare for raycast ------------------------------------------------------ iPoint mouse; mouse.x = App->input->GetMouseX(); mouse.y = App->input->GetMouseY(); int ray_hit = ray.DistanceTo(mouse); fVector normal(0.0f, 0.0f); // All draw functions ------------------------------------------------------ // ray ----------------- if(ray_on == true) { fVector destination(mouse.x-ray.x, mouse.y-ray.y); destination.Normalize(); destination *= ray_hit; App->renderer->DrawLine(ray.x, ray.y, ray.x + destination.x, ray.y + destination.y, 255, 255, 255); if(normal.x != 0.0f) App->renderer->DrawLine(ray.x + destination.x, ray.y + destination.y, ray.x + destination.x + normal.x * 25.0f, ray.y + destination.y + normal.y * 25.0f, 100, 255, 100); } char title[100]; sprintf_s(title, "%s Balls: %d Score: %06d Best Score: %06d Respawn Press < 1 >", TITLE, App->player->hp, App->player->score, App->player->best_score); App->window->SetTitle(title); time++; return UPDATE_CONTINUE; }
int main(int argc, char** argv) { std::cout << "\nsend_rpc_ra\n"; std::cout << "\n(C) 2015 Alexander Holler\n\n"; if (argc != 4) { std::cout << "Usage: " << "send_rpc_ra interface destination_ipv6 prefix_ipv6\n" << "Example: " << "send_ra eth0 ff02::1 fecd::\n\n"; return 1; } std::string interface(argv[1]); std::string destination(argv[2]); std::string prefix(argv[3]); struct { nd_router_advert nra; nd_opt_prefix_info opt_prefix_info; } my_ra; std::memset(&my_ra, 0, sizeof(my_ra)); my_ra.nra.nd_ra_type = ND_ROUTER_ADVERT; msghdr msghdr; std::memset(&msghdr, 0, sizeof(msghdr)); // destination address sockaddr_in6 dst; std::memset(&dst, 0, sizeof(dst)); dst.sin6_family = AF_INET6; dst.sin6_port = htons(IPPROTO_ICMPV6); if (inet_pton(AF_INET6, destination.c_str(), &dst.sin6_addr) != 1) { std::cerr << "Error setting destination '" << destination << "'\n"; return 2; } msghdr.msg_name = &dst; msghdr.msg_namelen = sizeof(dst); iovec iov[2]; std::memset(&iov, 0, sizeof(iov)); iov[0].iov_base = &my_ra; iov[0].iov_len = sizeof(my_ra); msghdr.msg_iov = (struct iovec *) &iov; msghdr.msg_iovlen = sizeof(iov) / sizeof(struct iovec); in6_pktinfo* ipi; cmsghdr* cmsg_hdr; uint8_t cmsgbuf[CMSG_SPACE(sizeof(int)) + CMSG_SPACE(sizeof(*ipi))]; std::memset(&cmsgbuf, 0, sizeof(cmsgbuf)); msghdr.msg_control = &cmsgbuf; msghdr.msg_controllen = sizeof(cmsgbuf); // hop limit cmsg_hdr = CMSG_FIRSTHDR(&msghdr); cmsg_hdr->cmsg_level = IPPROTO_IPV6; cmsg_hdr->cmsg_type = IPV6_HOPLIMIT; cmsg_hdr->cmsg_len = CMSG_LEN(sizeof(int)); cmsgbuf[sizeof(*cmsg_hdr)] = 255; // using CMSG_DATA throws a warning // packet info cmsg_hdr = CMSG_NXTHDR(&msghdr, cmsg_hdr); cmsg_hdr->cmsg_level = IPPROTO_IPV6; cmsg_hdr->cmsg_type = IPV6_PKTINFO; cmsg_hdr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); ipi = (struct in6_pktinfo *) CMSG_DATA(cmsg_hdr); ipi->ipi6_ifindex = if_nametoindex(interface.c_str()); if (!ipi->ipi6_ifindex) { std::cerr << "Interface '" << interface << "' not found!\n"; return 3; } in6_addr s_addr; std::memset(&s_addr, 0, sizeof(s_addr)); if (set_src_addr(interface, s_addr)) { std::cerr << "Error finding link-local address of interface '" << interface << "'!\n"; return 4; } std::memcpy(&ipi->ipi6_addr, &s_addr, sizeof(ipi->ipi6_addr)); msghdr.msg_iovlen = 1; my_ra.opt_prefix_info.nd_opt_pi_type = ND_OPT_PREFIX_INFORMATION; my_ra.opt_prefix_info.nd_opt_pi_len = 4; if (inet_pton(AF_INET6, prefix.c_str(), &my_ra.opt_prefix_info.nd_opt_pi_prefix) != 1) { std::cerr << "Error converting prefix '" << prefix << "'!\n"; return 5; } my_ra.opt_prefix_info.nd_opt_pi_prefix_len = 64; if (check_prefix(interface, my_ra.opt_prefix_info.nd_opt_pi_prefix)) { std::cerr << "Prefix " << prefix << " seems to be in use!\n"; return 6; } my_ra.opt_prefix_info.nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_AUTO; my_ra.opt_prefix_info.nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_RADDR; // Setting both lifetimes to 1 means the kernel will only delete the // link-local address without creating it before. my_ra.opt_prefix_info.nd_opt_pi_valid_time = htonl(1); my_ra.opt_prefix_info.nd_opt_pi_preferred_time = htonl(1); int sock = ::socket(AF_INET6, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_ICMPV6); if (sock < 0) { std::cerr << "Error opening raw socket, are you root?\n"; return 7; } if (::sendmsg(sock, &msghdr, 0) < 0) { ::close(sock); std::cerr << "Error sending RA ( " << strerror(errno) << ")!\n"; return 8; } ::close(sock); std::cout << "Sent a Router Advertisment with prefix " << prefix << " to " << destination << "\n"; return 0; }
void MkPath::internalDoThisPath() { if(waitAction || pathList.isEmpty()) return; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("source: %1, destination: %2, move: %3").arg(pathList.first().source.absoluteFilePath()).arg(pathList.first().destination.absoluteFilePath()).arg(pathList.first().actionType)); #ifdef ULTRACOPIER_PLUGIN_RSYNC if(pathList.first().actionType==ActionType_RmSync) { if(pathList.first().destination.isFile()) { QFile removedFile(pathList.first().destination.absoluteFilePath()); if(!removedFile.remove()) { if(stopIt) return; waitAction=true; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to remove the inode: "+pathList.first().destination.absoluteFilePath()+", error: "+removedFile.errorString()); emit errorOnFolder(pathList.first().destination,removedFile.errorString()); return; } } else if(!rmpath(pathList.first().destination.absoluteFilePath())) { if(stopIt) return; waitAction=true; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to remove the inode: "+pathList.first().destination.absoluteFilePath()); emit errorOnFolder(pathList.first().destination,tr("Unable to remove")); return; } pathList.removeFirst(); emit firstFolderFinish(); checkIfCanDoTheNext(); return; } #endif doTheDateTransfer=false; if(keepDate) { if(!pathList.first().source.exists()) { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"the sources not exists: "+pathList.first().source.absoluteFilePath()); doTheDateTransfer=false; } else if(maxTime>=pathList.first().source.lastModified()) { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"the sources is older to copy the time: "+pathList.first().source.absoluteFilePath()+": "+maxTime.toString("dd.MM.yyyy hh:mm:ss.zzz")+">="+pathList.first().source.lastModified().toString("dd.MM.yyyy hh:mm:ss.zzz")); doTheDateTransfer=false; } else { doTheDateTransfer=readFileDateTime(pathList.first().source); /*if(!doTheDateTransfer) { if(stopIt) return; waitAction=true; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to get source folder time: "+pathList.first().source.absoluteFilePath()); emit errorOnFolder(pathList.first().source,tr("Unable to get time")); return; }*/ } } if(dir.exists(pathList.first().destination.absoluteFilePath()) && pathList.first().actionType==ActionType_RealMove) pathList.first().actionType=ActionType_MovePath; if(pathList.first().actionType!=ActionType_RealMove) { if(!dir.exists(pathList.first().destination.absoluteFilePath())) if(!dir.mkpath(pathList.first().destination.absoluteFilePath())) { if(!dir.exists(pathList.first().destination.absoluteFilePath())) { if(stopIt) return; waitAction=true; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to make the folder: "+pathList.first().destination.absoluteFilePath()); emit errorOnFolder(pathList.first().destination,tr("Unable to create the folder")); return; } } } else { if(!pathList.first().source.exists()) { if(stopIt) return; waitAction=true; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"The source folder don't exists: "+pathList.first().source.absoluteFilePath()); emit errorOnFolder(pathList.first().destination,tr("The source folder don't exists")); return; } if(!pathList.first().source.isDir())//it's really an error? { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"The source is not a folder: "+pathList.first().source.absoluteFilePath()); /*if(stopIt) return; waitAction=true; emit errorOnFolder(pathList.first().destination,tr("The source is not a folder")); return;*/ } if(pathList.first().destination.absoluteFilePath().startsWith(pathList.first().source.absoluteFilePath()+text_slash)) { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"move into it self: "+pathList.first().destination.absoluteFilePath()); int random=rand(); QFileInfo tempFolder=pathList.first().source.absolutePath()+text_slash+QString::number(random); while(tempFolder.exists()) { random=rand(); tempFolder=pathList.first().source.absolutePath()+text_slash+QString::number(random); } if(!dir.rename(pathList.first().source.absoluteFilePath(),tempFolder.absoluteFilePath())) { if(stopIt) return; waitAction=true; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to temporary rename the folder: "+pathList.first().destination.absoluteFilePath()); emit errorOnFolder(pathList.first().destination,tr("Unable to temporary rename the folder")); return; } /* http://doc.qt.io/qt-5/qdir.html#rename * On most file systems, rename() fails only if oldName does not exist, or if a file with the new name already exists. if(!dir.mkpath(pathList.first().destination.absolutePath())) { if(!dir.exists(pathList.first().destination.absolutePath())) { if(stopIt) return; waitAction=true; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to make the folder: "+pathList.first().destination.absoluteFilePath()); emit errorOnFolder(pathList.first().destination,tr("Unable to create the folder")); return; } }*/ if(!dir.rename(tempFolder.absoluteFilePath(),pathList.first().destination.absoluteFilePath())) { if(stopIt) return; waitAction=true; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to do the final real move the folder: "+pathList.first().destination.absoluteFilePath()); emit errorOnFolder(pathList.first().destination,tr("Unable to do the final real move the folder")); return; } } else { /* http://doc.qt.io/qt-5/qdir.html#rename * On most file systems, rename() fails only if oldName does not exist, or if a file with the new name already exists. if(!dir.mkpath(pathList.first().destination.absolutePath())) { if(!dir.exists(pathList.first().destination.absolutePath())) { if(stopIt) return; waitAction=true; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to make the folder: "+pathList.first().destination.absoluteFilePath()); emit errorOnFolder(pathList.first().destination,tr("Unable to create the folder")); return; } }*/ if(!dir.rename(pathList.first().source.absoluteFilePath(),pathList.first().destination.absoluteFilePath())) { if(stopIt) return; waitAction=true; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to make the folder: from: "+pathList.first().source.absoluteFilePath()+", soruce exists: "+QString::number(QDir(pathList.first().source.absoluteFilePath()).exists())+", to: "+pathList.first().destination.absoluteFilePath()+", destination exist: "+QString::number(QDir(pathList.first().destination.absoluteFilePath()).exists())); emit errorOnFolder(pathList.first().destination,tr("Unable to move the folder")); return; } } } if(doTheDateTransfer) if(!writeFileDateTime(pathList.first().destination)) { if(!pathList.first().destination.exists()) ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to set destination folder time (not exists): "+pathList.first().destination.absoluteFilePath()); else if(!pathList.first().destination.isDir()) ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to set destination folder time (not a dir): "+pathList.first().destination.absoluteFilePath()); else ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to set destination folder time: "+pathList.first().destination.absoluteFilePath()); /*if(stopIt) return; waitAction=true; emit errorOnFolder(pathList.first().source,tr("Unable to set time")); return;*/ } if(doRightTransfer && pathList.first().actionType!=ActionType_RealMove) { QFile source(pathList.first().source.absoluteFilePath()); QFile destination(pathList.first().destination.absoluteFilePath()); if(!destination.setPermissions(source.permissions())) { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to set the right: "+pathList.first().destination.absoluteFilePath()); /*if(stopIt) return; waitAction=true; emit errorOnFolder(pathList.first().source,tr("Unable to set the access-right")); return;*/ } } if(pathList.first().actionType==ActionType_MovePath) { if(!rmpath(pathList.first().source.absoluteFilePath())) { if(stopIt) return; waitAction=true; ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to remove the source folder: "+pathList.first().destination.absoluteFilePath()); emit errorOnFolder(pathList.first().source,tr("Unable to remove")); return; } } pathList.removeFirst(); emit firstFolderFinish(); checkIfCanDoTheNext(); }
bool TCPSocket::Connect( const rString& adress, const unsigned short port ) { IPv4Address destination( adress, port ); return Connect( destination ); }
virtual void decideDestination(WebKitDownload* download, const gchar* suggestedFilename) { GOwnPtr<char> destination(g_build_filename(kTempDirectory, suggestedFilename, NULL)); GOwnPtr<char> destinationURI(g_filename_to_uri(destination.get(), 0, 0)); webkit_download_set_destination(download, destinationURI.get()); }
void test_resampler_one_way(uint32_t channels, uint32_t source_rate, uint32_t target_rate, float chunk_duration) { size_t chunk_duration_in_source_frames = static_cast<uint32_t>(ceil(chunk_duration * source_rate / 1000.)); float resampling_ratio = static_cast<float>(source_rate) / target_rate; cubeb_resampler_speex_one_way<T> resampler(channels, source_rate, target_rate, 3); auto_array<T> source(channels * source_rate * 10); auto_array<T> destination(channels * target_rate * 10); auto_array<T> expected(channels * target_rate * 10); uint32_t phase_index = 0; uint32_t offset = 0; const uint32_t buf_len = 2; /* seconds */ // generate a sine wave in each channel, at the source sample rate source.push_silence(channels * source_rate * buf_len); while(offset != source.length()) { float p = phase_index++ / static_cast<float>(source_rate); for (uint32_t j = 0; j < channels; j++) { source.data()[offset++] = 0.5 * sin(440. * 2 * PI * p); } } dump("input.raw", source.data(), source.length()); expected.push_silence(channels * target_rate * buf_len); // generate a sine wave in each channel, at the target sample rate. // Insert silent samples at the beginning to account for the resampler latency. offset = resampler.latency() * channels; for (uint32_t i = 0; i < offset; i++) { expected.data()[i] = 0.0f; } phase_index = 0; while (offset != expected.length()) { float p = phase_index++ / static_cast<float>(target_rate); for (uint32_t j = 0; j < channels; j++) { expected.data()[offset++] = 0.5 * sin(440. * 2 * PI * p); } } dump("expected.raw", expected.data(), expected.length()); // resample by chunk uint32_t write_offset = 0; destination.push_silence(channels * target_rate * buf_len); while (write_offset < destination.length()) { size_t output_frames = static_cast<uint32_t>(floor(chunk_duration_in_source_frames / resampling_ratio)); uint32_t input_frames = resampler.input_needed_for_output(output_frames); resampler.input(source.data(), input_frames); source.pop(nullptr, input_frames * channels); resampler.output(destination.data() + write_offset, std::min(output_frames, (destination.length() - write_offset) / channels)); write_offset += output_frames * channels; } dump("output.raw", destination.data(), expected.length()); // compare, taking the latency into account bool fuzzy_equal = true; for (uint32_t i = resampler.latency() + 1; i < expected.length(); i++) { float diff = fabs(expected.data()[i] - destination.data()[i]); if (diff > epsilon<T>(resampling_ratio)) { fprintf(stderr, "divergence at %d: %f %f (delta %f)\n", i, expected.data()[i], destination.data()[i], diff); fuzzy_equal = false; } } ASSERT_TRUE(fuzzy_equal); }
/* LabSound const AtomicString& AudioContext::interfaceName() const { return eventNames().interfaceForAudioContext; } ScriptExecutionContext* AudioContext::scriptExecutionContext() const { return m_isStopScheduled ? 0 : ActiveDOMObject::scriptExecutionContext(); } */ void AudioContext::startRendering() { destination()->startRendering(); }
Plasma::ServiceJob* SolidDeviceService::createJob (const QString& operation, QMap <QString, QVariant>& parameters) { return new SolidDeviceJob (m_engine, destination(), operation, parameters, this); }
HBufC8* CIAUpdateXmlParser::ConvertUnicodeToUtf8L( const TDesC16& aUnicodeText ) { const TInt KConvertBufferSize( 64 ); // Place converted data here, // initial size double the conversion buffer. HBufC8* convertedData = HBufC8::NewL( KConvertBufferSize * 2 ); CleanupStack::PushL( convertedData ); TPtr8 destination( convertedData->Des() ); // Create a small output buffer TBuf8< KConvertBufferSize > outputBuffer; // Create a buffer for the unconverted text - initialised with the // input text TPtrC16 remainderOfUnicodeText( aUnicodeText ); for ( ;; ) // conversion loop { // Start conversion. When the output buffer is full, return the // number of characters that were not converted const TInt returnValue( CnvUtfConverter::ConvertFromUnicodeToUtf8( outputBuffer, remainderOfUnicodeText ) ); // check to see that the descriptor isn’t corrupt // - leave if it is if ( returnValue == CnvUtfConverter::EErrorIllFormedInput ) { User::Leave( KErrCorrupt ); } else if ( returnValue < 0 ) { // future-proof against "TError" expanding User::Leave( KErrGeneral ); } // Do something here to store the contents of the output buffer. if ( destination.Length() + outputBuffer.Length() >= destination.MaxLength() ) { HBufC8* newBuffer = convertedData->ReAllocL( ( destination.MaxLength() + outputBuffer.Length() ) * 2 ); CleanupStack::Pop( convertedData ); convertedData = newBuffer; CleanupStack::PushL( convertedData ); destination.Set( convertedData->Des() ); } destination.Append( outputBuffer ); outputBuffer.Zero(); // Finish conversion if there are no unconverted characters // in the remainder buffer if ( returnValue == 0 ) { break; } // Remove the converted source text from the remainder buffer. // The remainder buffer is then fed back into loop remainderOfUnicodeText.Set( remainderOfUnicodeText.Right( returnValue ) ); } CleanupStack::Pop( convertedData ); return convertedData; }
UDDSocket::UDDSocket(const char* localPath, const char* remotePath) :DatagramSocket() { if (localPath!=NULL) open(localPath); if (remotePath!=NULL) destination(remotePath); }
void ShareJob::start() { //KService::Ptr service = KService::serviceByStorageId("plasma-share-pastebincom.desktop"); KService::Ptr service = KService::serviceByStorageId(destination()); if (!service) { showError(i18n("Could not find the provider with the specified destination")); return; } QString pluginName = service->property("X-KDE-PluginInfo-Name", QVariant::String).toString(); const QString path = KStandardDirs::locate("data", "plasma/shareprovider/" + pluginName + '/' ); if (path.isEmpty()) { showError(i18n("Invalid path for the requested provider")); return; } m_package = new Plasma::Package(path, ShareProvider::packageStructure()); if (m_package->isValid()) { const QString mainscript = m_package->path() + m_package->structure()->contentsPrefixPaths().at(0) + m_package->structure()->path("mainscript"); if (!QFile::exists(mainscript)) { showError(i18n("Selected provider does not have a valid script file")); return; } const QString interpreter = Kross::Manager::self().interpreternameForFile(mainscript); if (interpreter.isEmpty()) { showError(i18n("Selected provider does not provide a supported script file")); return; } m_action = new Kross::Action(parent(), pluginName); if (m_action) { m_provider = new ShareProvider(this); connect(m_provider, SIGNAL(readyToPublish()), this, SLOT(publish())); connect(m_provider, SIGNAL(finished(QString)), this, SLOT(showResult(QString))); connect(m_provider, SIGNAL(finishedError(QString)), this, SLOT(showError(QString))); // automatically connects signals and slots with the script m_action->addObject(m_provider, "provider", Kross::ChildrenInterface::AutoConnectSignals); // set the main script file and load it m_action->setFile(mainscript); m_action->trigger(); // check for any errors if(m_action->hadError()) { showError(i18n("Error trying to execute script")); return; } // do the work together with the loaded plugin const QStringList functions = m_action->functionNames(); if (!functions.contains("url") || !functions.contains("contentKey") || !functions.contains("setup")) { showError(i18n("Could not find all required functions")); return; } // call the methods from the plugin const QString url = m_action->callFunction("url", QVariantList()).toString(); m_provider->setUrl(url); // setup the method (get/post) QVariant vmethod; if (functions.contains("method")) { vmethod = m_action->callFunction("method", QVariantList()).toString(); } // default is POST (if the plugin does not specify one method) const QString method = vmethod.isValid() ? vmethod.toString() : "POST"; m_provider->setMethod(method); // setup the provider QVariant setup = m_action->callFunction("setup", QVariantList()); // get the content from the parameters, set the url and add the file // then we can wait the signal to publish the information const QString contentKey = m_action->callFunction("contentKey", QVariantList()).toString(); const QString content(parameters()["content"].toString()); m_provider->addPostFile(contentKey, content); } } }
Plasma::ServiceJob *ShareService::createJob(const QString &operation, QMap<QString, QVariant> ¶meters) { return new ShareJob(destination(), operation, parameters, this); }
void ICStub::clear() { if (CompiledIC::is_icholder_entry(destination())) { InlineCacheBuffer::queue_for_release((CompiledICHolder*)cached_value()); } _ic_site = NULL; }
double trajOptimizerplus::eval(vector<double> ¶ms) { cout << "IN EVAL "<<itrcount++<<" "<<params.size()<<endl; for (int i=0; i < params.size(); i++) cout << "PARAMS IN: "<<i<<" "<<params.at(i)<<endl; int factor = evidence.getFactor(); pair<int, int> dims = grid.dims(); int v_dim = seqFeat.num_V(); /* pair<int, int> lowDims((int)ceil((float)dims.first/factor), (int)ceil((float)dims.second/factor)); */ vector<vector<vector<double> > > prior(dims.first, vector<vector<double> >(dims.second, vector<double> (v_dim,-HUGE_VAL))); double obj = 0.0; vector<double> gradient(params.size(), 0.0); vector<vector<vector<double> > > occupancy; vector<vector<double> > layerOccupancy; layerOccupancy.resize(dims.first,vector<double>(dims.second,-HUGE_VAL)); vector<double> modelFeats, pathFeats; for (int i=0; i < evidence.size(); i++) { for (int j=0; j < params.size(); j++) { cout << " "<<j<<" "<<params.at(j); } cout<<endl; cout << "Evidence #"<<i<<endl; vector<pair<int, int> >& trajectory = evidence.at(i); vector<double>& velocityseq = evidence.at_v(i); pair<int,int>& bot = evidence.at_bot(i); // robot local blurres features for (int r=1; r <= NUMROBFEAT; r++) { cout << "Adding Robot Feature "<<r<<endl; RobotLocalBlurFeature robblurFeat(grid,bot,10*r); // RobotGlobalFeature robFeat(grid,bot); posFeatures.push_back(robblurFeat); } cout << " Creating feature array"<<endl; FeatureArray featArray2(posFeatures); FeatureArray featArray(featArray2, factor); for (int rr=1; rr<= NUMROBFEAT; rr++) posFeatures.pop_back(); // split different posfeatures and seqfeature weights vector<double> p_weights,s_weights; int itr = 0; for (; itr<featArray.size(); itr++) p_weights.push_back(params[itr]); for (; itr<params.size(); itr++) s_weights.push_back(params[itr]); //cout<<"Params"<<endl; Parameters p_parameters(p_weights), s_parameters(s_weights); /* cout<<featArray.size()<<endl; cout<<params.size()<<endl; cout<<p_weights.size()<<endl; cout<<s_weights.size()<<endl; cout<<p_parameters.size()<<endl; cout<<s_parameters.size()<<endl; */ //cout<<"Reward"<<endl; RewardMap rewards(featArray,seqFeat,p_parameters,s_parameters); DisSeqPredictor predictor(grid, rewards, engine); // sum of reward along the trajectory double cost = 0.0; //cout<< trajectory.size()<<endl; for (int j=0; j < trajectory.size(); j++) { //cout<<j<<" "<<trajectory.at(j).first<<" "<< trajectory.at(j).second<< " "<< seqFeat.getFeat(velocityseq.at(j))<<endl; cost+=rewards.at(trajectory.at(j).first, trajectory.at(j).second, seqFeat.getFeat(velocityseq.at(j))); } State initial(trajectory.front(),seqFeat.getFeat(velocityseq.front())); State destination(trajectory.back(),seqFeat.getFeat(velocityseq.back())); //for (int k=0;k<v_dim;k++) prior.at(destination.x()).at(destination.y()).at(destination.disV) = 0.0; cout << "Initial: "<<initial.x()<<" "<<initial.y()<<" "<<initial.disV<<endl; cout << "Destination: "<<destination.x()<<" " <<destination.y()<<" "<<destination.disV<<endl; predictor.setStart(initial); predictor.setPrior(prior); double norm = predictor.forwardBackwardInference(initial, occupancy); for (int l=0; l<v_dim; l++) { BMPFile gridView(dims.first, dims.second); for (int x= 0; x<dims.first; x++) { for(int y=0; y<dims.second; y++) { layerOccupancy.at(x).at(y) = occupancy.at(x).at(y).at(l); } } char buf[1024]; /* RobotGlobalFeature robblurFeat(grid,bot); gridView.addBelief(robblurFeat.getMap(), 0.0, 25, white, red); gridView.addVector(trajectory, blue, factor); gridView.addLabel(bot,green); sprintf(buf, "../figures/feat%04d_%d.bmp",i,l); gridView.write(buf); */ gridView.addBelief(layerOccupancy, -300.0, 5.0, white, red); //grid.addObstacles(gridView, black); gridView.addLabel(bot,green); gridView.addVector(trajectory, blue, factor); sprintf(buf, "../figures/train%04d_%d.bmp",i,l); gridView.write(buf); } /* for (int i=0; i < occupancy.size(); i++) for (int j=0; j < occupancy.at(i).size(); j++) if (occupancy.at(i).at(j) > -10) cout << i <<" "<<j<<" "<<occupancy.at(i).at(j)<<endl; */ featArray.featureCounts(occupancy, modelFeats); featArray.featureCounts(trajectory, pathFeats); seqFeat.featureCounts_vec(occupancy,modelFeats); seqFeat.featureCounts_vec(velocityseq,pathFeats); for (int k=0; k < params.size(); k++) { double diff = pathFeats.at(k) - modelFeats.at(k); gradient.at(k) -= diff; cout <<" Gradient ("<< k << " -grad: "<< gradient.at(k) <<" -path: "<< pathFeats.at(k)<<" -model: "<< modelFeats.at(k)<<")"; } cout<<endl; cout << "OBJ: "<<cost-norm<< " "<<cost<<" "<<norm<<endl; obj += (cost - norm); /* obj is the path probability * cost is the sum of rewards: sum f(s,a) * norm is V(s_1->G), since here s_T = G, V(s_T->G) = 0*/ prior.at(destination.x()).at(destination.y()).at(destination.disV) = -HUGE_VAL; } cout << "RETURN OBJ: "<<-obj<<endl; params = gradient; return -obj; }