Example #1
0
void write_db_users()
{
	m_write_db_users_time = srv_time();
	if (!m_use_sql)
		return;
	if (!m_torrents_users_updates_buffer.empty())
	{
		m_torrents_users_updates_buffer.pop_back();
		async_query("insert into " + db_name("files_users") + " (active, announced, completed, downloaded, `left`, uploaded, mtime, fid, uid) values "
			+ m_torrents_users_updates_buffer
			+ " on duplicate key update"
			+ "  active = values(active),"
			+ "  announced = announced + values(announced),"
			+ "  completed = completed + values(completed),"
			+ "  downloaded = downloaded + values(downloaded),"
			+ "  `left` = values(`left`),"
			+ "  uploaded = uploaded + values(uploaded),"
			+ "  mtime = values(mtime)");
		m_torrents_users_updates_buffer.erase();
	}
	async_query("update " + db_name("files_users") + " set active = 0 where mtime < unix_timestamp() - 60 * 60");
	if (!m_users_updates_buffer.empty())
	{
		m_users_updates_buffer.pop_back();
		async_query("insert into " + db_name("users") + " (downloaded, uploaded, " + db_name("uid") + ") values "
			+ m_users_updates_buffer
			+ " on duplicate key update"
			+ "  downloaded = downloaded + values(downloaded),"
			+ "  uploaded = uploaded + values(uploaded)");
		m_users_updates_buffer.erase();
	}
}
Example #2
0
bool ConfigReader::parse_obj(const std::string &key, std::string &obj,
		std::string &err)
{
	std::vector<std::string> items;
	std::string okey, oval;
	std::unordered_map<std::string, std::string> map;
	size_t ind;

	/* remove surrounding braces and whitespace */
	obj = obj.substr(1);
	remove_leading(obj);
	while (obj.back() != '}')
		obj.pop_back();
	obj.pop_back();
	while (isspace(obj.back()))
		obj.pop_back();

	utils::split(obj, '\n', items);

	for (std::string s : items) {
		if ((ind = s.find('=')) == std::string::npos) {
			err = "unrecognized token in list -- ";
			for (ind = 0; !isspace(s[ind]); ++ind)
				err += s[ind];
			return false;
		}
		okey = s.substr(0, ind);
		while (isspace(okey.back()))
			okey.pop_back();
		oval = parse_string(s);
		map[okey] = oval;
	}
	olistmap[key].emplace_back(map);
	return true;
}
Example #3
0
    void backtrack(int cur
            , int left_pare
            , int used_pairs
            , std::string& parenthesis)
    {
        if(cur==2*n_)
        {
            parenthesis_.push_back(parenthesis);
        }
        else
        {
            int left = n_-used_pairs-left_pare;
            int right = n_-used_pairs;

            if(left>0)
            {
                parenthesis.push_back('(');
                backtrack(cur+1, left_pare+1, used_pairs, parenthesis);
                parenthesis.pop_back();
            }

            if(left_pare>0 && right>0)
            {
                parenthesis.push_back(')');
                backtrack(cur+1, left_pare-1, used_pairs+1, parenthesis);
                parenthesis.pop_back();
            }
        }
    }
Example #4
0
    void generate(int l, int r)
    {
        if (l == 0)
        {
            for (int i = 0; i < r; ++i)
            {
                _s.push_back(')');
            }
            _res.push_back(_s);
            for (int i = 0; i < r; ++i)
            {
                _s.pop_back();
            }
            return ;
        }

        _s.push_back('(');
        generate(l-1, r);
        _s.pop_back();
        
        if (!_s.empty() && l < r)
        {
            _s.push_back(')');
            generate(l, r-1);
            _s.pop_back();
        }
    }
