/** \throw NonexistentParameterAccessed if \p name is not a key. */ ParameterMap::iterator ParameterMap::findOrThrow(const std::string& name) { map_type::iterator it = find(name); if (it != end()) return it; throw ParameterMap::NonexistentParameterAccessed(name, *this); }
std::pair<I, O> operator()(Rng &rng, O out, P proj = P{}) const { return (*this)(begin(rng), end(rng), std::move(out), std::move(proj)); }
SimpleAudioEngineOpenSL::~SimpleAudioEngineOpenSL() { end(); }
/* Fl_Group( X, Y, W, H, L) */ Chain::Chain ( ) : Fl_Group( 0, 0, 100, 100, "") { /* not really deleting here, but reusing this variable */ _deleting = true; int X = 0; int Y = 0; int W = 100; int H = 100; /* _outs = 1; */ /* _ins = 1; */ _configure_outputs_callback = NULL; _strip = NULL; _name = NULL; labelsize( 10 ); align( FL_ALIGN_TOP ); { Fl_Flip_Button* o = tab_button = new Fl_Flip_Button( X, Y, W, 16, "chain/controls"); o->type(1); o->labelsize( 12 ); o->callback( cb_handle, this ); } Y += 18; H -= 18; { Fl_Group *o = chain_tab = new Fl_Group( X, Y, W, H, "" ); o->labeltype( FL_NO_LABEL ); o->box( FL_FLAT_BOX ); // o->color( fl_darker( FL_BACKGROUND_COLOR ) ); // o->color( FL_BACKGROUND_COLOR ); // o->box( FL_NO_BOX ); { Fl_Packscroller *o = new Fl_Packscroller( X, Y, W, H ); o->color( FL_BACKGROUND_COLOR ); // o->box( FL_FLAT_BOX ); o->box( FL_THIN_UP_BOX ); o->type( Fl_Scroll::VERTICAL ); { Fl_Pack *o = modules_pack = new Fl_Pack( X, Y, W, H ); o->type( Fl_Pack::VERTICAL ); o->spacing( 6 ); o->end(); Fl_Group::current()->resizable( o ); } o->end(); } o->end(); } { Fl_Group *o = control_tab = new Fl_Group( X, Y, W, H, "" ); o->box( FL_FLAT_BOX ); o->color( FL_BACKGROUND_COLOR ); o->labeltype( FL_NO_LABEL ); o->hide(); { Fl_Scroll *o = new Fl_Scroll( X, Y, W, H ); o->color( FL_BACKGROUND_COLOR ); o->box( FL_NO_BOX ); o->type( Fl_Scroll::VERTICAL ); { Fl_Pack *o = controls_pack = new Fl_Pack( X, Y, W, H ); o->type( Fl_Pack::VERTICAL ); o->spacing( 5 ); // o->color( FL_RED ); o->end(); Fl_Group::current()->resizable( o ); } o->end(); Fl_Group::current()->resizable( o ); } o->end(); o->hide(); Fl_Group::current()->resizable( o ); } end(); log_create(); _deleting = false; }
void inventory::form_from_map( const tripoint &origin, int range, bool assign_invlet ) { items.clear(); for( const tripoint &p : g->m.points_in_radius( origin, range ) ) { if (g->m.has_furn( p ) && g->m.accessible_furniture( origin, p, range )) { const furn_t &f = g->m.furn_at( p ); itype *type = f.crafting_pseudo_item_type(); if (type != NULL) { item furn_item(type->id, 0); const itype *ammo = f.crafting_ammo_item_type(); if (ammo != NULL) { furn_item.charges = count_charges_in_list( ammo, g->m.i_at( p ) ); } furn_item.item_tags.insert("PSEUDO"); add_item(furn_item); } } if( !g->m.accessible_items( origin, p, range ) ) { continue; } for (auto &i : g->m.i_at( p )) { if (!i.made_of(LIQUID)) { add_item(i, false, assign_invlet); } } // Kludges for now! ter_id terrain_id = g->m.ter( p ); if (g->m.has_nearby_fire( p, 0 )) { item fire("fire", 0); fire.charges = 1; add_item(fire); } if (terrain_id == t_water_sh || terrain_id == t_water_dp || terrain_id == t_water_pool || terrain_id == t_water_pump) { item water("water", 0); water.charges = 50; add_item(water); } if (terrain_id == t_swater_sh || terrain_id == t_swater_dp) { item swater("salt_water", 0); swater.charges = 50; add_item(swater); } // add cvd forge from terrain if (terrain_id == t_cvdmachine) { item cvd_machine("cvd_machine", 0); cvd_machine.charges = 1; cvd_machine.item_tags.insert("PSEUDO"); add_item(cvd_machine); } // kludge that can probably be done better to check specifically for toilet water to use in // crafting if (g->m.furn_at( p ).examine == &iexamine::toilet) { // get water charges at location auto toilet = g->m.i_at( p ); auto water = toilet.end(); for( auto candidate = toilet.begin(); candidate != toilet.end(); ++candidate ) { if( candidate->typeId() == "water" ) { water = candidate; break; } } if( water != toilet.end() && water->charges > 0) { add_item( *water ); } } // keg-kludge if (g->m.furn_at( p ).examine == &iexamine::keg) { auto liq_contained = g->m.i_at( p ); for( auto &i : liq_contained ) { if( i.made_of(LIQUID) ) { add_item(i); } } } // WARNING: The part below has a bug that's currently quite minor // When a vehicle has multiple faucets in range, available water is // multiplied by the number of faucets. // Same thing happens for all other tools and resources, but not cargo int vpart = -1; vehicle *veh = g->m.veh_at( p, vpart ); if( veh == nullptr ) { continue; } //Adds faucet to kitchen stuff; may be horribly wrong to do such.... //ShouldBreak into own variable const int kpart = veh->part_with_feature(vpart, "KITCHEN"); const int faupart = veh->part_with_feature(vpart, "FAUCET"); const int weldpart = veh->part_with_feature(vpart, "WELDRIG"); const int craftpart = veh->part_with_feature(vpart, "CRAFTRIG"); const int forgepart = veh->part_with_feature(vpart, "FORGE"); const int chempart = veh->part_with_feature(vpart, "CHEMLAB"); const int cargo = veh->part_with_feature(vpart, "CARGO"); if (cargo >= 0) { *this += std::list<item>( veh->get_items(cargo).begin(), veh->get_items(cargo).end() ); } if(faupart >= 0 ) { item clean_water("water_clean", 0); clean_water.charges = veh->fuel_left("water_clean"); add_item(clean_water); item water("water", 0); water.charges = veh->fuel_left("water"); // TODO: Poison add_item(water); } if (kpart >= 0) { item hotplate("hotplate", 0); hotplate.charges = veh->fuel_left("battery", true); hotplate.item_tags.insert("PSEUDO"); add_item(hotplate); item clean_water("water_clean", 0); clean_water.charges = veh->fuel_left("water_clean"); add_item(clean_water); item water("water", 0); water.charges = veh->fuel_left("water"); // TODO: Poison add_item(water); item pot("pot", 0); pot.item_tags.insert("PSEUDO"); add_item(pot); item pan("pan", 0); pan.item_tags.insert("PSEUDO"); add_item(pan); } if (weldpart >= 0) { item welder("welder", 0); welder.charges = veh->fuel_left("battery", true); welder.item_tags.insert("PSEUDO"); add_item(welder); item soldering_iron("soldering_iron", 0); soldering_iron.charges = veh->fuel_left("battery", true); soldering_iron.item_tags.insert("PSEUDO"); add_item(soldering_iron); } if (craftpart >= 0) { item vac_sealer("vac_sealer", 0); vac_sealer.charges = veh->fuel_left("battery", true); vac_sealer.item_tags.insert("PSEUDO"); add_item(vac_sealer); item dehydrator("dehydrator", 0); dehydrator.charges = veh->fuel_left("battery", true); dehydrator.item_tags.insert("PSEUDO"); add_item(dehydrator); item press("press", 0); press.charges = veh->fuel_left("battery", true); press.item_tags.insert("PSEUDO"); add_item(press); } if (forgepart >= 0) { item forge("forge", 0); forge.charges = veh->fuel_left("battery", true); forge.item_tags.insert("PSEUDO"); add_item(forge); } if (chempart >= 0) { item hotplate("hotplate", 0); hotplate.charges = veh->fuel_left("battery", true); hotplate.item_tags.insert("PSEUDO"); add_item(hotplate); item chemistry_set("chemistry_set", 0); chemistry_set.charges = veh->fuel_left("battery", true); chemistry_set.item_tags.insert("PSEUDO"); add_item(chemistry_set); } } }
//-------------------------------------------------- ofBuffer::ofBuffer() :currentLine(end(),end()){ buffer.resize(1); }
//-------------------------------------------------- ofBuffer::ofBuffer(const string & text) :buffer(text.begin(),text.end()) ,currentLine(end(),end()){ buffer.resize(buffer.size()+1,0); }
std::string WizardImpl::searchForSpell(std::string const &wish) { auto const spell = find(begin(books), end(books), wish); return spell!=end(books)?*spell:""; }
Potion WizardImpl::mixPotion(std::string const &recipe) { auto const potion = find(begin(potions), end(potions), recipe); return potion!=end(potions)?*potion:""; }
bool UniString::IsEqualAscii(char const * s) const { return (size() == strlen(s) && equal(begin(), end(), s)); }
int main() { try { enum pubnub_res res; std::string chan("hello_world"); pubnub::context pb("demo", "demo"); /* Leave this commented out to use the default - which is blocking I/O on most platforms. Uncomment to use non- blocking I/O. */ pb.set_blocking_io(pubnub::non_blocking); if (0 != pb.set_uuid_v4_random()) { pb.set_uuid("zeka-peka-iz-jendeka"); } else { std::cout << "Generated UUID: " << pb.uuid() << std::endl; } pb.set_auth("danaske"); pb.set_transaction_timeout( #if __cplusplus >= 201103L std::chrono::seconds(10) #else 10000 #endif ); std::cout << "First subscribe / connect" << std::endl; if (PNR_OK == pb.subscribe(chan).await()) { std::cout << "Subscribe/connected!" << std::endl; } else { std::cout << "Subscribe failed!" << std::endl; } #if PUBNUB_CRYPTO_API std::cout << "Publishing encrypted" << std::endl; pubnub::futres futres = pb.publish_encrypted(chan, "\"Hello world from C++!\"", "KUKUMENEGRDNA"); #else std::cout << "Publishing" << std::endl; pubnub::futres futres = pb.publish(chan, "\"Hello world from C++!\""); #endif res = futres.await(); if (PNR_OK == res) { std::cout << "Published! Response from Pubnub: " << pb.last_publish_result() << std::endl; } else if (PNR_PUBLISH_FAILED == res) { std::cout << "Published failed on Pubnub, description: " << pb.last_publish_result() << std::endl; } else { std::cout << "Publishing failed with code: " << res << std::endl; } std::cout << "Subscribing" << std::endl; if (PNR_OK == pb.subscribe(chan).await()) { std::cout << "Subscribed! Got messages:" << std::endl; /// Lets illustrate getting all the message in a vector, /// and iterating over it #if __cplusplus >= 201103L #if PUBNUB_CRYPTO_API auto msg = pb.get_all_decrypted("KUKUMENEGRDNA"); #else auto msg = pb.get_all(); #endif for (auto it = msg.begin(); it != msg.end(); ++it) { std::cout << *it << std::endl; } #else #if PUBNUB_CRYPTO_API std::vector<std::string> msg = pb.get_all_decrypted("KUKUMENEGRDNA"); #else std::vector<std::string> msg = pb.get_all(); #endif for (std::vector<std::string>::iterator it = msg.begin(); it != msg.end(); ++it) { std::cout << *it << std::endl; } #endif } else { std::cout << "Subscribe failed!" << std::endl; } std::cout << "Getting time" << std::endl; if (PNR_OK == pb.time().await()) { std::cout << "Gotten time " << pb.get() << "; last time token="<< pb.last_time_token() << std::endl; } else { std::cout << "Getting time failed!" << std::endl; } std::cout << "Getting history" << std::endl; res = pb.history(chan).await(); if (PNR_OK == res) { std::cout << "Got history! Messages:" << std::endl; /// Lets illustrate getting all the message in a vector, /// and then accessing each vector index in a loop #if __cplusplus >= 201103L auto msg = pb.get_all(); /// a for-each loop for C++11 for (auto &&m : msg) { std::cout << m << std::endl; } #else std::vector<std::string> msg = pb.get_all(); for (unsigned i = 0; i < msg.size(); ++i) { std::cout << msg.at(i) << std::endl; } #endif } else { std::cout << "Getting history failed! error code: " << res << std::endl; } std::cout << "Getting history with `include_token`" << std::endl; if (PNR_OK == pb.history(chan, 10, true).await()) { std::cout << "Got history with time token! Messages:" << std::endl; /// Here we illustrate getting the messages one-by-one std::string msg; do { msg = pb.get(); std::cout << msg << std::endl; } while (!msg.empty()); } else { std::cout << "Getting history with time token failed!" << std::endl; } std::cout << "Getting here-now presence" << std::endl; if (PNR_OK == pb.here_now(chan).await()) { std::cout << "Got here-now presence: " << pb.get() << std::endl; } else { std::cout << "Getting here-now presence failed!" << std::endl; } /** Global here_now presence for "demo" subscribe key is _very_ long, so we disable it. Enable to try out, or if you use a "real" subscribe key*/ #if 0 std::cout << "Getting global here-now presence" << std::endl; if (PNR_OK == pb.global_here_now().await()) { std::cout << "Got global here-now presence: " << pb.get() << std::endl; } } else { std::cout << "Getting here-now presence failed!" << std::endl; } #endif std::cout << "Getting where-now presence" << std::endl; if (PNR_OK == pb.where_now().await()) { std::cout << "Got where-now presence: " << pb.get() << std::endl; } else { std::cout << "Getting where-now presence failed!" << std::endl; } std::cout << "Setting state" << std::endl; if (PNR_OK == pb.set_state(chan, "", pb.uuid(), "{\"x\":5}").await()) { std::cout << "State was set: " << pb.get() << std::endl; } else { std::cout << "Setting state failed!" << std::endl; } std::cout << "Getting state" << std::endl; if (PNR_OK == pb.state_get(chan).await()) { std::cout << "State gotten: " << pb.get() << std::endl; } else { std::cout << "Getting state failed!" << std::endl; } }
void emit_class(EmitUnitState& state, UnitEmitter& ue, const php::Class& cls) { FTRACE(2, " class: {}\n", cls.name->data()); auto const pce = ue.newPreClassEmitter( cls.name, cls.hoistability ); pce->init( std::get<0>(cls.srcInfo.loc), std::get<1>(cls.srcInfo.loc), ue.bcPos(), cls.attrs, cls.parentName ? cls.parentName : s_empty.get(), cls.srcInfo.docComment ); pce->setUserAttributes(cls.userAttributes); for (auto& x : cls.interfaceNames) pce->addInterface(x); for (auto& x : cls.usedTraitNames) pce->addUsedTrait(x); for (auto& x : cls.requirements) pce->addClassRequirement(x); for (auto& x : cls.traitPrecRules) pce->addTraitPrecRule(x); for (auto& x : cls.traitAliasRules) pce->addTraitAliasRule(x); for (auto& m : cls.methods) { FTRACE(2, " method: {}\n", m->name->data()); auto const fe = ue.newMethodEmitter(m->name, pce); emit_init_func(*fe, *m); pce->addMethod(fe); auto const info = emit_bytecode(state, ue, *m); emit_finish_func(*m, *fe, info); } auto const privateProps = state.index.lookup_private_props(&cls); auto const privateStatics = state.index.lookup_private_statics(&cls); for (auto& prop : cls.properties) { auto const repoTy = [&] (const PropState& ps) -> RepoAuthType { // TODO(#3599292): we don't currently infer closure use var types. if (is_closure(cls)) return RepoAuthType{}; auto it = ps.find(prop.name); if (it == end(ps)) return RepoAuthType{}; auto const rat = make_repo_type(*state.index.array_table_builder(), it->second); merge_repo_auth_type(ue, rat); return rat; }; pce->addProperty( prop.name, prop.attrs, prop.typeConstraint, prop.docComment, &prop.val, (prop.attrs & AttrStatic) ? repoTy(privateStatics) : repoTy(privateProps) ); } for (auto& cconst : cls.constants) { pce->addConstant( cconst.name, cconst.typeConstraint, &cconst.val, cconst.phpCode ); } pce->setEnumBaseTy(cls.enumBaseTy); }
/* * Traverse the actual block layout, and find out the intervals for * each exception region in the tree. * * The basic idea here is that we haven't constrained block layout * based on the exception tree, but adjacent blocks are still * reasonably likely to have the same ExnNode. Try to coalesce the EH * regions we create for in those cases. */ void emit_ehent_tree(FuncEmitter& fe, const php::Func& func, const EmitBcInfo& info) { std::map< borrowed_ptr<const php::ExnNode>, std::vector<std::unique_ptr<EHRegion>> > exnMap; /* * While walking over the blocks in layout order, we track the set * of "active" exnNodes. This are a list of exnNodes that inherit * from each other. When a new active node is pushed, begin an * EHEnt, and when it's popped, it's done. */ std::vector<borrowed_ptr<const php::ExnNode>> activeList; auto pop_active = [&] (Offset past) { auto p = activeList.back(); activeList.pop_back(); exnMap[p].back()->past = past; }; auto push_active = [&] (const php::ExnNode* p, Offset start) { auto const parent = activeList.empty() ? nullptr : borrow(exnMap[activeList.back()].back()); exnMap[p].push_back( folly::make_unique<EHRegion>( EHRegion { p, parent, start, kInvalidOffset } ) ); activeList.push_back(p); }; /* * Walk over the blocks, and compare the new block's exnNode path to * the active one. Find the least common ancestor of the two paths, * then modify the active list by popping and then pushing nodes to * set it to the new block's path. */ for (auto& b : info.blockOrder) { auto const offset = info.blockInfo[b->id].offset; if (!b->exnNode) { while (!activeList.empty()) pop_active(offset); continue; } std::vector<borrowed_ptr<const php::ExnNode>> current; exn_path(current, b->exnNode); auto const prefix = shared_prefix(current, activeList); for (size_t i = prefix, sz = activeList.size(); i < sz; ++i) { pop_active(offset); } for (size_t i = prefix, sz = current.size(); i < sz; ++i) { push_active(current[i], offset); } if (debug && !activeList.empty()) { current.clear(); exn_path(current, activeList.back()); assert(current == activeList); } } while (!activeList.empty()) { pop_active(info.blockInfo[info.blockOrder.back()->id].past); } /* * We've created all our regions, but we need to sort them instead * of trying to get the UnitEmitter to do it. * * The UnitEmitter expects EH regions that look a certain way * (basically the way emitter.cpp likes them). There are some rules * about the order it needs to have at runtime, which we set up * here. * * Essentially, an entry a is less than an entry b iff: * * - a starts before b * - a starts at the same place, but encloses b entirely * - a has the same extents as b, but is a parent of b */ std::vector<borrowed_ptr<EHRegion>> regions; for (auto& mapEnt : exnMap) { for (auto& region : mapEnt.second) { regions.push_back(borrow(region)); } } std::sort( begin(regions), end(regions), [&] (borrowed_ptr<const EHRegion> a, borrowed_ptr<const EHRegion> b) { if (a == b) return false; if (a->start == b->start) { if (a->past == b->past) { // When regions exactly overlap, the parent is less than the // child. for (auto p = b->parent; p != nullptr; p = p->parent) { if (p == a) return true; } // If a is not a parent of b, and they have the same region; // then b better be a parent of a. if (debug) { auto p = a->parent; for (; p != b && p != nullptr; p = p->parent) continue; assert(p == b); } return false; } return a->past > b->past; } return a->start < b->start; } ); std::map<borrowed_ptr<const EHRegion>,uint32_t> parentIndexMap; for (auto& r : regions) { emit_eh_region(fe, r, info.blockInfo, parentIndexMap); } fe.setEHTabIsSorted(); }
inline void setpg(char_type * pp, char_type * gp) { setp(pp, end()); setg(gp, gp, pp); }
std::pair<I, O> operator()(Rng &rng, ORng &result, BOp bop = BOp{}, P proj = P{}) const { return (*this)(begin(rng), end(rng), begin(result), end(result), std::move(bop), std::move(proj)); }
bool Bitmap_Handler::export_image(Image_8 * image, const char * file_name) { auto output = std::ofstream{ file_name, std::ios::binary }; output << "BM"; //File Size Parameter uint32_t var_32_u = 54 + 3 * image->get_pixels()->size(); for (int i = 0; i < ((image->size_x * 3) % 4); i++) { var_32_u += image->size_y; } output.write( (char*) &var_32_u, sizeof(var_32_u)); //Reserved var_32_u = 0; output.write((char*)&var_32_u, sizeof(var_32_u)); //Image offset var_32_u = 54; output.write((char*)&var_32_u, sizeof(var_32_u)); //Infoheader Size var_32_u = 40; output.write((char*)&var_32_u, sizeof(var_32_u)); //Width int32_t var_32_s = image->size_x; output.write((char*)&var_32_s, sizeof(var_32_s)); //Height var_32_s = image->size_y; output.write((char*)&var_32_s, sizeof(var_32_s)); //Unused uint16_t var_16_u = 1; output.write((char*)&var_16_u, sizeof(var_16_u)); //biBitCount var_16_u = 24; output.write((char*)&var_16_u, sizeof(var_16_u)); //Compression var_32_u = 0; output.write((char*)&var_32_u, sizeof(var_32_u)); //SizeImage var_32_u = 0; output.write((char*)&var_32_u, sizeof(var_32_u)); //Pixels per Meter var_32_u = 0; output.write((char*)&var_32_u, sizeof(var_32_u)); output.write((char*)&var_32_u, sizeof(var_32_u)); //Color Table var_32_u = 0; output.write((char*)&var_32_u, sizeof(var_32_u)); //Colors used var_32_u = 0; output.write((char*)&var_32_u, sizeof(var_32_u)); unsigned int row_ind = 0; auto pixels = image->get_pixels(); unsigned int z = 0; for (auto it = pixels->begin(); it != pixels->end(); it++) { int t_r = (*it).get_r(); output.write((char*)&(t_r), 1); int t_g = (*it).get_g(); output.write((char*)&(t_g), 1); int t_b = (*it).get_b(); output.write((char*)&(t_b), 1); row_ind += 3; z++; //Catch last Bytes in Row if (z == (image->size_x)) { while (row_ind % 4 != 0) { row_ind++; uint8_t t_a = 0; output.write((char*)&t_a, 1); } row_ind = 0; z = 0; } } output.close(); return true; }
void MobileSimulator::MouseUpEvent(Vec2i screenCoordinates, MouseButtonInput button) { _multiGestureOngoing = false; _gestureType = NONE; _mouseDown = false; TouchList* tl = &TouchListener::GetTouchList(); if (theInput.IsKeyDown(ANGEL_KEY_LEFTCONTROL) || theInput.IsKeyDown(ANGEL_KEY_RIGHTCONTROL)) { TouchList::iterator it = tl->begin(); while (it != tl->end()) { SendTouchNotifiers((*it), TOUCH_END); delete (*it); it = tl->erase(it); } } else { // just a single touch, but we'll iterate anyway TouchList::iterator it = tl->begin(); while (it != tl->end()) { if ( (theWorld.GetCurrentTimeSeconds() - (*it)->MotionStartTime) < SWIPE_MAX_DURATION) { Vector2 start((*it)->StartingPoint); Vector2 end((*it)->CurrentPoint); Vector2 motion = end - start; if (motion.LengthSquared() >= (SWIPE_MIN_DISTANCE * SWIPE_MIN_DISTANCE)) { float angle = MathUtil::ToDegrees(acos(Vector2::Dot(Vector2::UnitX, Vector2::Normalize(motion)))); if (motion.Y > 0.0f) { angle = 360.0f - angle; } if ( (angle > 45.0f) && (angle <= 135.0f) ) { // swipe up theSwitchboard.Broadcast(new Message("MultiTouchSwipeUp")); } else if ( (angle > 135.0f) && (angle <= 225.0f) ) { // swipe left theSwitchboard.Broadcast(new Message("MultiTouchSwipeLeft")); } else if ( (angle > 225.0f) && (angle <= 315.0f) ) { // swipe down theSwitchboard.Broadcast(new Message("MultiTouchSwipeDown")); } else { // swipe right theSwitchboard.Broadcast(new Message("MultiTouchSwipeRight")); } } } SendTouchNotifiers((*it), TOUCH_END); delete (*it); it = tl->erase(it); } } }
std::shared_ptr<Image_8> Bitmap_Handler::get_Image(const char * file_name) { auto input = std::ifstream{ file_name, std::ios::binary }; if (input.is_open()) { // get length of file: input.seekg(0, input.end); unsigned long length = input.tellg(); input.seekg(0, input.beg); if (length > 50) { //Should be replaced by an import into a vector char *buffer = new char[length]; input.read(buffer, length); auto data_offset = merge_bytes_unsigned(buffer, 10, 4); auto size_x = merge_bytes_unsigned(buffer, 18, 4); auto size_y = merge_bytes_unsigned(buffer, 22, 4); auto biBitCount = merge_bytes_unsigned(buffer, 28, 2); auto bCompression = merge_bytes_unsigned(buffer, 30, 24); auto output = std::make_shared<Image_8>(size_x, size_y); unsigned long index = data_offset; unsigned int row_ind = 0; auto pixels = output->get_pixels(); unsigned int z = 0; for (auto it = pixels->begin(); it != pixels->end(); it++) { (*it).set_RGB((unsigned char)(buffer[index]),(unsigned char)(buffer[index + 1]),(unsigned char)(buffer[index + 2])); index += 3; row_ind += 3; z++; //Catch last Bytes in Row if (z == (size_x)) { while (row_ind % 4 != 0) { index++; row_ind++; } row_ind = 0; z = 0; } } input.close(); delete[] buffer; return output; } } else { return std::make_shared<Image_8>(0, 0); std::cout << "Image not found" << std::endl; } }
//-------------------------------------------------- ofBuffer::ofBuffer(const char * _buffer, std::size_t size) :buffer(_buffer,_buffer+size) ,currentLine(end(),end()){ buffer.resize(buffer.size()+1,0); }
std::vector<tripoint> map::route( const tripoint &f, const tripoint &t, const pathfinding_settings &settings, const std::set<tripoint> &pre_closed ) const { /* TODO: If the origin or destination is out of bound, figure out the closest * in-bounds point and go to that, then to the real origin/destination. */ std::vector<tripoint> ret; if( f == t || !inbounds( f ) ) { return ret; } if( !inbounds( t ) ) { tripoint clipped = t; clip_to_bounds( clipped ); return route( f, clipped, settings, pre_closed ); } // First, check for a simple straight line on flat ground // Except when the line contains a pre-closed tile - we need to do regular pathing then constexpr auto non_normal = PF_SLOW | PF_WALL | PF_VEHICLE | PF_TRAP; if( f.z == t.z ) { const auto line_path = line_to( f, t ); const auto &pf_cache = get_pathfinding_cache_ref( f.z ); // Check all points for any special case (including just hard terrain) if( std::all_of( line_path.begin(), line_path.end(), [&pf_cache, non_normal]( const tripoint & p ) { return !( pf_cache.special[p.x][p.y] & non_normal ); } ) ) { const std::set<tripoint> sorted_line( line_path.begin(), line_path.end() ); if( is_disjoint( sorted_line, pre_closed ) ) { return line_path; } } } // If expected path length is greater than max distance, allow only line path, like above if( rl_dist( f, t ) > settings.max_dist ) { return ret; } int max_length = settings.max_length; int bash = settings.bash_strength; bool doors = settings.allow_open_doors; bool trapavoid = settings.avoid_traps; const int pad = 16; // Should be much bigger - low value makes pathfinders dumb! int minx = std::min( f.x, t.x ) - pad; int miny = std::min( f.y, t.y ) - pad; int minz = std::min( f.z, t.z ); // TODO: Make this way bigger int maxx = std::max( f.x, t.x ) + pad; int maxy = std::max( f.y, t.y ) + pad; int maxz = std::max( f.z, t.z ); // Same TODO as above clip_to_bounds( minx, miny, minz ); clip_to_bounds( maxx, maxy, maxz ); pathfinder pf( minx, miny, maxx, maxy ); // Make NPCs not want to path through player // But don't make player pathing stop working for( const auto &p : pre_closed ) { if( p.x >= minx && p.x < maxx && p.y >= miny && p.y < maxy ) { pf.close_point( p ); } } // Start and end must not be closed pf.unclose_point( f ); pf.unclose_point( t ); pf.add_point( 0, 0, f, f ); bool done = false; do { auto cur = pf.get_next(); const int parent_index = flat_index( cur.x, cur.y ); auto &layer = pf.get_layer( cur.z ); auto &cur_state = layer.state[parent_index]; if( cur_state == ASL_CLOSED ) { continue; } if( layer.gscore[parent_index] > max_length ) { // Shortest path would be too long, return empty vector return std::vector<tripoint>(); } if( cur == t ) { done = true; break; } cur_state = ASL_CLOSED; const auto &pf_cache = get_pathfinding_cache_ref( cur.z ); const auto cur_special = pf_cache.special[cur.x][cur.y]; // 7 3 5 // 1 . 2 // 6 4 8 constexpr std::array<int, 8> x_offset{{ -1, 1, 0, 0, 1, -1, -1, 1 }}; constexpr std::array<int, 8> y_offset{{ 0, 0, -1, 1, -1, 1, -1, 1 }}; for( size_t i = 0; i < 8; i++ ) { const tripoint p( cur.x + x_offset[i], cur.y + y_offset[i], cur.z ); const int index = flat_index( p.x, p.y ); // @todo Remove this and instead have sentinels at the edges if( p.x < minx || p.x >= maxx || p.y < miny || p.y >= maxy ) { continue; } if( layer.state[index] == ASL_CLOSED ) { continue; } // Penalize for diagonals or the path will look "unnatural" int newg = layer.gscore[parent_index] + ( ( cur.x != p.x && cur.y != p.y ) ? 1 : 0 ); const auto p_special = pf_cache.special[p.x][p.y]; // @todo De-uglify, de-huge-n if( !( p_special & non_normal ) ) { // Boring flat dirt - the most common case above the ground newg += 2; } else { int part = -1; const maptile &tile = maptile_at_internal( p ); const auto &terrain = tile.get_ter_t(); const auto &furniture = tile.get_furn_t(); const vehicle *veh = veh_at_internal( p, part ); const int cost = move_cost_internal( furniture, terrain, veh, part ); // Don't calculate bash rating unless we intend to actually use it const int rating = ( bash == 0 || cost != 0 ) ? -1 : bash_rating_internal( bash, furniture, terrain, false, veh, part ); if( cost == 0 && rating <= 0 && ( !doors || !terrain.open ) && veh == nullptr ) { layer.state[index] = ASL_CLOSED; // Close it so that next time we won't try to calc costs continue; } newg += cost; if( cost == 0 ) { // Handle all kinds of doors // Only try to open INSIDE doors from the inside if( doors && terrain.open && ( !terrain.has_flag( "OPENCLOSE_INSIDE" ) || !is_outside( cur ) ) ) { // To open and then move onto the tile newg += 4; } else if( veh != nullptr ) { part = veh->obstacle_at_part( part ); int dummy = -1; if( doors && veh->part_flag( part, VPFLAG_OPENABLE ) && ( !veh->part_flag( part, "OPENCLOSE_INSIDE" ) || veh_at_internal( cur, dummy ) == veh ) ) { // Handle car doors, but don't try to path through curtains newg += 10; // One turn to open, 4 to move there } else if( part >= 0 && bash > 0 ) { // Car obstacle that isn't a door // @todo Account for armor int hp = veh->parts[part].hp(); if( hp / 20 > bash ) { // Threshold damage thing means we just can't bash this down layer.state[index] = ASL_CLOSED; continue; } else if( hp / 10 > bash ) { // Threshold damage thing means we will fail to deal damage pretty often hp *= 2; } newg += 2 * hp / bash + 8 + 4; } else if( part >= 0 ) { if( !doors || !veh->part_flag( part, VPFLAG_OPENABLE ) ) { // Won't be openable, don't try from other sides layer.state[index] = ASL_CLOSED; } continue; } } else if( rating > 1 ) { // Expected number of turns to bash it down, 1 turn to move there // and 5 turns of penalty not to trash everything just because we can newg += ( 20 / rating ) + 2 + 10; } else if( rating == 1 ) { // Desperate measures, avoid whenever possible newg += 500; } else { // Unbashable and unopenable from here if( !doors || !terrain.open ) { // Or anywhere else for that matter layer.state[index] = ASL_CLOSED; } continue; } } if( trapavoid && p_special & PF_TRAP ) { const auto &ter_trp = terrain.trap.obj(); const auto &trp = ter_trp.is_benign() ? tile.get_trap_t() : ter_trp; if( !trp.is_benign() ) { // For now make them detect all traps if( has_zlevels() && terrain.has_flag( TFLAG_NO_FLOOR ) ) { // Special case - ledge in z-levels // Warning: really expensive, needs a cache if( valid_move( p, tripoint( p.x, p.y, p.z - 1 ), false, true ) ) { tripoint below( p.x, p.y, p.z - 1 ); if( !has_flag( TFLAG_NO_FLOOR, below ) ) { // Otherwise this would have been a huge fall auto &layer = pf.get_layer( p.z - 1 ); // From cur, not p, because we won't be walking on air pf.add_point( layer.gscore[parent_index] + 10, layer.score[parent_index] + 10 + 2 * rl_dist( below, t ), cur, below ); } // Close p, because we won't be walking on it layer.state[index] = ASL_CLOSED; continue; } } else if( trapavoid ) { // Otherwise it's walkable newg += 500; } } } } // If not visited, add as open // If visited, add it only if we can do so with better score if( layer.state[index] == ASL_NONE || newg < layer.gscore[index] ) { pf.add_point( newg, newg + 2 * rl_dist( p, t ), cur, p ); } } if( !has_zlevels() || !( cur_special & PF_UPDOWN ) || !settings.allow_climb_stairs ) { // The part below is only for z-level pathing continue; } const maptile &parent_tile = maptile_at_internal( cur ); const auto &parent_terrain = parent_tile.get_ter_t(); if( settings.allow_climb_stairs && cur.z > minz && parent_terrain.has_flag( TFLAG_GOES_DOWN ) ) { tripoint dest( cur.x, cur.y, cur.z - 1 ); dest = vertical_move_destination<TFLAG_GOES_UP>( *this, dest ); if( inbounds( dest ) ) { auto &layer = pf.get_layer( dest.z ); pf.add_point( layer.gscore[parent_index] + 2, layer.score[parent_index] + 2 * rl_dist( dest, t ), cur, dest ); } } if( settings.allow_climb_stairs && cur.z < maxz && parent_terrain.has_flag( TFLAG_GOES_UP ) ) { tripoint dest( cur.x, cur.y, cur.z + 1 ); dest = vertical_move_destination<TFLAG_GOES_DOWN>( *this, dest ); if( inbounds( dest ) ) { auto &layer = pf.get_layer( dest.z ); pf.add_point( layer.gscore[parent_index] + 2, layer.score[parent_index] + 2 * rl_dist( dest, t ), cur, dest ); } } if( cur.z < maxz && parent_terrain.has_flag( TFLAG_RAMP ) && valid_move( cur, tripoint( cur.x, cur.y, cur.z + 1 ), false, true ) ) { auto &layer = pf.get_layer( cur.z + 1 ); for( size_t it = 0; it < 8; it++ ) { const tripoint above( cur.x + x_offset[it], cur.y + y_offset[it], cur.z + 1 ); pf.add_point( layer.gscore[parent_index] + 4, layer.score[parent_index] + 4 + 2 * rl_dist( above, t ), cur, above ); } } } while( !done && !pf.empty() ); if( done ) { ret.reserve( rl_dist( f, t ) * 2 ); tripoint cur = t; // Just to limit max distance, in case something weird happens for( int fdist = max_length; fdist != 0; fdist-- ) { const int cur_index = flat_index( cur.x, cur.y ); const auto &layer = pf.get_layer( cur.z ); const tripoint &par = layer.parent[cur_index]; if( cur == f ) { break; } ret.push_back( cur ); // Jumps are acceptable on 1 z-level changes // This is because stairs teleport the player too if( rl_dist( cur, par ) > 1 && abs( cur.z - par.z ) != 1 ) { debugmsg( "Jump in our route! %d:%d:%d->%d:%d:%d", cur.x, cur.y, cur.z, par.x, par.y, par.z ); return ret; } cur = par; } std::reverse( ret.begin(), ret.end() ); } return ret; }
//-------------------------------------------------- ofBuffer::ofBuffer(istream & stream) :currentLine(end(),end()){ set(stream); }
int main(int argc, char **argv) { QApplication app(argc, argv); QCommandLineParser parser; parser.addPositionalArgument(QStringLiteral("WId"), QStringLiteral("window id for the window to take the icon from"), QStringLiteral("[WId]")); parser.addHelpOption(); parser.process(app); QWidget window; QVBoxLayout *vbox = new QVBoxLayout(&window); bool ok = false; qulonglong id = parser.positionalArguments().first().toULongLong(&ok); if (!ok) { // try hex id = parser.positionalArguments().first().toULongLong(&ok, 16); } if (!ok) { return 1; } NETWinInfo info(QX11Info::connection(), id, QX11Info::appRootWindow(), NET::WMIcon, NET::WM2WindowClass | NET::WM2IconPixmap); auto addIcons = [&window, vbox, &id, &info] (const QString &name, int flag) { QLabel *title = new QLabel(name, &window); vbox->addWidget(title); QIcon icons; if (flag & KWindowSystem::NETWM) { const int *iconSizes = info.iconSizes(); int index = 0; while (iconSizes[index] != 0 && iconSizes[index + 1] != 0) { const int width = iconSizes[index++]; const int height = iconSizes[index++]; NETIcon ni = info.icon(width, height); if (ni.data) { QImage img((uchar *) ni.data, (int) ni.size.width, (int) ni.size.height, QImage::Format_ARGB32); if (!img.isNull()) { icons.addPixmap(QPixmap::fromImage(img)); } } } } if (flag & KWindowSystem::WMHints) { icons.addPixmap(KWindowSystem::icon(id, 0, 0, false, KWindowSystem::WMHints, &info)); } if (flag & KWindowSystem::ClassHint) { icons = QIcon::fromTheme(QString::fromUtf8(info.windowClassClass()).toLower()); } if (flag & KWindowSystem::XApp) { icons = QIcon::fromTheme(QLatin1String("xorg")); } if (icons.isNull()) { return; } QHBoxLayout *layout = new QHBoxLayout(); const auto sizes = icons.availableSizes(); for (auto it = sizes.begin(); it != sizes.end(); ++it) { const QSize &s = *it; QVBoxLayout *v = new QVBoxLayout(); QLabel *l = new QLabel(QStringLiteral("%1/%2").arg(s.width()).arg(s.height()), &window); v->addWidget(l); QLabel *p = new QLabel(&window); p->setPixmap(icons.pixmap(s)); v->addWidget(p); layout->addLayout(v); } vbox->addLayout(layout); }; addIcons(QStringLiteral("NetWM"), KWindowSystem::NETWM); addIcons(QStringLiteral("WMHints"), KWindowSystem::WMHints); addIcons(QStringLiteral("ClassHint"), KWindowSystem::ClassHint); addIcons(QStringLiteral("XApp"), KWindowSystem::XApp); window.setLayout(vbox); window.show(); return app.exec(); }
// Destroy a universal proxy. PyQtProxy::~PyQtProxy() { Q_ASSERT((proxy_flags & PROXY_SLOT_INVOKED) == 0); if (hashed) { mutex->lock(); switch (type) { case ProxySlot: { ProxyHash::iterator it(proxy_slots.find(saved_key)); ProxyHash::iterator end(proxy_slots.end()); while (it != end && it.key() == saved_key) { if (it.value() == this) it = proxy_slots.erase(it); else ++it; } break; } case ProxySignal: { ProxyHash::iterator it(proxy_signals.find(saved_key)); ProxyHash::iterator end(proxy_signals.end()); while (it != end && it.key() == saved_key) { if (it.value() == this) it = proxy_signals.erase(it); else ++it; } break; } } mutex->unlock(); } if (type == ProxySlot && real_slot.signature) { // Qt can still be tidying up after Python has gone so make sure that // it hasn't. if (Py_IsInitialized()) { SIP_BLOCK_THREADS sipFreeSipslot(&real_slot.sip_slot); SIP_UNBLOCK_THREADS } if (proxy_flags & PROXY_OWNS_SLOT_SIG) delete real_slot.signature; real_slot.signature = 0; } if (meta_object) { #if QT_VERSION >= 0x050000 free(const_cast<QMetaObject *>(meta_object)); #else if (meta_object != &staticMetaObject) { // The casts are needed for MSVC 6. delete[] const_cast<char *>(meta_object->d.stringdata); delete[] const_cast<uint *>(meta_object->d.data); delete meta_object; } #endif } }
void NegateFace(Face & f) { f.plane() = -f.plane(); std::reverse(begin(f.vertex), end(f.vertex)); }
std::string set_of_chars::as_string() const { return std::string( begin(), end() ) ; }
void Private:: ParseKeywords( std::string const & keywords, Table const & mapping, IdSetTable & set_table, Expression & rule) { if (keywords.empty() || mapping.empty()) return; auto tmp_table = set_table; auto tmp_exp = rule; auto npos = std::string::npos; auto beg = keywords.find_first_of( LeftBound, 0U); auto end = keywords.find_first_of(RightBound, 0U); bool valid = beg != npos && end != npos && beg < end; while (valid && beg != npos && end != npos && beg < end) { auto mid = keywords.find_first_of(Separator, beg); valid = valid && mid < end; auto caller_idx = npos; if (valid) { /* caller */ auto len = mid - beg - 1U; auto caller_beg = keywords.find_first_not_of(Space, beg + 1U, len); auto caller_end = keywords.find_last_not_of (Space, mid - 1U, len); valid = caller_beg != npos && caller_end != npos && caller_beg <= caller_end; if (valid) { auto is_keyword_complete = keywords.at(caller_beg) != Incomplete; if (!is_keyword_complete) caller_beg++; auto word = keywords.substr(caller_beg, caller_end + 1U - caller_beg); caller_idx = IndexKeywords(word, mapping, tmp_table, is_keyword_complete); if (caller_idx == ~size_t(0U)) valid = false; } } auto callee_idx = npos; if (valid) { /* callee */ auto len = end - mid - 1U; auto callee_beg = keywords.find_first_not_of(Space, mid + 1U, len); auto callee_end = keywords.find_last_not_of (Space, end - 1U, len); valid = callee_beg != npos && callee_end != npos && callee_beg <= callee_end; if (valid) { auto is_keyword_complete = keywords.at(callee_beg) != Incomplete; if (!is_keyword_complete) callee_beg++; auto word = keywords.substr(callee_beg, callee_end + 1U - callee_beg); callee_idx = IndexKeywords(word, mapping, tmp_table, is_keyword_complete); if (callee_idx == ~size_t(0U)) valid = false; } } if (valid) { tmp_exp.push_back(std::make_pair(caller_idx, callee_idx)); beg = keywords.find_first_of( LeftBound, end); end = keywords.find_first_of(RightBound, beg); } } if (valid) { set_table.insert(set_table.end(), tmp_table.begin(), tmp_table.end()); rule.insert(rule.end(), tmp_exp.begin(), tmp_exp.end()); } }
void print(std::ostream& os, const Block* block, const RegAllocInfo* regs, const AsmInfo* asmInfo, const GuardConstraints* guards, BCMarker* markerPtr) { BCMarker dummy; BCMarker& curMarker = markerPtr ? *markerPtr : dummy; TcaRange blockRange = asmInfo ? asmInfo->asmRanges[block] : TcaRange(nullptr, nullptr); os << '\n' << std::string(kIndent - 3, ' '); printLabel(os, block); os << punc(":"); auto& preds = block->preds(); if (!preds.empty()) { os << " (preds"; for (auto const& edge : preds) { os << " B" << edge.inst()->block()->id(); } os << ')'; } os << "\n"; if (block->empty()) { os << std::string(kIndent, ' ') << "empty block\n"; return; } const char* markerEndl = ""; for (auto it = block->begin(); it != block->end();) { auto& inst = *it; ++it; if (inst.marker() != curMarker) { std::ostringstream mStr; auto const& newMarker = inst.marker(); if (!newMarker.hasFunc()) { os << color(ANSI_COLOR_BLUE) << std::string(kIndent, ' ') << "--- invalid marker" << color(ANSI_COLOR_END) << '\n'; } else { auto func = newMarker.func(); if (!curMarker.hasFunc() || func != curMarker.func()) { func->prettyPrint(mStr, Func::PrintOpts().noFpi()); } mStr << std::string(kIndent, ' ') << newMarker.show() << '\n'; auto bcOffset = newMarker.bcOff(); func->unit()->prettyPrint( mStr, Unit::PrintOpts() .range(bcOffset, bcOffset+1) .noLineNumbers() .noFuncs() .indent(0)); std::vector<std::string> vec; folly::split('\n', mStr.str(), vec); os << markerEndl; markerEndl = "\n"; for (auto& s : vec) { if (s.empty()) continue; os << color(ANSI_COLOR_BLUE) << s << color(ANSI_COLOR_END) << '\n'; } } curMarker = newMarker; } if (inst.op() == DefLabel) { // print phi pseudo-instructions for (unsigned i = 0, n = inst.numDsts(); i < n; ++i) { os << std::string(kIndent + folly::format("({}) ", inst.id()).str().size(), ' '); auto dst = inst.dst(i); JIT::print(os, dst, dstLoc(regs, &inst, i)); os << punc(" = ") << color(ANSI_COLOR_CYAN) << "phi " << color(ANSI_COLOR_END); bool first = true; inst.block()->forEachSrc(i, [&](IRInstruction* jmp, SSATmp*) { if (!first) os << punc(", "); first = false; printSrc(os, jmp, i, regs); os << punc("@"); printLabel(os, jmp->block()); }); os << '\n'; } } os << std::string(kIndent, ' '); JIT::print(os, &inst, regs, guards); os << '\n'; if (asmInfo) { TcaRange instRange = asmInfo->instRanges[inst]; if (!instRange.empty()) { disasmRange(os, instRange.begin(), instRange.end()); os << '\n'; assert(instRange.end() >= blockRange.start() && instRange.end() <= blockRange.end()); blockRange = TcaRange(instRange.end(), blockRange.end()); } } } if (asmInfo) { // print code associated with this block that isn't tied to any // instruction. This includes code after the last isntruction (e.g. // jmp to next block), and ACold or AFrozen code. if (!blockRange.empty()) { os << std::string(kIndent, ' ') << punc("A:") << "\n"; disasmRange(os, blockRange.start(), blockRange.end()); } auto acoldRange = asmInfo->acoldRanges[block]; if (!acoldRange.empty()) { os << std::string(kIndent, ' ') << punc("ACold:") << "\n"; disasmRange(os, acoldRange.start(), acoldRange.end()); } auto afrozenRange = asmInfo->afrozenRanges[block]; if (!afrozenRange.empty()) { os << std::string(kIndent, ' ') << punc("AFrozen:") << "\n"; disasmRange(os, afrozenRange.start(), afrozenRange.end()); } if (!blockRange.empty() || !acoldRange.empty() || !afrozenRange.empty()) { os << '\n'; } } os << std::string(kIndent - 2, ' '); auto next = block->empty() ? nullptr : block->next(); if (next) { os << punc("-> "); printLabel(os, next); os << '\n'; } else { os << "no fallthrough\n"; } }
void GridWidget::paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); qreal wantedHeight = CELL_HEIGHT * (ROW_COUNT + 1); qreal wantedWidth = FIRST_COL_WIDTH + CELL_WIDTH * COL_COUNT; qreal scaleWidth = width()/wantedWidth; qreal scaleHeight = height()/ wantedHeight; qreal minScale = qMin(scaleWidth, scaleHeight); painter.setRenderHint(QPainter::Antialiasing, true); painter.translate((width()-minScale*wantedWidth) /2,0); painter.scale(minScale,minScale); painter.fillRect(QRectF(0,0, wantedWidth, wantedHeight), QBrush(QColor("#FFF"))); painter.setPen(textColor); painter.setFont(QFont("Segoe UI", 8)); for(int row=1; row<ROW_COUNT+1; row++) { QRect textRect(0, row*CELL_HEIGHT, FIRST_COL_WIDTH, CELL_HEIGHT); QString rowLabel = QString("%1 - %2") .arg(1+(row-1)*32) .arg((row)*32); painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter)); } for(int col=0; col<COL_COUNT; col++) { QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, 0, CELL_WIDTH, CELL_HEIGHT); QString rowLabel = QString("%1") .arg(col+1); painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter)); } for(int row=0; row<ROW_COUNT; row++) for(int col=0; col<COL_COUNT; col++) { int address = row*COL_COUNT + col; QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, (row+1)*CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT); QString value = m_values[address]; if(!value.isEmpty()) { QColor fillColor = m_colors[address]; QString rowLabel = value; painter.fillRect(textRect, fillColor); painter.drawText(textRect, rowLabel, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter)); } } painter.setPen(gridLineColor); for(int row=0; row<ROW_COUNT + 1; row++) { QPoint start(0, row*CELL_HEIGHT); QPoint end(wantedWidth, row*CELL_HEIGHT); painter.drawLine(start, end); } for(int col=0; col<COL_COUNT + 1; col++) { QPoint start(FIRST_COL_WIDTH + col*CELL_WIDTH, 0); QPoint end(FIRST_COL_WIDTH + col*CELL_WIDTH, wantedHeight); painter.drawLine(start, end); } // Draw the highlight for the selected one if(m_selectedAddress>-1) { int col = m_selectedAddress % 32; int row = m_selectedAddress / 32; QRect textRect(FIRST_COL_WIDTH + col*CELL_WIDTH, (row+1)*CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT); painter.setPen(QColor(Qt::black)); painter.drawRect(textRect); } }
size_t size() { return end() - begin(); }
int main() { std::cout << std::unitbuf; Table table; { struct Fill { Section s; Chapter c; Page p; }; for (auto& tup : std::vector<Fill> { { "Jugement", 18 , 2 }, { "Conclusions", 11 , 1 }, { "Assignation", 43 , 1 }, { "Assignation", 43 , 2 }, { "Conclusions", 10 , 1 }, { "Jugement", 17 , 3 }, { "Assignation", 45 , 1 }, { "Jugement", 17 , 1 }, { "Conclusions", 9 , 1 }, { "Jugement", 17 , 2 }, { "Jugement", 18 , 1 }, }) { table[{tup.s, tup.c}] += tup.p; // add page to (existing) range } } std::cout << "------------- table: \n"; for (auto& r:table) std::cout << r << "\n"; { using rv = rw<Table::value_type>; std::vector<rv> vw(begin(table), end(table)); // blind shuffle srand(time(0)); std::random_shuffle(vw.begin(), vw.end()); // try to avoid subsequent modules from equal sections (dup) auto dup = [](rv a, rv b) { return a.get().first.section == b.get().first.section; }; auto it = vw.begin(); auto const e = vw.end(); while(it != e) // bit redundant, could be while(true) { std::cout << "------------- STATE: \n"; for (auto& rv:vw) std::cout << rv.get() << (it->get_pointer() == rv.get_pointer()? "*\n":"\n"); it = std::adjacent_find(it, e, dup); if (it == e) break; std::cout << "------------- dupes: \n"; std::cout << "\t" << (it+0)->get() << "\n"; std::cout << "\t" << (it+1)->get() << "\n"; auto m = std::find_if(it+1, e, [&] (rv r) { return r.get().first.section != it->get().first.section; }); if (m == e) { it = m; } else { std::cout << "------------- rotating to: \n"; std::cout << "\t" << m->get() << "\n"; std::rotate(it+1, m, e); it = std::adjacent_find(it, e, dup); } } std::cout << "------------- selection: \n"; for (auto& r : vw) std::cout << r.get() << "\n"; } }