text:
#pragma once

#include <boost/serialization/array.hpp>
#include <boost/serialization/nvp.hpp>

#include <numeric/PlaneFitting.hpp>

namespace boost { namespace serialization
{

    /** Serializes base::TransformWithCovariance */
    template<typename _Archive,typename ScalarType>
    inline void serialize(
        _Archive & ar,
        ::numeric::PlaneFitting<ScalarType>& pf,
        const unsigned int version)
    {
        ar & boost::serialization::make_nvp("x", pf.x);
        ar & boost::serialization::make_nvp("y", pf.y);
        ar & boost::serialization::make_nvp("z", pf.z);
        ar & boost::serialization::make_nvp("xx", pf.xx);
        ar & boost::serialization::make_nvp("yy", pf.yy);
        ar & boost::serialization::make_nvp("xy", pf.xy);
        ar & boost::serialization::make_nvp("xz", pf.xz);
        ar & boost::serialization::make_nvp("yz", pf.yz);
        ar & boost::serialization::make_nvp("zz", pf.zz);
        ar & boost::serialization::make_nvp("n", pf.n);
    }

}}

ext: hpp


text:
/***************************************************************************
 *   Copyright (C) 2008-2021 by Andrzej Rybczak                            *
 *   andrzej@rybczak.net                                                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.              *
 ***************************************************************************/

#include <boost/locale.hpp>
#include "charset.h"
#include "settings.h"

namespace Charset {

std::locale internalLocale()
{
	boost::locale::generator gen;
	std::locale loc = gen("");
	bool is_utf = std::use_facet<boost::locale::info>(loc).utf8();
	std::string name = std::use_facet<boost::locale::info>(loc).name();
	if (!is_utf && name != "C" && name != "POSIX")
	{
		// if current locale does not use unicode, use variant of this
		// locale with utf8 as mpcplus uses utf8 internally and we need
		// current locale for sorting, case conversions etc.
		std::string new_name = std::use_facet<boost::locale::info>(loc).language()
		                     + "_"
		                     + std::use_facet<boost::locale::info>(loc).country()
		                     + ".UTF-8";
		loc = gen(new_name);
	}
	return loc;
}

std::string toUtf8From(const std::string &s, const char *charset)
{
	return boost::locale::conv::to_utf<char>(s, charset);
}

std::string fromUtf8To(const std::string &s, const char *charset)
{
	return boost::locale::conv::to_utf<char>(s, charset);
}

std::string utf8ToLocale(const std::string &s)
{
	return Config.system_encoding.empty()
	     ? s
	     : boost::locale::conv::from_utf<char>(s, Config.system_encoding);
}

std::string localeToUtf8(const std::string &s)
{
	return Config.system_encoding.empty()
	     ? s
	     : boost::locale::conv::to_utf<char>(s, Config.system_encoding);
}

std::string utf8ToLocale(std::string &&s)
{
	if (!Config.system_encoding.empty())
		s = boost::locale::conv::from_utf<char>(s, Config.system_encoding);
	return std::move(s);
}

std::string localeToUtf8(std::string &&s)
{
	if (!Config.system_encoding.empty())
		s = boost::locale::conv::to_utf<char>(s, Config.system_encoding);
	return std::move(s);
}

}

ext: cpp

max_stars_repo_name: doctorfree/mpcplus

max_issues_repo_name: doctorfree/mpcplus

max_forks_repo_name: doctorfree/mpcplus


text:
//////////////////////////////////////////////////////////////////////////////////////////////
/// \file ParseSphere.hpp
/// \brief Parses a sphere dataset, as released with iSAM1
///
/// \author Sean Anderson, modified from iSAM1 parsing tools
//////////////////////////////////////////////////////////////////////////////////////////////

#ifndef STEAM_PARSE_SPHERE_HPP
#define STEAM_PARSE_SPHERE_HPP

#include <stdio.h>
#include <iostream>
#include <vector>

#include <Eigen/Core>
#include <lgmath.hpp>

namespace steam {
namespace data {

//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Structure used to store relative edge measurements
//////////////////////////////////////////////////////////////////////////////////////////////
struct SphereEdge {
  unsigned int idA;
  unsigned int idB;
  lgmath::se3::Transformation T_BA;
  Eigen::MatrixXd sqrtInformation;
};

//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Function that parses an iSAM1 sphere dataset
//////////////////////////////////////////////////////////////////////////////////////////////
std::vector<SphereEdge> parseSphereDataset(const std::string& file);

} // data
} // steam

#endif // STEAM_PARSE_SPHERE_HPP

max_stars_repo_name: neophack/steam

max_issues_repo_name: neophack/steam

max_forks_repo_name: neophack/steam


text:
#define BOOST_TEST_MODULE "Boost Log unit tests"
#include <boost/test/unit_test.hpp>

max_stars_repo_name: dustcloud/serialmux

max_issues_repo_name: dustcloud/serialmux

max_forks_repo_name: dustcloud/serialmux


text:
/*

imap.cpp
--------

Copyright (C) 2016, Tomislav Karastojkovic (http://www.alepho.com).

Distributed under the FreeBSD license, see the accompanying file LICENSE or
copy at http://www.freebsd.org/copyright/freebsd-license.html.

*/

#include <algorithm>
#include <locale>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/compare.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/regex.hpp>
#include <mailio/imap.hpp>

using std::find_if;
using std::invalid_argument;
using std::list;
using std::make_optional;
using std::make_shared;
using std::make_tuple;
using std::map;
using std::move;
using std::out_of_range;
using std::pair;
using std::shared_ptr;
using std::stoul;
using std::string;
using std::stringstream;
using std::to_string;
using std::tuple;
using std::vector;
using std::chrono::milliseconds;
using boost::system::system_error;
using boost::iequals;
using boost::regex;
using boost::regex_match;
using boost::smatch;
using boost::split;
using boost::trim;
using boost::algorithm::trim_copy_if;
using boost::algorithm::trim_if;
using boost::algorithm::is_any_of;