Example #5
0
bool CreditCard::Validate(std::string creditCardNumber)
{
    unsigned int sum=0;
    bool toggle=true;
    unsigned int otherCheckDigit=creditCardNumber.back() - '0';
    unsigned int myCheckDigit=0;

    creditCardNumber.pop_back();

    while(!creditCardNumber.empty())
    {
        unsigned int temp=creditCardNumber.back() - '0'; //saves last digit

        if (toggle)
        {
            temp= temp*2;

            if (temp>=10)
                temp=temp-9;
        }

        sum=sum+temp;

        toggle=!toggle;
        creditCardNumber.pop_back(); //deletes last digit
    }

    myCheckDigit= (sum*9)%10;

    return (otherCheckDigit==myCheckDigit);
}
bool GenericSocket::receive(int timeout, std::string &reply, int expected, bool raw)
{
	int length;
	int run;
	struct pollfd pfd = { .fd = fd, .events = POLLIN | POLLERR | POLLHUP, .revents = 0 };
	char buffer[8192];

	reply.clear();

	for(run = 8; run > 0; run--)
	{
		if(poll(&pfd, 1, timeout) != 1)
			return(false);

		if(pfd.revents & (POLLERR | POLLHUP))
			return(false);

		if((length = read(fd, buffer, sizeof(buffer) - 1)) < 0)
			return(false);

		if(length == 0)
		{
			if(reply.length() == 0) // ignore terminating empty udp packed from previous output
				continue;
			else
				break;
		}

		reply.append(buffer, (size_t)length);

		if((expected > 0) && (expected > length))
			expected -= length;
		else
			break;
	}

	if(reply.back() == '\n')
		reply.pop_back();

	if(!raw && (reply.back() == '\r'))
		reply.pop_back();

	return(true);
}

static std::string sha_hash_to_text(const unsigned char *hash)
{
	unsigned int current;
	std::stringstream hash_string;

	for(current = 0; current < SHA_DIGEST_LENGTH; current++)
		hash_string << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)hash[current];

	return(hash_string.str());
}
Example #7
0
void write_db_torrents()
{
	m_write_db_torrents_time = srv_time();
	if (!m_use_sql)
		return;
	try
	{
		std::string buffer;
		while (1)
		{
			for (auto& i : m_torrents)
			{
				t_torrent& file = i.second;
				if (!file.dirty)
					continue;
				if (!file.fid)
				{
					Csql_query(m_database, "insert into @files (info_hash, mtime, ctime) values (?, unix_timestamp(), unix_timestamp())")(i.first).execute();
					file.fid = m_database.insert_id();
				}
				buffer += Csql_query(m_database, "(?,?,?,?),")(file.leechers)(file.seeders)(file.completed)(file.fid).read();
				file.dirty = false;
				if (buffer.size() > 255 << 10)
					break;
			}
			if (buffer.empty())
				break;
			buffer.pop_back();
			async_query("insert into " + db_name("files") + " (" + db_name("leechers") + ", " + db_name("seeders") + ", " + db_name("completed") + ", " + db_name("fid") + ") values "
				+ buffer
				+ " on duplicate key update"
				+ "  " + db_name("leechers") + " = values(" + db_name("leechers") + "),"
				+ "  " + db_name("seeders") + " = values(" + db_name("seeders") + "),"
				+ "  " + db_name("completed") + " = values(" + db_name("completed") + "),"
				+ "  mtime = unix_timestamp()");
			buffer.clear();
		}
	}
	catch (bad_query&)
	{
	}
	if (!m_announce_log_buffer.empty())
	{
		m_announce_log_buffer.pop_back();
		async_query("insert delayed into " + db_name("announce_log") + " (ipa, port, event, info_hash, peer_id, downloaded, left0, uploaded, uid, mtime) values " + m_announce_log_buffer);
		m_announce_log_buffer.erase();
	}
	if (!m_scrape_log_buffer.empty())
	{
		m_scrape_log_buffer.pop_back();
		async_query("insert delayed into " + db_name("scrape_log") + " (ipa, uid, mtime) values " + m_scrape_log_buffer);
		m_scrape_log_buffer.erase();
	}
}
Example #8
0
std::string get_path(std::string f) {
    while (true) {
        if (f.empty())
            throw exception("failed to locate Lean executable location");
        if (f.back() == g_sep) {
            f.pop_back();
            return f;
        }
        f.pop_back();
    }
}
void SplitGltfAttribute(std::string attribute, std::string *semanticName, DWORD *semanticIndex)
{
    *semanticIndex = 0;

    if (isdigit(attribute.back()))
    {
        *semanticIndex = attribute.back() - '0';

        attribute.pop_back();
        if (attribute.back() == '_')
            attribute.pop_back();
    }

    *semanticName = attribute;
}
Example #10
0
LogLevel
Logging::findLevel(std::string mn) const
{
  while (!mn.empty()) {
    auto it = m_enabledLevel.find(mn);
    if (it != m_enabledLevel.end()) {
      return it->second;
    }
    size_t pos = mn.find_last_of('.');
    if (pos < mn.size() - 1) {
      mn = mn.substr(0, pos + 1);
    }
    else if (pos == mn.size() - 1) {
      mn.pop_back();
      pos = mn.find_last_of('.');
      if (pos != std::string::npos) {
        mn = mn.substr(0, pos + 1);
      }
      else {
        mn = "";
      }
    }
    else {
      mn = "";
    }
  }

  auto it = m_enabledLevel.find(mn);
  return it != m_enabledLevel.end() ? it->second : INITIAL_DEFAULT_LEVEL;
}
    void on_key(dick::Key key, bool down) override
    {
        if (!down) {
            return;
        }

        if (key >= dick::Key::A && key <= dick::Key::Z) {
            m_name.push_back(
                static_cast<int>(key) -
                static_cast<int>(dick::Key::A) +
                'A');

        } else if (key == dick::Key::SPACE) {
            m_name.push_back(' ');

        } else if (key == dick::Key::BACKSPACE && !m_name.empty()) {
            m_name.pop_back();

        } else if (key == dick::Key::ENTER) {
            m_high_score.add_entry(
                m_context->m_var.m_ball_count,
                { m_context->m_var.m_score, m_name });
            HighScore::store("high_score", m_high_score);
            t_transition_required = true;
        }
    }
