int reverse(int x) { string s = to_string(x); bool hasNegative = false; if(s[0] == '-'){ hasNegative = true; } if(hasNegative){ int a = abs(x); s = to_string(a); string t = ""; for(unsigned long i = s.length() -1; i != 0 ; i --){ t += s[i]; } t += s[0]; string b = '-' + t; long long c = stoll(b); if(c < INT_MIN){ return 0; } return stoi(b); }else{ string t = ""; for(unsigned long i = s.length() -1; i != 0 ; i --){ t += s[i]; } t += s[0]; long long c = stoll(t); if(c > INT_MAX){ return 0; } return stoi(t); } }
RoleInfo* GameDB::GetRole(const ROLE_ID roleid) { const char* selectSQL = "select * from role where roleid = '%d'"; char sqlstr[1024] = {0}; snprintf(sqlstr,1024, selectSQL, roleid); auto func = [](char** result, int nCol, void* arg) { RoleInfo* roleinfo = (game::RoleInfo*)arg; int index=0; roleinfo = new RoleInfo(); roleinfo->roleID = stoll(result[index++]); roleinfo->rolename = result[index++]; roleinfo->accountID = stoll(result[index++]); roleinfo->money = stoll(result[index++]); roleinfo->exp = stoll(result[index++]); roleinfo->level = stoi(result[index++]); }; RoleInfo* roleinfo = nullptr; if(!((SQLiteInterface*)db)->Select(sqlstr, func, roleinfo)) return nullptr; }
int strobogrammaticInRange(string low, string high) { int n1 = (int) low.length(), n2 = (int) high.length(); long long l1 = stoll(low), l2 = stoll(high); if (stol(low) > stol(high)) return 0; int l = 0, h = 0, count = 0; vector<string> ls = helper(n1, n1); vector<string> hs = helper(n2, n2); for (string s : ls) { long long n = stoll(s); if (n < l1) l++; } for (string s : hs) { long long n = stoll(s); if (n > l2) h++; } vector<int> dp(n2 + 1, 0); for (int i = 0; i <= n2; i++) { if (i == 0) dp[i] = 0; else if (i == 1) dp[i] = 3; else if (i == 2) dp[i] = 4; else if (i == 3) dp[i] = 12; else dp[i] = dp[i-2] * 5; } for (int i = n1; i <= n2; i++) count += dp[i]; return count - l - h; }
//how states change between various states void create_states(i64 n, vector<vector<int> >& vtransit ) { //states gives us all effective numbers, the last one is n vector<string> states;//for each state, empty, a, ab, abc....; states.push_back(string()); string tstr(to_string(n)); for(unsigned int i = 0; i < tstr.size(); ++i){ states.push_back(tstr.substr(0,i+1)); } vtransit.clear(); //vtransit tells us how the state changes when we have //some new input vtransit.resize(states.size()); for(unsigned int i = 0; i < vtransit.size(); ++i){ vtransit[i].resize(states.size(), 0); } //the last state is not necessary to consider for(unsigned int j = 0; j < states.size()-1; ++j){ i64 n0 = 0; if(!states[j].empty()) n0 = stoll(states[j]); n0 *= 10; for(unsigned int i = 0; i < 10; ++i){ i64 num = n0 + i; string si(to_string(num)); int matched = check_states(si, j+1, states); ++vtransit[j][matched]; } } }
void get_results( const string &num, int start, const string ¤t, vector<string> &result, int target, int64_t val, int64_t last) { if (start >= num.length()) { if (!current.empty() && val == target) { result.push_back(current); } return; } string current_num_s = string(1, num[start]); for (int i=start+1; i<=num.length(); ++i) { if (current_num_s.length() > 1 && current_num_s[0] == '0') { return; } auto current_num = stoll(current_num_s); if (current.empty()) { get_results(num, i, current_num_s, result, target, current_num, current_num); } else { get_results(num, i, current + "+" + current_num_s, result, target, val + current_num, current_num); get_results(num, i, current + "-" + current_num_s, result, target, val - current_num, -current_num); get_results(num, i, current + "*" + current_num_s, result, target, val - last + last * current_num, last * current_num); } if (i != num.length()) { current_num_s.push_back(num[i]); } } }
void dfs_search(vector<string> &ans, string path, const string &num, int target, int pos, long value, long pre_num){ /* Put binary operator in pos, and then calculate the new value. @pre_num: when process *, we need to know the previous number. */ if(pos == num.size()){ if(value == target){ ans.push_back(path); } return; } for(int i=1; i+pos<=num.size(); i++){ string cur_str = num.substr(pos, i); // Digit can not begin with 0 (01, 00, 02 are not valid), except 0 itself. if(i>1 && cur_str[0] == '0') break; long cur_d = stoll(cur_str); if(pos==0){ dfs_search(ans, cur_str, num, target, pos+i, cur_d, cur_d); } // All three different binary operators: +, -, * else{ dfs_search(ans, path+"+"+cur_str, num, target, pos+i, value+cur_d, cur_d); dfs_search(ans, path+"-"+cur_str, num, target, pos+i, value-cur_d, -cur_d); dfs_search(ans, path+"*"+cur_str, num, target, pos+i, value-pre_num+pre_num*cur_d, cur_d*pre_num); } } }
UserInfo* GameDB::CheckAccount(const char* username, const char* password) { const char* selectSQL = "select * from account where username = '******' and password = '******'"; char sqlstr[1024] = {0}; snprintf(sqlstr,1024, selectSQL, username, password); auto user = new UserInfo(); auto func = [](char** result, int nCol, void* arg) { auto user =(UserInfo*)arg; user->id = stoll(result[0]); user->username = result[1]; user->password = result[2]; all_users_by_id[user->id]=user; all_users_by_name[user->username]=user; }; if(!((SQLiteInterface*)db)->Select(sqlstr, func, user)) return nullptr; return user; }
/** * Example of the config file: * 5 * A C g T * 0 5 2 5 * 5 0 5 2 * 2 5 0 5 * 5 2 5 0 * * i.e. * Line 1: Contains the gap cost * Line 2: Contains the alphabet (not case sentitive) * Line 3-|alphabet|: The score for any given combination, i.e. The (i,i)'th is the score of a match, all others * are scores for miss. In the above example (0, 3) is a miss between A and G. */ void Parser::parse_score_file() { ifstream fin; string line; fin.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { fin.open("config/score.cfg"); // Set the gap cost getline(fin, line); gap_cost = stoll(line); // Define the alphabet getline(fin, line); istringstream acids(line); string tmp; while (getline(acids, tmp, ' ')) { if (tmp.size() == 1) { char c = (char) toupper(tmp.c_str()[0]); proteins.push_back(c); } } // Set the score matrix const uint64_t SIZE = proteins.size(); score.resize(SIZE, vector<int64_t>(SIZE)); for (uint64_t i = 0; i < SIZE; i++) { getline(fin, line); istringstream current(line); uint64_t j = 0; while (getline(current, tmp, ' ')) { if (tmp.size() != 0) { score[i][j] = stoll(tmp); j++; } } } // Close the config file fin.close(); } catch (ifstream::failure e) { cerr << "Failed parsing config: Check that file exists, that permission are correct and that it is formatted correctly!" << endl; exit(EXIT_FAILURE); } catch (invalid_argument e) { cerr << "Could not parse config: Failed to " << e.what() << endl; } }
void Response::get_header( const string& name, long long& value, const long long default_value ) const { try { value = stoll( get_header( name ) ); } catch ( const invalid_argument& ) { value = default_value; } }
TCPMetadata Server::ExtractMetadata(std::string metadata) { TCPMetadata metadata_st; std::string value; std::stringstream ss(metadata); std::getline(ss, value, METADATA_DELIM); metadata_st.fileName = value; std::getline(ss, value, PATH_DELIM); metadata_st.progress = stoll(value); return metadata_st; }
void helper(string num, int target, long long diff, long long curNum, string tmp, vector<string> &res) { if (num.size()==0 && curNum==target) res.push_back(tmp); for (int i=1; i<=num.size(); i++) { string cur = num.substr(0, i); if (cur.size()>1 && cur[0]=='0') return; string next = num.substr(i); if (tmp.size()>0) { helper(next, target, stoll(cur), curNum+stoll(cur), tmp+'+'+cur, res); helper(next, target, -stoll(cur), curNum-stoll(cur), tmp+'-'+cur, res); helper(next, target, diff*stoll(cur), (curNum-diff)+diff*stoll(cur), tmp+'*'+cur, res); } else helper(next, target, stoll(cur), stoll(cur), cur, res); } }
my_int::my_int(const string &int_str) : sign(1) { decltype(int_str.size()) i, first_digit_index; if (!is_valid_int_str(int_str)) throw std::invalid_argument(int_str); if (int_str[0] == '-') { sign = 0; first_digit_index = 1; } else first_digit_index = 0; i = int_str.size(); while (i - first_digit_index >= my_digit_num) { my_digit_list.push_back( stoll(int_str.substr(i - my_digit_num, my_digit_num))); i -= my_digit_num; } if (i - first_digit_index > 0) my_digit_list.push_back( stoll(int_str.substr(first_digit_index, i - first_digit_index))); return; }
// USIプロトコル経由で値を設定されたときにそれをcurrentValueに反映させる。 Option& Option::operator=(const string& v) { ASSERT_LV1(!type.empty()); // 範囲外なら設定せずに返る。 // "EvalDir"などでstringの場合は空の文字列を設定したいことがあるので"string"に対して空の文字チェックは行わない。 if (((type != "button" && type != "string") && v.empty()) || (type == "check" && v != "true" && v != "false") || (type == "spin" && (stoll(v) < min || stoll(v) > max))) return *this; // ボタン型は値を設定するものではなく、単なるトリガーボタン。 // ボタン型以外なら入力値をcurrentValueに反映させてやる。 if (type != "button") currentValue = v; // 値が変化したのでハンドラを呼びだす。 if (on_change) on_change(*this); return *this; }
void dfs(string num, int target, long cur, long diff, string path, vector<string>& result) { if (num.empty() && target==cur) result.push_back(path); for (int i=1;i<num.size();i++) { string left=num.substr(0,i); string right=num.substr(i); long long val=stoll(left); if (left.size()>1 && left[0]=='0') return; if (path.empty()) dfs(right,target, val, val, left, result); else { dfs(right,target, cur+val, val, path+'+'+left, result); dfs(right,target, cur-val, val, path+'-'+left, result); dfs(right,target, cur-diff+val*diff, val*diff, path+'*'+left, result); } } }
void CustomIndexerPlugin::tearDown(const zcm::Json::Value& index, zcm::Json::Value& pluginIndex, zcm::LogFile& log) { std::cout << "sorting " << name() << std::endl; fseeko(log.getFilePtr(), 0, SEEK_END); off_t logSize = ftello(log.getFilePtr()); auto comparator = [&](off_t a, off_t b) { if (a < 0 || b < 0 || a > logSize || b > logSize) { std::cerr << "Sorting has failed. " << "Sorting function is probably broken. " << "Aborting." << std::endl; exit(1); } example_t msgA, msgB; const zcm::LogEvent* evtA = log.readEventAtOffset(a); assert(evtA); assert(msgA.decode(evtA->data, 0, evtA->datalen)); const zcm::LogEvent* evtB = log.readEventAtOffset(b); assert(evtB); assert(msgB.decode(evtB->data, 0, evtB->datalen)); return msgA.position[0] < msgB.position[0]; }; for (std::string channel : pluginIndex.getMemberNames()) { for (std::string type : pluginIndex[channel].getMemberNames()) { std::vector<off_t> offsets; for (size_t i = 0; i < pluginIndex[channel][type].size(); ++i) { std::string offset = pluginIndex[channel][type][(int)i].asString(); size_t sz = 0; long long off = stoll(offset, &sz, 0); assert(sz <= offset.length()); offsets.push_back((off_t) off); } std::sort(offsets.begin(), offsets.end(), comparator); for (size_t i = 0; i < pluginIndex[channel][type].size(); ++i) { pluginIndex[channel][type][(int)i] = std::to_string(offsets[i]); } } } }
long long parseLL(const char* n) { long long ret; uassert(13307, "cannot convert empty string to long long", *n != 0); #if !defined(_WIN32) char* endPtr = 0; errno = 0; ret = strtoll(n, &endPtr, 10); uassert(13305, "could not convert string to long long", *endPtr == 0 && errno == 0); #else size_t endLen = 0; try { ret = stoll(n, &endLen, 10); } catch (...) { endLen = 0; } uassert(13306, "could not convert string to long long", endLen != 0 && n[endLen] == 0); #endif // !defined(_WIN32) return ret; }
void helper(string num, string tmp, int target, long long diff, long long curNum){ if(num.size()==0 && curNum==target){ res.push_back(tmp); return; } for(int i = 1; i <= num.size(); ++i){ string cur = num.substr(0, i); if(cur.size()>1 && cur[0]=='0') return; string next = num.substr(i); if(tmp.size()){ helper(next, tmp+"+"+cur, target, stoll(cur), curNum+stoll(cur)); helper(next, tmp+"-"+cur, target, -stoll(cur), curNum-stoll(cur)); helper(next, tmp+"*"+cur, target, diff*stoll(cur), (curNum-diff)+diff*stoll(cur)); } else helper(next, cur, target, stoll(cur), stoll(cur)); } }
void helper(string num, int target, string path, int start, long long diff, long long curNum) { if(start==num.size() && target==curNum) { res.push_back(path); return; } for(int i = start; i < num.size(); ++i) { string cur = num.substr(start, i+1-start); if(cur.size()>1 && cur[0]=='0') return; if(path.size()) { helper(num, target, path+"+"+cur, i+1, stoll(cur), curNum+stoll(cur)); helper(num, target, path+"-"+cur, i+1, -stoll(cur), curNum-stoll(cur)); helper(num, target, path+"*"+cur, i+1, diff * stoll(cur), curNum-diff+diff*stoll(cur)); } else helper(num, target, cur, i+1, stoll(cur), stoll(cur)); } }
// for creating ranges in lookup tables // input s=lower limit in hex, m=manuf name OuiRange::OuiRange(std::string s, std::string m) { const std::string hexWithSlash = "0123456789ABCDEFabcdef/"; int mask; strncpy(manufDesc, m.c_str(), sizeof(manufDesc)); std::string cleaned; for (char c : s) { if (hexWithSlash.find(c) != std::string::npos) cleaned += c; } if (cleaned.find('/') == std::string::npos) { if (cleaned.length() == 6) { cleaned += "/24"; } if (cleaned.length() == 12) { cleaned += "/48"; } } if (cleaned.length() < 15) { int pad = 15 - cleaned.length(); for (int i = 0; i < pad; i++) { cleaned.insert(cleaned.length() - 3, "0"); } } lowerLimit = stoll(cleaned.substr(0, 12), 0, 16); mask = stoi(cleaned.substr(13, 2), 0, 10); upperLimit = lowerLimit + std::pow(2, 48 - mask); }
void GameDB::GetRoleList(const ACCOUNT_ID accountid, std::vector< RoleInfo* >* roles) { const char* selectSQL = "select roleid,rolename,level from role where accountid = '%d'"; char sqlstr[1024] = {0}; snprintf(sqlstr,1024, selectSQL, accountid); auto func = [](char** result, int nCol, void* arg) { vector< game::RoleInfo* >* roles = (vector< game::RoleInfo* >*)arg; int index=0; RoleInfo* r = new RoleInfo(); r->roleID = stoll(result[index++]); r->rolename = result[index++]; r->level = stoi(result[index++]); roles->push_back(r); }; ((SQLiteInterface*)db)->Select(sqlstr, func, roles); }
long long parseLL( const char *n ) { long long ret; uassert( 13307, "cannot convert empty string to long long", *n != 0 ); #if !defined(_WIN32) char *endPtr = 0; errno = 0; ret = strtoll( n, &endPtr, 10 ); uassert( 13305, "could not convert string to long long", *endPtr == 0 && errno == 0 ); #elif _MSC_VER>=1600 // 1600 is VS2k10 1500 is VS2k8 size_t endLen = 0; try { ret = stoll( n, &endLen, 10 ); } catch ( ... ) { endLen = 0; } uassert( 13306, "could not convert string to long long", endLen != 0 && n[ endLen ] == 0 ); #else // stoll() wasn't introduced until VS 2010. char* endPtr = 0; ret = _strtoi64( n, &endPtr, 10 ); uassert( 13310, "could not convert string to long long", (*endPtr == 0) && (ret != _I64_MAX) && (ret != _I64_MIN) ); #endif // !defined(_WIN32) return ret; }
long long stoll(Iterable &object) { return stoll(std::begin(object), std::end(object)); }
long long operator()(const std::string& s) { return stoll(s); }
AtomPtr Atom::fromJson(std::istream& is) { int next_ch = skipWhitespace(is); switch (next_ch) { case 'n': { readChar(is); if ((readChar(is) == 'u') && (readChar(is) == 'l') && (readChar(is) == 'l')) return Atom::make(); else throw runtime_error("Syntax error"); } case 't': { readChar(is); if ((readChar(is) == 'r') && (readChar(is) == 'u') && (readChar(is) == 'e')) return Atom::make(true); else throw runtime_error("Syntax error"); } case 'f': { readChar(is); if ((readChar(is) == 'a') && (readChar(is) == 'l') && (readChar(is) == 's') && (readChar(is) == 'e')) return Atom::make(false); else throw runtime_error("Syntax error"); } default: break; } // end switch // ostringstream os{}; NumberState state = NumberState::START; bool isPositive = true; bool isDecimal = false; while (state != NumberState::DONE) { next_ch = is.peek(); if (next_ch == -1) break; switch (state) { case NumberState::START: switch (next_ch) { case '-': os << '-'; state = NumberState::AFTER_SIGN; readChar(is); isPositive = false; break; case '0': os << '0'; state = NumberState::AFTER_INITIAL_ZERO; readChar(is); break; default: digit(static_cast<char>(next_ch)); os << static_cast<char>(next_ch); state = NumberState::AFTER_FIRST_DIGIT; readChar(is); break; } // end switch(ch) // break; case NumberState::AFTER_SIGN: switch (next_ch) { case '0': os << '0'; state = NumberState::AFTER_INITIAL_ZERO; readChar(is); break; default: digit(static_cast<char>(next_ch)); os << static_cast<char>(next_ch); state = NumberState::AFTER_FIRST_DIGIT; readChar(is); break; } // end switch(ch) // break; case NumberState::AFTER_INITIAL_ZERO: switch (next_ch) { case -1: state = NumberState::DONE; break; case '.': os << '.'; state = NumberState::AFTER_PERIOD; readChar(is); isDecimal = true; break; case 'e': case 'E': os << 'e'; state = NumberState::AFTER_EXPONENT; readChar(is); isDecimal = true; break; default: state = NumberState::DONE; break; } // end switch(ch) // break; case NumberState::AFTER_FIRST_DIGIT: switch (next_ch) { case -1: state = NumberState::DONE; break; case '.': os << '.'; state = NumberState::AFTER_PERIOD; readChar(is); isDecimal = true; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': os << static_cast<char>(next_ch); readChar(is); break; case 'e': case 'E': os << 'e'; state = NumberState::AFTER_EXPONENT; readChar(is); isDecimal = true; break; default: state = NumberState::DONE; break; } // end switch(ch) // break; case NumberState::AFTER_PERIOD: digit(static_cast<char>(next_ch)); os << static_cast<char>(next_ch); state = NumberState::AFTER_DEC_DIGIT; readChar(is); break; case NumberState::AFTER_DEC_DIGIT: switch (next_ch) { case -1: state = NumberState::DONE; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': os << static_cast<char>(next_ch); readChar(is); break; case 'e': case 'E': os << 'e'; state = NumberState::AFTER_EXPONENT; readChar(is); isDecimal = true; break; default: state = NumberState::DONE; break; } // end switch(ch) // break; case NumberState::AFTER_EXPONENT: switch (next_ch) { case '+': case '-': os << static_cast<char>(next_ch); state = NumberState::AFTER_EXPONENT_SIGN; readChar(is); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': os << static_cast<char>(next_ch); state = NumberState::AFTER_EXPONENT_DIGIT; readChar(is); break; default: throw runtime_error( "Unexpected character '" + to_string(static_cast<char>(next_ch)) + "' in state " + to_string(static_cast<int>(state))); } // end switch(ch) // break; case NumberState::AFTER_EXPONENT_SIGN: digit(static_cast<char>(next_ch)); os << static_cast<char>(next_ch); state = NumberState::AFTER_EXPONENT_DIGIT; readChar(is); break; case NumberState::AFTER_EXPONENT_DIGIT: switch (next_ch) { case -1: state = NumberState::DONE; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': os << static_cast<char>(next_ch); readChar(is); break; default: state = NumberState::DONE; break; } // end switch(ch) // break; default: throw runtime_error("Invalid number state " + to_string(static_cast<int>(state))); } // end switch (state) // } // end for // if (state != NumberState::DONE) throw runtime_error("Premature end of number in state " + to_string(static_cast<int>(state))); try { string t = os.str(); if (!isDecimal) { if (isPositive) { unsigned long long _v = stoll(t); return Atom::make(static_cast<uint64_t>(_v)); } else { // is negative: signed long long _v = strtoll(t.c_str(), 0, 0); return Atom::make(static_cast<int64_t>(_v)); } } // Here we must handle with double: double _v = stod(t); return Atom::make(_v); } catch (const exception& ex) { throw runtime_error(string("Invalid number format: ") + ex.what()); } catch (...) { throw runtime_error("Invalid number format"); } }
/* Split the large input file into multiple chunks, and physically dump each chuck into a file in the disk */ int split_input_file(const char *input_filename, int &number_of_chunks) { string line; // A file line int split_num = 0; // File split index; int count = 0; // Count estimated number of bytes added to a file // Open the input file for reading ifstream input_file_ptr(string(input_filename), ifstream::in); // Error exception if(! input_file_ptr.is_open()) return -1; // Error in opening a file int i = 0; char dirname[20]; sprintf(dirname, "split_%d", i); mkdir(dirname, S_IRWXU); // Open an output file for writing char output_filename[100]; sprintf(output_filename, "split_%d/data_part_%d.txt", i, split_num); ofstream output_file_ptr; output_file_ptr.open( string(output_filename), ofstream::out | ofstream::app ); // Error exception if(! output_file_ptr.is_open()) return -2; // Error in openeing a file vector<string> vec; int flag = 1; while(getline(input_file_ptr, line)) { vec.push_back(line); // Add an estimated value count += LINE_SIZE_EST; // Maximum allowable file limit if(count > FILE_SIZE_LIMIT) { int k = 0; for(k = 0; k < vec.size();k++) output_file_ptr << vec[k] << endl; output_file_ptr.close(); char ff[100]; sprintf(ff, "split_%d/split_index.txt", i); long long key = stoll(vec[0].substr(0, line.find(" "))); FILE *fd = fopen(ff, "a"); fprintf(fd, "%lld %d\n", key, split_num); fclose(fd); vec.clear(); // Close the current opened output file cout << "*** SPLIT: File: " << split_num << " is done" << endl; split_num++; if(split_num % 100 == 0) { i++; char dirname[20]; sprintf(dirname, "split_%d", i); mkdir(dirname, S_IRWXU); } // Generate a new output file name with different split sprintf(output_filename, "split_%d/data_part_%d.txt", i, split_num); // Open a new file with different split number for writing output_file_ptr.open( string(output_filename), ofstream::out | ofstream::app ); // Error exception if(! output_file_ptr.is_open()) return -2; // Error in openeing a file // Zero out the count to start counting again count = 0; } } if(! vec.empty()) { int k = 0; for(k = 0; k < vec.size();k++) output_file_ptr << vec[k] << endl; output_file_ptr.close(); char ff[100]; sprintf(ff, "split_%d/split_index.txt", i); long long key = stoll(vec[0].substr(0, line.find(" "))); FILE *fd = fopen(ff, "a"); fprintf(fd, "%lld %d\n", key, split_num); fclose(fd); vec.clear(); cout << "**** Write the residual\n\n"; } cout << "*** SPLIT: File: " << split_num << " is done (LAST ONE)" << endl; output_file_ptr.close(); input_file_ptr.close(); // Number of generated files number_of_chunks = split_num + 1; return 1; // Success flags }