namespace mailio
{

const string imap::UNTAGGED_RESPONSE{"*"};
const string imap::CONTINUE_RESPONSE{"+"};
const string imap::RANGE_SEPARATOR{":"};
const string imap::RANGE_ALL{"*"};
const string imap::LIST_SEPARATOR{","};
const string imap::TOKEN_SEPARATOR_STR{" "};
const string imap::QUOTED_STRING_SEPARATOR{"\""};

string imap::messages_range_to_string(imap::messages_range_t id_pair)
{
    return to_string(id_pair.first) + (id_pair.second.has_value() ? RANGE_SEPARATOR + to_string(id_pair.second.value()) : RANGE_SEPARATOR + RANGE_ALL);
}

string imap::messages_range_list_to_string(list<messages_range_t> ranges)
{
    return boost::join(ranges | boost::adaptors::transformed(static_cast<string(*)(messages_range_t)>(messages_range_to_string)), LIST_SEPARATOR);
}

imap::search_condition_t::search_condition_t(imap::search_condition_t::key_type condition_key, imap::search_condition_t::value_type condition_value) :
    key(condition_key), value(condition_value)
{
    try
    {
        switch (key)
        {
            case ALL:
                imap_string = "ALL";
                break;

            case SID_LIST:
            {
                imap_string = messages_range_list_to_string(std::get<list<messages_range_t>>(value));
                break;
            }

            case UID_LIST:
            {
                imap_string = "UID " + messages_range_list_to_string(std::get<list<messages_range_t>>(value));
                break;
            }

            case SUBJECT:
                imap_string = "SUBJECT " + QUOTED_STRING_SEPARATOR + std::get<string>(value) + QUOTED_STRING_SEPARATOR;
                break;

            case FROM:
                imap_string = "FROM " + QUOTED_STRING_SEPARATOR + std::get<string>(value) + QUOTED_STRING_SEPARATOR;
                break;

            case TO:
                imap_string = "TO " + QUOTED_STRING_SEPARATOR + std::get<string>(value) + QUOTED_STRING_SEPARATOR;
                break;

            case BEFORE_DATE:
                imap_string = "BEFORE " + imap_date_to_string(std::get<boost::gregorian::date>(value));
                break;

            case ON_DATE:
                imap_string = "ON " + imap_date_to_string(std::get<boost::gregorian::date>(value));
                break;

            case SINCE_DATE:
                imap_string = "SINCE " + imap_date_to_string(std::get<boost::gregorian::date>(value));
                break;

            default:
                break;
        }
    }
    catch (std::bad_variant_access&)
    {
        throw imap_error("Invaid search condition.");
    }
}

string imap::tag_result_response_t::to_string() const
{
    string result_s;
    if (result.has_value())
    {
        switch (result.value())
        {
        case OK:
            result_s = "OK";
            break;

        case NO:
            result_s = "MO";
            break;

        case BAD:
            result_s = "BAD";
            break;

        default:
            break;
        }
    }
    else
        result_s = "<null>";
    return tag + " " + result_s + " " + response;
}

imap::imap(const string& hostname, unsigned port, milliseconds timeout) :
    _dlg(make_shared<dialog>(hostname, port, timeout)), _tag(0), _optional_part_state(false), _atom_state(atom_state_t::NONE),
    _parenthesis_list_counter(0), _literal_state(string_literal_state_t::NONE), _literal_bytes_read(0), _eols_no(2)
{
}

imap::~imap()
{
    try
    {
        _dlg->send(format("LOGOUT"));
    }
    catch (...)
    {
    }
}

string imap::authenticate(const string& username, const string& password, auth_method_t method)
{
    string greeting = connect();
    if (method == auth_method_t::LOGIN)
        auth_login(username, password);
    return greeting;
}

auto imap::select(const list<string>& folder_name, bool /*read_only*/) -> mailbox_stat_t
{
    string delim = folder_delimiter();
    string folder_name_s = folder_tree_to_string(folder_name, delim);
    return select(folder_name_s);
}

auto imap::select(const string& mailbox, bool read_only) -> mailbox_stat_t
{
    string cmd;
    if (read_only)
        cmd = format("EXAMINE " + QUOTED_STRING_SEPARATOR + mailbox + QUOTED_STRING_SEPARATOR);
    else
        cmd = format("SELECT " + QUOTED_STRING_SEPARATOR + mailbox + QUOTED_STRING_SEPARATOR);
    _dlg->send(cmd);

    mailbox_stat_t stat;
    bool exists_found = false;
    bool recent_found = false;
    bool has_more = true;

    try
    {
        while (has_more)
        {
            reset_response_parser();
            string line = _dlg->receive();
            tag_result_response_t parsed_line = parse_tag_result(line);
            parse_response(parsed_line.response);

            if (parsed_line.tag == UNTAGGED_RESPONSE)
            {
                const auto result = parsed_line.result;
                if (result.has_value() && result.value() == tag_result_response_t::OK)
                {
                    if (_optional_part.size() != 2)
                        continue;

                    auto key = _optional_part.front();
                    _optional_part.pop_front();
                    if (key->token_type == response_token_t::token_type_t::ATOM)
                    {
                        auto value = _optional_part.front();
                        if (iequals(key->atom, "UNSEEN"))
                        {
                            if (value->token_type != response_token_t::token_type_t::ATOM)
                                throw imap_error("Parsing failure.");
                            stat.messages_first_unseen = stoul(value->atom);
                        }
                        else if (iequals(key->atom, "UIDNEXT"))
                        {
                            if (value->token_type != response_token_t::token_type_t::ATOM)
                                throw imap_error("Parsing failure.");
                            stat.uid_next = stoul(value->atom);
                        }
                        else if (iequals(key->atom, "UIDVALIDITY"))
                        {
                            if (value->token_type != response_token_t::token_type_t::ATOM)
                                throw imap_error("Parsing failure.");
                            stat.uid_validity = stoul(value->atom);
                        }
                    }
                }
                else
                {
                    if (_mandatory_part.size() == 2 && _mandatory_part.front()->token_type == response_token_t::token_type_t::ATOM)
                    {
                        auto value = _mandatory_part.front();
                        _mandatory_part.pop_front();
                        auto key = _mandatory_part.front();
                        _mandatory_part.pop_front();
                        if (iequals(key->atom, "EXISTS"))
                        {
                            stat.messages_no = stoul(value->atom);
                            exists_found = true;
                        }
                        else if (iequals(key->atom, "RECENT"))
                        {
                            stat.messages_recent = stoul(value->atom);
                            recent_found = true;
                        }
                    }
                }
            }
            else if (parsed_line.tag == to_string(_tag))
            {
                if (!parsed_line.result.has_value() || parsed_line.result.value() != tag_result_response_t::OK)
                    throw imap_error("Select or examine mailbox failure.");

                has_more = false;
            }
            else
                throw imap_error("Parsing failure.");
        }
    }
    catch (const invalid_argument& exc)
    {
        throw imap_error("Parsing failure.");
    }
    catch (const out_of_range& exc)
    {
        throw imap_error("Parsing failure.");
    }

    // The EXISTS and RECENT are required, the others may be missing in earlier protocol versions.
    if (!exists_found || !recent_found)
        throw imap_error("Parsing failure.");

    reset_response_parser();
    return stat;
}

void imap::fetch(const string& mailbox, unsigned long message_no, message& msg, bool header_only)
{
    select(mailbox);
    fetch(message_no, msg, false, header_only);
}

// Fetching literal is the only place where line is ended with LF only, instead of CRLF. Thus, `receive(true)` and counting EOLs is performed.
void imap::fetch(unsigned long message_no, message& msg, bool is_uid, bool header_only)
{
    const string RFC822_TOKEN = string("RFC822") + (header_only ? ".HEADER" : "");

    string cmd;
    if (is_uid)
        cmd.append("UID ");
    cmd.append("FETCH " + to_string(message_no) + TOKEN_SEPARATOR_STR + RFC822_TOKEN);
    _dlg->send(format(cmd));

    // Stores a message as string literals for parsing after the OK response.
    string msg_str;
    bool has_more = true;
    while (has_more)
    {
        reset_response_parser();
        string line = _dlg->receive();
        tag_result_response_t parsed_line = parse_tag_result(line);

        if (parsed_line.tag == UNTAGGED_RESPONSE)
        {
            parse_response(parsed_line.response);

            auto msg_no_token = _mandatory_part.front();
            // TODO: If UID is not wanted, then `message_no` is equal to this atom.
            if (msg_no_token->token_type != response_token_t::token_type_t::ATOM)
                throw imap_error("Fetching message failure.");
            _mandatory_part.pop_front();

            auto fetch_token = _mandatory_part.front();
            if (fetch_token->token_type != response_token_t::token_type_t::ATOM || !iequals(fetch_token->atom, "FETCH"))
                throw imap_error("Fetching message failure.");
            _mandatory_part.pop_front();

            shared_ptr<response_token_t> literal_token = nullptr;
            if (!_mandatory_part.empty())
                for (auto part : _mandatory_part)
                {
                    if (part->token_type == response_token_t::token_type_t::LIST)
                    {
                        bool rfc_found = false;
                        for (auto token = part->parenthesized_list.begin(); token != part->parenthesized_list.end(); token++)
                        {
                            if ((*token)->token_type == response_token_t::token_type_t::ATOM && iequals((*token)->atom, RFC822_TOKEN))
                            {
                                rfc_found = true;
                                continue;
                            }

                            if ((*token)->token_type == response_token_t::token_type_t::LITERAL)
                            {
                                if (rfc_found)
                                {
                                    literal_token = *token;
                                    break;
                                }
                                else
                                    throw imap_error("Parsing failure.");
                            }
                        }
                    }
                }

            if (literal_token != nullptr)
            {
                // Loop to read string literal.
                while (_literal_state == string_literal_state_t::READING)
                {
                    string line = _dlg->receive(true);
                    if (!line.empty())
                        trim_eol(line);
                    parse_response(line);
                }
                // Closing parenthesis not yet read.
                if (_literal_state == string_literal_state_t::DONE && _parenthesis_list_counter > 0)
                {
                    string line = _dlg->receive(true);
                    if (!line.empty())
                        trim_eol(line);
                    parse_response(line);
                }
                msg_str = std::move(literal_token->literal);
            }
            else
                throw imap_error("Parsing failure.");
        }
        else if (parsed_line.tag == to_string(_tag))
        {
            if (parsed_line.result.value() == tag_result_response_t::OK)
            {
                has_more = false;
                // Wait for the OK response in order to parse the message.
                msg.parse(msg_str);
            }
            else
                throw imap_error("Fetching message failure.");
        }
        else
            throw imap_error("Parsing failure.");
    }

    reset_response_parser();
}

void imap::fetch(const list<messages_range_t> messages_range, map<unsigned long, message>& found_messages, bool is_uids, bool header_only,
    codec::line_len_policy_t line_policy)
{
    const string RFC822_TOKEN = string("RFC822") + (header_only ? ".HEADER" : "");
    const string message_ids = messages_range_list_to_string(messages_range);

    string cmd;
    if (is_uids)
        cmd.append("UID ");
    cmd.append("FETCH " + message_ids + TOKEN_SEPARATOR_STR + RFC822_TOKEN);
    _dlg->send(format(cmd));

    // Stores messages as string literals for parsing after the OK response.
    map<unsigned long, string> msg_str;
    bool has_more = true;
    while (has_more)
    {
        reset_response_parser();
        string line = _dlg->receive();
        tag_result_response_t parsed_line = parse_tag_result(line);

        if (parsed_line.tag == UNTAGGED_RESPONSE)
        {
            parse_response(parsed_line.response);
            unsigned long msg_no = 0;
            if (_mandatory_part.front()->token_type != response_token_t::token_type_t::ATOM)
                throw imap_error("Fetching message failure.");
            msg_no = stoul(_mandatory_part.front()->atom);
            _mandatory_part.pop_front();
            if (msg_no == 0)
                throw imap_error("Fetching message failure.");

            if (!iequals(_mandatory_part.front()->atom, "FETCH"))
                throw imap_error("Fetching message failure.");

            unsigned long uid = 0;
            shared_ptr<response_token_t> literal_token = nullptr;
            if (!_mandatory_part.empty())
                for (auto part : _mandatory_part)
                {
                    if (part->token_type == response_token_t::token_type_t::LIST)
                    {
                        bool key_found = false;
                        string key;

                        for (auto token = part->parenthesized_list.begin(); token != part->parenthesized_list.end(); token++)
                        {
                            if ((*token)->token_type == response_token_t::token_type_t::ATOM)
                            {
                                const string& atm = (*token)->atom;
                                if (key_found)
                                {
                                    if(iequals(key, "UID"))
                                    {
                                        uid = stoul(atm);
                                    }
                                    // Reset.
                                    key_found = false;
                                }
                                else
                                {
                                    key = atm;
                                    key_found = true;
                                }
                            }
                            else if ((*token)->token_type == response_token_t::token_type_t::LITERAL)
                            {
                                if (key_found)
                                {
                                    if (iequals(key, RFC822_TOKEN))
                                    {
                                        literal_token = *token;
                                        // Break because reading the string literal text should follow.
                                        break;
                                    }
                                    key_found = false;
                                }
                                // Anything else is an error.
                                throw imap_error("Parsing failure.");
                            }
                        }
                    }
                }

            if (literal_token != nullptr)
            {
                // Loop to read string literal.
                while (_literal_state == string_literal_state_t::READING)
                {
                    string line = _dlg->receive(true);
                    if (!line.empty())
                        trim_eol(line);
                    parse_response(line);
                }
                // Closing parenthesis not yet read.
                if (_literal_state == string_literal_state_t::DONE && _parenthesis_list_counter > 0)
                {
                    string line = _dlg->receive(true);
                    if (!line.empty())
                        trim_eol(line);
                    parse_response(line);
                }
                msg_str.emplace(is_uids ? uid : msg_no, move(literal_token->literal));

                // If no UID was found, but we asked for them, it's an error.
                if (is_uids && uid == 0)
                {
                    throw imap_error("Parsing failure.");
                }
            }
            else
                throw imap_error("Parsing failure.");
        }
        else if (parsed_line.tag == to_string(_tag))
        {
            if (parsed_line.result.value() == tag_result_response_t::OK)
            {
                has_more = false;
                for (const auto& ms : msg_str)
                {
                    message msg;
                    msg.line_policy(codec::line_len_policy_t::RECOMMENDED, line_policy);
                    msg.parse(ms.second);
                    found_messages.emplace(ms.first, move(msg));
                }
            }
            else
                throw imap_error("Fetching message failure.");
        }
        else
            throw imap_error("Parsing failure.");
    }

    reset_response_parser();
}

void imap::append(const list<string>& folder_name, const message& msg)
{
    string delim = folder_delimiter();
    string folder_name_s = folder_tree_to_string(folder_name, delim);
    append(folder_name_s, msg);
}

void imap::append(const string& folder_name, const message& msg)
{
    string msg_str;
    msg.format(msg_str, true);

    string cmd = "APPEND " + folder_name;
    cmd.append(" {" + to_string(msg_str.size()) + "}");
    _dlg->send(format(cmd));
    string line = _dlg->receive();
    tag_result_response_t parsed_line = parse_tag_result(line);
    if (parsed_line.result == tag_result_response_t::BAD || parsed_line.tag != CONTINUE_RESPONSE)
        throw imap_error("Message appending failure.");

    _dlg->send(msg_str);
    bool has_more = true;
    while (has_more)
    {
        line = _dlg->receive();
        tag_result_response_t parsed_line = parse_tag_result(line);
        if (parsed_line.tag == to_string(_tag))
        {
            if (parsed_line.result != tag_result_response_t::OK)
                throw imap_error("Message appending failure.");
            has_more = false;
        }
        else if (parsed_line.tag != UNTAGGED_RESPONSE)
            throw imap_error("Message appending failure.");
    }
}

auto imap::statistics(const string& mailbox, unsigned int info) -> mailbox_stat_t
{
    // It doesn't like search terms it doesn't recognize.
    // Some older protocol versions or some servers may not support them.
    // So unseen uidnext and uidvalidity are optional.
    string cmd = "STATUS " + QUOTED_STRING_SEPARATOR + mailbox + QUOTED_STRING_SEPARATOR + " (messages recent";
    if (info & mailbox_stat_t::UNSEEN)
        cmd += " unseen";
    if (info & mailbox_stat_t::UID_NEXT)
        cmd += " uidnext";
    if (info & mailbox_stat_t::UID_VALIDITY)
        cmd += " uidvalidity";
    cmd += ")";

    _dlg->send(format(cmd));
    mailbox_stat_t stat;

    bool has_more = true;
    while (has_more)
    {
        reset_response_parser();
        string line = _dlg->receive();
        tag_result_response_t parsed_line = parse_tag_result(line);

        if (parsed_line.tag == UNTAGGED_RESPONSE)
        {
            parse_response(parsed_line.response);
            if (!iequals(_mandatory_part.front()->atom, "STATUS"))
                throw imap_error("Getting statistics failure.");
            _mandatory_part.pop_front();

            bool mess_found = false, recent_found = false;
            for (auto it = _mandatory_part.begin(); it != _mandatory_part.end(); it++)
                if ((*it)->token_type == response_token_t::token_type_t::LIST && (*it)->parenthesized_list.size() >= 2)
                {
                    bool key_found = false;
                    string key;
                    auto mp = *it;
                    for(auto il = mp->parenthesized_list.begin(); il != mp->parenthesized_list.end(); ++il)
                    {
                        const string& value = (*il)->atom;
                        if (key_found)
                        {
                            if (iequals(key, "MESSAGES"))
                            {
                                stat.messages_no = stoul(value);
                                mess_found = true;
                            }
                            else if (iequals(key, "RECENT"))
                            {
                                stat.messages_recent = stoul(value);
                                recent_found = true;
                            }
                            else if (iequals(key, "UNSEEN"))
                            {
                                stat.messages_unseen = stoul(value);
                            }
                            else if (iequals(key, "UIDNEXT"))
                            {
                                stat.uid_next = stoul(value);
                            }
                            else if (iequals(key, "UIDVALIDITY"))
                            {
                                stat.uid_validity = stoul(value);
                            }
                            key_found = false;
                        }
                        else
                        {
                            key = value;
                            key_found = true;
                        }
                    }
                }
            // The MESSAGES and RECENT are required.
            if (!mess_found || !recent_found)
                throw imap_error("Parsing failure.");
        }
        else if (parsed_line.tag == to_string(_tag))
        {
            if (parsed_line.result.value() == tag_result_response_t::OK)
                has_more = false;
            else
                throw imap_error("Getting statistics failure.");
        }
        else
            throw imap_error("Parsing failure.");
    }

    reset_response_parser();
    return stat;
}

auto imap::statistics(const list<string>& folder_name, unsigned int info) -> mailbox_stat_t
{
    string delim = folder_delimiter();
    string folder_name_s = folder_tree_to_string(folder_name, delim);
    return statistics(folder_name_s, info);
}

void imap::remove(const string& mailbox, unsigned long message_no)
{
    select(mailbox);
    remove(message_no);
}

void imap::remove(unsigned long message_no, bool is_uid)
{
    string cmd;
    if (is_uid)
        cmd.append("UID ");
    cmd.append("STORE " + to_string(message_no) + " +FLAGS (\\Deleted)");
    _dlg->send(format(cmd));

    bool has_more = true;
    while (has_more)
    {
        reset_response_parser();
        string line = _dlg->receive();
        tag_result_response_t parsed_line = parse_tag_result(line);

        if (parsed_line.tag == UNTAGGED_RESPONSE)
        {
            parse_response(parsed_line.response);
            auto token = _mandatory_part.front();
            if (token->token_type != response_token_t::token_type_t::ATOM || stoul(token->atom) != message_no)
                throw imap_error("Deleting message failure.");
            // TODO: Untagged FETCH response also to be checked?
            continue;
        }
        else if (parsed_line.tag == to_string(_tag))
        {
            if (!parsed_line.result.has_value() || parsed_line.result.value() != tag_result_response_t::OK)
                throw imap_error("Deleting message failure.");
            else
            {
                reset_response_parser();
                _dlg->send(format("CLOSE"));
                string line = _dlg->receive();
                tag_result_response_t parsed_line = parse_tag_result(line);

                if (!iequals(parsed_line.tag, to_string(_tag)))
                    throw imap_error("Parsing failure.");
                if (!parsed_line.result.has_value() || parsed_line.result.value() != tag_result_response_t::OK)
                    throw imap_error("Deleting message failure.");
            }
            has_more = false;
        }
        else
            throw imap_error("Parsing failure.");
    }
}

void imap::search(const list<imap::search_condition_t>& conditions, list<unsigned long>& results, bool want_uids)
{
    string cond_str;
    std::size_t elem = 0;
    for (const auto& c : conditions)
        if (elem++ < conditions.size() - 1)
            cond_str += c.imap_string + TOKEN_SEPARATOR_STR;
        else
            cond_str += c.imap_string;
    search(cond_str, results, want_uids);
}

bool imap::create_folder(const list<string>& folder_tree)
{
    string delim = folder_delimiter();
    string folder_str = folder_tree_to_string(folder_tree, delim);
    _dlg->send(format("CREATE " + QUOTED_STRING_SEPARATOR + folder_str + QUOTED_STRING_SEPARATOR));

    string line = _dlg->receive();
    tag_result_response_t parsed_line = parse_tag_result(line);
    if (parsed_line.tag != to_string(_tag))
        throw imap_error("Parsing failure.");
    if (parsed_line.result.value() == tag_result_response_t::NO)
        return false;
    if (parsed_line.result.value() != tag_result_response_t::OK)
        throw imap_error("Creating folder failure.");
    return true;
}

auto imap::list_folders(const list<string>& folder_name) -> mailbox_folder
{
    string delim = folder_delimiter();
    string folder_name_s = folder_tree_to_string(folder_name, delim);
    _dlg->send(format("LIST " + QUOTED_STRING_SEPARATOR + QUOTED_STRING_SEPARATOR + TOKEN_SEPARATOR_STR + QUOTED_STRING_SEPARATOR + folder_name_s + "*" +
        QUOTED_STRING_SEPARATOR));
    mailbox_folder mailboxes;

    bool has_more = true;
    while (has_more)
    {
        string line = _dlg->receive();
        tag_result_response_t parsed_line = parse_tag_result(line);
        parse_response(parsed_line.response);
        if (parsed_line.tag == UNTAGGED_RESPONSE)
        {
            auto token = _mandatory_part.front();
            _mandatory_part.pop_front();
            if (!iequals(token->atom, "LIST"))
                 throw imap_error("Listing folders failure.");

            if (_mandatory_part.size() < 3)
                throw imap_error("Parsing failure.");
            auto found_folder = _mandatory_part.begin();
            found_folder++; found_folder++;
            if (found_folder != _mandatory_part.end() && (*found_folder)->token_type == response_token_t::token_type_t::ATOM)
            {
                vector<string> folders_hierarchy;
                // TODO: May `delim` contain more than one character?
                split(folders_hierarchy, (*found_folder)->atom, is_any_of(delim));
                map<string, mailbox_folder>* mbox = &mailboxes.folders;
                for (auto f : folders_hierarchy)
                {
                    auto fit = find_if(mbox->begin(), mbox->end(), [&f](const std::pair<string, mailbox_folder>& mf){ return mf.first == f; });
                    if (fit == mbox->end())
                        mbox->insert(std::make_pair(f, mailbox_folder{}));
                    mbox = &(mbox->at(f).folders);
                }
            }
            else
                throw imap_error("Parsing failure.");
        }
        else if (parsed_line.tag == to_string(_tag))
        {
            has_more = false;
        }
        reset_response_parser();
    }

    return mailboxes;
}

bool imap::delete_folder(const list<string>& folder_name)
{
    string delim = folder_delimiter();
    string folder_name_s = folder_tree_to_string(folder_name, delim);
    _dlg->send(format("DELETE " + QUOTED_STRING_SEPARATOR + folder_name_s + QUOTED_STRING_SEPARATOR));

    string line = _dlg->receive();
    tag_result_response_t parsed_line = parse_tag_result(line);
    if (parsed_line.tag != to_string(_tag))
        throw imap_error("Parsing failure.");
    if (parsed_line.result.value() == tag_result_response_t::NO)
        return false;
    if (parsed_line.result.value() != tag_result_response_t::OK)
        throw imap_error("Deleting folder failure.");
    return true;
}

bool imap::rename_folder(const list<string>& old_name, const list<string>& new_name)
{
    string delim = folder_delimiter();
    string old_name_s = folder_tree_to_string(old_name, delim);
    string new_name_s = folder_tree_to_string(new_name, delim);
    _dlg->send(format("RENAME " + QUOTED_STRING_SEPARATOR + old_name_s + QUOTED_STRING_SEPARATOR + TOKEN_SEPARATOR_STR + QUOTED_STRING_SEPARATOR + new_name_s +
        QUOTED_STRING_SEPARATOR));

    string line = _dlg->receive();
    tag_result_response_t parsed_line = parse_tag_result(line);
    if (parsed_line.tag != to_string(_tag))
        throw imap_error("Parsing failure.");
    if (parsed_line.result.value() == tag_result_response_t::NO)
        return false;
    if (parsed_line.result.value() != tag_result_response_t::OK)
        throw imap_error("Renaming folder failure.");
    return true;
}

string imap::connect()
{
    // read greetings message
    string line = _dlg->receive();
    tag_result_response_t parsed_line = parse_tag_result(line);

    if (parsed_line.tag != UNTAGGED_RESPONSE)
        throw imap_error("Parsing failure.");
    if (!parsed_line.result.has_value() || parsed_line.result.value() != tag_result_response_t::OK)
        throw imap_error("Connection to server failure.");
    return parsed_line.response;
}

void imap::auth_login(const string& username, const string& password)
{
    auto cmd = format("LOGIN " + username + TOKEN_SEPARATOR_STR + password);
    _dlg->send(cmd);

    bool has_more = true;
    while (has_more)
    {
        string line = _dlg->receive();
        tag_result_response_t parsed_line = parse_tag_result(line);

        if (parsed_line.tag == UNTAGGED_RESPONSE)
            continue;
        if (parsed_line.tag != to_string(_tag))
            throw imap_error("Parsing failure.");
        if (parsed_line.result.value() != tag_result_response_t::OK)
            throw imap_error("Authentication failure.");

        has_more = false;
    }
}

void imap::search(const string& conditions, list<unsigned long>& results, bool want_uids)
{
    string cmd;
    if (want_uids)
        cmd.append("UID ");
    cmd.append("SEARCH " + conditions);
    _dlg->send(format(cmd));

    bool has_more = true;
    try
    {
        while (has_more)
        {
            reset_response_parser();
            string line = _dlg->receive();
            tag_result_response_t parsed_line = parse_tag_result(line);
            if (parsed_line.tag == UNTAGGED_RESPONSE)
            {
                parse_response(parsed_line.response);

                auto search_token = _mandatory_part.front();
                if (search_token->token_type == response_token_t::token_type_t::ATOM && !iequals(search_token->atom, "SEARCH"))
                    throw imap_error("Search mailbox failure.");
                _mandatory_part.pop_front();

                for (auto it = _mandatory_part.begin(); it != _mandatory_part.end(); it++)
                    if ((*it)->token_type == response_token_t::token_type_t::ATOM)
                    {
                        const unsigned long idx = stoul((*it)->atom);
                        if (idx == 0)
                            throw imap_error("Parsing failure.");
                        results.push_back(idx);
                    }
            }
            else if (parsed_line.tag == to_string(_tag))
            {
                if (parsed_line.result.value() != tag_result_response_t::OK)
                    throw imap_error("Search mailbox failure.");

                has_more = false;
            }
            else
            {
                throw imap_error("Parsing failure.");
            }
        }
    }
    catch (const invalid_argument& exc)
    {
        throw imap_error("Parsing failure.");
    }
    catch (const out_of_range& exc)
    {
        throw imap_error("Parsing failure.");
    }
    reset_response_parser();
}

string imap::folder_delimiter()
{
    static string delimiter;
    if (delimiter.empty())
    {
        _dlg->send(format("LIST " + QUOTED_STRING_SEPARATOR + QUOTED_STRING_SEPARATOR + TOKEN_SEPARATOR_STR + QUOTED_STRING_SEPARATOR + QUOTED_STRING_SEPARATOR));
        bool has_more = true;
        while (has_more)
        {
            string line = _dlg->receive();
            tag_result_response_t parsed_line = parse_tag_result(line);
            if (parsed_line.tag == UNTAGGED_RESPONSE && delimiter.empty())
            {
                parse_response(parsed_line.response);
                if (!iequals(_mandatory_part.front()->atom, "LIST"))
                    throw imap_error("Determining folder delimiter failure.");
                _mandatory_part.pop_front();

                if (_mandatory_part.size() < 3)
                    throw imap_error("Determining folder delimiter failure.");
                auto it = _mandatory_part.begin();
                if ((*(++it))->token_type != response_token_t::token_type_t::ATOM)
                    throw imap_error("Determining folder delimiter failure.");
                delimiter = trim_copy_if((*it)->atom, [](char c ){ return c == QUOTED_STRING_SEPARATOR_CHAR; });
                reset_response_parser();
            }
            else if (parsed_line.tag == to_string(_tag))
            {
                if (parsed_line.result.value() != tag_result_response_t::OK)
                    throw imap_error("Determining folder delimiter failure.");

                has_more = false;
            }
        }
    }
    return delimiter;
}

auto imap::parse_tag_result(const string& line) const -> tag_result_response_t
{
    string::size_type tag_pos = line.find(TOKEN_SEPARATOR_STR);
    if (tag_pos == string::npos)
        throw imap_error("Parsing failure.");
    string tag = line.substr(0, tag_pos);

    string::size_type result_pos = string::npos;
    result_pos = line.find(TOKEN_SEPARATOR_STR, tag_pos + 1);
    string result_s = line.substr(tag_pos + 1, result_pos - tag_pos - 1);
    std::optional<tag_result_response_t::result_t> result = std::nullopt;
    if (iequals(result_s, "OK"))
        result = make_optional(tag_result_response_t::OK);
    if (iequals(result_s, "NO"))
        result = make_optional(tag_result_response_t::NO);
    if (iequals(result_s, "BAD"))
        result = make_optional(tag_result_response_t::BAD);

    string response;
    if (result.has_value())
        response = line.substr(result_pos + 1);
    else
        response = line.substr(tag_pos + 1);
    return tag_result_response_t(tag, result, response);
}

/*
Protocol defines response line as tag (including plus and asterisk chars), result (ok, no, bad) and the response content which consists of optional
and mandatory part. Protocol grammar defines the response as sequence of atoms, string literals and parenthesized list (which itself can contain
atoms, string literal and parenthesized lists). The grammar can be parsed in one pass by counting which token is read: atom, string literal or
parenthesized list:
1. if a square bracket is reached, then an optional part is found, so parse its content as usual
2. if a brace is read, then string literal size is found, so read a number and then literal itself
3. if a parenthesis is found, then a list is being read, so increase the parenthesis counter and proceed
4. for a regular char check the state and determine if an atom or string size/literal is read

Token of the grammar is defined by `response_token_t` and stores one of the three types. Since parenthesized list is recursively defined, it keeps
sequence of tokens. When a character is read, it belongs to the last token of the sequence of tokens at the given parenthesis depth. The last token
of the response expression is found by getting the last token of the token sequence at the given depth (in terms of parenthesis count).
*/
void imap::parse_response(const string& response)
{
    list<shared_ptr<imap::response_token_t>>* token_list;

    if (_literal_state == string_literal_state_t::READING)
    {
        token_list = _optional_part_state ? find_last_token_list(_optional_part) : find_last_token_list(_mandatory_part);
        if (token_list->back()->token_type == response_token_t::token_type_t::LITERAL && _literal_bytes_read > token_list->back()->literal.size())
            throw imap_error("Parser failure.");
        unsigned long literal_size = stoul(token_list->back()->literal_size);
        if (_literal_bytes_read + response.size() < literal_size)
        {
            token_list->back()->literal += response + codec::END_OF_LINE;
            _literal_bytes_read += response.size() + _eols_no;
            if (_literal_bytes_read == literal_size)
                _literal_state = string_literal_state_t::DONE;
            return;
        }
        else
        {
            string::size_type resp_len = response.size();
            token_list->back()->literal += response.substr(0, literal_size - _literal_bytes_read);
            _literal_bytes_read += literal_size - _literal_bytes_read;
            _literal_state = string_literal_state_t::DONE;
            parse_response(response.substr(resp_len - (literal_size - _literal_bytes_read) - 1));
            return;
        }
    }

    shared_ptr<response_token_t> cur_token;
    for (auto ch : response)
    {
        switch (ch)
        {
            case OPTIONAL_BEGIN:
            {
                if (_atom_state == atom_state_t::QUOTED)
                    cur_token->atom +=ch;
                else
                {
                    if (_optional_part_state)
                        throw imap_error("Parser failure.");

                    _optional_part_state = true;
                }
            }
            break;

            case OPTIONAL_END:
            {
                if (_atom_state == atom_state_t::QUOTED)
                    cur_token->atom +=ch;
                else
                {
                    if (!_optional_part_state)
                        throw imap_error("Parser failure.");

                    _optional_part_state = false;
                    _atom_state = atom_state_t::NONE;
                }
            }
            break;

            case LIST_BEGIN:
            {
                if (_atom_state == atom_state_t::QUOTED)
                    cur_token->atom +=ch;
                else
                {
                    cur_token = make_shared<response_token_t>();
                    cur_token->token_type = response_token_t::token_type_t::LIST;
                    token_list = _optional_part_state ? find_last_token_list(_optional_part) : find_last_token_list(_mandatory_part);
                    token_list->push_back(cur_token);
                    _parenthesis_list_counter++;
                    _atom_state = atom_state_t::NONE;
                }
            }
            break;

            case LIST_END:
            {
                if (_atom_state == atom_state_t::QUOTED)
                    cur_token->atom +=ch;
                else
                {
                    if (_parenthesis_list_counter == 0)
                        throw imap_error("Parser failure.");

                    _parenthesis_list_counter--;
                    _atom_state = atom_state_t::NONE;
                }
            }
            break;

            case STRING_LITERAL_BEGIN:
            {
                if (_atom_state == atom_state_t::QUOTED)
                    cur_token->atom +=ch;
                else
                {
                    if (_literal_state == string_literal_state_t::SIZE)
                        throw imap_error("Parser failure.");

                    cur_token = make_shared<response_token_t>();
                    cur_token->token_type = response_token_t::token_type_t::LITERAL;
                    token_list = _optional_part_state ? find_last_token_list(_optional_part) : find_last_token_list(_mandatory_part);
                    token_list->push_back(cur_token);
                    _literal_state = string_literal_state_t::SIZE;
                    _atom_state = atom_state_t::NONE;
                }
            }
            break;

            case STRING_LITERAL_END:
            {
                if (_atom_state == atom_state_t::QUOTED)
                    cur_token->atom +=ch;
                else
                {
                    if (_literal_state == string_literal_state_t::NONE)
                        throw imap_error("Parser failure.");

                    _literal_state = string_literal_state_t::WAITING;
                }
            }
            break;

            case TOKEN_SEPARATOR_CHAR:
            {
                if (_atom_state == atom_state_t::QUOTED)
                    cur_token->atom +=ch;
                else
                {
                    if (cur_token != nullptr)
                    {
                        trim(cur_token->atom);
                        _atom_state = atom_state_t::NONE;
                    }
                }
            }
            break;

            case QUOTED_ATOM:
            {
                if (_atom_state == atom_state_t::NONE)
                {
                    cur_token = make_shared<response_token_t>();
                    cur_token->token_type = response_token_t::token_type_t::ATOM;
                    token_list = _optional_part_state ? find_last_token_list(_optional_part) : find_last_token_list(_mandatory_part);
                    token_list->push_back(cur_token);
                    _atom_state = atom_state_t::QUOTED;
                }
                else if (_atom_state == atom_state_t::QUOTED)
                    _atom_state = atom_state_t::NONE;
            }
            break;

            default:
            {
                if (_literal_state == string_literal_state_t::SIZE)
                {
                    if (!isdigit(ch))
                        throw imap_error("Parser failure.");

                    cur_token->literal_size += ch;
                }
                else if (_literal_state == string_literal_state_t::WAITING)
                {
                    // no characters allowed after the right brace, crlf is required
                    throw imap_error("Parser failure.");
                }
                else
                {
                    if (_atom_state == atom_state_t::NONE)
                    {
                        cur_token = make_shared<response_token_t>();
                        cur_token->token_type = response_token_t::token_type_t::ATOM;
                        token_list = _optional_part_state ? find_last_token_list(_optional_part) : find_last_token_list(_mandatory_part);
                        token_list->push_back(cur_token);
                        _atom_state = atom_state_t::PLAIN;
                    }
                    cur_token->atom += ch;
                }
            }
        }
    }
    if (_literal_state == string_literal_state_t::WAITING)
        _literal_state = string_literal_state_t::READING;
}

void imap::reset_response_parser()
{
    _optional_part.clear();
    _mandatory_part.clear();
    _optional_part_state = false;
    _atom_state = atom_state_t::NONE;
    _parenthesis_list_counter = 0;
    _literal_state = string_literal_state_t::NONE;
    _literal_bytes_read = 0;
    _eols_no = 2;
}

string imap::format(const string& command)
{
    return to_string(++_tag) + TOKEN_SEPARATOR_STR + command;
}

void imap::trim_eol(string& line)
{
    if (line.length() >= 1 && line[line.length() - 1] == codec::END_OF_LINE[0])
    {
        _eols_no = 2;
        line.pop_back();
    }
    else
        _eols_no = 1;
}

string imap::folder_tree_to_string(const list<string>& folder_tree, string delimiter) const
{
    string folders;
    std::size_t elem = 0;
    for (const auto& f : folder_tree)
        if (elem++ < folder_tree.size() - 1)
            folders += f + delimiter;
        else
            folders += f;
    return folders;
}

string imap::imap_date_to_string(const boost::gregorian::date& gregorian_date)
{
    stringstream ss;
    ss.exceptions(std::ios_base::failbit);
    boost::gregorian::date_facet* facet = new boost::gregorian::date_facet("%d-%b-%Y");
    ss.imbue(std::locale(ss.getloc(), facet));
    ss << gregorian_date;
    return ss.str();
}

list<shared_ptr<imap::response_token_t>>* imap::find_last_token_list(list<shared_ptr<response_token_t>>& token_list)
{
    list<shared_ptr<response_token_t>>* list_ptr = &token_list;
    unsigned int depth = 1;
    while (!list_ptr->empty() && list_ptr->back()->token_type == response_token_t::token_type_t::LIST && depth <= _parenthesis_list_counter)
    {
        list_ptr = &(list_ptr->back()->parenthesized_list);
        depth++;
    }
    return list_ptr;
}

imaps::imaps(const string& hostname, unsigned port, milliseconds timeout) : imap(hostname, port, timeout)
{
}

string imaps::authenticate(const string& username, const string& password, auth_method_t method)
{
    string greeting;
    if (method == auth_method_t::LOGIN)
    {
        switch_to_ssl();
        greeting = connect();
        auth_login(username, password);
    }
    else if (method == auth_method_t::START_TLS)
    {
        greeting = connect();
        start_tls();
        auth_login(username, password);
    }
    return greeting;
}

void imaps::start_tls()
{
    _dlg->send(format("STARTTLS"));
    string line = _dlg->receive();
    tag_result_response_t parsed_line = parse_tag_result(line);
    if (parsed_line.tag == UNTAGGED_RESPONSE)
        throw imap_error("Bad server response.");
    if (parsed_line.result.value() != tag_result_response_t::OK)
        throw imap_error("Start TLS refused by server.");

    switch_to_ssl();
}

void imaps::switch_to_ssl()
{
    _dlg = std::make_shared<dialog_ssl>(*_dlg);
}

} // namespace mailio

