void TestWordBddaDiscoverStrategy::TestDiscoverFootNotes() { MockVisitor visitor; WordSchemaSoftPolicy policy; policy.EnableFootNotes(); WordSchemaSoftDiscoverStrategy strategy(visitor, policy, TEST_FILE_PATH _T("TestDiscoverFootnotes\\Footnotes.doc")); strategy.Execute(); assertEquals(_T("<TestFootnoteTestEndnote>"), visitor.GetFootNotes()); }
/* * Find a valid disklabel. */ static int search_label(struct of_dev *devp, u_long off, u_char *buf, struct disklabel *lp, u_long off0) { size_t nread; struct mbr_partition *p; int i; u_long poff; static int recursion; if (strategy(devp, F_READ, off, DEV_BSIZE, buf, &nread) || nread != DEV_BSIZE) return ERDLAB; if (*(u_int16_t *)&buf[MBR_MAGIC_OFFSET] != sa_htole16(MBR_MAGIC)) return ERDLAB; if (recursion++ <= 1) off0 += off; for (p = (struct mbr_partition *)(buf + MBR_PART_OFFSET), i = 4; --i >= 0; p++) { if (p->mbrp_type == MBR_PTYPE_NETBSD #ifdef COMPAT_386BSD_MBRPART || (p->mbrp_type == MBR_PTYPE_386BSD && (printf("WARNING: old BSD partition ID!\n"), 1) /* XXX XXX - libsa printf() is void */ ) #endif ) { poff = get_long(&p->mbrp_start) + off0; if (strategy(devp, F_READ, poff + 1, DEV_BSIZE, buf, &nread) == 0 && nread == DEV_BSIZE) { if (!getdisklabel(buf, lp)) { recursion--; return 0; } } if (strategy(devp, F_READ, off, DEV_BSIZE, buf, &nread) || nread != DEV_BSIZE) { recursion--; return ERDLAB; } } else if (p->mbrp_type == MBR_PTYPE_EXT) { poff = get_long(&p->mbrp_start); if (!search_label(devp, poff, buf, lp, off0)) { recursion--; return 0; } if (strategy(devp, F_READ, off, DEV_BSIZE, buf, &nread) || nread != DEV_BSIZE) { recursion--; return ERDLAB; } } } recursion--; return ERDLAB; }
int discovery_service_start(discovery_service *svc, discovery_strategy *strategy) { JNXCHECK(svc); // *** TODO Set up brodcast or multicast *** // It should just be a simple matter of passing a flag to the service // or changing the function signature and calling either // set_up_sockets_for_broadcast or set_up_sockets_for_multicast. // set_up_sockets_for_broadcast(svc); svc->sock_send = jnx_socket_udp_create(svc->family); svc->udp_listener = jnx_socket_udp_listener_broadcast_create( port_to_string(svc), svc->family); svc->isrunning = 1; if (0 != listen_for_discovery_packets(svc)) { JNXLOG(0, "[DISCOVERY] Couldn't start the discovery listener.\n"); return ERR_DISCOVERY_START; } initiate_discovery(svc); if (strategy == NULL) { svc->peers->is_active_peer = is_active_peer_ask_once; send_discovery_request(svc); } else { svc->peers->is_active_peer = is_active_peer_periodic_update; strategy(svc); } return 0; }
LiveNodeModelPtr RowStoreModel::subModel ( QModelIndex const &topleft_inclusive, QModelIndex const &bottomright_exclusive , QList<int> const &columns_mapping) { QModelIndex tl(topleft_inclusive), br(bottomright_exclusive); if (columns_mapping.size()) { tl = tl.sibling(tl.row(), 0); br = br.sibling(br.row(), 0); } if(tl.row() > br.row()) warning(this) << "topleft row greater than bottomright row:" << tl; else if(tl.column() > br.column()) warning(this) << "topleft column greater than bottomright column:" << tl; else if(tl.column() < 0) warning(this) << "topleft.column(" << tl.column() << ") < 0"; else if(br.column() > columns_.visibleColumnCount()) warning(this) << "bottomright.column(" << br.column() << ") > column count(" << columns_.visibleColumnCount() << ")"; else { if(ContentModule *ct = contentModule().data()) return ct->subModel(tl, br, columns_mapping); // TODO: frak this, figure out const correctness policy return const_cast<RowStoreModel *>(this)->subModelImpl ( strategy(topleft_inclusive), tl, br, columns_mapping); } return LiveNodeModelPtr(); }
void test_with_ax(std::string const& wkt, std::string const& expected, T const& adt, T const& xdt) { typedef typename bg::point_type<Geometry>::type point_type; typedef bg::strategy::distance::detail::projected_point_ax<> ax_type; typedef typename bg::strategy::distance::services::return_type < bg::strategy::distance::detail::projected_point_ax<>, point_type, point_type >::type return_type; typedef bg::strategy::distance::detail::projected_point_ax_less < return_type > comparator_type; typedef bg::strategy::simplify::detail::douglas_peucker < point_type, bg::strategy::distance::detail::projected_point_ax<>, comparator_type > dp_ax; return_type max_distance(adt, xdt); comparator_type comparator(max_distance); dp_ax strategy(comparator); test_geometry<Geometry>(wkt, expected, max_distance, strategy); }
QJsonDocument Api::get(const QString& path, CancellationToken cancellationToken) const { qInfo() << "Executing GET " << path; ApiConnectionSettings connectionSettings = defaultConnectionSettings(); ApiConnectionStrategy strategy(connectionSettings, Config::minConnectionTimeoutMsec, Config::maxConnectionTimeoutMsec); QBuffer buffer; buffer.open(QIODevice::WriteOnly); if (!strategy.execute(m_dataSource, path, buffer, cancellationToken)) { throw ApiConnectionError("Failed to connect to the api."); } auto data = buffer.data(); QJsonParseError parseError; auto doc = QJsonDocument::fromJson(data, &parseError); if (parseError.error != QJsonParseError::NoError) { throw InvalidFormatException(parseError.errorString()); } return doc; }
EnumerationConstraint* ModelEnumerator::doInit(SharedContext& ctx, SharedMinimizeData* opt, int numModels) { initProjection(ctx); uint32 st = strategy(); if (detectStrategy() || (ctx.concurrency() > 1 && !ModelEnumerator::supportsParallel())) { st = 0; } bool optOne = opt && opt->mode() == MinimizeMode_t::optimize; bool trivial = optOne || std::abs(numModels) == 1; if (optOne && projectionEnabled()) { for (const WeightLiteral* it = minimizer()->lits; !isSentinel(it->first) && trivial; ++it) { trivial = ctx.varInfo(it->first.var()).project(); } if (!trivial) { ctx.report(warning(Event::subsystem_prepare, "Projection: Optimization may depend on enumeration order.")); } } if (st == strategy_auto) { st = trivial || (projectionEnabled() && ctx.concurrency() > 1) ? strategy_record : strategy_backtrack; } if (trivial) { st |= trivial_flag; } options_ &= ~uint32(strategy_opts_mask); options_ |= st; const LitVec* dom = (projectOpts() & project_dom_lits) != 0 ? (ctx.heuristic.domRec = &domRec_) : 0; EnumerationConstraint* c = st == strategy_backtrack ? static_cast<ConPtr>(new BacktrackFinder(projectOpts())) : static_cast<ConPtr>(new RecordFinder(dom)); if (projectionEnabled()) { setIgnoreSymmetric(true); } return c; }
QString Api::tryGetCountryCode(CancellationToken cancellationToken) const { qInfo() << "Getting the country code"; try { ApiConnectionSettings connectionSettings(Config::geolocationApiUrl, QStringList()); ApiConnectionStrategy strategy(connectionSettings, Config::geolocationTimeout, Config::geolocationTimeout); QString path = "v1/country"; QBuffer buffer; if (!strategy.execute(m_dataSource, path, buffer, cancellationToken)) { throw ApiConnectionError("Failed to connect to the api."); } auto document = QJsonDocument::fromBinaryData(buffer.data()); return document.object()["country"].toString(); } catch (ApiConnectionError&) { return QString(); } }
int main(int argc, char* argv[]) { try { const std::string cfgFileName = "../config/tt.cfg"; const std::string symbol = "xx"; const std::string maturityMonthYear = "xx"; const std::string account = "uchidts10"; // create our strategy and connect it to our Application FIX interface MyStrategy strategy(symbol, maturityMonthYear, account); Application Application(strategy); Application.Init(cfgFileName); // quickfix is now running in the background, so we just wait here until the user hits ENTER to shut us down std::cout << std::endl << "Hit [ENTER] to quit..." << std::endl; std::string input; std::getline(std::cin, input); } catch(const std::exception & e) { std::cerr << std::endl << e.what() << std::endl; return 1; } return 0; }
static inline bool apply(S const& seg, P const& selection_point, T const& search_radius) { assert_dimension_equal<S, P>(); if (! outside_loop < S, P, T, 0, dimension<P>::type::value >::apply(seg, selection_point, search_radius)) { // Not outside, calculate dot product/square distance to segment. // Call corresponding strategy typedef typename strategy_distance_segment < typename cs_tag<P>::type, typename cs_tag<S>::type, P, S >::type strategy_type; typedef typename strategy_type::return_type return_type; strategy_type strategy; return_type result = strategy(selection_point, seg); return result < search_radius; } return false; }
int load_disklabel(struct of_dev *ofdev, struct disklabel *label) { char buf[DEV_BSIZE]; size_t read; int error = 0; char *errmsg = NULL; /* First try to find a disklabel without MBR partitions */ DNPRINTF(BOOT_D_OFDEV, "load_disklabel: trying to read disklabel\n"); if (strategy(ofdev, F_READ, LABELSECTOR, DEV_BSIZE, buf, &read) != 0 || read != DEV_BSIZE || (errmsg = getdisklabel(buf, label))) { #ifdef BOOT_DEBUG if (errmsg) DNPRINTF(BOOT_D_OFDEV, "load_disklabel: getdisklabel says %s\n", errmsg); #endif /* Else try MBR partitions */ errmsg = search_label(ofdev, LABELSECTOR, buf, label, 0); if (errmsg) { printf("load_disklabel: search_label says %s\n", errmsg); error = ERDLAB; } } return (error); }
EnumerationConstraint* ModelEnumerator::doInit(SharedContext& ctx, MinimizeConstraint* min, int numModels) { delete queue_; queue_ = 0; initProjection(ctx); uint32 st = strategy(); if (detectStrategy() || (ctx.concurrency() > 1 && !ModelEnumerator::supportsParallel())) { st = 0; } bool optOne = minimizer() && minimizer()->mode() == MinimizeMode_t::optimize; bool trivial = optOne || std::abs(numModels) == 1; if (optOne && project_) { const SharedMinimizeData* min = minimizer(); for (const WeightLiteral* it = min->lits; !isSentinel(it->first) && trivial; ++it) { trivial = ctx.varInfo(it->first.var()).project(); } if (!trivial) { ctx.report(warning(Event::subsystem_prepare, "Projection: Optimization may depend on enumeration order.")); } } if (st == strategy_auto) { st = trivial || (project_ && ctx.concurrency() > 1) ? strategy_record : strategy_backtrack; } if (trivial) { st |= trivial_flag; } if (ctx.concurrency() > 1 && !trivial && st != strategy_backtrack) { queue_ = new SolutionQueue(ctx.concurrency()); queue_->reserve(ctx.concurrency() + 1); } options_ &= ~uint32(strategy_opts_mask); options_ |= st; Solver& s = *ctx.master(); EnumerationConstraint* c = st == strategy_backtrack ? static_cast<ConPtr>(new BacktrackFinder(s, min, project_, projectOpts())) : static_cast<ConPtr>(new RecordFinder(s, min, project_, queue_)); if (projectionEnabled()) { setIgnoreSymmetric(true); } return c; }
int32_t elect_write_ds(const LayoutManager& meta, const int32_t elect_count, VUINT64& elect_ds_list) { WriteStrategy strategy(meta.get_elect_seq(), *meta.get_ns_global_info()); int64_t elect_seq = meta.get_elect_seq(); int32_t ret = elect_ds(strategy, ExcludeGroupElectOperation(), meta, elect_count, elect_seq, elect_ds_list); meta.set_elect_seq(elect_seq); return ret; }
static inline bool checkOneSelector(const CSSSelector& selector, const WillBeHeapVector<RawPtrWillBeMember<Node>, 32>& siblings, int nth) { Element* element = toElement(siblings[nth]); SelectorChecker selectorChecker(element->document(), SelectorChecker::CollectingCSSRules); SelectorChecker::SelectorCheckingContext context(selector, element, SelectorChecker::VisitedMatchEnabled); ShadowDOMSiblingTraversalStrategy strategy(siblings, nth); return selectorChecker.match(context, strategy) == SelectorChecker::SelectorMatches; }
static jlong android_view_VelocityTracker_nativeInitialize(JNIEnv* env, jclass clazz, jstring strategyStr) { if (strategyStr) { ScopedUtfChars strategy(env, strategyStr); return reinterpret_cast<jlong>(new VelocityTrackerState(strategy.c_str())); } return reinterpret_cast<jlong>(new VelocityTrackerState(NULL)); }
void TestWordBddaDiscoverStrategy::TestCacheRevisionAuthors() { MockVisitor visitor; WordSchemaSoftPolicy policy; policy.EnableFootNotes(); WordSchemaSoftDiscoverStrategy strategy(visitor, policy, TEST_FILE_PATH _T("TestDiscoverFootnotes\\Footnotes.doc")); assertMessage(0 < strategy.m_RevisionAuthors.size(), _T("We expected the ctor to load the revision authors table")); }
int main (int argc, char const* argv[]) { std::function<void(const char*)> log = [](const char* msg){ std::cout << msg << std::endl; }; if( argc < 3 ) { log("Too few arguments!!!"); exit(1); } const int MATCH_TOTAL_NUMBER = atoi(argv[1]); // choose enemy strategy std::function<Action(int)> strategy = STRATEGIES[atoi(argv[2])]; try { // define qlplayer QLAgent<Action,Action> player = QLAgent<Action,Action>( [](Action act){ std::vector<Action> vact = {ROCK,PAPER,SCISSOR}; return vact; } ); player.setQLParameters(0.1,0.2,1.); player.setCurrentState(ROCK); for(int counter = 0; counter != MATCH_TOTAL_NUMBER; counter++) { // choose actions Action playerChoice = player.chooseAction(); Action enemyChoice = strategy(counter); // evaluate the match float reward; int matchResult = ((int)(playerChoice) - (int)(enemyChoice)) %3; switch(matchResult) { case 1: reward = LOSE_REWARD; std::cout << "L"; break; case 0: reward = DRAW_REWARD; std::cout << "D"; break; case -1: reward = WIN_REWARD; std::cout << "W"; break; default: reward = 0; break; } player.update(enemyChoice,reward); } } catch (std::exception e) { log(e.what()); } log(""); log("Game has ended!"); return 0; }
int32_t elect_replicate_dest_ds(const LayoutManager& meta, const ReplicateSourceStrategy::counter_type& dest_counter, const int32_t elect_count, VUINT64& elect_ds_list) { ReplicateDestStrategy strategy(meta.get_elect_seq(), *meta.get_ns_global_info(), dest_counter); int64_t elect_seq = meta.get_elect_seq(); int32_t ret = elect_ds(strategy, ExcludeGroupElectOperation(), meta, elect_count, elect_seq, elect_ds_list); meta.set_elect_seq(elect_seq); return ret; }
void TestWordBddaDiscoverStrategy::TestDiscoverWhiteTextInsideTrackchange() { MockSmallTextVisitor visitor; WordSchemaSoftPolicy policy; policy.EnableWhiteText(); WordSchemaSoftDiscoverStrategy strategy(visitor, policy, TEST_FILE_PATH _T("TestDiscoverWhiteText\\WhiteTextInTrackChange.doc")); strategy.Execute(); assertEquals(1, visitor.GetNumberOfTimesOnWhiteTextWasCalled()); }
Alg7::Alg7(computeInfo *computeArray, patchInfo *patchArray, processorInfo *processorArray, int nComps, int nPatches, int nPes) : Rebalancer(computeArray, patchArray, processorArray, nComps, nPatches, nPes) { strategyName = "Alg7"; strategy(); }
void TestWordBddaDiscoverStrategy::TestDiscoverSmallTextWithStyles() { MockSmallTextVisitor visitor; WordSchemaSoftPolicy policy; policy.EnableSmallText(); WordSchemaSoftDiscoverStrategy strategy(visitor, policy, TEST_FILE_PATH _T("TestDiscoverSmallText\\SmallTextWithStyles.doc")); strategy.Execute(); assertEquals(1, visitor.GetNumberOfTimesOnSmallTextWasCalled()); }
void multiplex_strategy(struct bio *bio) { struct device *dev = bio->bio_dev; devop_strategy_t strategy = *((devop_strategy_t *)dev->private_data); uint64_t len = bio->bio_bcount; bio->bio_offset += bio->bio_dev->offset; uint64_t offset = bio->bio_offset; void *buf = bio->bio_data; assert(strategy != NULL); if (len <= dev->max_io_size) { strategy(bio); return; } // It is better to initialize the refcounter beforehand, specially because we can // trivially determine what is the number going to be. Otherwise, we can have a // situation in which we bump the refcount to 1, get scheduled out, the bio is // finished, and when it drops its refcount to 0, we consider the main bio finished. refcount_init(&bio->bio_refcnt, (len / dev->max_io_size) + !!(len % dev->max_io_size)); while (len > 0) { uint64_t req_size = MIN(len, dev->max_io_size); struct bio *b = alloc_bio(); b->bio_bcount = req_size; b->bio_data = buf; b->bio_offset = offset; b->bio_cmd = bio->bio_cmd; b->bio_dev = bio->bio_dev; b->bio_caller1 = bio; b->bio_done = multiplex_bio_done; strategy(b); buf += req_size; offset += req_size; len -= req_size; } }
static void test(double lon1, double lat1, double lon2, double lat2, double radius, return_type expected, double tolerance) { haversine_type strategy(radius); Point p1, p2; bg::assign_values(p1, lon1, LatitudePolicy::apply(lat1)); bg::assign_values(p2, lon2, LatitudePolicy::apply(lat2)); return_type d = strategy.apply(p1, p2); BOOST_CHECK_CLOSE(d, expected, tolerance); }
static void test(double lon1, double lat1, double lon2, double lat2, double radius, double expected, double tolerance) { haversine_type strategy(radius); Point p1, p2; boost::geometry::assign(p1, lon1, lat1); boost::geometry::assign(p2, lon2, lat2); typename haversine_type::return_type d1 = strategy.apply(p1, p2); BOOST_CHECK_CLOSE((double) d1, expected, tolerance); }
TorusLB::TorusLB(computeInfo *cs, patchInfo *pas, processorInfo *pes, int ncs, int npas, int npes) : RefineTorusLB(cs, pas, pes, ncs, npas, npes, 0) { strategyName = "TorusLB"; strategy(); //if ( computeMax() <= origMaxLoad ) { // binaryRefine(); // printLoads(); //} // CREATE THE SPANNING TREE IN THE LOAD BALANCER //if(proxySendSpanning || proxyRecvSpanning) // createSpanningTree(); }
void TestExcelMetadataOccurenceDiscoverStrategy::TestDiscoverTrackChangesForDocWithTrackChanges() { MockVisitor visitor; ExcelMetadataOccurencePolicy policy; policy.EnableTrackChanges(); ExcelMetadataOccurenceDiscoveryStrategy strategy(visitor, policy, TEST_FILE_PATH _T("DiscoverMetaData.xls")); strategy.Execute(); assertMessage(visitor.IsEventRaised(_T("MockVisitor::OnTrackChangesBegin")), _T("The event [MockVisitor::OnTrackChangesBegin] was not raised.")); assertMessage(visitor.IsEventRaised(_T("MockVisitor::OnTrackChangesEnd")), _T("The event [MockVisitor::OnTrackChangesEnd] was not raised.")); assertMessage(visitor.IsEventRaised(_T("MockVisitor::OnTrackChange")), _T("We expected Track Changes to be found")); }
void TestExcelMetadataOccurenceDiscoverStrategy::TestDiscoverTrackChangesForDocWithoutComments() { MockVisitor visitor; ExcelMetadataOccurencePolicy policy; policy.EnableComments(); ExcelMetadataOccurenceDiscoveryStrategy strategy(visitor, policy, TEST_FILE_PATH _T("NoMetadata.xls")); strategy.Execute(); assertMessage(visitor.IsEventRaised(_T("MockVisitor::OnCommentsBegin")), _T("The event [MockVisitor::OnCommentsBegin] was not raised.")); assertMessage(visitor.IsEventRaised(_T("MockVisitor::OnCommentsEnd")), _T("The event [MockVisitor::OnCommentsEnd] was not raised.")); assertMessage(false == visitor.IsEventRaised(_T("MockVisitor::OnComment")), _T("We did not expected Comments to be found")); }
int RowStoreModel::rowCount(const QModelIndex &index) const { if(index.isValid()) return 0; // if running, but not streaming nor windowed, do blocking refresh. if(((strategy(index) ^ RDFStrategy::Running) & (RDFStrategy::Running | RDFStrategy::Streaming | RDFStrategy::Windowed)) == 0) const_cast<RowStoreModel *>(this)->refreshModel (LiveNodeModel::Block | LiveNodeModel::CoverDerivedProperties); return row_store.size(); }
void TestWordBddaDiscoverStrategy::TestDiscoverSmallWhiteOrHiddenText_AllPresent() { MockSmallTextVisitor visitor; WordSchemaSoftPolicy policy; policy.EnableSmallText(); policy.EnableWhiteText(); policy.EnableHiddenText(); WordSchemaSoftDiscoverStrategy strategy(visitor, policy, TEST_FILE_PATH _T("TestDiscoverSmallWhiteOrHiddenText\\all.doc")); strategy.Execute(); assertEquals(1, visitor.GetNumberOfTimesOnSmallTextWasCalled()); assertEquals(1, visitor.GetNumberOfTimesOnWhiteTextWasCalled()); assertEquals(1, visitor.GetNumberOfTimesOnHiddenTextWasCalled()); }
// main program int main_prog() { // Initialize game initializeGame(); // Initialize interrupts initializeInterrupts(); // Send initial co-ordinates for all players sendInitialPositionsPackets(); u8 i; for(i = 0; ; i++) { // Read data numberOfPackets = 0; readQueueData(); //See if any player is inside foul box playerInDefendingFoulBox = numberOfPlayersInFoulBox(teamA, DEFENDING_FOUL); playerInAttackingFoulBox = numberOfPlayersInFoulBox(teamA, ATTACKING_FOUL); // Develop strategy for player movement by considering position of ball/players strategy(); // offensive/defensive strategy switch u8 switches = XGpio_DiscreteRead(&GpioInputSwitch, 1); // if 4th bit of switch == 1, offensive if((switches >> 3) == 1) { //xil_printf("Inside offensive\n"); // move all players to offensive side u8 j; for(j = 0; j < 5; j++) { if(fieldSide == FIELD_LEFT && teamA.player[j].position.x > 310) { position pos = {170, 200}; movePlayer(&teamA.player[j], &pos); } else if(fieldSide == FIELD_RIGHT && teamA.player[j].position.x < 310) { position pos = {470, 200}; movePlayer(&teamA.player[j], &pos); } } } else { // offensive // do nothing } // Send player movement updates sendUpdatePackets(); }