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)); }
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 {}); } }
bool populateVec7Messages(unordered_map<string,string>& htabVecMessages){ ifstream infile(vec7messagesFileName); if(infile.is_open()){ string line; while(getline(infile,line)){ if(line.find(",") != string::npos){ vector<string> messageLine = splitStringByDelimiter(line,','); if(messageLine.size() == 2){ string key = trimWhiteSpaces(messageLine[0]); string value = messageLine[1]; if(htabVecMessages.find(key) != htabVecMessages.end()){ string temp = htabVecMessages.at(key); temp = temp + ";" + value; htabVecMessages.at(key) = temp; } else htabVecMessages.insert(make_pair<string,string>(key,value)); } } } infile.close(); } else return false; return true; }
void UpdateArrow(const Arrow &a) { if (status_by_arrow.count(a) > 0) return; int node2 = ArrowEnd(a); Status status = statii.at(a.first); bool found_reverse = false; for (const auto &ia : incoming_arrows.at(a.first)) { assert(ArrowEnd(ia) == a.first); //cout << " ia " << ia << " " << ArrowEnd(ia) << endl; if (ia.first == node2) { found_reverse = true; continue; } UpdateArrow(ia); status.Merge(status_by_arrow.at(ia)); } // cout << "UA " << a << " " << node2 << endl; assert(!incoming_arrows.at(a.first).empty()); // todo: remove in non-tree case if (!incoming_arrows.at(a.first).empty()) assert(found_reverse); status_by_arrow[a] = status.Translate(a.second, dfa); }
/* get_code_indexes */ pair<unsigned long, unsigned long> get_code_indexes(string& origin, string& destin, unordered_map<string, unsigned long> code_index_map) { bool bad_origin = false; bool bad_destin = false; unsigned long origin_index; unsigned long destin_index; try { origin_index = code_index_map.at(origin); } catch(out_of_range& e) { bad_origin = true; } try { destin_index = code_index_map.at(destin); } catch(out_of_range& e) { bad_destin = true; } if(bad_origin && bad_destin) { cerr << "\nTerminating: The origin & destin airport codes provided were not found" << endl; exit(1); } else if(bad_origin) { cerr << "\nTerminating: The origin airport code provided was not found" << endl; exit(1); } else if(bad_destin) { cerr << "\nTerminating: The destin airport code provided was not found" << endl; exit(1); } return make_pair(origin_index, destin_index); }
void get_value_ides(string id, unsigned long threshold){ timeb first_uniq; ftime(&first_uniq); string snps = "[\"OK\",["; unsigned long index = ides_name_index.at(id); unsigned long related_samples = 0; for(unsigned long i=0; i<num_samples; i++){ if(matrix[index][i] <= threshold && i!=index){ snps.append("\""+ides_index_name.at(i)+"\"").append(","); related_samples++; } } //f(snps.length() > 0) snps.pop_back(); if(snps.length() > 0 && related_samples>0) snps.pop_back(); snps.append("]]"); cout << snps << endl; timeb end_first_uniq; ftime(&end_first_uniq); int dif = (int)((end_first_uniq.time*1000+end_first_uniq.millitm)-(first_uniq.time*1000+first_uniq.millitm)); write_log("{action:get_value, time:"+std::to_string(dif)+", date:"+current_date_time()+"}"); }
void user_predictions(unordered_map<string, size_t> &items, unordered_map<string, size_t> &users, vector<vector<float>> &items_stats, vector<vector<float>> &users_stats, vector<vector<pair<size_t, float>>> &ranking_user, vector<vector<string>> &targets, vector<size_t> target_users, vector<float> &predictions, vector<float> &missing_predictions, float **users_fvs) { for (size_t index = 0; index < targets.size(); index++) { float item_avg = 5; // getting the item bias size_t item_pos; if (items.find(targets[index][1]) != items.end()) { item_pos = items.at(targets[index][1]); item_avg = items_stats[item_pos][1]; if (item_avg == 0) item_avg = 5; } // Look for the user within the ranking if (users.find(targets[index][0]) != users.end()) { float user_avg = 0; size_t query_pos =users.at(targets[index][0]); // Capturing the average rating from the nearest neighbors of the user float base = 0; size_t target_user_index = find_by_value<size_t>(target_users, query_pos); for (size_t vect_index = 0; vect_index < NN; vect_index++) { size_t user_pos = ranking_user[target_user_index][vect_index].first; float value = users_fvs[user_pos][item_pos]; if ((value == 0) || isnan(value)) value = users_stats[user_pos][1]; #ifdef DEBUG cout << ranking_user[target_user_index][vect_index].second << "*" << value << endl; #endif user_avg += ranking_user[target_user_index][vect_index].second * value; base += ranking_user[target_user_index][vect_index].second; } // Average them user_avg /= base; if (base == 0) { predictions.push_back(item_avg); missing_predictions.push_back(index); } else predictions.push_back(user_avg); } else { predictions.push_back(item_avg); if (items.find(targets[index][1]) == items.end()) missing_predictions.push_back(index); } // if (index == targets.size() - 1) // cout << "Last" << endl; } }
void printGraph(){ queue<node*> list; list.push(&graph.at("Quinn")); while(!list.empty()){ node*n = list.front(); list.pop(); for(node* n2 : n->neighbours){ if(n2->visited == false){ list.push(n2); n2->depth=(n->depth+1); n2->visited = true; } } } vector<string> vec; for(auto ele = graph.begin(); ele != graph.end(); ++ele){ string s = ""; if(ele->second.depth < 0) s = ele->first + " uncool"; else s= ele->first + " " + to_string(ele->second.depth); vec.push_back(s); } sort(vec.begin(),vec.end()); for(string ele : vec) cout << ele <<endl; }
string Student::GetMajor2Description() const { if (!major2_) { return "NA"; } double major_code{major2_.get()}; assert(major_code_map.count(major_code) == 1); return major_code_map.at(major_code); }
void embed_in_soource_code(set<string>& sourceFiles,unordered_map<string,set<string>>& htabLines,int returnValue){ for(set<string>::iterator it=sourceFiles.begin();it!=sourceFiles.end();it++){ ifstream infile(*it); int intIndexOfDelimiter = (*it).find_first_of("."); string rawFileName = (*it).substr(0,intIndexOfDelimiter); string fileExtension = (*it).substr(intIndexOfDelimiter+1,(*it).size()-intIndexOfDelimiter-1); string tempOutputFileName = rawFileName + "_temp." + fileExtension; ofstream outfile(tempOutputFileName); int ct = 0; string line; if(infile.is_open()){ while(getline(infile,line)){ ct++; string strCount = std::to_string(static_cast<long long>(ct)); string strKey = (*it) + ";" + strCount; if(htabLines.find(strKey) != htabLines.end()){ set<string> reasons = htabLines.at(strKey); string sourceLine = line + "/* " + addCategory(reasons) + " */"; outfile<<sourceLine<<endl; } else{ outfile<<line<<endl; } } infile.close(); outfile.close(); } string finalOutputFileName = rawFileName + "_out." + fileExtension; string cmdRemoveLineFeedCharacters = "sed -e 's/\r//g' " + tempOutputFileName + " > " + finalOutputFileName; returnValue = executeCommand(cmdRemoveLineFeedCharacters); returnValue = executeCommand("rm " + tempOutputFileName); } }
/** Runs a sequence of graph algorithm tests on the input graph. Will emit an exception if either (a) any algorithm throws an an exception and that algorithm is not named in except_on, (b) an algorithm named in except_on does not throw, or (c) any algorithm's output is different than specified in the 'expect' map @param[in] g The input graph @param[in] source The source vertex for algorithms that need one @param[in] destination The destination vertex for algorithms that need one @param[in] except_on The algorithms that should throw an exception @param[in] expect A map indicating the expected output of each algorithm @return void */ void graph_tests(const digraph &g, digraph::nodename source, digraph::nodename destination, const set<string> & except_on, unordered_map<string,string> expect ) { auto exc_return = [] () { cout << "Caught Expected Exception" << endl; return string("Exception"); }; auto tst = [exc_return, except_on, expect] (string fcn, auto a) { auto exc_test = [except_on, fcn] () { return except_on.end()!=except_on.find(fcn); }; auto normal_return = [fcn] (auto retval) { stringstream ss; ss << fcn << " visiting " << retval; cout << ss.str() << endl; return ss.str(); }; expect_exception_l(a, exc_test, exc_return, normal_return, expect.at(fcn) ); }; cout << endl << "=====> Beginning a test set" << endl; tst("BFS", [g, source] () { return g.bfs(source); } ); tst("DFS", [g, source] () { return g.dfs(source); } ); tst("Topsort", [g] () { return g.topsort(); } ); tst("Dijkstra", [g, source, destination] () { return g.dijkstra(source, destination); } ); tst("Bellman", [g, source] () { return get<0>(g.bellman_ford(source).get()); } ); };
/* * This function takes a MAP and compares it with the MASTER_MAP to create the vector of frequency for a * given document: Output is an unordered_map<string, int> in relation with the master_map */ unordered_map <string, int> computeVector(const unordered_map <string, int> & FILE_MAP, const unordered_map<string, int> & MASTER_MAP){ unordered_map<string, int> FILE_VECTOR; FILE_VECTOR.insert(MASTER_MAP.begin(), MASTER_MAP.end()); // Make a copy of the master map // cout << "(" ; for(MAP_ITER IT = FILE_VECTOR.begin(); IT != FILE_VECTOR.end(); ++IT){ unordered_map<string, int>::const_iterator FILE_IT = FILE_MAP.find(IT->first); string KEY = IT->first; // Get the first key pointed by the iterator if(FILE_IT == FILE_MAP.end()){ // If the word is not there then set it to zero FILE_VECTOR.at(KEY) = 0; }else{ // Else set it to the file frequency FILE_VECTOR.at(KEY) = FILE_MAP.at(KEY); } // cout << FILE_VECTOR[KEY] << ", "; } // cout << ")" << endl;; return FILE_VECTOR; }
unordered_map<char, int> bfs(const vector<string>&grid, char source, const unordered_map<char, pair<int, int>>& locations) { static const vector<pair<int, int>> directions{{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; int r, c; tie(r, c) = locations.at(source); vector<vector<bool>> lookup(grid.size(), vector<bool>(grid[0].size())); lookup[r][c] = true; queue<tuple<int, int, int>> q; q.emplace(r, c, 0); unordered_map<char, int> dist; while (!q.empty()) { int r, c, d; tie(r, c, d) = q.front(); q.pop(); if (source != grid[r][c] && grid[r][c] != '.') { dist[grid[r][c]] = d; continue; } for (const auto& dir : directions) { int cr = r + dir.first, cc = c + dir.second; if (!((0 <= cr && cr < grid.size()) && (0 <= cc && cc < grid[0].size()))) { continue; } if (grid[cr][cc] != '#' && !lookup[cr][cc]) { lookup[cr][cc] = true; q.emplace(cr, cc, d + 1); } } } return dist ; }
shared_ptr<Material> FileParser::fetchMaterial(const Json::Value& materialNode, const unordered_map<string, shared_ptr<Material>>& materials) const { string name = parseString(materialNode, "material name"); try { return materials.at(name); } catch (const out_of_range& e) { throw RenderException("Unable to find material: \"" + name + "\""); } }
word TruthTableUtils::reorderBits(word x, uint bitCount, const unordered_map<uint, uint>& reorderMap) { word y = 0; for (uint index = 0; index < bitCount; ++index) y |= ((x >> index) & 1) << reorderMap.at(index); return y; }
void avg_predictions_personalized(unordered_map<string, size_t> &users, unordered_map<string, size_t> &items, const vector<vector<float>> &users_stats, const vector<vector<float>> &items_stats, const vector<vector<string>> &targets, vector<float> &predictions, vector<float> &missing_predictions) { { for (int index = 0; index < targets.size(); index++) { float user_avg = 5; float item_avg = 5; // getting the user bias if (users.find(targets[index][1]) != users.end()) { size_t user_pos = users.at(targets[index][1]); user_avg = users_stats[user_pos][1]; } if (items.find(targets[index][0]) != items.end()) { int item_pos = items.at(targets[index][0]); item_avg = items_stats[item_pos][1]; #ifdef BIAS predictions.push_back(user_avg + items_stats[item_pos][1]); #else predictions.push_back(items_stats[item_pos][1]); #endif } else if (users.find(targets[index][1]) != users.end()) { predictions.push_back(user_avg); } else { predictions.push_back(user_avg); missing_predictions.push_back(index); } if (predictions[index] > 10) { cout << "Error " << predictions[index] << "= " << item_avg << " + " << user_avg << endl; predictions[index] = 10; } if (predictions[index] < 0) { cout << "Error " << predictions[index] << "= " << item_avg << " + " << user_avg << endl; predictions[index] = 00; } } } }
void Node::PrintChildren(const unordered_map<int, string>& vocabulary, vector<string>* print_vector, int children_size=3) const { vector<pair<Link*, double>> link_weight; for (const auto& child: children_) { link_weight.push_back(make_pair(get<1>(child), get<2>(child))); } auto SortLinksByWeightDesc = [](const pair<Link*, double>& link1, const pair<Link*, double>& link2) { return link1.second > link2.second; }; sort(link_weight.begin(), link_weight.end(), SortLinksByWeightDesc); vector<string> pool; int count = children_size; for (const auto& child_link: link_weight) { if (count <= 0) return; auto child_node = child_link.first->GetChildNode(); if (child_node->IsContentUnit()) { string content_unit = vocabulary.at(child_node->GetId()); unsigned int min_distance = 100; for (const auto& unit: pool) { unsigned int distance = edit_distance(unit, content_unit); if (distance < min_distance) { min_distance = distance; } } if (min_distance > 4) { std::ostringstream s; if (count == children_size) { s << content_unit << ": " << child_link.second; } else { s << content_unit << ": " << child_link.second; } print_vector->push_back(s.str()); pool.push_back(content_unit); --count; } } /*else { // auto descendents = child_node->GetChildNode(); // vector<string> sub_print_vector; // child_node->PrintChildren(vocabulary, &sub_print_vector, 1); // for (const string& element: sub_print_vector) { // s << element; // } std::ostringstream s; s << "[" << vocabulary.at(child_node->GetId()) << "]: " << child_link.second << ", "; print_vector->push_back(s.str()); }*/ // --children_size; } // print_vector->push_back(" ..."); }
unordered_map<id_t, id_t> overlay_node_translations(const unordered_map<id_t, id_t>& over, const unordered_map<id_t, id_t>& under) { unordered_map<id_t, id_t> overlaid; overlaid.reserve(over.size()); for (const pair<id_t, id_t>& node_trans : over) { overlaid[node_trans.first] = under.at(node_trans.second); } return overlaid; }
/*! Prints gnuplot commands and data to plot given variable in 2d. */ void write_gnuplot_cmd_2d( ofstream& gnuplot_file, const std::array<double, 3>& grid_geom_start, const std::array<double, 3>& grid_geom_length, const std::array<uint64_t, 3>& grid_size, const std::array<size_t, 2>& dimensions, const unordered_map<uint64_t, HD_Conservative>& simulation_data, const std::vector<uint64_t>& cells, const std::string& common_cmd, const std::string& output_file_name_prefix, const std::string& output_file_name_suffix, const std::string& var_name, const std::string& var_cmd, const std::function<double(const HD_Conservative& data)>& value_for_plot ) { const auto grid_size1 = grid_size[dimensions[0]], grid_size2 = grid_size[dimensions[1]]; const auto grid_start1 = grid_geom_start[dimensions[0]], grid_start2 = grid_geom_start[dimensions[1]], grid_length1 = grid_geom_length[dimensions[0]], grid_length2 = grid_geom_length[dimensions[1]]; gnuplot_file << common_cmd << "set output '" << output_file_name_prefix + "_" << var_name << "." << output_file_name_suffix << "'\nset ylabel 'Dimension " << boost::lexical_cast<std::string>(dimensions[1] + 1) << "'\nset xlabel 'Dimension " << boost::lexical_cast<std::string>(dimensions[0] + 1) << "'\nset xrange[" << boost::lexical_cast<std::string>(grid_start1) << " : " << boost::lexical_cast<std::string>(grid_start1 + grid_length1) << "]" << "\nset yrange[" << boost::lexical_cast<std::string>(grid_start2) << " : " << boost::lexical_cast<std::string>(grid_start2 + grid_length2) << "]\n" << var_cmd << "\nplot '-' using ($1 / " << grid_size1 << " * " << grid_length1 << " + " << grid_start1 << "):($2 / " << grid_size2 << " * " << grid_length2 << " + " << grid_start2 << "):3 matrix with image title ''\n"; for (size_t i = 0; i < cells.size(); i++) { gnuplot_file << value_for_plot(simulation_data.at(cells[i])) << " "; if (i % grid_size1 == grid_size1 - 1) { gnuplot_file << "\n"; } } gnuplot_file << "\nend\nreset\n"; }
shape_ptr interpreter::make_text (param begin, param end) { DEBUGF ('f', range (begin, end)); auto iter = begin; void* font_to_use = fontcode.at(*iter++); string txt = *iter++; for(; iter != end; ++iter){ txt.append(" " + *iter); } return make_shared<text> (font_to_use, txt); }
void get_values_neighbour(string id, string idrelated){ timeb first_uniq; ftime(&first_uniq); string snps = "[\"OK\","; unsigned long index = ides_name_index.at(id); unsigned long indexrelated = ides_name_index.at(idrelated); snps.append(to_string(matrix[index][indexrelated])); snps.append("]"); cout << snps << endl; timeb end_first_uniq; ftime(&end_first_uniq); int dif = (int)((end_first_uniq.time*1000+end_first_uniq.millitm)-(first_uniq.time*1000+first_uniq.millitm)); write_log("{action:get_value_neighbour, time:"+std::to_string(dif)+", date:"+current_date_time()+"}"); }
unordered_map<id_t, pair<id_t, bool>> overlay_node_translations(const unordered_map<id_t, pair<id_t, bool>>& over, const unordered_map<id_t, pair<id_t, bool>>& under) { unordered_map<id_t, pair<id_t, bool>> overlaid; overlaid.reserve(over.size()); for (const pair<id_t, pair<id_t, bool>>& node_trans : over) { const pair<id_t, bool>& trans_thru = under.at(node_trans.second.first); overlaid[node_trans.first] = make_pair(trans_thru.first, trans_thru.second != node_trans.second.second); } return overlaid; }
/* * method isBuiltFromDictionaryWords * @input: * dictionary - in the first call the unordered_map contains all the words in the input list with value "true". during the processing it is enhanced to * hold all the strings that are examined so far as keys, with value "true" if the key is a word or made of words or false otherwise or false otherwize * str - string to check if built from dictionary words * @output: true if str can be split to words from the given dictionary, false otherwise */ bool isBuiltFromDictionaryWords(string& str, unordered_map<string, bool>& dictionary) { if(dictionary.find(str) != dictionary.end()) // memoization is used to save examining the same strings in different calls { return dictionary.at(str); } string prefix =""; for (unsigned int i = 0 ; i < str.size(); i++) { prefix+=str[i]; if (dictionary.find(prefix) != dictionary.end() && dictionary.at(prefix) == true) { string cont = str.substr(i+1); if(isBuiltFromDictionaryWords(cont, dictionary) ) return true; } } dictionary.insert(pair<string, bool>(str, false)); return false; }
ll product(unordered_map<ll,ll> const & xs, unordered_map<ll,ll> const & ys, ll acc, ll k) { ll cnt = 0; for (auto it : xs) { ll x, xcnt; tie(x, xcnt) = it; ll y = - (acc + x); y = (y % k + k) % k; if (ys.count(y)) { ll ycnt = ys.at(y); cnt += xcnt * ycnt; } } return cnt; }
/* * Find an edge in the hash table corresponding to NODE & ASCIICHAR */ Edge Edge::findEdge(int node, int asciiChar) { long key = returnHashKey(node, asciiChar); unordered_map<long, Edge>::const_iterator search = edgeHash.find(key); if (search != edgeHash.end()) { // cout << "Entry found for " << node << " " << asciiChar << endl; return edgeHash.at(key); } // cout << "Entry NOT found for " << node << " " << asciiChar << endl; // Return an invalid edge if the entry is not found. return Edge(); }
void buildPaths(const string& word, const string& beginWord, const unordered_map<string, vector<string>>& parents, vector<string>& path, vector<vector<string>>& result) { if (word == beginWord) { result.push_back(vector<string>(path.rbegin(), path.rend())); return; } for (const string& p: parents.at(word)) { path.push_back(p); buildPaths(p, beginWord, parents, path, result); path.pop_back(); } }
int fMem (int n){ try{ return table.at(n);; } catch(const out_of_range& e){ list<int> needed = next(n); list<int> result; for(int i: needed) result.push_back(fMem(i)); return (table[n] = action(result, n)); } }
// print the list void DoublyLinkedList::print(unordered_map<string, double> &map, double cashBal) { double totVal = 0; if (isListEmpty()) { cout << "List is empty" << endl; } else { Node *currentPtr = headPtr; cout << "Ticker Number Price per share TotalValue" << endl; while (currentPtr != 0) { totVal += ( map.at(currentPtr->ticker) * currentPtr->numberOfShares) ; cout << currentPtr->ticker << " " << currentPtr->numberOfShares << " "<< map.at(currentPtr->ticker) <<" " << map.at(currentPtr->ticker) * currentPtr->numberOfShares <<endl; // increment currentPtr = currentPtr->nextPtr; } } cout << "Total portfolio value: " << totVal + cashBal << endl; }
void Union(int x, int y) { int x_root = Find(x); int y_root = Find(y); assert(x_root != y_root); if (rank.at(x_root) < rank.at(y_root)) { up.at(x_root) = y_root; } else if (rank.at(x_root) > rank.at(y_root)) { up.at(y_root) = x_root; } else { up.at(y_root) = x_root; rank.at(x_root)++; } }
// calculate the total value of share and store it in each node void DoublyLinkedList::totalValueCalculation(unordered_map <string, double> &newUmap) { double totVal = 0; Node *currentPtr = headPtr; while (currentPtr != 0) { currentPtr->totalValueOfShare= (newUmap.at(currentPtr->ticker) * currentPtr->numberOfShares); // increment currentPtr = currentPtr->nextPtr; } }