max_stars_repo_name: david-antiteum/mailio

max_issues_repo_name: david-antiteum/mailio

max_forks_repo_name: david-antiteum/mailio


text:
/**
  * Iskandar Setiadi 13511073@std.stei.itb.ac.id
  * Institut Teknologi Bandung (ITB) - Indonesia
  * Final Project (c) 2015
  * http://freedomofkeima.com/
  * DBLocalTestcase.cpp
  *
  */

#include <boost/lexical_cast.hpp>
#include <assert.h>
#include <iostream>
#include <unistd.h>
#include <string>

#include "leveldb/comparator.h"
#include "leveldb/db.h"

using namespace std;

long long max_iteration, counter;
uint64_t t1, t2, total, one_second, one_us;
// Constants, the minimum number of cycles required for calling RDTSC_START and RDTSC_STOP
uint64_t rdtscp_cycle = 50;

/** This benchmarking code is adapted from https://idea.popcount.org/2013-01-28-counting-cycles---rdtsc/ */
#ifdef __i386__
#  define RDTSC_DIRTY "%eax", "%ebx", "%ecx", "%edx"
#elif __x86_64__
#  define RDTSC_DIRTY "%rax", "%rbx", "%rcx", "%rdx"
#else
# error unknown platform
#endif

#define RDTSC_START(cycles)								\
	do {												   \
		register unsigned cyc_high, cyc_low;			   \
		asm volatile("CPUID\n\t"						   \
					 "RDTSC\n\t"						   \
					 "mov %%edx, %0\n\t"				   \
					 "mov %%eax, %1\n\t"				   \
					 : "=r" (cyc_high), "=r" (cyc_low)	 \
					 :: RDTSC_DIRTY);					  \
		(cycles) = ((uint64_t)cyc_high << 32) | cyc_low;   \
	} while (0)