Example #12
0
bool
OOFEMTXTDataReader :: giveRawLineFromInput(std :: ifstream &stream, int &lineNum, std :: string &line)
{
    //
    // reads one line from inputStream - for private use only.
    //
    do {
        lineNum++;
        std :: getline(stream, line);
        if ( !stream ) {
            return false;
        } if ( line.length() > 0 ) {
            if ( line.back() == '\\' ) {
                std :: string continuedLine;
                do {
                    lineNum++;
                    std :: getline(stream, continuedLine);
                    if ( !stream ) {
                        return false;
                    }
                    line.pop_back();
                    line += continuedLine;
                } while ( continuedLine.back() == '\\' );
            }
        }
    } while ( line.length() == 0 || line [ 0 ] == '#' ); // skip comments
    return true;
}
Example #13
0
 void unmake_move(std::string& to, int sz)
 {
     while((int)to.size()>sz)
     {
         to.pop_back();
     }
 }
Example #14
0
    void backtrack(int cur, int& nth, std::string& perm, std::vector<bool>& flags)
    {
        if(cur==n_)
        {
            if(++nth==k_) found_ = true;
            return;
        }
        else
        {
            for(int i=1; i<=n_; ++i)
            {
                if(!flags[i])
                {
                    flags[i]=true;
                    perm.push_back(i-0+'0');
                    backtrack(cur+1, nth, perm, flags);

                    if(found_) break;

                    flags[i]=false;
                    perm.pop_back();
                }
            }
        }
    }
