Range<AsyncIO::Op**> AsyncIO::pollCompleted() { CHECK(ctx_); CHECK_NE(pollFd_, -1) << "pollCompleted() only allowed on pollable object"; uint64_t numEvents; // This sets the eventFd counter to 0, see // http://www.kernel.org/doc/man-pages/online/pages/man2/eventfd.2.html ssize_t rc; do { rc = ::read(pollFd_, &numEvents, 8); } while (rc == -1 && errno == EINTR); if (UNLIKELY(rc == -1 && errno == EAGAIN)) { return Range<Op**>(); // nothing completed } checkUnixError(rc, "AsyncIO: read from event fd failed"); DCHECK_EQ(rc, 8); DCHECK_GT(numEvents, 0); DCHECK_LE(numEvents, pending_); // Don't reap more than numEvents, as we've just reset the counter to 0. return doWait(numEvents, numEvents); }
void ReshapeLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { CHECK_NE(top[0], bottom[0]) << this->type() << " Layer does not " "allow in-place computation."; inferred_axis_ = -1; copy_axes_.clear(); const BlobShape& top_blob_shape = this->layer_param_.reshape_param().shape(); const int top_num_axes = top_blob_shape.dim_size(); constant_count_ = 1; for (int i = 0; i < top_num_axes; ++i) { const int top_dim = top_blob_shape.dim(i); if (top_dim == 0) { copy_axes_.push_back(i); } else if (top_dim == -1) { CHECK_EQ(inferred_axis_, -1) << "new shape contains multiple " << "-1 dims; at most a single (1) value of -1 may be specified"; inferred_axis_ = i; } else { constant_count_ *= top_dim; } } }
bool ReadOrderlyShutdown(int fd) { char buf[16]; // Only call this function if you're sure that the peer does // orderly/graceful shutdown of the socket, closing the socket so that // adb_read() will return 0. If the peer keeps the socket open, adb_read() // will never return. int result = adb_read(fd, buf, sizeof(buf)); if (result == -1) { // If errno is EAGAIN, that means this function was called on a // nonblocking socket and it would have blocked (which would be bad // because we'd probably block the main thread where nonblocking IO is // done). Don't do that. If you have a nonblocking socket, use the // fdevent APIs to get called on FDE_READ, and then call this function // if you really need to, but it shouldn't be needed for server sockets. CHECK_NE(errno, EAGAIN); // Note that on Windows, orderly shutdown sometimes causes // recv() == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET. That // can be ignored. return false; } else if (result == 0) { // Peer has performed an orderly/graceful shutdown. return true; } else { // Unexpectedly received data. This is essentially a protocol error // because you should not call this function unless you expect no more // data. We don't repeatedly call adb_read() until we get zero because // we don't know how long that would take, but we do know that the // caller wants to close the socket soon. VLOG(RWX) << "ReadOrderlyShutdown(" << fd << ") unexpectedly read " << dump_hex(buf, result); // Shutdown the socket to prevent the caller from reading or writing to // it which doesn't make sense if we just read and discarded some data. adb_shutdown(fd); errno = EINVAL; return false; } }
int main() { LOG(INFO) << "Dump log test"; // CHECK Operation CHECK_NE(1, 2) << ": The world must be ending!"; // Check if it is euqual CHECK_EQ(std::string("abc")[1], 'b'); int x = 2; int y = 1; LOG_IF(ERROR, x > y) << "2 > 1. This should be also OK"; // Test dump log in different thread int err = pthread_create(&newTid, NULL, ThreadRunnable, NULL); if (err != 0) { LOG(FATAL) << "Unable to create a thread"; return 1; } sleep(1); TestStopWatch(); return 0; }
void nub_loop_dispose(nub_loop_t* loop) { ASSERT(0 == uv_loop_alive(&loop->uvloop)); ASSERT(1 == fuq_empty(&loop->blocking_queue_)); ASSERT(0 == loop->ref_); ASSERT(NULL != loop->work_ping_); ASSERT(0 == uv_has_ref((uv_handle_t*) loop->work_ping_)); ASSERT(1 == fuq_empty(&loop->thread_dispose_queue_)); uv_close((uv_handle_t*) loop->work_ping_, nub__free_handle_cb); uv_close((uv_handle_t*) &loop->queue_processor_, NULL); ASSERT(0 == uv_is_active((uv_handle_t*) loop->work_ping_)); fuq_dispose(&loop->thread_dispose_queue_); uv_mutex_destroy(&loop->thread_dispose_lock_); uv_sem_destroy(&loop->loop_lock_sem_); fuq_dispose(&loop->blocking_queue_); uv_mutex_destroy(&loop->queue_processor_lock_); fuq_dispose(&loop->work_queue_); uv_mutex_destroy(&loop->work_lock_); CHECK_EQ(0, uv_run(&loop->uvloop, UV_RUN_NOWAIT)); CHECK_NE(UV_EBUSY, uv_loop_close(&loop->uvloop)); }
void ResizeImagePeriodic(const cv::Mat& src_img, const int h_off, const int w_off, cv::Mat* dst_img) { const int h_src = src_img.rows; const int w_src = src_img.cols; const int h_dst = dst_img->rows; const int w_dst = dst_img->cols; const int num_channels = src_img.channels(); CHECK_EQ(num_channels, dst_img->channels()) << "number of channels of source and destimation images have to be equal"; CHECK_NE(dst_img, &src_img) << "doesn't support in place calculation"; const int cvwidth_src = w_src * num_channels; for (int h = 0; h < h_dst; ++h) { uchar* ptr_dst = dst_img->ptr<uchar>(h); const uchar* ptr_src = src_img.ptr<uchar>(positive_mod(h-h_off, h_src)); int index_dst = 0; int index_src = positive_mod(-num_channels*w_off, cvwidth_src); for (int w = 0; w < w_dst; ++w) { for (int c = 0; c < num_channels; ++c) { ptr_dst[index_dst++] = ptr_src[positive_mod(index_src++, cvwidth_src)]; } } } }
HTTP2PriorityQueue::Handle HTTP2PriorityQueue::updatePriority(HTTP2PriorityQueue::Handle handle, http2::PriorityUpdate pri) { Node* node = handle; pendingWeightChange_ = true; node->updateWeight(pri.weight); CHECK_NE(pri.streamDependency, node->getID()) << "Tried to create a loop in the tree";; if (pri.streamDependency == node->parentID() && !pri.exclusive) { // no move return handle; } Node* newParent = find(pri.streamDependency); if (!newParent) { newParent = &root_; } if (newParent->isDescendantOf(node)) { newParent = newParent->reparent(node->getParent(), false); } return node->reparent(newParent, pri.exclusive); }
// Add a new node as a child of this node HTTP2PriorityQueue::Handle HTTP2PriorityQueue::Node::emplaceNode( unique_ptr<HTTP2PriorityQueue::Node> node, bool exclusive) { CHECK(!node->isEnqueued()); list<unique_ptr<Node>> children; CHECK_NE(id_, node->id_) << "Tried to create a loop in the tree"; if (exclusive) { // this->children become new node's children std::swap(children, children_); totalChildWeight_ = 0; bool wasInEgressTree = inEgressTree(); totalEnqueuedWeight_ = 0; #ifndef NDEBUG totalEnqueuedWeightCheck_ = 0; #endif if (wasInEgressTree && !inEgressTree()) { propagatePendingEgressClear(this); } } auto res = addChild(std::move(node)); res->addChildren(std::move(children)); return res; }
LDAStats::LDAStats() { // Topic model parameters. Context& context = Context::get_instance(); K_ = context.get_int32("num_topics"); V_ = context.get_int32("num_vocabs"); CHECK_NE(-1, V_); beta_ = context.get_double("beta"); beta_sum_ = beta_ * V_; alpha_ = context.get_double("alpha"); alpha_sum_ = K_ * alpha_; loggamma_alpha_offset_.resize(kNumLogGammaAlpha_); loggamma_alpha_sum_offset_.resize(kNumLogGammaAlphaSum_); loggamma_beta_offset_.resize(kNumLogGammaBeta_); for (int i = 0; i < kNumLogGammaAlpha_; ++i) { loggamma_alpha_offset_[i] = LogGamma(i + alpha_); } for (int i = 0; i < kNumLogGammaAlphaSum_; ++i) { loggamma_alpha_sum_offset_[i] = LogGamma(i + alpha_sum_); } for (int i = 0; i < kNumLogGammaBeta_; ++i) { loggamma_beta_offset_[i] = LogGamma(i + beta_); } // Precompute LLH parameters log_doc_normalizer_ = LogGamma(alpha_sum_) - K_ * LogGamma(alpha_); log_topic_normalizer_ = K_ * (LogGamma(beta_sum_) - V_ * LogGamma(beta_)); // PS tables. int32_t summary_table_id = context.get_int32("summary_table_id"); int32_t word_topic_table_id = context.get_int32("word_topic_table_id"); int32_t llh_table_id = context.get_int32("llh_table_id"); summary_table_ = petuum::PSTableGroup::GetTableOrDie<int>(summary_table_id); word_topic_table_ = petuum::PSTableGroup::GetTableOrDie<int>( word_topic_table_id); llh_table_ = petuum::PSTableGroup::GetTableOrDie<double>(llh_table_id); }
void TopicCount::UpdateCount(int old_topic, int new_topic, int doc_id, std::unique_ptr<std::mutex[]> &mutex_pool_) { std::lock_guard<std::mutex>lock(mutex_pool_[doc_id]); if (old_topic == new_topic) return; // Find old and new index int old_index = -1; int new_index = -1; for (size_t i = 0; i < item_.size(); ++i) { if (item_[i].top_ == old_topic) old_index = i; if (item_[i].top_ == new_topic) new_index = i; if (old_index != -1 and new_index != -1) break; // early stop } CHECK_NE(old_index, -1); // Decrement old index while maintaining new index Pair temp(item_[old_index].top_, item_[old_index].cnt_ - 1); int last_index = item_.size() - 1; if (item_[old_index].cnt_ == 1) { if (new_index == last_index) new_index = old_index; // maintain std::swap(item_[old_index], item_.back()); // swap with last/self item_.pop_back(); } // end of "need to shrink" else if (old_index < last_index and temp.cnt_ < item_[old_index+1].cnt_) { auto it = std::lower_bound(item_.begin() + old_index + 1, item_.end(), temp, [](Pair a, Pair b){ return a.cnt_ > b.cnt_; })-1; if (item_.begin() + new_index == it) new_index = old_index; // maintain item_[old_index] = *it; *it = temp; } // end of "no need to shrink but need to rearrange" else { --item_[old_index].cnt_; } // end of "no need to rearrange" // Increment new if (new_index != -1) IncrementExisting(new_index); else item_.emplace_back(new_topic, 1); }
const Distribution1D *SpatialLightDistribution::Lookup(const Point3f &p) const { ProfilePhase _(Prof::LightDistribLookup); ++nLookups; // First, compute integer voxel coordinates for the given point |p| // with respect to the overall voxel grid. Vector3f offset = scene.WorldBound().Offset(p); // offset in [0,1]. Point3i pi; for (int i = 0; i < 3; ++i) // The clamp should almost never be necessary, but is there to be // robust to computed intersection points being slightly outside // the scene bounds due to floating-point roundoff error. pi[i] = Clamp(int(offset[i] * nVoxels[i]), 0, nVoxels[i] - 1); // Pack the 3D integer voxel coordinates into a single 64-bit value. uint64_t packedPos = (uint64_t(pi[0]) << 40) | (uint64_t(pi[1]) << 20) | pi[2]; CHECK_NE(packedPos, invalidPackedPos); // Compute a hash value from the packed voxel coordinates. We could // just take packedPos mod the hash table size, but since packedPos // isn't necessarily well distributed on its own, it's worthwhile to do // a little work to make sure that its bits values are individually // fairly random. For details of and motivation for the following, see: // http://zimbry.blogspot.ch/2011/09/better-bit-mixing-improving-on.html uint64_t hash = packedPos; hash ^= (hash >> 31); hash *= 0x7fb5d329728ea185; hash ^= (hash >> 27); hash *= 0x81dadef4bc2dd44d; hash ^= (hash >> 33); hash %= hashTableSize; CHECK_GE(hash, 0); // Now, see if the hash table already has an entry for the voxel. We'll // use quadratic probing when the hash table entry is already used for // another value; step stores the square root of the probe step. int step = 1; int nProbes = 0; while (true) { ++nProbes; HashEntry &entry = hashTable[hash]; // Does the hash table entry at offset |hash| match the current point? uint64_t entryPackedPos = entry.packedPos.load(std::memory_order_acquire); if (entryPackedPos == packedPos) { // Yes! Most of the time, there should already by a light // sampling distribution available. Distribution1D *dist = entry.distribution.load(std::memory_order_acquire); if (dist == nullptr) { // Rarely, another thread will have already done a lookup // at this point, found that there isn't a sampling // distribution, and will already be computing the // distribution for the point. In this case, we spin until // the sampling distribution is ready. We assume that this // is a rare case, so don't do anything more sophisticated // than spinning. ProfilePhase _(Prof::LightDistribSpinWait); while ((dist = entry.distribution.load(std::memory_order_acquire)) == nullptr) // spin :-(. If we were fancy, we'd have any threads // that hit this instead help out with computing the // distribution for the voxel... ; } // We have a valid sampling distribution. ReportValue(nProbesPerLookup, nProbes); return dist; } else if (entryPackedPos != invalidPackedPos) { // The hash table entry we're checking has already been // allocated for another voxel. Advance to the next entry with // quadratic probing. hash += step * step; if (hash >= hashTableSize) hash %= hashTableSize; ++step; } else { // We have found an invalid entry. (Though this may have // changed since the load into entryPackedPos above.) Use an // atomic compare/exchange to try to claim this entry for the // current position. uint64_t invalid = invalidPackedPos; if (entry.packedPos.compare_exchange_weak(invalid, packedPos)) { // Success; we've claimed this position for this voxel's // distribution. Now compute the sampling distribution and // add it to the hash table. As long as packedPos has been // set but the entry's distribution pointer is nullptr, any // other threads looking up the distribution for this voxel // will spin wait until the distribution pointer is // written. Distribution1D *dist = ComputeDistribution(pi); entry.distribution.store(dist, std::memory_order_release); ReportValue(nProbesPerLookup, nProbes); return dist; } } } }
int64_t AudioPlayer::getRealTimeUsLocked() const { CHECK(mStarted); CHECK_NE(mSampleRate, 0); return -mLatencyUs + (mNumFramesPlayed * 1000000) / mSampleRate; }
void RemoteFontFaceSource::FontLoadHistograms::recordLoadTimeHistogram( const FontResource* font, int duration, bool isInterventionTriggered) { CHECK_NE(FromUnknown, m_dataSource); if (font->errorOccurred()) { DEFINE_STATIC_LOCAL(CustomCountHistogram, loadErrorHistogram, ("WebFont.DownloadTime.LoadError", 0, 10000, 50)); DEFINE_STATIC_LOCAL( CustomCountHistogram, missedCacheLoadErrorHistogram, ("WebFont.MissedCache.DownloadTime.LoadError", 0, 10000, 50)); loadErrorHistogram.count(duration); if (m_dataSource == FromNetwork) missedCacheLoadErrorHistogram.count(duration); return; } unsigned size = font->encodedSize(); if (size < 10 * 1024) { DEFINE_STATIC_LOCAL(CustomCountHistogram, under10kHistogram, ("WebFont.DownloadTime.0.Under10KB", 0, 10000, 50)); DEFINE_STATIC_LOCAL( CustomCountHistogram, missedCacheUnder10kHistogram, ("WebFont.MissedCache.DownloadTime.0.Under10KB", 0, 10000, 50)); under10kHistogram.count(duration); if (m_dataSource == FromNetwork) missedCacheUnder10kHistogram.count(duration); return; } if (size < 50 * 1024) { DEFINE_STATIC_LOCAL(CustomCountHistogram, under50kHistogram, ("WebFont.DownloadTime.1.10KBTo50KB", 0, 10000, 50)); DEFINE_STATIC_LOCAL( CustomCountHistogram, missedCacheUnder50kHistogram, ("WebFont.MissedCache.DownloadTime.1.10KBTo50KB", 0, 10000, 50)); // Breakdowns metrics to understand WebFonts intervention. // Now we only cover this 10KBto50KB range because 70% of requests are // covered in this range, and having metrics for all size cases cost. DEFINE_STATIC_LOCAL(CustomCountHistogram, missedCacheAndInterventionTriggeredUnder50kHistogram, ("WebFont.MissedCacheAndInterventionTriggered." "DownloadTime.1.10KBTo50KB", 0, 10000, 50)); DEFINE_STATIC_LOCAL(CustomCountHistogram, missedCacheAndInterventionNotTriggeredUnder50kHistogram, ("WebFont.MissedCacheAndInterventionNotTriggered." "DownloadTime.1.10KBTo50KB", 0, 10000, 50)); under50kHistogram.count(duration); if (m_dataSource == FromNetwork) { missedCacheUnder50kHistogram.count(duration); if (isInterventionTriggered) missedCacheAndInterventionTriggeredUnder50kHistogram.count(duration); else missedCacheAndInterventionNotTriggeredUnder50kHistogram.count(duration); } return; } if (size < 100 * 1024) { DEFINE_STATIC_LOCAL(CustomCountHistogram, under100kHistogram, ("WebFont.DownloadTime.2.50KBTo100KB", 0, 10000, 50)); DEFINE_STATIC_LOCAL( CustomCountHistogram, missedCacheUnder100kHistogram, ("WebFont.MissedCache.DownloadTime.2.50KBTo100KB", 0, 10000, 50)); under100kHistogram.count(duration); if (m_dataSource == FromNetwork) missedCacheUnder100kHistogram.count(duration); return; } if (size < 1024 * 1024) { DEFINE_STATIC_LOCAL(CustomCountHistogram, under1mbHistogram, ("WebFont.DownloadTime.3.100KBTo1MB", 0, 10000, 50)); DEFINE_STATIC_LOCAL( CustomCountHistogram, missedCacheUnder1mbHistogram, ("WebFont.MissedCache.DownloadTime.3.100KBTo1MB", 0, 10000, 50)); under1mbHistogram.count(duration); if (m_dataSource == FromNetwork) missedCacheUnder1mbHistogram.count(duration); return; } DEFINE_STATIC_LOCAL(CustomCountHistogram, over1mbHistogram, ("WebFont.DownloadTime.4.Over1MB", 0, 10000, 50)); DEFINE_STATIC_LOCAL( CustomCountHistogram, missedCacheOver1mbHistogram, ("WebFont.MissedCache.DownloadTime.4.Over1MB", 0, 10000, 50)); over1mbHistogram.count(duration); if (m_dataSource == FromNetwork) missedCacheOver1mbHistogram.count(duration); }
int main(int argc, char *argv[]) { void *lowest_segments[2] = { NULL, NULL }; Elf32_Ehdr hdr; Elf32_Phdr *phdr; FILE *fi; maps_range maps[16]; int map_cnt; int i, ret, envc, sfp; long *stack_frame; struct stat st; char buf[64]; long lret; if (argc < 2) { fprintf(stderr, "usage: %s <program> [args]\n", argv[0]); return 1; } g_argv = argv; lret = g_personality(-1); if (g_syscall_error(lret) != -1) { lret |= 0x0240000; // ADDR_COMPAT_LAYOUT | ADDR_NO_RANDOMIZE g_personality(lret); } fi = fopen("/proc/self/maps", "r"); CHECK_NE(fi, NULL, "fopen maps"); for (i = 0; i < ARRAY_SIZE(maps); i++) { ret = fscanf(fi, "%lx-%lx %*s %*s %*s %*s %*s\n", &maps[i].start, &maps[i].end); if (ret <= 0) break; CHECK_EQ(ret, 2, "maps parse error"); } fclose(fi); map_cnt = i; CHECK_NE(map_cnt, 0, "no maps"); CHECK_NE(map_cnt, ARRAY_SIZE(maps), "too many maps"); fi = fopen(argv[1], "rb"); if (fi == NULL) FAIL_PERROR("fopen"); if (fread(&hdr, 1, sizeof(hdr), fi) != sizeof(hdr)) FAIL_PERROR("too small or"); if (memcmp(hdr.e_ident, ELFMAG "\x01\x01", SELFMAG + 2) != 0) { fprintf(stderr, "not 32bit LE ELF?\n"); return 1; } HDR_CHECK_EQ(e_type, ET_EXEC, "not executable"); HDR_CHECK_EQ(e_machine, EM_ARM, "not ARM"); HDR_CHECK_EQ(e_phentsize, sizeof(Elf32_Phdr), "bad PH entry size"); HDR_CHECK_NE(e_phnum, 0, "no PH entries"); phdr = malloc(hdr.e_phnum * hdr.e_phentsize); CHECK_NE(phdr, NULL, "OOM"); if (fread(phdr, hdr.e_phentsize, hdr.e_phnum, fi) != hdr.e_phnum) FAIL_PERROR("too small or"); for (i = 0; i < hdr.e_phnum; i++) { Elf32_Addr end_addr = phdr[i].p_vaddr + phdr[i].p_memsz; Elf32_Addr align; void *ptr, *map_ptr; if (phdr[i].p_type == PT_NOTE) continue; if (phdr[i].p_type != PT_LOAD) { fprintf(stderr, "skipping section %d\n", phdr[i].p_type); continue; } ret = is_range_used(maps, map_cnt, phdr[i].p_vaddr, end_addr); if (ret) { fprintf(stderr, "segment %d (%08x-%08x) hits %08lx-%08lx in maps\n", i, phdr[i].p_vaddr, end_addr, maps[ret - 1].start, maps[ret - 1].end); return 1; } log("load %d %08x-%08x from %08x\n", phdr[i].p_type, phdr[i].p_vaddr, end_addr, phdr[i].p_offset); align = phdr[i].p_vaddr & 0xfff; map_ptr = (void *)(phdr[i].p_vaddr - align); ptr = mmap(map_ptr, phdr[i].p_memsz + align, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_FIXED|MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (ptr == MAP_FAILED || ptr != map_ptr) FAIL_PERROR("mmap"); if (phdr[i].p_filesz > 0) { if (fseek(fi, phdr[i].p_offset, SEEK_SET) != 0) FAIL_PERROR("fseek"); if (fread((char *)ptr + align, 1, phdr[i].p_filesz, fi) != phdr[i].p_filesz) FAIL_PERROR("too small or"); if (phdr[i].p_flags & PF_X) do_patches((char *)ptr + align, phdr[i].p_filesz); } if (lowest_segments[0] == NULL || map_ptr < lowest_segments[0]) lowest_segments[0] = map_ptr; } // build self bin path snprintf(buf, sizeof(buf), "/proc/self/fd/%d", fileno(fi)); if (lstat(buf, &st) != 0) FAIL_PERROR("lstat bin_path"); bin_path = malloc(st.st_size + 1); CHECK_NE(bin_path, NULL, "bin_path"); ret = readlink(buf, bin_path, st.st_size); if (ret < 0) FAIL_PERROR("readlink"); bin_path[ret] = 0; fclose(fi); emu_init(lowest_segments, 0); // generate stack frame: argc, argv[], NULL, env[], NULL for (envc = 0; environ[envc] != NULL; envc++) ; stack_frame = calloc(argc + envc + 3, sizeof(stack_frame[0])); if (stack_frame == NULL) { fprintf(stderr, "stack_frame OOM\n"); return 1; } // update the environment setenv("_", bin_path, 1); sfp = 0; stack_frame[sfp++] = argc - 1; for (i = 1; i < argc; i++) stack_frame[sfp++] = (long)argv[i]; stack_frame[sfp++] = 0; for (i = 0; i < envc; i++) stack_frame[sfp++] = (long)environ[i]; stack_frame[sfp++] = 0; log("entering %08x, %d stack entries\n", hdr.e_entry, sfp); do_entry(hdr.e_entry, stack_frame, sfp, NULL); fprintf(stderr, "do_entry failed!\n"); return 1; }
AsyncIOOp::~AsyncIOOp() { CHECK_NE(state_, State::PENDING); }
void zoo(RetBase* obj) { Base2* ret = obj->foo(); CHECK_NE(0, ret); CHECK_EQ(2, ret->b); }
void AbsValLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { NeuronLayer<Dtype>::LayerSetUp(bottom, top); CHECK_NE(top[0], bottom[0]) << this->type() << " Layer does not " "allow in-place computation."; }
void RTSPSource::onMessageReceived(const sp<AMessage> &msg) { if (msg->what() == kWhatDisconnect) { uint32_t replyID; CHECK(msg->senderAwaitsResponse(&replyID)); mDisconnectReplyID = replyID; finishDisconnectIfPossible(); return; } else if (msg->what() == kWhatPerformSeek) { int32_t generation; CHECK(msg->findInt32("generation", &generation)); if (generation != mSeekGeneration) { // obsolete. return; } int64_t seekTimeUs; CHECK(msg->findInt64("timeUs", &seekTimeUs)); performSeek(seekTimeUs); return; } else if (msg->what() == kWhatPerformPlay) { int64_t playTimeUs; CHECK(msg->findInt64("timeUs", &playTimeUs)); performPlay(playTimeUs); return; } else if (msg->what() == kWhatPerformPause) { performPause(); return; } else if (msg->what() == kWhatPerformResume) { performResume(); return; } else if (msg->what() == kWhatPerformSuspend) { performSuspend(); return; } CHECK_EQ(msg->what(), (uint32_t)kWhatNotify); int32_t what; int32_t isSeekable = 0; CHECK(msg->findInt32("what", &what)); switch (what) { case RtspConnectionHandler::kWhatConnected: CHECK(msg->findInt32("isSeekable", &isSeekable)); onConnected((isSeekable ? true:false)); break; case RtspConnectionHandler::kWhatDisconnected: onDisconnected(msg); break; case RtspConnectionHandler::kWhatSeekDone: { mState = PLAYING; // Even if we have reset mLatestPausedUnit in performSeek(), // it's still possible that kWhatPausedDone event may arrive // because of previous performPause() command. for (size_t i = 0; i < mTracks.size(); ++i) { TrackInfo *info = &mTracks.editItemAt(i); info->mLatestPausedUnit = 0; } mLatestPausedUnit = 0; break; } case RtspConnectionHandler::kWhatPausedDone: { for (size_t i = 0; i < mTracks.size(); ++i) { TrackInfo *info = &mTracks.editItemAt(i); info->mLatestPausedUnit = info->mLatestReceivedUnit; } // The timestamp after a 'Pause' is done is the earliest // timestamp among all of the latest received units. TrackInfo *info = &mTracks.editItemAt(0); mLatestPausedUnit = info->mLatestReceivedUnit; for (size_t i = 1; i < mTracks.size(); ++i) { TrackInfo *info = &mTracks.editItemAt(i); if (mLatestPausedUnit > info->mLatestReceivedUnit) { mLatestPausedUnit = info->mLatestReceivedUnit; } } break; } case RtspConnectionHandler::kWhatAccessUnit: { size_t trackIndex; CHECK(msg->findSize("trackIndex", &trackIndex)); CHECK_LT(trackIndex, mTracks.size()); sp<RefBase> obj; CHECK(msg->findObject("accessUnit", &obj)); sp<ABuffer> accessUnit = static_cast<ABuffer *>(obj.get()); int32_t damaged; if (accessUnit->meta()->findInt32("damaged", &damaged) && damaged) { LOGI("dropping damaged access unit."); break; } TrackInfo *info = &mTracks.editItemAt(trackIndex); sp<AnotherPacketSource> source = info->mSource; if (source != NULL) { uint32_t rtpTime; CHECK(accessUnit->meta()->findInt32("rtp-time", (int32_t *)&rtpTime)); if (!info->mNPTMappingValid) { // This is a live stream, we didn't receive any normal // playtime mapping. Assume the first packets correspond // to time 0. LOGV("This is a live stream, assuming time = 0"); info->mRTPTime = rtpTime; info->mNormalPlaytimeUs = 0ll; info->mNPTMappingValid = true; } int64_t nptUs = ((double)rtpTime - (double)info->mRTPTime) / info->mTimeScale * 1000000ll + info->mNormalPlaytimeUs; accessUnit->meta()->setInt64("timeUs", nptUs); info->mLatestReceivedUnit = nptUs; // Drop the frames that are older than the frames in the queue. if (info->mLatestPausedUnit && (int64_t)info->mLatestPausedUnit > nptUs) { break; } source->queueAccessUnit(accessUnit); } onTrackDataAvailable(trackIndex); break; } case RtspConnectionHandler::kWhatEOS: { size_t trackIndex; CHECK(msg->findSize("trackIndex", &trackIndex)); CHECK_LT(trackIndex, mTracks.size()); int32_t finalResult; CHECK(msg->findInt32("finalResult", &finalResult)); CHECK_NE(finalResult, (status_t)OK); TrackInfo *info = &mTracks.editItemAt(trackIndex); sp<AnotherPacketSource> source = info->mSource; if (source != NULL) { source->signalEOS(finalResult); } break; } case RtspConnectionHandler::kWhatSeekDiscontinuity: { size_t trackIndex; CHECK(msg->findSize("trackIndex", &trackIndex)); CHECK_LT(trackIndex, mTracks.size()); TrackInfo *info = &mTracks.editItemAt(trackIndex); sp<AnotherPacketSource> source = info->mSource; if (source != NULL) { source->queueDiscontinuity(ATSParser::DISCONTINUITY_SEEK, NULL); } break; } case RtspConnectionHandler::kWhatNormalPlayTimeMapping: { size_t trackIndex; CHECK(msg->findSize("trackIndex", &trackIndex)); CHECK_LT(trackIndex, mTracks.size()); uint32_t rtpTime; CHECK(msg->findInt32("rtpTime", (int32_t *)&rtpTime)); int64_t nptUs; CHECK(msg->findInt64("nptUs", &nptUs)); TrackInfo *info = &mTracks.editItemAt(trackIndex); info->mRTPTime = rtpTime; info->mNormalPlaytimeUs = nptUs; info->mNPTMappingValid = true; break; } case RtspConnectionHandler::kWhatTryTCPInterleaving: { // By default, we will request to deliver RTP over UDP. If the play // request timed out and we didn't receive any RTP packet, we will // fail back to use RTP interleaved in the existing RTSP/TCP // connection. And in this case, we have to explicitly perform // another play event to request the server to start streaming // again. int64_t playTimeUs; if (!msg->findInt64("timeUs", &playTimeUs)) { playTimeUs = 0; } performPlay(playTimeUs); break; } default: TRESPASS(); } }
// static void ThreadLocalPlatform::AllocateSlot(SlotType& slot) { slot = TlsAlloc(); CHECK_NE(slot, TLS_OUT_OF_INDEXES); }
inline MassiveBody::Parameters::Parameters(Mass const& mass) : gravitational_parameter_(mass * GravitationalConstant), mass_(mass) { CHECK_NE(mass, Mass()) << "Massive body cannot have zero mass"; }
INITIALIZE_EASYLOGGINGPP int main(void) { el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog); // These checks should fail LOG(INFO) << "----- DONT WORRY ABOUT FOLLOWING CHECKS FAILING - THEY ARE EXPECTED"; CHECK(1 > 2) << "1 is not greater than 2"; CHECK_EQ(1, 2) << "1 is not equal to 2"; CHECK_NE(1, 1) << "Wow, I did not know 1 == 1"; CHECK_STREQ("abc", "def") << " :)"; CHECK_STRNE("abc", "abc") << " :("; CHECK_STRCASEEQ("abc", "ABCD") << " :p"; CHECK_STRCASENE("abc", "ABC") << " B)"; int* f = new int; CHECK_NOTNULL(f); delete f; f = nullptr; // These checks should pass LOG(WARNING) << "----- START WORRYING ABOUT CHECKS NOW"; CHECK(1 < 2) << " snap -- lib has bug!"; CHECK_EQ(1, 1) << " snap -- lib has bug!"; CHECK_NE(1, 2) << " snap -- lib has bug!"; CHECK_STREQ("abc", "abc") << " snap -- lib has bug!"; CHECK_STRNE("abc", "abe") << " snap -- lib has bug!"; CHECK_STRCASEEQ("abc", "ABC") << " snap -- lib has bug!"; CHECK_STRCASENE("abc", "ABE") << " snap -- lib has bug!"; LOG(INFO) << "----- HOPEFULLY NO CHECK FAILED SINCE YOU STARTED WORRYING!"; // DCHECKs DCHECK(1 > 2) << "1 is not greater than 2"; DCHECK_EQ(1, 2) << "1 is not equal to 2"; DCHECK_NE(1, 1) << "Wow, I did not know 1 == 1"; DCHECK_STREQ("abc", "def") << " :)"; DCHECK_STRNE("abc", "abc") << " :("; DCHECK_STRCASEEQ("abc", "ABCD") << " :p"; DCHECK_STRCASENE("abc", "ABC") << " B)"; // PCHECKs std::fstream fstr("a/file/that/does/not/exist", std::fstream::in); PCHECK(fstr.is_open()); DPCHECK(fstr.is_open()); int min = 1; int max = 5; CHECK_BOUNDS(1, min, max) << "Index out of bounds"; CHECK_BOUNDS(2, min, max) << "Index out of bounds"; CHECK_BOUNDS(3, min, max) << "Index out of bounds"; CHECK_BOUNDS(4, min, max) << "Index out of bounds"; CHECK_BOUNDS(5, min, max) << "Index out of bounds"; CHECK_BOUNDS(6, min, max) << "Index out of bounds"; DCHECK_BOUNDS(1, min, max) << "Index out of bounds"; DCHECK_BOUNDS(2, min, max) << "Index out of bounds"; DCHECK_BOUNDS(3, min, max) << "Index out of bounds"; DCHECK_BOUNDS(4, min, max) << "Index out of bounds"; DCHECK_BOUNDS(5, min, max) << "Index out of bounds"; DCHECK_BOUNDS(6, min, max) << "Index out of bounds"; return 0; }
void Query::Execute() { std::ostream& output = GetEnvironment().GetOutputStream(); if (m_isSingleQuery) { output << "Processing query \"" << m_query << "\"" << std::endl; auto instrumentation = QueryRunner::Run(m_query.c_str(), GetEnvironment().GetSimpleIndex(), GetEnvironment().GetCompilerMode(), GetEnvironment().GetCacheLineCountMode()); output << "Results:" << std::endl; CsvTsv::CsvTableFormatter formatter(output); QueryInstrumentation::Data::FormatHeader(formatter); instrumentation.Format(formatter); } else { CHECK_NE(*GetEnvironment().GetOutputDir().c_str(), '\0') << "Output directory not set. " << "Please use the 'cd' command to set an " << "output directory"; output << "Processing queries from log at \"" << m_query << "\"" << std::endl; std::string const & filename = m_query; auto fileSystem = Factories::CreateFileSystem(); // TODO: Use environment file system auto queries = ReadLines(*fileSystem, filename.c_str()); const size_t c_threadCount = GetEnvironment().GetThreadCount(); const size_t c_iterations = 1; auto statistics = QueryRunner::Run(GetEnvironment().GetSimpleIndex(), GetEnvironment().GetOutputDir().c_str(), c_threadCount, queries, c_iterations, GetEnvironment().GetCompilerMode(), GetEnvironment().GetCacheLineCountMode()); output << "Results:" << std::endl; statistics.Print(output); // TODO: unify this with the fileManager that's passed into // QueryRunner::Run. auto outFileManager = Factories::CreateFileManager(GetEnvironment().GetOutputDir().c_str(), GetEnvironment().GetOutputDir().c_str(), GetEnvironment().GetOutputDir().c_str(), GetEnvironment().GetSimpleIndex().GetFileSystem()); auto outSummary = outFileManager->QuerySummaryStatistics().OpenForWrite(); statistics.Print(*outSummary); } }
std::vector<llvm::Value*> Executor::codegen(const Analyzer::Expr* expr, const bool fetch_columns, const CompilationOptions& co) { if (!expr) { return {posArg(expr)}; } auto iter_expr = dynamic_cast<const Analyzer::IterExpr*>(expr); if (iter_expr) { #ifdef ENABLE_MULTIFRAG_JOIN if (iter_expr->get_rte_idx() > 0) { const auto offset = cgen_state_->frag_offsets_[iter_expr->get_rte_idx()]; if (offset) { return {cgen_state_->ir_builder_.CreateAdd(posArg(iter_expr), offset)}; } else { return {posArg(iter_expr)}; } } #endif return {posArg(iter_expr)}; } auto bin_oper = dynamic_cast<const Analyzer::BinOper*>(expr); if (bin_oper) { return {codegen(bin_oper, co)}; } auto u_oper = dynamic_cast<const Analyzer::UOper*>(expr); if (u_oper) { return {codegen(u_oper, co)}; } auto col_var = dynamic_cast<const Analyzer::ColumnVar*>(expr); if (col_var) { return codegen(col_var, fetch_columns, co); } auto constant = dynamic_cast<const Analyzer::Constant*>(expr); if (constant) { if (constant->get_is_null()) { const auto& ti = constant->get_type_info(); return {ti.is_fp() ? static_cast<llvm::Value*>(inlineFpNull(ti)) : static_cast<llvm::Value*>(inlineIntNull(ti))}; } // The dictionary encoding case should be handled by the parent expression // (cast, for now), here is too late to know the dictionary id CHECK_NE(kENCODING_DICT, constant->get_type_info().get_compression()); return {codegen(constant, constant->get_type_info().get_compression(), 0, co)}; } auto case_expr = dynamic_cast<const Analyzer::CaseExpr*>(expr); if (case_expr) { return {codegen(case_expr, co)}; } auto extract_expr = dynamic_cast<const Analyzer::ExtractExpr*>(expr); if (extract_expr) { return {codegen(extract_expr, co)}; } auto dateadd_expr = dynamic_cast<const Analyzer::DateaddExpr*>(expr); if (dateadd_expr) { return {codegen(dateadd_expr, co)}; } auto datediff_expr = dynamic_cast<const Analyzer::DatediffExpr*>(expr); if (datediff_expr) { return {codegen(datediff_expr, co)}; } auto datetrunc_expr = dynamic_cast<const Analyzer::DatetruncExpr*>(expr); if (datetrunc_expr) { return {codegen(datetrunc_expr, co)}; } auto charlength_expr = dynamic_cast<const Analyzer::CharLengthExpr*>(expr); if (charlength_expr) { return {codegen(charlength_expr, co)}; } auto like_expr = dynamic_cast<const Analyzer::LikeExpr*>(expr); if (like_expr) { return {codegen(like_expr, co)}; } auto regexp_expr = dynamic_cast<const Analyzer::RegexpExpr*>(expr); if (regexp_expr) { return {codegen(regexp_expr, co)}; } auto likelihood_expr = dynamic_cast<const Analyzer::LikelihoodExpr*>(expr); if (likelihood_expr) { return {codegen(likelihood_expr->get_arg(), fetch_columns, co)}; } auto in_expr = dynamic_cast<const Analyzer::InValues*>(expr); if (in_expr) { return {codegen(in_expr, co)}; } auto in_integer_set_expr = dynamic_cast<const Analyzer::InIntegerSet*>(expr); if (in_integer_set_expr) { return {codegen(in_integer_set_expr, co)}; } auto function_oper_with_custom_type_handling_expr = dynamic_cast<const Analyzer::FunctionOperWithCustomTypeHandling*>(expr); if (function_oper_with_custom_type_handling_expr) { return {codegenFunctionOperWithCustomTypeHandling(function_oper_with_custom_type_handling_expr, co)}; } auto function_oper_expr = dynamic_cast<const Analyzer::FunctionOper*>(expr); if (function_oper_expr) { return {codegenFunctionOper(function_oper_expr, co)}; } abort(); }
void NuPlayer::RTSPSource::onMessageReceived(const sp<AMessage> &msg) { if (msg->what() == kWhatDisconnect) { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); mDisconnectReplyID = replyID; finishDisconnectIfPossible(); return; } else if (msg->what() == kWhatPerformSeek) { int32_t generation; CHECK(msg->findInt32("generation", &generation)); CHECK(msg->senderAwaitsResponse(&mSeekReplyID)); if (generation != mSeekGeneration) { // obsolete. finishSeek(OK); return; } int64_t seekTimeUs; CHECK(msg->findInt64("timeUs", &seekTimeUs)); performSeek(seekTimeUs); return; } else if (msg->what() == kWhatPollBuffering) { onPollBuffering(); return; } else if (msg->what() == kWhatSignalEOS) { onSignalEOS(msg); return; } CHECK_EQ(msg->what(), (int)kWhatNotify); int32_t what; CHECK(msg->findInt32("what", &what)); switch (what) { case MyHandler::kWhatConnected: { onConnected(); notifyVideoSizeChanged(); uint32_t flags = 0; if (mHandler->isSeekable()) { flags = FLAG_CAN_PAUSE | FLAG_CAN_SEEK | FLAG_CAN_SEEK_BACKWARD | FLAG_CAN_SEEK_FORWARD; } notifyFlagsChanged(flags); schedulePollBuffering(); break; } case MyHandler::kWhatDisconnected: { onDisconnected(msg); break; } case MyHandler::kWhatSeekDone: { mState = CONNECTED; // Unblock seekTo here in case we attempted to seek in a live stream finishSeek(OK); break; } case MyHandler::kWhatSeekPaused: { sp<AnotherPacketSource> source = getSource(true /* audio */); if (source != NULL) { source->queueDiscontinuity(ATSParser::DISCONTINUITY_NONE, /* extra */ NULL, /* discard */ true); } source = getSource(false /* video */); if (source != NULL) { source->queueDiscontinuity(ATSParser::DISCONTINUITY_NONE, /* extra */ NULL, /* discard */ true); }; status_t err = OK; msg->findInt32("err", &err); if (err == OK) { int64_t timeUs; CHECK(msg->findInt64("time", &timeUs)); mHandler->continueSeekAfterPause(timeUs); } else { finishSeek(err); } break; } case MyHandler::kWhatAccessUnit: { size_t trackIndex; CHECK(msg->findSize("trackIndex", &trackIndex)); if (mTSParser == NULL) { CHECK_LT(trackIndex, mTracks.size()); } else { CHECK_EQ(trackIndex, 0u); } sp<ABuffer> accessUnit; CHECK(msg->findBuffer("accessUnit", &accessUnit)); int32_t damaged; if (accessUnit->meta()->findInt32("damaged", &damaged) && damaged) { ALOGI("dropping damaged access unit."); break; } if (mTSParser != NULL) { size_t offset = 0; status_t err = OK; while (offset + 188 <= accessUnit->size()) { err = mTSParser->feedTSPacket( accessUnit->data() + offset, 188); if (err != OK) { break; } offset += 188; } if (offset < accessUnit->size()) { err = ERROR_MALFORMED; } if (err != OK) { signalSourceEOS(err); } postSourceEOSIfNecessary(); break; } TrackInfo *info = &mTracks.editItemAt(trackIndex); sp<AnotherPacketSource> source = info->mSource; if (source != NULL) { uint32_t rtpTime; CHECK(accessUnit->meta()->findInt32("rtp-time", (int32_t *)&rtpTime)); if (!info->mNPTMappingValid) { // This is a live stream, we didn't receive any normal // playtime mapping. We won't map to npt time. source->queueAccessUnit(accessUnit); break; } int64_t nptUs = ((double)rtpTime - (double)info->mRTPTime) / info->mTimeScale * 1000000ll + info->mNormalPlaytimeUs; accessUnit->meta()->setInt64("timeUs", nptUs); source->queueAccessUnit(accessUnit); } postSourceEOSIfNecessary(); break; } case MyHandler::kWhatEOS: { int32_t finalResult; CHECK(msg->findInt32("finalResult", &finalResult)); CHECK_NE(finalResult, (status_t)OK); if (mTSParser != NULL) { signalSourceEOS(finalResult); } size_t trackIndex; CHECK(msg->findSize("trackIndex", &trackIndex)); CHECK_LT(trackIndex, mTracks.size()); TrackInfo *info = &mTracks.editItemAt(trackIndex); sp<AnotherPacketSource> source = info->mSource; if (source != NULL) { source->signalEOS(finalResult); } break; } case MyHandler::kWhatSeekDiscontinuity: { size_t trackIndex; CHECK(msg->findSize("trackIndex", &trackIndex)); CHECK_LT(trackIndex, mTracks.size()); TrackInfo *info = &mTracks.editItemAt(trackIndex); sp<AnotherPacketSource> source = info->mSource; if (source != NULL) { source->queueDiscontinuity( ATSParser::DISCONTINUITY_TIME, NULL, true /* discard */); } break; } case MyHandler::kWhatNormalPlayTimeMapping: { size_t trackIndex; CHECK(msg->findSize("trackIndex", &trackIndex)); CHECK_LT(trackIndex, mTracks.size()); uint32_t rtpTime; CHECK(msg->findInt32("rtpTime", (int32_t *)&rtpTime)); int64_t nptUs; CHECK(msg->findInt64("nptUs", &nptUs)); TrackInfo *info = &mTracks.editItemAt(trackIndex); info->mRTPTime = rtpTime; info->mNormalPlaytimeUs = nptUs; info->mNPTMappingValid = true; break; } case SDPLoader::kWhatSDPLoaded: { onSDPLoaded(msg); break; } default: TRESPASS(); } }
} else { // no, so return nack. DVLOG(7) << "Failed with no more space available"; return -1; // did not succeed } } ); // insert succeeded, so move to next edge if( retval >= 0 ) { local_max++; } // no more space available on target, so move to next core if( local_max < read_count && retval != 0 ) { likely_consumer = (likely_consumer + 1) % Grappa::cores(); CHECK_NE( likely_consumer, Grappa::mycore() ) << "No more space to place edge on cluster?"; } } // wait for everybody else to fill in our remaining spaces Grappa::barrier(); // discard temporary read buffer read_edges.clear(); } ); // done! return tg; } /// Matrix Market format loader
// Sets the landmark as a potential match for this observation. The observation // still has not been incorporated into the landmark. void Observation::SetMatchedLandmark(LandmarkIndex landmark_index) { CHECK_NE(kInvalidLandmark, landmark_index); landmark_index_ = landmark_index; is_matched_ = true; }
void ReshapeOp::Forward() { const auto *bottom = bottoms<float>(0); auto *top = mutable_tops<float>(0); CHECK_NE(bottom, top); int inferred_axis = -1, constant_count = 1; VecInt copy_axes; for (int d = 0; d < shape_.size(); ++d) { int top_dim = shape_[d]; if (top_dim == 0) { copy_axes.push_back(d); } else if (top_dim == -1) { CHECK_EQ(inferred_axis, -1); inferred_axis = d; } else { constant_count *= top_dim; } } int start_axis = (axis_ >= 0) ? axis_ : (bottom->num_axes() + axis_ + 1); CHECK_GE(start_axis, 0); CHECK_LE(start_axis, bottom->num_axes()); int end_axis = (num_axes_ == -1) ? bottom->num_axes() : (start_axis + num_axes_); CHECK_LE(end_axis, bottom->num_axes()); int num_axes_replaced = end_axis - start_axis; int num_axes_retained = bottom->num_axes() - num_axes_replaced; VecInt top_shape(num_axes_retained + shape_.size()); int top_shape_index = 0; for (int d = 0; d < start_axis; ++d) { top_shape[top_shape_index++] = bottom->shape(d); } for (auto dim : shape_) { top_shape[top_shape_index++] = dim; } for (int d = end_axis; d < bottom->num_axes(); ++d) { top_shape[top_shape_index++] = bottom->shape(d); } CHECK_EQ(top_shape_index, top_shape.size()); for (auto d : copy_axes) { CHECK_GT(bottom->num_axes(), start_axis + d); top_shape[start_axis + d] = bottom->shape(start_axis + d); } if (inferred_axis >= 0) { int explicit_count = constant_count; explicit_count *= bottom->count(0, start_axis); explicit_count *= bottom->count(end_axis); for (auto d : copy_axes) { explicit_count *= top_shape[start_axis + d]; } CHECK_EQ(0, bottom->count() % explicit_count); top_shape[start_axis + inferred_axis] = bottom->count() / explicit_count; } top->clear(); top->set_shape(top_shape); CHECK_EQ(top->count(), bottom->count()); top->share_data(*bottom); }
int check_ne_example(int x) { CHECK_NE(x, 5); return x; }
Subprocess::~Subprocess() { CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING) << "Subprocess destroyed without reaping child"; closeAll(); }
void HighResolutionTimer::restart() { int status = clock_gettime(CLOCK_MONOTONIC, &start_time_); CHECK_NE(-1, status) << "Couldn't initialize start_time_"; }