#define RDTSC_STOP(cycles)								 \
	do {												   \
		register unsigned cyc_high, cyc_low;			   \
		asm volatile("RDTSCP\n\t"						  \
					 "mov %%edx, %0\n\t"				   \
					 "mov %%eax, %1\n\t"				   \
					 "CPUID\n\t"						   \
					 : "=r" (cyc_high), "=r" (cyc_low)	 \
					 :: RDTSC_DIRTY);					  \
		(cycles) = ((uint64_t)cyc_high << 32) | cyc_low;   \
	} while(0)

void print_result(uint64_t cycle) {
	cout << "Number of iteration: " << max_iteration << endl;
	printf("Average number of cycles: %.2f cycles\n", ((double) cycle / max_iteration));
	printf("Average elapsed time: %.8f us\n\n", ((double) cycle / one_us) / max_iteration);
}

void init() {
	RDTSC_START(t1);
	usleep(1000000); // sleep for 1 second
	RDTSC_STOP(t2);
	one_second = t2 - t1 - rdtscp_cycle;
	cout << "Approximate number of cycles in 1 second: " << one_second << endl;
	one_us = one_second / 1e6;
}

int main(int argc, char** argv) {
  if (argc != 2) {
	cout << "Usage: ./application_name db_path" << endl;
	return 1;
  }
  cout << "DB path: " << argv[1] << endl;

  init();

  leveldb::DB* db;
  leveldb::Options options;
  leveldb::WriteOptions write_options;
  leveldb::WriteOptions write_options2;
  write_options2.sync = true;
  leveldb::ReadOptions read_options;
  options.create_if_missing = true;
  leveldb::Status status = leveldb::DB::Open(options, argv[1], &db);
  assert(status.ok());
  cout << status.ToString() << endl;
  // leveldb::Slice key = "";
  string value;

  cout << "** Starting local benchmarking **" << endl << endl;
  cout << "Key length: " << 10 << " byte(s)" << endl;
  cout << "Value length: " << 10 << " byte(s)" << endl << endl;
  max_iteration = 10;

  /** FILL (local) operation **/
  cout << "--FILL (local)--" << endl;
  counter = 10000000; total = 0;
  while (counter < max_iteration + 10000000) {
	value = "val" + boost::lexical_cast<std::string>(counter);
	leveldb::Slice key("key" + boost::lexical_cast<std::string>(counter));
	// cout << "Key: " << key.ToString() << " ; " << "Value: " << value << endl;
	RDTSC_START(t1); // start operation
	status = db->Put(write_options, key, value);
	RDTSC_STOP(t2); // stop operation
	total += t2 - t1 - rdtscp_cycle;
	counter++;
  }
  print_result(total);
  /** End of FILL (local) operation **/

  usleep(50000); // cooldown 50 ms

  /** FILLSYNC (local) operation **/
  cout << "--FILLSYNC (local)--" << endl;
  counter = 10000000; total = 0;
  while (counter < max_iteration + 10000000) {
	value = "val" + boost::lexical_cast<std::string>(counter);
	leveldb::Slice key("keys" + boost::lexical_cast<std::string>(counter));
	// cout << "Key: " << key.ToString() << " ; " << "Value: " << value << endl;
	RDTSC_START(t1); // start operation
	status = db->Put(write_options2, key, value);
	RDTSC_STOP(t2); // stop operation
	total += t2 - t1 - rdtscp_cycle;
	counter++;
  }
  print_result(total);
  /** End of FILLSYNC (local) operation **/

  usleep(50000); // cooldown 50 ms

  /** OVERWRITE (local) operation **/
  cout << "--OVERWRITE (local)--" << endl;
  counter = 10000000; total = 0;
  while (counter < max_iteration + 10000000) {
	value = "val" + boost::lexical_cast<std::string>(counter);
	leveldb::Slice key("key" + boost::lexical_cast<std::string>(counter));
	// cout << "Key: " << key.ToString() << " ; " << "Value: " << value << endl;
	RDTSC_START(t1); // start operation
	status = db->Put(write_options, key, value);
	RDTSC_STOP(t2); // stop operation
	total += t2 - t1 - rdtscp_cycle;
	counter++;
  }
  print_result(total);
  /** End of OVERWRITE (local) operation **/

  usleep(50000); // cooldown 50 ms

  /** READ (local) operation **/
  cout << "--READ (local)--" << endl;
  counter = 10000000; total = 0;
  while (counter < max_iteration + 10000000) {
	leveldb::Slice key("key" + boost::lexical_cast<std::string>(counter));
	RDTSC_START(t1); // start operation
	status = db->Get(read_options, key, &value);
	RDTSC_STOP(t2); // stop operation
	// cout << "Key: " << key.ToString() << " ; " << "Value: " << value << endl;
	total += t2 - t1 - rdtscp_cycle;
	counter++;
  }
  print_result(total);
  /** End of READ (local) operation **/

  usleep(50000); // cooldown 50 ms

  /** DELETE (local) operation **/
  cout << "--DELETE (local)--" << endl;
  counter = 10000000; total = 0;
  while (counter < max_iteration + 10000000) {
	leveldb::Slice key("key" + boost::lexical_cast<std::string>(counter));
	// cout << "Key: " << key.ToString() << endl;
	RDTSC_START(t1); // start operation
	status = db->Delete(write_options, key);
	RDTSC_STOP(t2); // stop operation
	total += t2 - t1 - rdtscp_cycle;
	counter++;
  }
  print_result(total);
  /** End of DELETE (local) operation **/

  return 0;
}