Example #15
0
void unpack(std::vector<std::string>& leftcol, std::vector<std::string>& rightcol, std::vector<std::string> origv, std::string perm)
{
    std::string tempstring, leftval, rightval;
    std::vector<std::string> tempvec;
    int count = 0;
    while(std::find(origv.begin(), origv.end(), perm) == origv.end()) {
	tempvec = split(perm);
	perm = "";
	tempstring = tempvec.back();
	tempvec.pop_back();
	tempvec.insert(tempvec.begin(), tempstring);
	for(const auto &ref:tempvec)
	    perm += ref + " ";
	perm.pop_back();
	count++;
    }
    if(count != 0) {
        for(int i = 0; i < tempvec.size(); i++) {
            if(i < count) {
	        leftval += tempvec[i] + " ";
	    }
	    else {
	        rightval += tempvec[i] + " ";
	    }    
        }
    leftval.pop_back();
    rightval.pop_back();
    leftcol.push_back(leftval);
    rightcol.push_back(rightval);
    }
    else {
	leftcol.push_back(" ");
	rightcol.push_back(perm);
    }
}
BigNumber& BigNumber::operator*= (const BigNumber& rhs)
{
    BigNumber tmp(*this);
    if (is_negative ^ rhs.is_negative) {
        is_negative = true;
    }

    number = number + std::string(rhs.number.size(), 0);
    for(auto &c: number) {
        c = 0;
    }

    int carry = 0;
    for (int i = 0; i < tmp.number.size(); ++i) {
        carry = 0;
        for (int j =0; j < rhs.number.size() || carry; ++j) {
            int new_digit = number[i+j] + carry; 
            if (j < rhs.number.size()) { 
                new_digit += tmp.number[i]*rhs.number[j];
            }
            number[i+j] = new_digit % 10;
            carry = new_digit/10;
        }
    }
    while(number.back() == 0) {
        number.pop_back();
    }
    return *this;
}
Example #17
0
/**
* This method processes all of the layers in the level.
*/
void Level::processLayers(std::string& layer_text)
{
    // Remove all white space from the layer data because it may be indented, and spaces aren't needed.
    layer_text.erase(std::remove(layer_text.begin(), layer_text.end(), ' '), layer_text.end());

    // Remove newlines from the beginning and end of the layer data, as they would mess with splitting by lines.
    layer_text.erase(layer_text.begin());
    layer_text.pop_back();

    // Split the layer data by line.
    auto layer_data = Tools::splitString(layer_text, '\n');

    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            if (layer_data[y][x] == '2')
            {
                // Add walls.
                wall_rects.push_back({x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE});
            }
        }
    }

    map_data.push_back(layer_data);
}
Example #18
0
        void etcd_packer::pack_key_range(rapidjson::Value &json_val, const std::string &key, std::string range_end, rapidjson::Document &doc) {
            if ("+1" == range_end) {
                range_end      = key;
                bool need_plus = true;
                while (!range_end.empty() && need_plus) {
                    char c = range_end[range_end.size() - 1];
                    if (static_cast<unsigned char>(c) == 0xff) {
                        range_end.pop_back();
                    } else {
                        range_end[range_end.size() - 1] = c + 1;
                        need_plus                       = false;
                    }
                }

                if (range_end.empty() && need_plus && !key.empty()) {
                    range_end = "\0";
                }
            }

            if (!key.empty()) {
                pack_base64(json_val, "key", key, doc);
            }

            if (!range_end.empty()) {
                pack_base64(json_val, "range_end", range_end, doc);
            }
        }
Example #19
0
    void getting_pin()
    {
        incoming.wait()
        .handle<digit_pressed>(
        [&](digit_pressed const & msg) {
            unsigned const pin_length = 4;
            pin += msg.digit;

            if (pin.length() == pin_length) {
                bank.send(verify_pin(account, pin, incoming));
                state = &atm::verifying_pin;
            }
        }
        )
        .handle<clear_last_pressed>(
        [&](clear_last_pressed const & msg) {
            if (!pin.empty()) {
                pin.pop_back();
            }
        }
        )
        .handle<cancel_pressed>(
        [&](cancel_pressed const & msg) {
            state = &atm::done_processing;
        }
        );
    }
Example #20
0
char CreditCard::generateCheckSum(std::string numbers)
{
    unsigned int sum=0;
    bool toggle=true;
    unsigned int checkDigit=0;


    while(!numbers.empty())
    {
        unsigned int temp=numbers.back() - '0'; //saves last digit

        if (toggle)
        {
            temp= temp*2;

            if (temp>=10)
                temp=temp-9;
        }

        sum=sum+temp;

        toggle=!toggle;
        numbers.pop_back(); //deletes last digit
    }

    checkDigit= (sum*9)%10;

    return checkDigit+'0';
}
Example #21
0
	bool read_line( FILE* ft, std::string& line, unsigned int& content_start, int* current_line_num )
	{
		content_start = 0;
		bool something_found = false;
		bool start_found = false;
		for(;;) // through all chars - just read the line
		{
			char ch;
			int res = fread( &ch, 1, 1, ft );
			if ( res != 1 )
				break;
			something_found = true;
			if ( ch == '\n' )
			{
				(*current_line_num) ++;
				break;
			}
			line.push_back( ch );
			if ( !start_found && (ch == ' ' || ch == '\t') )
				content_start++;
			else
				start_found = true;
		}
		while ( line.size() && *(line.end()-1) == '\r' )
			line.pop_back();
		return something_found;
	}
