void beFriend(string s1, string s2){ if(graph.find(s1) == graph.end())//Finish statment graph.emplace(s1,node(s1)); if(graph.find(s2) == graph.end()) graph.emplace(s2, node(s2)); graph.at(s1).attach(&graph.at(s2)); }
void* GPUMemory::thread_pinned_buffer(size_t size, int group) { CHECK_GT(size, 0); auto host_buffer_cleaner = [&](void* buffer) { shared_lock<shared_mutex> lock(GPUMemory::read_write_mutex()); CUDA_CHECK(cudaFreeHost(buffer)); }; auto device_buffer_cleaner = [&](void* buffer) {}; static thread_local unordered_map<int, unique_ptr<void, decltype(host_buffer_cleaner)>> host_buffers; static thread_local unordered_map<int, unique_ptr<void, decltype(device_buffer_cleaner)>> device_buffers; static thread_local vector<size_t> sizes; if (group + 1U > sizes.size()) { sizes.resize(group + 1U); } if (size > sizes[group]) { void* hptr; void* dptr; CUDA_CHECK(cudaHostAlloc(&hptr, size, cudaHostAllocMapped)); CUDA_CHECK(cudaHostGetDevicePointer(&dptr, hptr, 0)); host_buffers.emplace(std::make_pair(group, unique_ptr<void, decltype(host_buffer_cleaner)>(hptr, host_buffer_cleaner))); device_buffers.emplace(std::make_pair(group, unique_ptr<void, decltype(device_buffer_cleaner)>(dptr, device_buffer_cleaner))); sizes[group] = size; } return device_buffers.find(group)->second.get(); }
contractor mk_contractor_gsl(box const & box, shared_ptr<ode_constraint> const ctr, contractor const & eval_ctc, ode_direction const dir, bool const use_cache, double const timeout) { if (!use_cache) { return contractor(make_shared<contractor_gsl>(box, ctr, eval_ctc, dir, timeout)); } if (dir == ode_direction::FWD) { static unordered_map<shared_ptr<ode_constraint>, contractor> gsl_fwd_ctc_cache; auto it = gsl_fwd_ctc_cache.find(ctr); if (it == gsl_fwd_ctc_cache.end()) { contractor ctc(make_shared<contractor_gsl>(box, ctr, eval_ctc, dir, timeout)); gsl_fwd_ctc_cache.emplace(ctr, ctc); return ctc; } else { return it->second; } } else { static unordered_map<shared_ptr<ode_constraint>, contractor> gsl_bwd_ctc_cache; auto it = gsl_bwd_ctc_cache.find(ctr); if (it == gsl_bwd_ctc_cache.end()) { contractor ctc(make_shared<contractor_gsl>(box, ctr, eval_ctc, dir, timeout)); gsl_bwd_ctc_cache.emplace(ctr, ctc); return ctc; } else { return it->second; } } }
shared_ptr<Event> read() { uint8_t buffer_in[3]; snd_rawmidi_read(handle_in, &buffer_in, 3); shared_ptr<NoteOnEvent> note_on, note_off; switch ( buffer_in[0] & 0xF0 ) { case MIDI_NOTE_ON: if ( buffer_in[2] ) { note_on = shared_ptr<NoteOnEvent>(new NoteOnEvent { buffer_in[1], buffer_in[2] }); open_notes.emplace(buffer_in[1], note_on); return note_on; } else { note_on = open_notes.at(buffer_in[1]); open_notes.erase(buffer_in[1]); return shared_ptr<Event>(new NoteOffEvent { note_on }); } case MIDI_NOTE_OFF: note_on = open_notes.at(buffer_in[1]); open_notes.erase(buffer_in[1]); return shared_ptr<Event>(new NoteOffEvent { note_on }); case MIDI_CONTROL: return shared_ptr<Event>(new ControlEvent { static_cast<ControlEvent::Controller>(buffer_in[1]), buffer_in[2] }); default: return shared_ptr<Event>(new Event {}); } }
//从构造好的树中挖掘频繁项集 void FPTree::mineTree(string &prefix, unordered_map<string,int> &frequent) { //头指针列表head中存储的实际是单频繁项。根据项值和计数值构造节点,插入到集合 //不同于建树时,此时是按照计数值从低到高顺序排序 vector<node> key_count; for (auto iter = head.begin(); iter != head.end(); ++iter) key_count.emplace_back(node(iter->first, iter->second->count)); sort(key_count.begin(), key_count.end(), node::comparer::less()); for (auto iter = key_count.begin(); iter != key_count.end(); ++iter) {//对于每一个单频繁项 prefix.append(iter->key); frequent.emplace(prefix + ')',iter->count); //发现一个频繁项 unordered_map<string, int> subdata; //以当前单频繁项为尾,在树中上溯挖掘条件基,也就是在已出现prefix的情况下挖掘记录 findPrefixPath(iter->key, subdata); FPTree subtree(eps); subtree.create(subdata); //根据挖掘到的记录构造的子数据集创建子FP树,以用于挖掘更复杂的频繁项 if (!subtree.empty()) {//如果树不空,即存在更复杂的频繁项 prefix += ' ';//用于分隔记录项 subtree.mineTree(prefix, frequent); //继续递归挖掘 prefix.pop_back(); //删除空格 } int index = prefix.rfind(' '); if (index == string::npos) prefix.resize(1); //删除iter->key else prefix.resize(index + 1); } }
pairSet appendProyectionParametrized( pairSet candidates, vector <seq_pointer_hash> &database, // int threshold, sequence_hash &prefix, // unordered_map <hashConv, vector<seq_pointer_hash> > &exit, unordered_map <string, int> &options){ pairSet::iterator candStart, candEnd; candStart = candidates.begin(); candEnd = candidates.end(); pairSet output; vector<seq_pointer_hash>::iterator dataStart, dataEnd, reset; dataStart = database.begin(); dataEnd = database.end(); //Best spot for parallelism, do all of candidate threads and only thread 3 or 4 proyections at a time //to not bother with things that fail threshold pretty fast int limit = database.size() - threshold; while(candStart!=candEnd){ vector <seq_pointer_hash> projectionResult; int complement =0; while((complement<=limit) && (dataStart!=dataEnd)){ seq_pointer_hash p1 = dataStart->proyect(candStart->first, candStart->second); if (p1.null()){++complement;} else{projectionResult.push_back(p1);} ++dataStart; }if(complement<=limit){ exit.emplace(convert(*candStart), projectionResult); output.insert(*candStart); } dataStart = database.begin(); ++candStart; } return output; }
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ bool insert(int val) { if (hash.find(val) != hash.end()) return false; nums.push_back(val); hash.emplace(val, nums.size() - 1); return true; }
string compressStringHelper(string in, unordered_map<string, string>& record) { if (in.empty()) { return ""; } auto it = record.find(in); if (it != record.end()) { return it->second; } const int s = in.size(); string res; res = in[0] + compressStringHelper(in.substr(1), record); for (int i = 1; i < s; ++i) { string tmp_r = compressStringHelper(in.substr(i + 1), record); int w_size = 1; string tmp_l = in.substr(0, i + 1); for (int w_size = 1; w_size <= (i + 1) / 2; ++w_size) { string tmp = encode(in.substr(0, i + 1), w_size); if (tmp.size() < tmp_l.size()) { tmp_l = tmp; } } if (res.size() > tmp_l.size() + tmp_r.size()) { res = tmp_l + tmp_r; } } record.emplace(move(in), res); return res; }
void copyGraph( unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> &mapping, UndirectedGraphNode *vertex) { if (mapping.find(vertex) == mapping.end()) { mapping.emplace(vertex, new UndirectedGraphNode(vertex->label)); for (auto *neighbor : vertex->neighbors) { copyGraph(mapping, neighbor); } } }
inline int testNadd(const char *s) { auto p = map.find(s); if (p == map.end()) { parent[cnt] = cnt; sizes[cnt] = 1; map.emplace(s, cnt); return cnt++; } else return p->second; }
contractor mk_contractor_eval(box const & box, nonlinear_constraint const * const ctr) { static thread_local unordered_map<nonlinear_constraint const *, contractor> cache; auto const it = cache.find(ctr); if (it == cache.cend()) { contractor ctc(make_shared<contractor_eval>(box, ctr)); cache.emplace(ctr, ctc); return ctc; } else { return it->second; } }
//挖掘条件基,实际上是(条件)路径 void FPTree::findPrefixPath(const string& tail, unordered_map<string, int> &paths) { treeNode *first = head[tail]->ptreenode; while (first) {//对于当前键为tail的节点 string prefix; ascendTree(first, prefix);//由此上溯到根获得条件基 if (!prefix.empty())//如果条件基存在 paths.emplace(move(prefix), first->count); first = first->next; } }
// Returns a resource by name. Creates the resource // if it doesn't yet exist. T& operator[](string name) { // Convert the string to lowercase. transform(name.begin(), name.end(), name.begin(), tolower); // Create the object if it doesn't exist. auto it = objects.find(name); if (it == objects.end()) { it = objects.emplace(name, name).first; } return it->second; }
// Initializes FMOD Studio and loads all sound banks. Audio() : Listener(system) { // Create the FMOD Studio system. FmodCall(fmod::System::create(&system)); // Initialize the system. FmodCall(system->initialize( maxChannels, // max channels capable of playing audio FMOD_STUDIO_INIT_NORMAL, // studio-specific flags FMOD_INIT_3D_RIGHTHANDED, // regular flags nullptr)); // extra driver data vector<fmod::Bank*> banks; // For each file in the Sounds directory with a *.bank extension: for (const string& file : PathInfo(config::Sounds).FilesWithExtension("bank")) { // Load the sound bank from file. fmod::Bank* bank = nullptr; FmodCall(system->loadBankFile(file.c_str(), FMOD_STUDIO_LOAD_BANK_NORMAL, &bank)); banks.push_back(bank); } for (fmod::Bank* bank : banks) { // Get the number of events in the bank. int eventCount = 0; FmodCall(bank->getEventCount(&eventCount)); if (eventCount == 0) continue; // Get the list of event descriptions from the bank. auto eventArray = vector<fmod::EventDescription*>(static_cast<size_t>(eventCount), nullptr); FmodCall(bank->getEventList(eventArray.data(), eventArray.size(), nullptr)); // For each event description: for (fmod::EventDescription* eventDescription : eventArray) { // Get the path to the event, e.g. "event:/Ambience/Country" auto path = string(512, ' '); int retrieved = 0; FmodCall(eventDescription->getPath(&path[0], path.size(), &retrieved)); path.resize(static_cast<size_t>(retrieved - 1)); // - 1 to account for null character // Save the event description in the event map. eventDescriptionMap.emplace(path, EventDescription(eventDescription, path)); } } Note(*this); }
int populate_hashmap(int i) { std::this_thread::sleep_for(std::chrono::nanoseconds(i*i*i*i*i*i*i)); cout<<"Move-assigned thread creation for value "<<i<<" ..."<<endl; hashmap.emplace(std::make_pair(std::to_string(i),i)); if (i%2 == 0) { hashmap.max_load_factor(hashmap.max_load_factor()*3); } else { hashmap.rehash(3); } }
contractor mk_contractor_eval(shared_ptr<nonlinear_constraint> const ctr, bool const use_cache) { if (!use_cache) { return contractor(make_shared<contractor_eval>(ctr)); } static unordered_map<shared_ptr<nonlinear_constraint>, contractor> eval_ctc_cache; auto const it = eval_ctc_cache.find(ctr); if (it == eval_ctc_cache.end()) { contractor ctc(make_shared<contractor_eval>(ctr)); eval_ctc_cache.emplace(ctr, ctc); return ctc; } else { return it->second; } }
//根据数据集构建FP树 void FPTree::create(const unordered_map<string, int> &data) { unordered_map<string, int> umkey_count;//记录所有的键,即每个记录项,以及计数 string k; for (auto iter1 = data.begin(); iter1 != data.end(); ++iter1) //第一次扫描整个数据集 {//每条记录都是字符串对象,采用空格分开 istringstream stream(iter1->first); //初始化一个字符串输入流 while (stream >> k) {//逐一获得记录项 if (umkey_count.find(k) == umkey_count.end()) //如果不存在于头指针列表,则插入 umkey_count.emplace(move(k), iter1->second); else //否则只需要累加计数值即可 umkey_count[k] += iter1->second; } } for (auto iter2 = umkey_count.begin(); iter2 != umkey_count.end(); ++iter2) {//扫描每个记录项 if (iter2->second >= eps) //把较高频数的记录项留下 { head.emplace(iter2->first, new headNode(iter2->second)); } } if (head.empty()) return; //如果没有出现次数超过阈值的记录项,则退出 for (auto iter3 = data.begin(); iter3 != data.end(); ++iter3) {//第二次扫描整个数据集 //对于每条记录,根据记录项和出现的总次数构造节点,然后插入到集合 vector<node> key_count; istringstream stream(iter3->first); while (stream >> k) {//对于该条记录中的每个记录项 if (head.find(k) != head.end()) //只有出现次数较高 key_count.emplace_back(node(k, head[k]->count)); //才会被插入到集合中 } if (!key_count.empty()) {//若最终该条记录中有出现次数较多的项 sort(key_count.begin(), key_count.end(), node::comparer::greater()); vector<string> order; //则按照出现次数从高到低的顺序提取出来 for_each(key_count.begin(), key_count.end(), [&order](const node &arg){order.emplace_back(arg.key); }); updateTree(order, 0, root, iter3->second);//用于更新树 } } }
int ComputeBinomialCoefficient::coefficientHelper(int n, int k, unordered_map<pair<int, int>, int, PairHash> &map) { assert(n >= 1 && n >= k); if (k == 0 || k == n) return 1; pair<int, int> intPair{n, k}; unordered_map<pair<int, int>, int, PairHash>::const_iterator it = map.find(intPair); if (it != map.end()) return it->second; int firstPart = coefficientHelper(n - 1, k, map); int secondPart = coefficientHelper(n - 1, k - 1, map); int res = firstPart + secondPart; map.emplace(intPair, res); return res; }
void init(const char* name, const ConfigSet::Entry* list, const map<string, string>& profile) { for (const ConfigSet::Entry* e = list; e && e->key; ++e) { ConfigSet::Entry newent = *e; string varname = ::config_var_name(name, e->key); // See if there is an entry in the config profile auto it = profile.find(varname); if (it != profile.end()) newent.value = it->second.c_str(); // See if there is a config variable set char* val = getenv(::config_var_name(name, e->key).c_str()); if (val) newent.value = val; m_dict.emplace(make_pair(string(e->key), newent)); } }
double waveSpectrum(float w) { if (w == 0){ return 0; } else { auto record = spectrum_lookup.find(w); if (record != spectrum_lookup.end()) { return record->second; } } float Tp = 15; float wp = 2*PI/Tp; float Hs = 100.0; float gamma = 3; float sigma; if (w <= wp) { sigma = 0.07; } else { sigma = 0.09; } float a = 5.0/(32*PI); float b = Hs*Hs*Tp; float c = pow((wp/w), 5); float d = exp(-5.0/4.0*pow((wp/w), 4)); float e = (1-0.287*log(gamma)); float f = pow(gamma, exp(-(pow((w/wp)-1, 2)/(2*sigma*sigma)))); float spectrum = a*b*c*d*e*f; spectrum_lookup.emplace(w, spectrum); cout<<spectrum<<endl; return spectrum; }
bool class_registerClass(Class cls, Class superClass) { // cls->super_class = superClass; return runtime_class_hashmap.emplace(cls->name, cls).second; }
// Adds a new model instance. shared_ptr<ModelInstance> AddModel() { auto result = models.emplace(modelCounter++, make_shared<ModelInstance>()); auto it = result.first; return it->second; }
friendGraph(){ graph.emplace("Quinn", node("Quinn")); graph.at("Quinn").depth = 0; graph.at("Quinn").visited = true; }
int main() { vector<string> x; string start; while(cin >> name1 >> name2) { if(graph.empty()) { start = name1; } if(graph.count(name1) == 0) { if(graph.count(name2) == 0) { //neither are in graph.emplace(name1, x); color.emplace(name1, "WHITE"); d.emplace(name1, 0); graph.emplace(name2, x); color.emplace(name2, "WHITE"); d.emplace(name2, 0); graph[name1].push_back(name2); graph[name2].push_back(name1); } else { //name1 is not in, but name2 is graph.emplace(name1, x); color.emplace(name1, "WHITE"); d.emplace(name1, 0); graph[name1].push_back(name2); graph[name2].push_back(name1); } } else if(graph.count(name1) > 0) { if(graph.count(name2) == 0) { //name1 is in, but not name2 graph.emplace(name2, x); color.emplace(name2, "WHITE"); d.emplace(name2, 0); graph[name1].push_back(name2); graph[name2].push_back(name1); } else { //both are in graph[name1].push_back(name2); graph[name2].push_back(name1); } } } BFS(start); }
int main(int argc, char **argv) { int port = 8080; if (argc > 1) { port = strtoul(argv[1], 0, 10); } std::array<uint8_t, 1024> recv_buffer; try { boost::asio::io_service service; boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::udp::v6(),port); boost::asio::ip::udp::socket socket(service, endpoint);/*server stuff*/ boost::asio::ip::udp::endpoint source; /*server's endpoint*/ std::function<void(boost::system::error_code, size_t)> handler = [&](boost::system::error_code err, size_t length) { auto msg = reinterpret_cast<const Message*>(recv_buffer.data()); cout << "INCOMMING" << endl; switch (msg->type) { case MessageType::Connect:{ ID id = id_counter++; auto result = clients.emplace(id, Client{ id,source,socket,Clock::now()}); result.first->second.send(MessageType::Connect, &id, sizeof(id)); break; } case MessageType::Disconnect: if (msg->size == sizeof(ID)) { auto id = *reinterpret_cast<const ID*>(msg->data); auto it = clients.find(id); clients.erase(it); } break; case MessageType::Status: { if (msg->size < sizeof(StatusMessage)) { cerr << "error" << endl; } else { auto pm = reinterpret_cast<const StatusMessage*> (msg->data); cout << "Recevied Status Message from: " << pm->id << endl; for (auto &client : clients) { if (client.first != pm->id) { client.second.send(MessageType::Status, msg->data, msg->size); } else { client.second.last_packet = Clock::now(); client.second.endpoint = source; } } } } break; case MessageType::Attack: { if (msg->size < sizeof(AttackMessage)) { cerr << "error" << endl; } else { auto pm = reinterpret_cast<const AttackMessage*> (msg->data); cout << "Recevied Attack Message from: " << pm->id << endl; for (auto &client : clients) { if (client.first != pm->id) { client.second.send(MessageType::Attack, msg->data, msg->size); } else { client.second.last_packet = Clock::now(); client.second.endpoint = source; } } } } } socket.async_receive_from(boost::asio::buffer(recv_buffer.data(), recv_buffer.size()), source, handler); }; socket.async_receive_from(boost::asio::buffer(recv_buffer.data(), recv_buffer.size()), source, handler); service.run(); } catch (exception e) { cerr << e.what() << endl; } return 0; }
int main(int argc, char** argv) { bool success = true; ostringstream oss; commands.emplace("help", Command(nullptr, help_options, "usage: fclip help [<command>]\n\n" "Display help information about a command." )); commands.emplace("add", Command(add_run, add_options, "usage: fclip add [<options>] [<files>...]\n\n" "Add one or more files to the clipboard. If no files are specified\n" "as arguments, they will be read from standard input." )); commands.emplace("clear", Command(clear_run, clear_options, "usage: fclip clear\n\n" "Remove all files from the clipboard." )); commands.emplace("for-each", Command(forEach_run, forEach_options, "usage: fclip for-each [<base-dir>] [<options>]\n" "aliases: foreach, each\n\n" "Perform actions for each file in the clipboard.\n" "If a base-dir is specified, only files in that directory\n" "will be processed." )); commands.emplace("list", Command(list_run, list_options, "usage: fclip list [<dir>]\n" "alias: ls\n\n" "Show the state of each of the files in the current directory\n" "or a given directory. The following file states are possible:\n" " [+] in clipboard\n" " [*] in clipboard and marked as 'recursive'\n" " [^] in clipboard because of a 'recursive' parent directory\n" " [>] not in clipboard, but contains files that are\n" " [ ] not in clipboard at all" )); commands.emplace("remove", Command(remove_run, remove_options, "usage: fclip remove [<files>...]\n" "alias: rm\n\n" "Remove one or more files from the clipboard. If no files are specified\n" "as arguments, they will be read from standard input." )); oss.str(""); oss << "usage: fclip stash [ push | pop [<id>] | drop [<id>] | list | clear ]\n\n" << "Manipulate the stack of saved clipboard states ('stashes'):\n" << left << setw(24) << " stash [push]" << "stash the current clipboard on the top\n" << setw(24) << " stash pop [<id>] " << "restore a stash\n" << setw(24) << " stash drop [<id>]" << "remove a stash\n" << setw(24) << " stash list" << "list all stashes\n" << setw(24) << " stash clear" << "remove all stashes"; commands.emplace("stash", Command(stash_run, stash_options, oss.str())); commands.emplace("status", Command(status_run, status_options, "usage: fclip status\n\n" "Show info about the clipboard." )); try{ po::options_description options = general_options(); po::variables_map vm; po::parsed_options parsed = po::command_line_parser(argc, argv) .options(options).allow_unregistered().run(); po::store(parsed, vm); po::notify(vm); vector<string> subargs = po::collect_unrecognized(parsed.options, po::include_positional); if(vm.count("help") || subargs.empty()) { subargs.insert(subargs.begin(), "help"); if(subargs.empty()){ help_run(subargs); return EXIT_FAILURE; } } string cmd = expandCommand(subargs[0]); subargs.erase(subargs.begin()); if(cmd == "help"){ help_run(subargs); return EXIT_FAILURE; } try{ DBus::default_dispatcher = &dispatcher; DBus::Connection bus = DBus::Connection::SessionBus(); FclipClient fclip(bus); auto it = commands.find(cmd); if(it == commands.end()){ throw runtime_error("unrecognised command or option '" + cmd + "'"); } (*it).second.action(subargs, fclip); for(const string &str : serverMessages){ err() << str << endl; } }catch(const DBus::Error &e){ err() << "failed to connect to fclip server" << endl; return EXIT_FAILURE; } }catch(const exception &e){ err() << e.what() << endl; return EXIT_FAILURE; } return success ? EXIT_SUCCESS : EXIT_FAILURE; }