max_stars_repo_name: freedomofkeima/TippyDB

max_issues_repo_name: freedomofkeima/TippyDB

max_forks_repo_name: freedomofkeima/TippyDB


text:
// Copyright (c) 2016-2019 Duality Blockchain Solutions Developers
// Copyright (c) 2014-2019 The Dash Core Developers
// Copyright (c) 2009-2019 The Bitcoin Developers
// Copyright (c) 2009-2019 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

/**
 * Copyright (c) 2013-2014 Tomas Dzetkulic
 * Copyright (c) 2013-2014 Pavol Rusnak
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

// Source:
// https://github.com/trezor/trezor-crypto

#include "bip39.h"
#include "wordlists/english.h"
#include "wordlists/chinese_simplified.h"
#include "wordlists/chinese_traditional.h"
#include "wordlists/french.h"
//#include "wordlists/german.h"  //exclude for now, but include later
#include "wordlists/italian.h"
#include "wordlists/japanese.h"
#include "wordlists/korean.h"
#include "wordlists/russian.h"
#include "wordlists/spanish.h"
#include "wordlists/ukrainian.h"
#include "crypto/sha256.h"
#include "random.h"

#include "util.h"

#include <boost/algorithm/string.hpp>

#include <openssl/evp.h>

SecureString CMnemonic::Generate(int strength, Language selectLanguage)
{
    if (strength < 128 || strength > 256) {
        return SecureString();
    }
    SecureVector data(32);
    GetRandBytes(&data[0], 32);
    SecureString mnemonic = FromData(data, strength / 8,selectLanguage);
    return mnemonic;
}

// SecureString CMnemonic::FromData(const uint8_t *data, int len)
SecureString CMnemonic::FromData(const SecureVector& data, int len, Language selectLanguage)
{
    const char* const* refWordList = nullptr; //initialize

    getWordList(refWordList,selectLanguage);

    if (len % 4 || len < 16 || len > 32) {
        return SecureString();
    }

    SecureVector checksum(32);
    CSHA256().Write(&data[0], len).Finalize(&checksum[0]);

    // data
    SecureVector bits(len);
    memcpy(&bits[0], &data[0], len);
    // checksum
    bits.push_back(checksum[0]);

    int mlen = len * 3 / 4;
    SecureString mnemonic;

    int i, j, idx;
    for (i = 0; i < mlen; i++) {
        idx = 0;
        for (j = 0; j < 11; j++) {
            idx <<= 1;
            idx += (bits[(i * 11 + j) / 8] & (1 << (7 - ((i * 11 + j) % 8)))) > 0;
        }
        mnemonic.append(refWordList[idx]);
        if (i < mlen - 1) {
            mnemonic += ' ';
        }
    }

    refWordList = nullptr; //reset
    return mnemonic;
}

void CMnemonic::getWordList(const char* const* &input, Language selectLanguage) {

    switch (selectLanguage) {
        case Language::ENGLISH:
            input = wordlist;
            break;
        case Language::FRENCH:
            input = wordlist_french;
            break;
        case Language::CHINESE_SIMPLIFIED:
            input = wordlist_chinese_simplified;
            break;
        case Language::CHINESE_TRADITIONAL:
            input = wordlist_chinese_traditional;
            break;
        //exclude for now but include later
        // case Language::GERMAN:
        //     input = wordlist_german;
        //     break;
        case Language::ITALIAN:
            input = wordlist_italian;
            break;
        case Language::JAPANESE:
            input = wordlist_japanese;
            break;
        case Language::KOREAN:
            input = wordlist_korean;
            break;
        case Language::RUSSIAN:
            input = wordlist_russian;
            break;
        case Language::SPANISH:
            input = wordlist_spanish;
            break;
        case Language::UKRAINIAN:
            input = wordlist_ukrainian;
            break;
        default:
            input = wordlist;
            break;

    } //switch

}

CMnemonic::Language CMnemonic::getLanguageEnumFromLabel(const std::string &input) {

    if (boost::algorithm::to_lower_copy(input) == "english") return CMnemonic::Language::ENGLISH;
    else if (boost::algorithm::to_lower_copy(input) == "french") return CMnemonic::Language::FRENCH;
    else if (boost::algorithm::to_lower_copy(input) == "chinesesimplified") return CMnemonic::Language::CHINESE_SIMPLIFIED;
    else if (boost::algorithm::to_lower_copy(input) == "chinesetraditional") return CMnemonic::Language::CHINESE_TRADITIONAL;
    //exclude for now but include later
    //else if (boost::algorithm::to_lower_copy(input) == "german") return CMnemonic::Language::GERMAN;
    else if (boost::algorithm::to_lower_copy(input) == "italian") return CMnemonic::Language::ITALIAN;
    else if (boost::algorithm::to_lower_copy(input) == "japanese") return CMnemonic::Language::JAPANESE;
    else if (boost::algorithm::to_lower_copy(input) == "korean") return CMnemonic::Language::KOREAN;
    else if (boost::algorithm::to_lower_copy(input) == "russian") return CMnemonic::Language::RUSSIAN;
    else if (boost::algorithm::to_lower_copy(input) == "spanish") return CMnemonic::Language::SPANISH;
    else if (boost::algorithm::to_lower_copy(input) == "ukrainian") return CMnemonic::Language::UKRAINIAN;
    else return CMnemonic::Language::ENGLISH;

} //getLanguageEnumFromLabel

bool CMnemonic::Check(SecureString mnemonic, Language selectLanguage)
{
    const char* const* refWordList = nullptr; //initialize

    getWordList(refWordList,selectLanguage);

    if (mnemonic.empty()) {
        return false;
    }

    uint32_t nWordCount{};

    for (size_t i = 0; i < mnemonic.size(); ++i) {
        if (mnemonic[i] == ' ') {
            nWordCount++;
        }
    }
    nWordCount++;
    // check number of words
    if (nWordCount != 12 && nWordCount != 18 && nWordCount != 24) {
        return false;
    }

    SecureString ssCurrentWord;
    SecureVector bits(32 + 1);

    uint32_t nWordIndex, ki, nBitsCount{};

    for (size_t i = 0; i < mnemonic.size(); ++i) {
        ssCurrentWord = "";
        while (i + ssCurrentWord.size() < mnemonic.size() && mnemonic[i + ssCurrentWord.size()] != ' ') {
            // if (ssCurrentWord.size() >= 26) { //was 9
            //     return false;
            // }
            ssCurrentWord += mnemonic[i + ssCurrentWord.size()];
        }
        //moved to get count AFTER space
        std::string teststring = "";
        teststring = ssCurrentWord.c_str();
        int characterSize = mbstowcs(NULL,teststring.c_str(), teststring.size());
        if (characterSize >= 25) { //was 9
            return false;
        }
        i += ssCurrentWord.size();
        nWordIndex = 0;
        for (;;) {
            if (!refWordList[nWordIndex]) { // word not found
                return false;
            }
            if (ssCurrentWord == refWordList[nWordIndex]) { // word found on index nWordIndex
                for (ki = 0; ki < 11; ki++) {
                    if (nWordIndex & (1 << (10 - ki))) {
                        bits[nBitsCount / 8] |= 1 << (7 - (nBitsCount % 8));
                    }
                    nBitsCount++;
                }
                break;
            }
            nWordIndex++;
        }
    }

    refWordList = nullptr; //reset

    if (nBitsCount != nWordCount * 11) {
        return false;
    }
    bits[32] = bits[nWordCount * 4 / 3];
    CSHA256().Write(&bits[0], nWordCount * 4 / 3).Finalize(&bits[0]);

    bool fResult = 0;
    if (nWordCount == 12) {
        fResult = (bits[0] & 0xF0) == (bits[32] & 0xF0); // compare first 4 bits
    } else if (nWordCount == 18) {
        fResult = (bits[0] & 0xFC) == (bits[32] & 0xFC); // compare first 6 bits
    } else if (nWordCount == 24) {
        fResult = bits[0] == bits[32]; // compare 8 bits
    }

    return fResult;
}

// passphrase must be at most 256 characters or code may crash
void CMnemonic::ToSeed(SecureString mnemonic, SecureString passphrase, SecureVector& seedRet)
{
    SecureString ssSalt = SecureString("mnemonic") + passphrase;
    SecureVector vchSalt(ssSalt.begin(), ssSalt.end());
    seedRet.resize(64);
    // int PKCS5_PBKDF2_HMAC(const char *pass, int passlen,
    //                    const unsigned char *salt, int saltlen, int iter,
    //                    const EVP_MD *digest,
    //                    int keylen, unsigned char *out);
    PKCS5_PBKDF2_HMAC(mnemonic.c_str(), mnemonic.size(), &vchSalt[0], vchSalt.size(), 2048, EVP_sha512(), 64, &seedRet[0]);
}

max_stars_repo_name: LordDarkHelmet/Dynamic

max_issues_repo_name: LordDarkHelmet/Dynamic

max_forks_repo_name: LordDarkHelmet/Dynamic


text:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_UNITS_UTILITY_HPP
#define BOOST_UNITS_UTILITY_HPP

#include <cstdlib>
#include <typeinfo>
#include <string>

#if defined(__GLIBCXX__) || defined(__GLIBCPP__)
#define BOOST_UNITS_USE_DEMANGLING
#include <cxxabi.h>
#endif // __GNUC__

#ifdef BOOST_UNITS_USE_DEMANGLING

#include <boost/algorithm/string/replace.hpp>

namespace boost {

namespace units {

namespace detail {

inline
std::string
demangle(const char* name)
{
    // need to demangle C++ symbols
    char*       realname;
    std::size_t len;
    int         stat;

    realname = abi::__cxa_demangle(name,NULL,&len,&stat);

    if (realname != NULL)
    {
        std::string   out(realname);

        std::free(realname);

        boost::replace_all(out,"boost::units::","");

        return out;
    }

    return std::string("demangle :: error - unable to demangle specified symbol");
}

} // namespace detail

template<class L>
std::string simplify_typename(const L& /*source*/)
{
    const std::string   demangled = detail::demangle(typeid(L).name());

    return demangled;
}

} // namespace units

} // namespace boost