Example #22
0
void CodeWriter::operator+=(std::string text) {
  while (true) {
    auto begin = text.find("{{");
    if (begin == std::string::npos) { break; }

    auto end = text.find("}}");
    if (end == std::string::npos || end < begin) { break; }

    // Write all the text before the first {{ into the stream.
    stream_.write(text.c_str(), begin);

    // The key is between the {{ and }}.
    const std::string key = text.substr(begin + 2, end - begin - 2);

    // Find the value associated with the key.  If it exists, write the
    // value into the stream, otherwise write the key itself into the stream.
    auto iter = value_map_.find(key);
    if (iter != value_map_.end()) {
      const std::string &value = iter->second;
      stream_ << value;
    } else {
      FLATBUFFERS_ASSERT(false && "could not find key");
      stream_ << key;
    }

    // Update the text to everything after the }}.
    text = text.substr(end + 2);
  }
  if (!text.empty() && string_back(text) == '\\') {
    text.pop_back();
    stream_ << text;
  } else {
    stream_ << text << std::endl;
  }
}
void SpellcheckingTrie::handlePossibleWrongVowel(Node* currentNode, std::string& currentSuggestion)
{
	for (auto i = 0; m_vowels[i] != '\0'; i++)
	{
		// Search for this vowel.

		auto vowel = m_vowels[i];
		auto parentVowelNode = currentNode->findChild(vowel);
		auto temp = parentVowelNode;

		// If we find a trie path with this vowel, then for each child node of the parentVowelNode,
		// continue down every trie path and build up all possible words. Later on we will sort through
		// all of the words that we find through this method to find the best one.

		if (parentVowelNode)
		{
			currentSuggestion.push_back(parentVowelNode->content());
			buildUpWordListFromNode(parentVowelNode, currentSuggestion);
			currentSuggestion.pop_back();
		}
	}

	if (m_suggestions.empty())
	{
		auto tempNode = currentNode;
		while ( !tempNode->wordMarker() )
		{
			tempNode = tempNode->firstChildNode();
			currentSuggestion.push_back(tempNode->content());
		}

		m_suggestions.insert(currentSuggestion);
	}
}
Example #24
0
std::string Model::cleanNamespaceTrailingChars(std::string ns) {
    static const std::set<char> IGNORED_LAST_CHARS = {'#', ':', '/'};
    if ( IGNORED_LAST_CHARS.count(ns.back()) ) {
        ns.pop_back();
    }
    return ns;
}
void RemoveOuterCharacters(std::string &str)
{
	assert(str.length() >= 2);

	// Always on front and back
	str.erase(str.begin());
	str.pop_back();
}
	std::string InputState::UpdateText(std::string pText)
	{ 
		pText += _text;
		if (_backspacePressed && pText.size() > 0)
			pText.pop_back();

		return pText;
	}
void compute_encoding (std::shared_ptr<BTN> root, 
        std::unordered_map<char, std::string>& encoding, 
        std::string& current_encoding)
{
    if (!root->left && !root->right) {
        assert(root->data->symbol != 0);
        encoding[root->data->symbol] = current_encoding;
        return;
    }
    current_encoding.push_back('0');
    compute_encoding(root->left, encoding, current_encoding);
    current_encoding.pop_back();

    current_encoding.push_back('1');
    compute_encoding(root->right, encoding, current_encoding);
    current_encoding.pop_back();
}
// trimEndOfLine()
// Requires:  std::string reference
// Returns:   None
// Trims end of line control characters from the passed string reference.
// Empty strings are ignored.
void trimEndOfLine(std::string &s) {
  char last;
  while(!s.empty() && ((strncmp(&(last = s.back()), "\n", 1) == 0) ||
		       (strncmp(&last, "\r", 1) == 0))) {
    //    if(kDoDebug) printf("Removed control character.\n");
    s.pop_back();
  }
}
 /*
  *  GetLastPathComponent
  *      @path: Path to get the last component from
  *      @return: Returns the last path component position in the string
  */
 inline std::string::size_type GetLastPathComponent(std::string path)
 {
     // Remove any slash at the end of the string, so our finding can be safe
     while(path.back() == '/' || path.back() == '\\') path.pop_back();
     // Do the search
     size_t pos = path.find_last_of("/\\");
     return (pos == path.npos? 0 : pos + 1);
 }
 /*
  *  NormalizePath
  *      Normalizates a path string, so for example:
  *          "somefolder/something" will output "somefolder\\something"
  *          "SOMEfoldER/something/" will output "somefolder\\something"
  *          "somefolder\\something" will output "somefolder\\something"
  *          etc
  */
 inline std::string NormalizePath(std::string path)
 {
     
     std::replace(path.begin(), path.end(), '/', '\\');  // Replace all '/' with '\\'
     tolower(path);                                      // tolower the strings (Windows paths are case insensitive)
     while(path.back() == '/' || path.back() == '\\')    // We don't want a slash at the end of the folder path
         path.pop_back();                                // ..
     trim(path);                                         // Trim the string...
     return path;
 }