void Aggregate::splitter() try { // Check if any of the Chunk is splittable while (!isComplete() && !hasFailed()) { RemoteData::Partial p = isSplittable(); if(p == RemoteData::Partial::no) return; else if(p==RemoteData::Partial::yes) break; boost::this_thread::sleep(boost::posix_time::millisec(100)); } // Loop while a bottleneck exists while (!isComplete() && !hasFailed()) { // Get the bottle neck and split if(activeChunks() < m_chunks && isSplitReady() ) { // NOTE: Removing this showed the synronization bug std::vector<Chunk*>::size_type bneck = bottleNeck(); split(bneck); // Just sleep for a while boost::this_thread::sleep(boost::posix_time::millisec(1000)); } boost::this_thread::sleep(boost::posix_time::millisec(100)); } } catch (ex::aggregator::NoBottleneck e) { // This isn't a bad thing, just signifies // that no further segmentation can occur. // It helps to get outside both of splitting // loops. }
/** *Receive messages from server about file locks status */ int handleLocks(int *socket,char *curr_file) { char *buffer = malloc(32); memset(buffer,0,32); int read_size = 0,total_read = 0; while((read_size = recv(*socket , buffer+total_read, 32 , 0)) > 0) //Receive a message,of at least 32 bytes,from client { total_read += read_size; if(isComplete(buffer,total_read)) break; } if(checkRecvErrors(&read_size)) { if(strcmp(buffer,"ok") == 0) //acquired locked for file { printf("Acquired lock for file %s.\n",curr_file); free(buffer); return 1; } else if(strcmp(buffer,"locked") == 0) //file is already locked by another client { while(1) { printf("File %s is locked.Waiting for unlock message..\n",curr_file); memset(buffer,0,32); total_read = 0; //client will block until server sends an unlock message while((read_size = recv(*socket , buffer+total_read, 32 , 0)) > 0) //Receive a message,of at least 32 bytes,from client { total_read += read_size; if(isComplete(buffer,total_read)) break; } if(checkRecvErrors(&read_size)) { if(strcmp(buffer,"ok") == 0) { printf("File %s is now unlocked.\n",curr_file); free(buffer); return 1; } } } } else if(strcmp(buffer,"unlocked") == 0) //timeout occurred,server will unlock the file { printf("WARNING!Server will unlock file %s.Maybe the file is too big or the connection too slow.Sync has stopped.\n",curr_file); } } free(buffer); return 0; }
///////////////////////////////////////////////////////////////////////////////// // Adds a NAT Port Mapping // Params: // UPNPNAT_MAPPING *mapping -> Port Mapping Data // If mapping->externalPort is 0, then // mapping->externalPort gets the value of mapping->internalPort // bool tryRandom: // If If mapping->externalPort is in use, tries to find a free // random external port. // // Return: // UNAT_OK: // Successfull. // UNAT_EXTERNAL_PORT_IN_USE: // Error, you are trying to add a port mapping with an external port // in use. // UNAT_NOT_IN_LAN: // Error, you aren't in a LAN -> no router or firewall // UNAT_ERROR: // Error, use GetLastError() to get an error description. ///////////////////////////////////////////////////////////////////////////////// MyUPnP::UPNPNAT_RETURN MyUPnP::AddNATPortMapping(UPNPNAT_MAPPING *mapping, bool tryRandom) { CString ProtoStr, Proto; if(!IsLANIP(GetLocalIP())){ SetLastError(GetResString(IDS_UPNPSTATUS_NOTINLAN)); //zz_fly :: localize output return UNAT_NOT_IN_LAN; } if (!isComplete()) { Search(); if (!isComplete()) { SetLastError(GetResString(IDS_UPNPSTATUS_ERROR)); //zz_fly :: localize output return UNAT_ERROR; } } if (mapping->protocol == UNAT_TCP){ Proto = _T("TCP"); ProtoStr = _T("TCP"); } else { Proto = _T("UDP"); ProtoStr = _T("UDP"); } if(mapping->externalPort == 0) mapping->externalPort = mapping->internalPort; //WORD rndPort = mapping->externalPort; for (int retries = 200; retries>0; retries--) { CString Desc; Desc.Format(_T("eMule (%s) [%s: %u]"), mapping->description, ProtoStr, mapping->externalPort); if (addPortmap(mapping->externalPort, mapping->internalPort, GetLocalIPStr(), Desc, Proto)) { m_Mappings.AddTail(*mapping); SetLastError(GetResString(IDS_UPNPSTATUS_OK)); //zz_fly :: localize output return UNAT_OK; } if (!tryRandom) { SetLastError(GetResString(IDS_UPNPSTATUS_PORTINUSE)); //zz_fly :: localize output return UNAT_EXTERNAL_PORT_IN_USE; } mapping->externalPort = (WORD)(2049 + (65535 - 2049) * rand() / (RAND_MAX + 1)); } SetLastError(GetResString(IDS_UPNPSTATUS_PORTINUSE2)); //zz_fly :: localize output return UNAT_EXTERNAL_PORT_IN_USE; }
bool MyUPnP::GetDescription() { if(!Valid())return false; CString post, host, addr; int port = 0; addr = NGetAddressFromUrl(m_description, post, host, port); if(addr.IsEmpty())return false; CString request = CString(_T("GET ")) + post + _T(" HTTP/1.1\r\nHOST: ") + host + _T("\r\nACCEPT-LANGUAGE: en\r\n\r\n"); CString response; if (!SOAP_action(addr, (uint16)port, request, response)) return false; CString result; if (!parseHTTPResponse(response, result)) return false; m_friendlyname = getProperty(result, _T("friendlyName")); m_modelname = getProperty(result, _T("modelName")); m_baseurl = getProperty(result, _T("URLBase")); if(m_baseurl.IsEmpty())m_baseurl = CString(_T("http://")) + host + _T("/"); if(m_baseurl[m_baseurl.GetLength() - 1]!='/')m_baseurl += _T("/"); CString serviceType = _T("<serviceType>") + m_name + _T("</serviceType>"); int pos = result.Find(serviceType); if (pos >= 0) { result.Delete(0, pos + serviceType.GetLength()); pos = result.Find(_T("</service>")); if (pos >= 0) { result = result.Mid(0, pos); m_controlurl = getProperty(result, _T("controlURL")); if (!m_controlurl.IsEmpty() && m_controlurl[0] == '/') { m_controlurl = m_baseurl + m_controlurl.Mid(1); } } } return isComplete(); }
DWORD WINAPI AsyncSocket::recvHandler(void *_sock) { #else void *AsyncSocket::recvHandler(void *_sock) { #endif static Buffer b; unsigned char buf[2048]; //read a large chunk, we'll be notified if there is more AsyncSocket *sock = (AsyncSocket*)_sock; while (sock->conn != INVALID_SOCKET) { int len = sock->recv(buf, sizeof(buf)); if (len <= 0) { #ifdef _WIN32 //timeouts are okay if (WSAGetLastError() == WSAETIMEDOUT) { continue; } #else //timeouts are okay if (errno == EAGAIN || errno == EWOULDBLOCK) { continue; } #endif // assumption is that socket is borked and next send will fail also // maybe should close socket here at a minimum. // in any case thread is exiting break; } if (sock->d) { b.write(buf, len); //append new data into static buffer while (isComplete(b)) { Buffer *data = new Buffer(b.get_buf() + sizeof(int), requiredSize(b) - sizeof(int)); sock->drt->queueBuffer(data); shift(b); //shift any remaining portions of the buffer to the front } } } return 0; } int send_all(Buffer &b) { if (comm) { return comm->sendAll(b); } return 0; } int send_data(Buffer &b) { if (comm) { return comm->send(b); } else { if (changeCache != NULL) { // msg("writing to change cache\n"); changeCache->writeInt(b.size() + sizeof(int)); *changeCache << b; return b.size(); } } return 0; }
bool Plan::tryRemoveContextAndCancelIfLast(Context& context) { LockHolder locker(m_lock); if (!ASSERT_DISABLED) { // We allow the first completion task to not have a Context. for (unsigned i = 1; i < m_completionTasks.size(); ++i) ASSERT(m_completionTasks[i].first); } bool removedAnyTasks = false; m_completionTasks.removeAllMatching([&] (const std::pair<Context*, CompletionTask>& pair) { bool shouldRemove = pair.first == &context; removedAnyTasks |= shouldRemove; return shouldRemove; }); if (!removedAnyTasks) return false; if (isComplete()) { // We trivially cancel anything that's completed. return true; } // FIXME: Make 0 index not so magical: https://bugs.webkit.org/show_bug.cgi?id=171395 if (m_completionTasks.isEmpty() || (m_completionTasks.size() == 1 && !m_completionTasks[0].first)) { fail(locker, "WebAssembly Plan was cancelled. If you see this error message please file a bug at bugs.webkit.org!"_s); return true; } return false; }
void CallTargetFinder<dsa>::print(llvm::raw_ostream &O, const Module *M) const { O << "[* = incomplete] CS: func list\n"; for (std::map<CallSite, std::vector<const Function*> >::const_iterator ii = IndMap.begin(), ee = IndMap.end(); ii != ee; ++ii) { if (ii->first.getCalledFunction()) //only print indirect continue; if(isa<Function>(ii->first.getCalledValue()->stripPointerCasts())) continue; if (!isComplete(ii->first)) { O << "* "; CallSite cs = ii->first; cs.getInstruction()->dump(); O << cs.getInstruction()->getParent()->getParent()->getName().str() << " " << cs.getInstruction()->getName().str() << " "; } O << ii->first.getInstruction() << ":"; for (std::vector<const Function*>::const_iterator i = ii->second.begin(), e = ii->second.end(); i != e; ++i) { O << " " << (*i)->getName().str(); } O << "\n"; } }
void Plan::waitForCompletion() { LockHolder locker(m_lock); if (!isComplete()) { m_completed.wait(m_lock); } }
int main(int argc, char** argv) { FILE* fproblem = fopen(argv[1], "r"); FILE* fsolution = fopen(argv[2], "r"); if(fproblem == 0 || fsolution == 0) { printf("Error opening file\n"); exit(1); } problem* prob = loadProblem(fproblem, fsolution); int* options = malloc(prob->size * sizeof(int)); // Fill out the numbers which must appear in each house for this size for (int i = 1; i <= prob->size; ++i) { options[i - 1] = i; } if (!isValidSolution(prob, sqrt(prob->size), options)) errInvalidSol(); else if (isComplete(prob)) printf("SOLVED\n"); else printf("INCOMPLETE\n"); freeProblem(prob); }
int countNodes(TreeNode* root) { int tmp = isComplete(root); if (tmp != -1) return tmp; int l = countNodes(root->left); int r = countNodes(root->right); return 1 + l + r; }
float64_t PulseClusterer::getNominalFreq(int idx) { if (!isComplete() || (idx < 0 || idx > (int) clusterList.size())) Fatal(666); return clusterList[idx]->sig.path.rfFreq; }
bool WriteMail::sendStage() { if (!isComplete()) { // The user must either complete the message, save as draft or explicitly cancel return false; } if (buildMail(true)) { if (largeAttachments()) { // Ensure this is intentional if (QMessageBox::question(qApp->activeWindow(), tr("Large attachments"), tr("The message has large attachments. Send now?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { draft(); QMessageBox::warning(qApp->activeWindow(), tr("Message saved"), tr("The message has been saved in the Drafts folder"), QMessageBox::Ok); return true; } } emit enqueueMail(mail); } else { qMailLog(Messaging) << "Unable to build mail for transmission!"; } // Prevent double deletion of composer textedit that leads to crash on exit reset(); close(); return true; }
void setValue( const PropertyAccessor & pa, const Variant & data ) { Key key; if (!createKey( pa, key )) { pa.setValue( data ); return; } std::unique_ptr< ReflectedPropertyCommandArgument > args( new ReflectedPropertyCommandArgument ); args->setContextId( key.first ); args->setPath( key.second.c_str() ); args->setValue( data ); // Access is only on the main thread assert( std::this_thread::get_id() == commandManager_.ownerThreadId() ); const auto commandId = getClassIdentifier< SetReflectedPropertyCommand >(); const auto pArgsDefinition = pa.getDefinitionManager()->getDefinition< ReflectedPropertyCommandArgument >(); ObjectHandle commandArgs( std::move( args ), pArgsDefinition ); auto command = commandManager_.queueCommand( commandId, commandArgs ); // Queuing may cause it to execute straight away // Based on the thread affinity of SetReflectedPropertyCommand if (!command->isComplete()) { commands_.emplace( std::pair< Key, CommandInstancePtr >( key, command ) ); } }
int recvRequests(int *socket,char **buffer,int *length) { int read_size=0,total_read=0; while((read_size = recv(*socket , *buffer+total_read, *length/2 , 0)) > 0) //Receive a message,of at least buffer/2 bytes,from client { total_read += read_size; if(total_read + (*length/2) > *length) //if next read will (probably) cause an overflow,we should double our buffer's size { *length *=2; char *tmp_ptr = realloc(*buffer, *length); if(tmp_ptr == NULL) //cannot realloc memory { fprintf(stderr,"realloc failed to allocate %d bytes of memory.Server will exit\n",*length); free(buffer); return 0; } memset(tmp_ptr+total_read,0,*length-total_read); *buffer = tmp_ptr; } if(isComplete(*buffer,total_read)) break; } if(checkRecvErrors(&read_size)) { if(*buffer[0] == 0) //First char of buffer is NULL,that means all files are up to date (server only sent EOT char) { printf("All files are up to date\n"); } return 1; } return 0; }
void encodeTail(std::string& encoding, const std::string& word) const { for (auto i = 1u; i < word.length(); i++) { if (!isComplete(encoding)) { encodeLetter(encoding, word[i], word[i - 1]); } } }
void DHAnimationInfo::update(float delta, float alpha) { if (m_alpha != alpha) { m_alpha = alpha; m_owner->setDirty(true); } if (isComplete()) { m_frameTime += delta; return; } if (delta == 0) { return; } m_owner->setDirty(true); if (delta < 0) { if (!m_inFadeOut) { m_data->applyEventsTo(m_owner, m_frameTime, delta); } m_frameTime += delta; if (m_frameTime <= 0) { if (m_loop < 0) { m_frameTime = getDuration() + fmodf(m_frameTime, getDuration()); } else if(m_loop > 1) { m_loop--; m_frameTime = getDuration() + fmodf(m_frameTime, getDuration()); } else { m_loop = 0; m_frameTime = 0; } if (!m_inFadeOut && m_loop) { m_data->applyEventsToBackward(m_owner, m_frameTime, getDuration()); m_data->applyEventsToFirstFrame(m_frameTime, m_owner); } } } else { if (!m_inFadeOut) { m_data->applyEventsTo(m_owner, m_frameTime, delta); } m_frameTime += delta; if (m_frameTime >= getDuration()) { if (m_loop < 0) { m_frameTime = fmodf(m_frameTime, getDuration()); } else if(m_loop > 1) { m_loop--; m_frameTime = fmodf(m_frameTime, getDuration()); } else { m_loop = 0; } if (!m_inFadeOut && m_loop) { m_data->applyEventsToFirstFrame(0.f, m_owner); m_data->applyEventsTo(m_owner, 0.f, m_frameTime); } } } }
float DHAnimationInfo::getNextFrameTime(float delta) { float duration = getDuration(); if (isComplete()) { return duration; } float frameTime = m_frameTime; if (delta < 0) { frameTime += delta; if (frameTime <= 0) { if (m_loop < 0) { frameTime = duration + fmodf(frameTime, duration); } else if(m_loop > 1) { frameTime = duration + fmodf(frameTime, duration); } else { frameTime = 0; } } } else { frameTime += delta; if (frameTime >= duration) { if (m_loop < 0) { frameTime = fmodf(frameTime, duration); } else if(m_loop > 1) { frameTime = fmodf(frameTime, duration); } else { frameTime = duration; } } } return frameTime; }
//------------------------- // cluster access //------------------------- int PulseClusterer::getCount() { if (!isComplete()) Fatal(666); return clusterList.size(); }
struct grid resolvGrid(struct grid Grid){ applyRules(&Grid); if(isComplete(Grid)){ return Grid; } else if(!isValid(Grid)){ Grid.line = -1; return Grid; } else{ struct grid g=copy(Grid); if(fixUncertainty(&g, 1)){ g = resolvGrid(g); if(g.line != -1){ return g; } else{ g=copy(Grid); fixUncertainty(&g, 0); g = resolvGrid(g); return g; } } else{ Grid.line = -1; return Grid; } } }
int EigenValue::verifyResults() { cl_uint offset = 0; if(verify) { cl_uint eigenIntervalsSizeBytes = (2*length) * sizeof(cl_float); for(int i=0 ; i < 2; ++i) { verificationEigenIntervals[i] = (cl_float *) malloc(eigenIntervalsSizeBytes); if(verificationEigenIntervals[i] == NULL) { sampleCommon->error("Failed to allocate host memory. (verificationEigenIntervals)"); return SDK_FAILURE; } } cl_float lowerLimit; cl_float upperLimit; computeGerschgorinInterval(&lowerLimit, &upperLimit, diagonal, offDiagonal, length); verificationIn = 0; verificationEigenIntervals[verificationIn][0]= lowerLimit; verificationEigenIntervals[verificationIn][1]= upperLimit; for(cl_int i=2 ; i < 2*length ; i++) { verificationEigenIntervals[verificationIn][i] = upperLimit; } int refTimer = sampleCommon->createTimer(); sampleCommon->resetTimer(refTimer); sampleCommon->startTimer(refTimer); while(isComplete(verificationEigenIntervals[verificationIn])) { offset = eigenValueCPUReference(diagonal,offDiagonal, length, verificationEigenIntervals[verificationIn], verificationEigenIntervals[1-verificationIn]); verificationIn = 1 - verificationIn; } sampleCommon->stopTimer(refTimer); referenceKernelTime = sampleCommon->readTimer(refTimer); if(sampleCommon->compare(eigenIntervals[in], verificationEigenIntervals[verificationIn], 2*length)) { std::cout<<"Passed!\n" << std::endl; return SDK_SUCCESS; } else { std::cout<<"Failed\n" << std::endl; return SDK_FAILURE; } } return SDK_SUCCESS; }
void Plan::addCompletionTask(Context* context, CompletionTask&& task) { LockHolder locker(m_lock); if (!isComplete()) m_completionTasks.append(std::make_pair(context, WTFMove(task))); else task->run(*this); }
bool MyUPnP::Search(int version) { if (isSearched) return isComplete(); isSearched = true; return InternalSearch(version); }
void SshIncomingPacket::consumeData(QByteArray &newData) { #ifdef CREATOR_SSH_DEBUG qDebug("%s: current data size = %d, new data size = %d", Q_FUNC_INFO, m_data.size(), newData.size()); #endif if (isComplete() || newData.isEmpty()) return; /* * Until we have reached the minimum packet size, we cannot decrypt the * length field. */ const quint32 minSize = minPacketSize(); if (currentDataSize() < minSize) { const int bytesToTake = qMin<quint32>(minSize - currentDataSize(), newData.size()); moveFirstBytes(m_data, newData, bytesToTake); #ifdef CREATOR_SSH_DEBUG qDebug("Took %d bytes from new data", bytesToTake); #endif if (currentDataSize() < minSize) return; } if (4 + length() + macLength() < currentDataSize()) throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR, "Server sent invalid packet."); const int bytesToTake = qMin<quint32>(length() + 4 + macLength() - currentDataSize(), newData.size()); moveFirstBytes(m_data, newData, bytesToTake); #ifdef CREATOR_SSH_DEBUG qDebug("Took %d bytes from new data", bytesToTake); #endif if (isComplete()) { #ifdef CREATOR_SSH_DEBUG qDebug("Message complete. Overall size: %u, payload size: %u", m_data.size(), m_length - paddingLength() - 1); #endif decrypt(); ++m_serverSeqNr; } }
void Plan::runCompletionTasks(const AbstractLocker&) { ASSERT(isComplete() && !hasWork()); for (auto& task : m_completionTasks) task.second->run(*this); m_completionTasks.clear(); m_completed.notifyAll(); }
string shortestCompletingWord(string licensePlate, vector<string>& words) { auto cnt = count(licensePlate); string ans; for (string &w : words) { if (!isComplete(w, cnt)) continue; if (ans.empty() || w.size() < ans.size()) ans = w; } return ans; }
void DataDownloader::complete(QNetworkReply* reply) { m_Data = reply->readAll(); reply->deleteLater(); if (!m_Data.isEmpty()) { emit isComplete(); } }
void MF_Message::addChunk(MF_ChunkInfo *c){ chkList.push_back(c); mCount++; if(isComplete()){ MF_Log::mf_log(MF_DEBUG, "MF_Message:addChunk chunk complete, ordering and creating vector of data"); sortList(); createData(); } }
void AccountPage::checkPathNames() { bool was = complete; complete = isComplete(); // let's not casually overwrite a valuable key enableMakeKey(); if ( was != complete ) emit completeChanged(); }
bool KeyMap::probeKeyMap(const InputDeviceIdentifier& deviceIdentifier, const String8& keyMapName) { if (!haveKeyLayout()) { loadKeyLayout(deviceIdentifier, keyMapName); } if (!haveKeyCharacterMap()) { loadKeyCharacterMap(deviceIdentifier, keyMapName); } return isComplete(); }
QVariant Algorithm_Impl::toVariant() const { QVariantMap map = AnalysisObject_Impl::toVariant().toMap(); map["complete"] = isComplete(); map["failed"] = failed(); map["iter"] = iter(); map["options"] = options().toVariant(); return QVariant(map); }