#else // BOOST_UNITS_USE_DEMANGLING

namespace boost {

namespace units {

namespace detail {

inline
std::string
demangle(const char* name)
{
    return name;
}

} // namespace detail

template<class L>
std::string simplify_typename(const L& /*source*/)
{
    return std::string(typeid(L).name());
}

} // namespace units

} // namespace boost

// To get system-specific predefined macros:
// gcc -arch ppc -dM -E - < /dev/null | sort

#endif // BOOST_UNITS_USE_DEMANGLING

#endif // BOOST_UNITS_UTILITY_HPP

max_stars_repo_name: importlib/klib

max_issues_repo_name: isuhao/klib

max_forks_repo_name: isuhao/klib


text:
/**
 * Copyright (C) 2012-2013 Allan SIMON (Sysko) <allan.simon@supinfo.com>
 * See accompanying file COPYING.TXT file for licensing details.
 *
 * @category Cppcms-skeleton
 * @author   Allan SIMON <allan.simon@supinfo.com>
 * @package  Models
 *
 */

#include <cppdb/frontend.h>
#include <cppcms/util.h>
#include <cppcms/cppcms_error.h>
#include <cppcms/http_file.h>
#include <booster/posix_time.h>
#include <booster/log.h>

#include <cppcms_skel/generics/Config.h>
#include "models/Uploads.h"

namespace cppcmsskel {
namespace models {

/**
 *
 */
Uploads::Uploads() :
    SqliteModel()
{
}

/**
 *
 */
std::string Uploads::save(
    booster::shared_ptr<cppcms::http::file> file
) {

    std::string filename = file->filename();
    try {
        //TODO if we keep the same name, we should then check that there's
        // not already a file with the same name
        file->write_data();
        file->save_to(
            (Config::get_upload_folder() + filename).c_str()
        );
    } catch (cppcms::cppcms_error const &e) {
        BOOSTER_ERROR("cppcms_skel") << e.what();
        return UPLOADS_SAVE_ON_DISK_ERROR;
    }

    cppdb::statement saveFile = sqliteDb.prepare(
        "INSERT INTO uploads(filename, created) "
        "VALUES(?,?)"
    );
    saveFile.bind(filename);
    saveFile.bind(
        booster::ptime::now().get_seconds()
    );

    if (!execute_simple(saveFile)) {
        return UPLOADS_SAVE_ON_DB_ERROR;
    }

    return Config::get_upload_url() + filename;
}

/**
 *
 */
results::Files Uploads::list(
    const unsigned limit,
    const unsigned page
) {
    results::Files files;
    cppdb::statement listFiles = sqliteDb.prepare(
        "SELECT "
        "   filename, "
        "   created "
        "FROM uploads "
        "LIMIT ? OFFSET ? "
    );
    listFiles.bind(limit);
    listFiles.bind(page*limit);

    std::string baseURL = Config::get_upload_url();

    cppdb::result res = listFiles.query();
    while (res.next()) {
        std::string name = res.get<std::string>("filename");

        files.push_back(results::File(
            name,
            baseURL + name,
            res.get<unsigned>("created")
        ));
    }
    listFiles.reset();

    return files;
}

} // end namespace models
} // end namespace cppcmsskel

max_stars_repo_name: Tatoeba/cppcms-skeleton

max_issues_repo_name: Tatoeba/cppcms-skeleton

max_forks_repo_name: Tatoeba/cppcms-skeleton


text:
/*
 * Copyright (c) 2009-2016, Albertas Vyšniauskas
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "ColorCell.h"
#include "../ColorObject.h"
#include <boost/math/special_functions/round.hpp>

static void init(CustomCellRendererColor *cellcolor);
static void class_init(CustomCellRendererColorClass *klass);
static void get_property(GObject *object, guint param_id, GValue *value, GParamSpec *pspec);
static void set_property(GObject *object, guint param_id, const GValue *value, GParamSpec *pspec);
static void finalize(GObject *gobject);
#if GTK_MAJOR_VERSION >= 3
static void get_preferred_width(GtkCellRenderer *cell, GtkWidget *widget, gint *minimum_size, gint *natural_size);
static void get_preferred_height(GtkCellRenderer *cell, GtkWidget *widget, gint *minimum_size, gint *natural_size);
static void render(GtkCellRenderer *cell, cairo_t *cr, GtkWidget *widget, const GdkRectangle *background_area, const GdkRectangle *cell_area, GtkCellRendererState flags);
#else
static void get_size(GtkCellRenderer *cell, GtkWidget *widget, GdkRectangle *cell_area, gint *x_offset, gint *y_offset, gint *width, gint *height);
static void render(GtkCellRenderer *cell, GdkDrawable *window, GtkWidget *widget, GdkRectangle *background_area, GdkRectangle *cell_area, GdkRectangle *expose_area, GtkCellRendererState flags);
#endif

enum
{
	PROP_COLOR = 1,
};
static gpointer parent_class;

GType custom_cell_renderer_color_get_type()
{
	static GType cell_color_type = 0;
	if (cell_color_type == 0){
		static const GTypeInfo cell_color_info = { sizeof(CustomCellRendererColorClass), nullptr, /* base_init */
		nullptr, /* base_finalize */
		(GClassInitFunc) class_init, nullptr, /* class_finalize */
		nullptr, /* class_data */
		sizeof(CustomCellRendererColor), 0, /* n_preallocs */
		(GInstanceInitFunc) init, };
		cell_color_type = g_type_register_static(GTK_TYPE_CELL_RENDERER, "CustomCellRendererColor", &cell_color_info, (GTypeFlags) 0);
	}
	return cell_color_type;
}
static void init(CustomCellRendererColor *cellrenderercolor)
{
#if GTK_MAJOR_VERSION >= 3
#else
	GTK_CELL_RENDERER(cellrenderercolor)->mode = GTK_CELL_RENDERER_MODE_INERT;
	GTK_CELL_RENDERER(cellrenderercolor)->xpad = 2;
	GTK_CELL_RENDERER(cellrenderercolor)->ypad = 2;
#endif
	cellrenderercolor->width = 32;
	cellrenderercolor->height = 16;
	cellrenderercolor->color = nullptr;
}
static void class_init(CustomCellRendererColorClass *klass)
{
	GtkCellRendererClass *cell_class = GTK_CELL_RENDERER_CLASS(klass);
	GObjectClass *object_class = G_OBJECT_CLASS(klass);
	parent_class = g_type_class_peek_parent(klass);
	object_class->finalize = finalize;
	object_class->get_property = get_property;
	object_class->set_property = set_property;
#if GTK_MAJOR_VERSION >= 3
	cell_class->get_preferred_width = get_preferred_width;
	cell_class->get_preferred_height = get_preferred_height;
#else
	cell_class->get_size = get_size;
#endif
	cell_class->render = render;
	g_object_class_install_property(object_class, PROP_COLOR, g_param_spec_pointer("color", "Color", "ColorObject pointer", (GParamFlags) G_PARAM_READWRITE));
}
static void finalize(GObject *object)
{
	(*G_OBJECT_CLASS(parent_class)->finalize)(object);
}
static void get_property(GObject *object, guint param_id, GValue *value, GParamSpec *psec)
{
	CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(object);
	switch (param_id){
	case PROP_COLOR:
		g_value_set_pointer(value, cellcolor->color);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(object, param_id, psec);
		break;
	}
}
static void set_property(GObject *object, guint param_id, const GValue *value, GParamSpec *pspec)
{
	CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(object);
	switch (param_id){
	case PROP_COLOR:
		cellcolor->color = (ColorObject*)g_value_get_pointer(value);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(object, param_id, pspec);
		break;
	}
}
GtkCellRenderer *custom_cell_renderer_color_new()
{
	return (GtkCellRenderer*)g_object_new(CUSTOM_TYPE_CELL_RENDERER_COLOR, nullptr);
}
void custom_cell_renderer_color_set_size(GtkCellRenderer *cell, gint width, gint height)
{
	CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell);
	cellcolor->width = width;
	cellcolor->height = height;
}
#if GTK_MAJOR_VERSION >= 3
static void get_preferred_width(GtkCellRenderer *cell, GtkWidget *widget, gint *minimum_size, gint *natural_size)
{
	CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell);
	if (minimum_size)
		*minimum_size = 1;
	*natural_size = cellcolor->width;
}
static void get_preferred_height(GtkCellRenderer *cell, GtkWidget *widget, gint *minimum_size, gint *natural_size)
{
	CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell);
	if (minimum_size)
		*minimum_size = 1;
	*natural_size = cellcolor->height;
}
static void render(GtkCellRenderer *cell, cairo_t *cr, GtkWidget *widget, const GdkRectangle *background_area, const GdkRectangle *cell_area, GtkCellRendererState flags)
{
	CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell);
	cairo_rectangle(cr, cell_area->x, cell_area->y, cell_area->width, cell_area->height);
	Color color = cellcolor->color->getColor();
	cairo_set_source_rgb(cr, round(color.rgb.red * 255.0) / 255.0, round(color.rgb.green * 255.0) / 255.0, round(color.rgb.blue * 255.0) / 255.0);
	cairo_fill(cr);
}
#else
static void get_size(GtkCellRenderer *cell, GtkWidget *widget, GdkRectangle *cell_area, gint *x_offset, gint *y_offset, gint *width, gint *height)
{
	CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell);
	gint calc_width;
	gint calc_height;
	calc_width = (gint) cell->xpad * 2 + cellcolor->width;
	calc_height = (gint) cell->ypad * 2 + cellcolor->height;
	if (width)
		*width = calc_width;
	if (height)
		*height = calc_height;
	if (cell_area){
		if (x_offset){
			*x_offset = gint(cell->xalign * (cell_area->width - calc_width));
			*x_offset = MAX(*x_offset, 0);
		}
		if (y_offset){
			*y_offset = gint(cell->yalign * (cell_area->height - calc_height));
			*y_offset = MAX(*y_offset, 0);
		}
	}
}
static void render(GtkCellRenderer *cell, GdkDrawable *window, GtkWidget *widget, GdkRectangle *background_area, GdkRectangle *cell_area, GdkRectangle *expose_area, GtkCellRendererState flags)
{
	using boost::math::round;
	CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell);
	cairo_t *cr;
	cr = gdk_cairo_create(window);
	cairo_rectangle(cr, expose_area->x, expose_area->y, expose_area->width, expose_area->height);
	cairo_clip(cr);
	cairo_rectangle(cr, expose_area->x, expose_area->y, expose_area->width, expose_area->height);
	Color color = cellcolor->color->getColor();
	cairo_set_source_rgb(cr, round(color.rgb.red * 255.0) / 255.0, round(color.rgb.green * 255.0) / 255.0, round(color.rgb.blue * 255.0) / 255.0);
	cairo_fill(cr);
	cairo_destroy(cr);
}
#endif

max_stars_repo_name: ryandesign/gpick

max_issues_repo_name: ryandesign/gpick

max_forks_repo_name: ryandesign/gpick


text:
// CG:SHOP 2021 Coordinated Motion Planning - Shadoks Team
//
// Class to detect collision of robots
//
/**
 * MIT License
 *
 * Copyright (c) 2020 Guilherme Dias da Fonseca <gfonsecabr@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifndef CRASH
#define CRASH

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <stack>
#include "robot.cpp"
#include <boost/unordered_set.hpp> // hash_combine
#include "tsl/hopscotch_map.h"
#include "tsl/hopscotch_set.h"

using namespace std;

// Hash for a pair of int and Point
struct int_point_hash : public unary_function<tuple<int,Point>, size_t> {
  size_t operator()(const tuple<int,Point>& k) const {
    size_t seed = 0;
    boost::hash_combine(seed, get<0>(k));
    boost::hash_combine(seed, get<1>(k).x);
    boost::hash_combine(seed, get<1>(k).y);
    return seed;
  }
};

class Crash {
  tsl::hopscotch_map<tuple<int,Point>, Robot *, int_point_hash>  pos;
  tsl::hopscotch_set<int> times;
  vector <Robot *> robots;

  void build(int t) {
    for(Robot *r : robots) {
      auto cur = make_tuple(t, r->pos(t));
      pos[cur] = r;
    }
    times.insert(t);
  }

public:
  void add(Robot *r) {
    robots.push_back(r);
  }

  bool compatible(const Move &m) {
    if(!times.contains(m.t0))
      build(m.t0);
    if(!times.contains(m.t0+1))
      build(m.t0+1);

    auto dest_fut = make_tuple(m.t0+1, m.q);
    if(pos.count(dest_fut))
      return false; // Another robot will be at q at destination time

    auto dest_now = make_tuple(m.t0, m.q);
    if(pos.count(dest_now)) {
      Robot *r = pos.at(dest_now);
      if(!r->compatible(m))
        return false;
    }

    auto start_fut = make_tuple(m.t0+1, m.p);
    if(pos.count(start_fut)) {
      Robot *r = pos.at(start_fut);
      if(!r->compatible(m))
        return false;
    }

    return true;
  }
};

// Similar to crash but handles conflicting robots
class SuperCrash {
  tsl::hopscotch_map<tuple<int,Point>, vector<Robot *>, int_point_hash>  pos;
  tsl::hopscotch_set<int> times;
  vector <Robot *> robots;

  void build(int t) {
    for(Robot *r : robots) {
      auto cur = make_tuple(t, r->pos(t));
      pos[cur].push_back(r);
    }
    times.insert(t);
  }

public:
  void add(Robot *r) {
    robots.push_back(r);
  }

  bool compatible(const Move &m) {
    if(!times.contains(m.t0))
      build(m.t0);
    if(!times.contains(m.t0+1))
      build(m.t0+1);

    auto dest_fut = make_tuple(m.t0+1, m.q);
    if(pos.count(dest_fut))
      return false; // Another robot will be at q at destination time

    auto dest_now = make_tuple(m.t0, m.q);
    if(pos.count(dest_now)) {
      for (Robot *r : pos.at(dest_now))
        if(!r->compatible(m))
          return false;
    }

    auto start_fut = make_tuple(m.t0+1, m.p);
    if(pos.count(start_fut)) {
      for (Robot *r : pos.at(start_fut))
        if(!r->compatible(m))
          return false;
    }

    return true;
  }

  tsl::hopscotch_set<Robot *> incompatible(const Move &m) {
    tsl::hopscotch_set<Robot *> ret;

    if(!times.contains(m.t0))
      build(m.t0);
    if(!times.contains(m.t0+1))
      build(m.t0+1);

    auto dest_fut = make_tuple(m.t0+1, m.q);
    if(pos.count(dest_fut))
      for(Robot *r : pos.at(dest_fut))
        ret.insert(r); // Another robot will be at q at destination time

    auto dest_now = make_tuple(m.t0, m.q);
    if(pos.count(dest_now)) {
      for(Robot *r : pos.at(dest_now))
        if(!r->compatible(m))
          ret.insert(r);
    }

    auto start_fut = make_tuple(m.t0+1, m.p);
    if(pos.count(start_fut)) {
      for(Robot *r : pos.at(start_fut))
        if(!r->compatible(m))
          ret.insert(r);
    }

    return ret;
  }
};

#endif

max_stars_repo_name: gfonsecabr/shadoks-robots

max_issues_repo_name: gfonsecabr/shadoks-robots

max_forks_repo_name: gfonsecabr/shadoks-robots


text:
#include <boost/foreach.hpp>

#include "Merge.h"
#include "Frame.h"
#include "FrameMetadata.h"
#include "Logger.h"
#include "AIPExceptions.h"

class Merge::Detail
{

public:
	Detail(MergeProps& _props):maxDelay(_props.maxDelay), lastIndex(0), mQueueSize(0)
	{

	}

	~Detail()
	{
		clear();
	}

	void setOutputPinId(std::string& pinId)
	{
		mOutputPinId = pinId;
	}

	bool queue(frame_container& frames)
	{
		for (auto it = frames.cbegin(); it != frames.cend(); it++)
		{
			auto& frame = it->second;
			if (frame->fIndex2 < lastIndex)
			{
				// frame index jumped may be because of drop upstream
				continue;
			}
			mQueue[frame->fIndex2] = frame;
			mQueueSize++;
		}

		return true;
	}

	bool get(frame_container& frames)
	{
		auto elem = mQueue.begin();

		if (mQueueSize > maxDelay)
		{
			// this should flush
			lastIndex = elem->first - 1;
		}

		if (mQueueSize == 0 || (elem->first != (lastIndex + 1) && !(elem->first == 0 && lastIndex == 0) ) )
		{
			return false;
		}

		frames[mOutputPinId] = elem->second;
		removeElement(elem->first);

		return true;
	}

	void clear()
	{
		mQueue.clear();
	}

private:
	void removeElement(uint64_t index)
	{
		lastIndex = index;
		mQueue.erase(index);
		mQueueSize--;
	}

	uint32_t mQueueSize;
	uint32_t maxDelay;
	uint64_t lastIndex;
	std::map<uint64_t, frame_sp> mQueue;
	std::string mOutputPinId;
};

Merge::Merge(MergeProps _props):Module(TRANSFORM, "Merge", _props)
{
	mDetail.reset(new Detail(_props));
}

bool Merge::validateInputPins()
{
	auto frameType = -1;
	for (auto const& elem: getInputMetadata())
	{
		if (frameType == -1)
		{
			frameType = elem.second->getFrameType();
			continue;
		}

		if (frameType == elem.second->getFrameType())
		{
			continue;
		}

		LOG_ERROR << "All inputs must be of same type. Expected<" << frameType << "> Actual<" << elem.second->getFrameType() << ">";
		return false;
	}

	return true;
}

bool Merge::validateOutputPins()
{
	if(getNumberOfOutputPins() != 1)
	{
		LOG_ERROR << "Expected only 1 output pin. But Actual<>" << getNumberOfOutputPins();
		return false;
	}

	return true;
}

bool Merge::init()
{
	if (!Module::init())
	{
		return false;
	}

	return true;
}

bool Merge::term()
{
	mDetail.reset();
	return Module::term();
}

void Merge::addInputPin(framemetadata_sp& metadata, string& pinId)
{
	Module::addInputPin(metadata, pinId);
	if(getNumberOfOutputPins() == 0)
    {
       auto pinId = addOutputPin(metadata);
	   mDetail->setOutputPinId(pinId);
    }
}

bool Merge::process(frame_container& frames)
{
	mDetail->queue(frames);

	frame_container outFrames;
	while (mDetail->get(outFrames))
	{
		send(outFrames);
	}

	return true;
}

max_stars_repo_name: yashrajsapra/ApraPipes

max_issues_repo_name: yashrajsapra/ApraPipes

max_forks_repo_name: yashrajsapra/ApraPipes


text:
//
// Created by redwards on 10/3/18.
// Process every file in the directory and make a count of all the hits
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <sstream>
#include <map>
#include <gzstream>
using namespace std;

int main (int argc, char* argv[]) {

    if ( argc < 2) {
        cerr << "Usage: " << argv[0] << " <directory to process>\n";
        return 1;
    }

    if (! boost::filesystem::is_directory(argv[1])) {
        cerr << "Please provide a directory with all the files to summarize" << endl;
        return 1;
    }

    map<string, float> counts;
    map<string, int> total;
    for(auto& filename : boost::make_iterator_range(boost::filesystem::directory_iterator(argv[1]), {})) {
        ifstream reader;
        reader.open(filename.path().string());
        if (!reader) {
            cerr << "Unable to open the input file" << filename << endl;
            return 1;
        }
        float c; string peg;
        // read each line and split into two tokens
        while (reader >> peg >> c) {
            counts[peg] += c;
            total[peg]++;
        }
        reader.close();
    }

    for( auto const& x : counts )
    {
        cout << x.first << " " << (float) x.second/ (float) total[x.first] << " " << total[x.first] << endl;
    }

}