text:
// Copyright (c) 2013, HelightXu
// Author:  Zhwen Xu<HelightXu@gmail.com>
// Created: 2013-12-16
// Description:
//

#include <arpa/inet.h>
#include <assert.h>
#include <dirent.h>
#include <errno.h>
#include <ifaddrs.h>
#include <linux/if.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <map>
// #include <boost/regex.hpp>
#include "glog/logging.h"
#include "util.h"

int64_t CUtil::milli_seconds()
{
    struct timeval now;
    gettimeofday(&now, 0);

    return static_cast<uint64_t>(now.tv_sec * 1000)
        + static_cast<uint64_t>(now.tv_usec / 1000);
}

int32_t CUtil::seconds()
{
    struct timeval now;
    gettimeofday(&now, 0);

    return static_cast<uint32_t>(now.tv_sec);
}

std::string CUtil::get_local_ip(const char* dev)
{
    struct ifaddrs* addr_struct = NULL;
    struct ifaddrs* ifaddr= NULL;
    std::string local_ip = "";
    void* tmp_addr = NULL;

    if (0 != getifaddrs(&addr_struct))
    {
        VLOG(3) << "Get device ip error";
        return local_ip;
    }

    ifaddr =  addr_struct;
    while (addr_struct != NULL)
    {
        if (addr_struct->ifa_addr->sa_family == AF_INET)
        {
            //  is a valid IP4 Address
            tmp_addr = &((struct sockaddr_in*)addr_struct->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, tmp_addr, addressBuffer, INET_ADDRSTRLEN);
            if (strcmp(addr_struct->ifa_name, dev) == 0)
            {
                local_ip = std::string(addressBuffer);
                break;
            }
        }
        else if (addr_struct->ifa_addr->sa_family == AF_INET6)
        {
            // is a valid IP6 Address
            tmp_addr = &((struct sockaddr_in *)addr_struct->ifa_addr)->sin_addr;
            char addressBuffer[INET6_ADDRSTRLEN];
            inet_ntop(AF_INET6, tmp_addr, addressBuffer, INET6_ADDRSTRLEN);
            if (strcmp(addr_struct->ifa_name, dev) == 0)
            {
                local_ip = std::string(addressBuffer);
                break;
            }
        }
        addr_struct = addr_struct->ifa_next;
    }

    if (ifaddr)
    {
        freeifaddrs(ifaddr);
    }

    return local_ip;
}

std::string CUtil::get_ip_by_dev(const char* dev)
{
    std::map<int,int>  m_ip_fd;   // 保存ip4和ip6的网络地址信息
    m_ip_fd[AF_INET] = socket(AF_INET, SOCK_DGRAM, 0);
    // m_ip_fd[AF_INET6] = socket(AF_INET6, SOCK_DGRAM, 0);
    std::map<int,int>::iterator it = m_ip_fd.begin();

    for (; it != m_ip_fd.end(); ++it)
    {
        int ip_type = it->first;
        int fd = it->second;

        int intrface;
        ifconf ifc;
        ifreq buf[32];  // 网卡信息数组(最多支持32个)

        if (fd <= 0)
        {
            LOG(ERROR) << "open socket error";
            continue;
        }
        ifc.ifc_len = sizeof(buf);
        ifc.ifc_buf = reinterpret_cast<caddr_t>(buf);

        if (0 != ioctl(fd, SIOCGIFCONF, reinterpret_cast<char*>(&ifc)))
        {
            LOG(ERROR) << "get ifconf info by ioctl error ";
            close (fd);
            continue;
        }
        intrface = ifc.ifc_len / sizeof(ifreq);
        while (intrface-- > 0)
        {
            if (0 != ioctl(fd, SIOCGIFADDR, reinterpret_cast<char*>(&buf[intrface])))
            {
                LOG(ERROR) << "get device info error";
                continue;
            }
            if (strcmp(buf[intrface].ifr_name, dev) == 0)
            {
                std::string ip;

                in_addr ip_address =
                    reinterpret_cast<sockaddr_in*>(&buf[intrface].ifr_addr)->sin_addr;
                ip = inet_ntop(ip_type, reinterpret_cast<void *>(&ip_address)
                               , const_cast<char*>(ip.data()), 32);
                close(fd);
                return ip;
            }
        }
        close (fd);
    }
    return "";
}

bool CUtil::regex(const std::string& str_txt, const std::string& pattern)
{
    /*
    boost::regex exp(pattern.c_str());
    boost::cmatch what;
    return boost::regex_match(str_txt.c_str(), what, exp);
    */
}

void CUtil::list(const std::string& dirpath,
    const std::string& pattern,
    std::vector<std::string>* file_names)
{
    if (NULL == file_names || pattern.empty())
    {
        LOG(ERROR) << "no file names vector or pattern is empty " << pattern;
        return;
    }

    DIR* dir = opendir(dirpath.c_str());
    if (NULL == dir || NULL == file_names)
    {
        LOG(ERROR) << "open dir error: " << errno << " path: " << dirpath;
        return;
    }

    // boost::regex reg(pattern);

    for (;;)
    {
        errno = 0;
        struct dirent* ent = readdir(dir);
        if (NULL == ent)
        {
            if (errno != 0)
            {
                int errcode = errno;
                if (EACCES == errcode)
                {
                    LOG(ERROR) << " Access denied: " << errno << " path: " << dirpath;
                    continue;
                }
                LOG(ERROR) << "read dir error: " << errno << " path: " << dirpath;
            }

            break; // over
        }

        if ((0 == strcmp(ent->d_name, "."))
         || (0 == strcmp(ent->d_name, "..")))
        {
            continue;
        }

        if (DT_REG == ent->d_type)
        {
            // boost::cmatch what;
            // if (boost::regex_match(ent->d_name, what, reg))
            // {
            //     file_names->push_back(ent->d_name);
            // }
            VLOG(4) << ent->d_name;
        }
    }

    closedir(dir);
}


text:
#ifndef SQL_PARSER_FUSION_EXPR_HPP
#define SQL_PARSER_FUSION_EXPR_HPP

#include "sql/ast/expr.hpp"

#include <boost/fusion/include/adapt_struct.hpp>

BOOST_FUSION_ADAPT_STRUCT(sql::ast::bind_parameter)

BOOST_FUSION_ADAPT_STRUCT(sql::ast::schema_column_identifier,
                         (sql::ast::identifier, schema)
                         (sql::ast::identifier, table)
                         (sql::ast::identifier, column)
)

BOOST_FUSION_ADAPT_STRUCT(sql::ast::table_column_identifier,
                         (sql::ast::identifier, table)
                         (sql::ast::identifier, column)
)

BOOST_FUSION_ADAPT_STRUCT(sql::ast::simple_column_identifier,
                         (sql::ast::identifier, column)
)

BOOST_FUSION_ADAPT_STRUCT(sql::ast::binary_operation,
                         (sql::ast::expr, first)
                         (sql::ast::bop, op)
                         (sql::ast::expr, second)
)

BOOST_FUSION_ADAPT_STRUCT(sql::ast::function_params_expr_list,
                         (bool, distinct)
                         (sql::ast::expr_list, expressions)
)

BOOST_FUSION_ADAPT_STRUCT(sql::ast::function_params_none)

BOOST_FUSION_ADAPT_STRUCT(sql::ast::function_params_row)

BOOST_FUSION_ADAPT_STRUCT(sql::ast::function_call,
                         (sql::ast::identifier, name)
                         (sql::ast::function_params, parameters)
)

#endif //SQL_PARSER_FUSION_EXPR_HPP

ext: hpp

max_stars_repo_name: cviebig/lib-sql

max_issues_repo_name: cviebig/lib-sql

max_forks_repo_name: cviebig/lib-sql


text:
/*
 * Copyright 2010,
 * François Bleibel,
 * Olivier Stasse,
 *
 * CNRS/AIST
 *
 * This file is part of dynamic-graph.
 * dynamic-graph is free software:
 * 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.
 *
 * 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 HOLDER 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 --------------------------------------------------------- */
/* --------------------------------------------------------------------- */

/* DG */
#include <iomanip>
#include <boost/bind.hpp>

#include <dynamic-graph/tracer-real-time.h>
#include <dynamic-graph/debug.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/all-commands.h>

using namespace std;
using namespace dynamicgraph;

DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(TracerRealTime,"TracerRealTime");

/* --------------------------------------------------------------------- */
/* --- DGOUTSTRINGSTREAM ---------------------------------------------- */
/* --------------------------------------------------------------------- */

OutStringStream::
OutStringStream  ()
  : std::ostringstream ()
    ,buffer( 0 ),index(0),bufferSize(0),full(false)
{
  dgDEBUGINOUT(15);
}

OutStringStream::
~OutStringStream  ()
{
  dgDEBUGIN(15);
  delete[] buffer;
  dgDEBUGOUT(15);
}

void OutStringStream::
resize (const std::streamsize& size)
{
  dgDEBUGIN(15);

  index=0;
  bufferSize = size;
  full=false;

  delete[] buffer;
  buffer = new char[static_cast<size_t> (size)];

  dgDEBUGOUT(15);
}

bool OutStringStream::
addData (const char * data, const std::streamoff& size)
{
  dgDEBUGIN(15);
  std::streamsize towrite = static_cast<std::streamsize> (size);
  if (index + towrite > bufferSize)
    {
      dgDEBUGOUT(15);
      full = true;
      return false;
    }
  memcpy (buffer + index, data, static_cast<size_t> (towrite));
  index += towrite;
  dgDEBUGOUT(15);
  return true;
}

void OutStringStream::
dump( std::ostream& os )
{
  dgDEBUGIN(15);
  os.write( buffer,index );
  dgDEBUGOUT(15);
}

void OutStringStream::
empty  ()
{
  dgDEBUGIN(15);
  index=0; full=false;
  dgDEBUGOUT(15);
}

/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */

TracerRealTime::TracerRealTime( const std::string & n )
  :Tracer(n)
   ,bufferSize( BUFFER_SIZE_DEFAULT )
{
  dgDEBUGINOUT(15);

  /* --- Commands --- */
  {
    using namespace dynamicgraph::command;
    std::string doc
      = docCommandVoid0("Trash the current content of the buffers, without saving it.");
    addCommand("empty",
	       makeCommandVoid0(*this,&TracerRealTime::emptyBuffers,doc ));

    addCommand("getBufferSize",
	       makeDirectGetter(*this,&bufferSize,
				docDirectGetter("bufferSize","int")));
    addCommand("setBufferSize",
	       makeDirectSetter(*this,&bufferSize,
				docDirectSetter("bufferSize","int")));
  } // using namespace command

  dgDEBUGOUT(15);
}

/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */

void TracerRealTime::
openFile( const SignalBase<int> & sig,
	  const std::string& givenname )
{
  dgDEBUGIN(15);
  string signame;
  if( givenname.length () )
    { signame = givenname;  } else { signame = sig.shortName (); }

  string filename = rootdir + basename + signame + suffix;
  dgDEBUG(5) << "Sig <"<<sig.getName ()
	      << ">: new file "<< filename << endl;
  std::ofstream * newfile = new std::ofstream( filename.c_str () );
  dgDEBUG(5) << "Newfile:" << (void*) newfile << endl;
  hardFiles.push_back( newfile );
  dgDEBUG(5) << "Creating Outstringstream" << endl;

  //std::stringstream * newbuffer = new std::stringstream ();
  OutStringStream * newbuffer = new OutStringStream (); // std::stringstream ();
  newbuffer->resize( bufferSize );
  newbuffer->givenname = givenname;
  files.push_back( newbuffer );

  dgDEBUGOUT(15);
}

void TracerRealTime::
closeFiles  ()
{
  dgDEBUGIN(15);

  FileList::iterator iter = files.begin ();
  HardFileList::iterator hardIter = hardFiles.begin ();

  while( files.end ()!=iter )
    {
      dgDEBUG(25) << "Close the files." << endl;

      std::stringstream * file = dynamic_cast< stringstream* >(*iter);
      std::ofstream * hardFile = *hardIter;

      (*hardFile) <<flush; hardFile->close ();
      delete file;
      delete hardFile;

      ++iter; ++hardIter;
    }

  dgDEBUG(25) << "Clear the lists." << endl;
  files.clear ();
  hardFiles.clear ();

  dgDEBUGOUT(15);
}

void TracerRealTime::
trace  ()
{
  dgDEBUGIN(15);

  FileList::iterator iter = files.begin ();
  HardFileList::iterator hardIter = hardFiles.begin ();

  while( files.end ()!=iter )
    {
      dgDEBUG(35) << "Next" << endl;
      std::ostream * os = *iter;
      if( NULL==os )
	{ DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN,
					"The buffer is null",""); }
      //std::stringstream & file = * dynamic_cast< stringstream* >(os);
      OutStringStream * file = dynamic_cast< OutStringStream* >(os); // segfault
      if( NULL==file )
	{ DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN,
					"The buffer is not open",""); }

      std::ofstream & hardFile = **hardIter;
      if(! hardFile.good () )
	{ DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN,
					"The file is not open",""); }

      if( (hardFile.good ())&&(NULL!=file) )
	{

// 	  const unsigned int SIZE = 1024*8;
// 	  char buffer[SIZE];
// 	  streambuf * pbuf = file.rdbuf ();
// 	  pbuf->pubseekpos(0);
// 	  const unsigned int NB_BYTE = pbuf->in_avail ();
// 	  dgDEBUG(35) << "Bytes in buffer: " << NB_BYTE << endl;
// 	  //dgDEBUG(35) << "Copie" <<endl<<file.str ()<< endl;

// 	  for( unsigned int index=0;index<NB_BYTE;index+=SIZE )
// 	    {
// 	      pbuf->pubseekpos( index );
// 	      int nget = pbuf->sgetn( buffer,SIZE );
// 	      dgDEBUG(35) << "Copie ["<<nget<<"] " <<buffer<<endl;
// 	      hardFile.write( buffer,nget );
// 	    }
	  //hardFile << file.str () << flush;
	  //file.seekp(0);

	  file->dump( hardFile );
	  file->empty ();
	  hardFile.flush ();

	  //file.str("");
	}

      ++iter; ++hardIter;
    }

  dgDEBUGOUT(15);
}

void TracerRealTime::
emptyBuffers  ()
{
  dgDEBUGIN(15);
  for( FileList::iterator iter = files.begin ();files.end ()!=iter;++iter )
    {
      //std::stringstream & file = * dynamic_cast< stringstream* >(*iter);
      try {
	OutStringStream & file  = * dynamic_cast< OutStringStream* >(*iter);
	file.empty ();
	//file.str("");
      }
      catch( ... ) { DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN,
						   "The buffer is not open",""); }
    }
  dgDEBUGOUT(15);
}

// void TracerRealTime::
// emptyBuffer( std::stringstream & file )
// {
//   streambuf * pbuf = file.rdbuf ();
//   pbuf->file.rdbuf () ->pubsetbuf( fileBuffer,10 );

// }
void TracerRealTime::
recordSignal( std::ostream& os,
	      const SignalBase<int>& sig )
{
  dgDEBUGIN(15);

  try {

    OutStringStream & file = dynamic_cast< OutStringStream& >(os);
    file.str("");
    dgDEBUG(45) << "Empty file [" << file.tellp ()
		 << "] <" << file.str ().c_str () <<"> " <<endl;

    Tracer::recordSignal( file,sig );
    file.addData( file.str ().c_str (),file.tellp () );
    dgDEBUG(35) << "Write data [" << file.tellp ()
		 << "] <" << file.str ().c_str () <<"> " <<endl;

  } catch( ExceptionAbstract & exc ) { throw exc; }
  catch( ... ) {
    DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN,
				  "The buffer is not open","");
  }

  dgDEBUGOUT(15);
  return ;
}

/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --------------------------------------------------------------------- */

void TracerRealTime::
display( std::ostream& os ) const
{
  os << CLASS_NAME << " " << name << " [mode=" << (play?"play":"pause")
     << "] : "<< endl
     << "  - Dep list: "<<endl;

  FileList::const_iterator iterFile = files.begin ();
  for( SignalList::const_iterator iter = toTraceSignals.begin ();
       toTraceSignals.end ()!=iter;++iter )
    {
      dgDEBUG(35) << "Next" << endl;
      const OutStringStream * file = dynamic_cast< OutStringStream* >(*iterFile);
      os << "     -> "<<(*iter)->getName ();
      if( file->givenname.length () ) os << " (in " << file->givenname << ")" ;
      os << "\t";
      if( file )
	{
	  const std::streamsize PRECISION = os.precision ();
	  const std::streamsize SIZE = file->index;
	  const std::streamsize MSIZE = file->bufferSize;
	  unsigned int dec=0; std::string unit ="";
	  if( (SIZE>>30)||(MSIZE>>30) ) { dec = 30; unit="Go"; }
	  else if( (SIZE>>20)||(MSIZE>>20) ) { dec = 20; unit="Mo"; }
	  else if( (SIZE>>10)||(MSIZE>>10) ) { dec = 10; unit="Ko"; }
 	  os << "[" << std::setw(1)<<std::setprecision(1)
 	     << (((double)SIZE+0.0)/(1<<dec)) << unit << "/"
 	     << std::setprecision(2)<<(((double)MSIZE+0.0)/(1<<dec))
 	     << unit << "]\t";
	  if( file->full ) os << "(FULL)";
	  os.precision(PRECISION);
	}
      os<<endl;
      iterFile++;
    }

}

std::ostream& operator<< ( std::ostream& os,const TracerRealTime& t )
{
  t.display(os);
  return os;
}

ext: cpp

max_stars_repo_name: ksyy/dynamic-graph

max_issues_repo_name: ksyy/dynamic-graph

max_forks_repo_name: ksyy/dynamic-graph


text:
#ifndef HOST_HPP
#define HOST_HPP

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <exception>
#include <iostream>
#include <unordered_map>
#include <memory>
#include <sstream>

#include "Service.hpp"
#include "Port.hpp"

using namespace boost::property_tree;
using namespace std;

class Host {
public:
  Host(string);
  void print_vulnerabilities();
  unordered_map<Port, Service> get_vulnerabilities();
  void load();
  string toJSON();
private:
  string host_scan_file;
  unordered_map<Port, Service> running_services;
  string os;
  string ip;
};

#endif

max_stars_repo_name: cyberImperial/attack-graphs

max_issues_repo_name: BenDerPan/attack-graphs

max_forks_repo_name: BenDerPan/attack-graphs


text:
/*
 * #%L
 * %%
 * Copyright (C) 2018 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

#include <boost/format.hpp>
#include <limits>

#include "mococrw/hash.h"
#include "mococrw/asymmetric_crypto_ctx.h"

namespace mococrw {

    using namespace openssl;

    using SSL_RSA_ENCRYPTION_DATA_Ptr = std::unique_ptr<unsigned char, SSLFree<unsigned char>>;

    using SSL_SIGNATURE_DATA_Ptr = std::unique_ptr<unsigned char, SSLFree<unsigned char>>;

    /* #############
     * #  Helpers  #
     * #############
     */

    /*
     * Creates the digest of the given message using the specified hash function
     */
    std::vector<uint8_t> createHash(openssl::DigestTypes hashFunction,
                                    const std::vector<uint8_t>& message) {
        switch (hashFunction) {
            case openssl::DigestTypes::SHA1:
                return sha1(message);
            case openssl::DigestTypes::SHA256:
                return sha256(message);
            case openssl::DigestTypes::SHA384:
                return sha384(message);
            case openssl::DigestTypes::SHA512:
                return sha512(message);
            default:
                throw MoCOCrWException("Unknown Hash Function");
        };
    }

    /*
     * Performs the signature using the openssl EVP_PKEY_sign interface
     * (common for RSA and ECDSA signatures)
     */
    std::vector<uint8_t> signHelper(SSL_EVP_PKEY_CTX_Ptr& keyCtx,
                                    const std::vector<uint8_t>& toBeSigned) {
        size_t sigLen;
        SSL_SIGNATURE_DATA_Ptr signatureData;

        _EVP_PKEY_sign(keyCtx.get(),
                       nullptr,
                       &sigLen,
                       reinterpret_cast<const unsigned char *>(toBeSigned.data()),
                       toBeSigned.size());

        signatureData.reset(static_cast<unsigned char *>(_OPENSSL_malloc(sigLen)));

        _EVP_PKEY_sign(keyCtx.get(),
                       signatureData.get(),
                       &sigLen,
                       reinterpret_cast<const unsigned char *>(toBeSigned.data()),
                       toBeSigned.size());

        return std::vector<uint8_t>(signatureData.get(), signatureData.get() + sigLen);
    }

    /*
     * Interface Destructors
     */
    EncryptionCtx::~EncryptionCtx() = default;
    DecryptionCtx::~DecryptionCtx() = default;
    DigestSignatureCtx::~DigestSignatureCtx() = default;
    MessageSignatureCtx::~MessageSignatureCtx() = default;
    DigestVerificationCtx::~DigestVerificationCtx() = default;
    MessageVerificationCtx::~MessageVerificationCtx() = default;

    /*
     * Base class for signature contexts that support specifying a hash function
     */
    class SignatureCtxImpl {
    public:
        SignatureCtxImpl(openssl::DigestTypes hashFunction) : hashFunction(hashFunction) {}

        openssl::DigestTypes hashFunction;
    };

    /*
     * ####################
     * #  RSA Encryption  #
     * ####################
     */

    /*
     * Common base class for all PIMPL classes of the RSA contexts
     *
     * Implements the check if the given key is a RSA key in the constructor and enables
     * to call the prepareOpenSSLContext method on the given padding.
     */
    template <class Key, class PaddingBase>
    class RSAImpl {
    public:
        /*
         * Constructor that checks the type of the given key
         */
        RSAImpl(const Key& key, std::shared_ptr<PaddingBase> padding) : key(key), padding(padding) {
            // Not really nice but necessary since we can't get rid of the generic keypair
            if (key.getType() != AsymmetricKey::KeyTypes::RSA) {
                throw MoCOCrWException("Expected RSA Key for RSA operation");
            }
        }

        Key key;
        std::shared_ptr<PaddingBase> padding;
    };

    /*
     * Intermediate base type for RSA Encryption Contexts
     */
    template<class Key>
    using RSAEncryptionImpl = RSAImpl<Key, RSAEncryptionPadding>;

    /*
     * PIMPL-Class of RSAEncryptionPrivateKeyCtx
     */
    class RSAEncryptionPrivateKeyCtx::Impl : public RSAEncryptionImpl<AsymmetricPrivateKey> {
        using RSAEncryptionImpl<AsymmetricPrivateKey>::RSAEncryptionImpl;
    };

    RSAEncryptionPrivateKeyCtx::RSAEncryptionPrivateKeyCtx(const AsymmetricPrivateKey& key,
                                                           std::shared_ptr<RSAEncryptionPadding> padding)
        : _impl(std::make_unique<RSAEncryptionPrivateKeyCtx::Impl>(key, padding)) {}

    RSAEncryptionPrivateKeyCtx::~RSAEncryptionPrivateKeyCtx() = default;

    RSAEncryptionPrivateKeyCtx::RSAEncryptionPrivateKeyCtx(const RSAEncryptionPrivateKeyCtx& other)
        : _impl(std::make_unique<RSAEncryptionPrivateKeyCtx::Impl>(*(other._impl))) {}

    RSAEncryptionPrivateKeyCtx& RSAEncryptionPrivateKeyCtx::operator=(const RSAEncryptionPrivateKeyCtx& other) {
        this->_impl = std::make_unique<RSAEncryptionPrivateKeyCtx::Impl>(*(other._impl));
        return *this;
    }

    std::vector<uint8_t> RSAEncryptionPrivateKeyCtx::decrypt(const std::vector<uint8_t>& message) {
        size_t decryptedMessageLen{0};
        SSL_RSA_ENCRYPTION_DATA_Ptr decryptedMessage{nullptr};

        try {
            auto keyCtx = _EVP_PKEY_CTX_new(_impl->key.internal());
            _EVP_PKEY_decrypt_init(keyCtx.get());

            /* Preform padding specific configurations*/
            _impl->padding->prepareOpenSSLContext(keyCtx);

            /* First call to determine the buffer length */
            _EVP_PKEY_decrypt(keyCtx.get(), nullptr, &decryptedMessageLen,
                              reinterpret_cast<const unsigned char *>(message.data()),
                              message.size());

            decryptedMessage.reset(static_cast<unsigned char*>(
                                           _OPENSSL_malloc(static_cast<int>(decryptedMessageLen))));

            /* Second call to perform the actual decryption */
            _EVP_PKEY_decrypt(keyCtx.get(), decryptedMessage.get(), &decryptedMessageLen,
                              reinterpret_cast<const unsigned char *>(message.data()),
                              message.size());

        } catch (const OpenSSLException &e) {
            throw MoCOCrWException(e.what());
        }

        return std::vector<uint8_t>(decryptedMessage.get(),
                                    decryptedMessage.get() + decryptedMessageLen);
    }

    /*
     * PIMPL-Class of RSAEncryptionPublicKeyCtx
     */
    class RSAEncryptionPublicKeyCtx::Impl : public RSAEncryptionImpl<AsymmetricPublicKey> {
        using RSAEncryptionImpl<AsymmetricPublicKey>::RSAEncryptionImpl;
    };

    RSAEncryptionPublicKeyCtx::RSAEncryptionPublicKeyCtx(const AsymmetricPublicKey& key,
                                                         std::shared_ptr<RSAEncryptionPadding> padding)
        : _impl(std::make_unique<RSAEncryptionPublicKeyCtx::Impl>(key, padding)) {}

    RSAEncryptionPublicKeyCtx::RSAEncryptionPublicKeyCtx(const X509Certificate& cert,
                                                         std::shared_ptr<RSAEncryptionPadding> padding)
        : RSAEncryptionPublicKeyCtx(cert.getPublicKey(), padding) {}

    RSAEncryptionPublicKeyCtx::RSAEncryptionPublicKeyCtx(const RSAEncryptionPublicKeyCtx& other)
        : _impl(std::make_unique<RSAEncryptionPublicKeyCtx::Impl>(*(other._impl))) {}

    RSAEncryptionPublicKeyCtx::~RSAEncryptionPublicKeyCtx() = default;

    RSAEncryptionPublicKeyCtx& RSAEncryptionPublicKeyCtx::operator=(const RSAEncryptionPublicKeyCtx& other) {
        this->_impl = std::make_unique<RSAEncryptionPublicKeyCtx::Impl>(*(other._impl));
        return *this;
    }

    std::vector<uint8_t> RSAEncryptionPublicKeyCtx::encrypt(const std::vector<uint8_t>& message) {
        SSL_RSA_ENCRYPTION_DATA_Ptr encryptedMessage{nullptr};
        size_t encryptedMessageLen{0};

        try {
            auto keyCtx = _EVP_PKEY_CTX_new(_impl->key.internal());
            if (!keyCtx.get()) {
                throw MoCOCrWException("Encryption context is empty");
            }

            // Check if message can be encrypted using the given key
            if (static_cast<size_t>(std::numeric_limits<int>::max()) < message.size()) {
                throw MoCOCrWException("Message size exceeds possible key size");
            } else if (!_impl->padding->checkMessageSize(_impl->key, message.size())) {
                throw MoCOCrWException((boost::format{"Message of size %1% can't be encrypted using"
                                                      " the given key and padding"}
                                                      % message.size()).str());
            }

            _EVP_PKEY_encrypt_init(keyCtx.get());
            _impl->padding->prepareOpenSSLContext(keyCtx);

            /* First call to determine the buffer length */
            _EVP_PKEY_encrypt(keyCtx.get(),
                              nullptr,
                              &encryptedMessageLen,
                              reinterpret_cast<const unsigned char *>(message.data()),
                              message.size());

            /* Allocate memory for the buffer, based on the size returned by _EVP_PKEY_encrypt */
            encryptedMessage.reset(static_cast<unsigned char*>(
                                           _OPENSSL_malloc(static_cast<int>(encryptedMessageLen))));

            /* Second call to perform the actual encryption */
            _EVP_PKEY_encrypt(keyCtx.get(),
                              encryptedMessage.get(),
                              &encryptedMessageLen,
                              reinterpret_cast<const unsigned char *>(message.data()),
                              message.size());

        } catch (const OpenSSLException &e) {
            throw MoCOCrWException(e.what());
        }

        return std::vector<uint8_t>(encryptedMessage.get(),
                                    encryptedMessage.get() + encryptedMessageLen);

    }

    /*
     * ###################
     * #  RSA Signature  #
     * ###################
     */

    /*
     * Intermediate base class for RSA Signature PIMPL classes
     *
     * Implements the retrieving of the hash function to be used of the stored padding object
     */
    template <class Key>
    class RSASignatureImpl : public RSAImpl<Key, RSASignaturePadding>, public SignatureCtxImpl {
    public:
        RSASignatureImpl(const Key& key, openssl::DigestTypes hashFunction, std::shared_ptr<RSASignaturePadding> padding)
            : RSAImpl<Key, RSASignaturePadding>(key, padding), SignatureCtxImpl(hashFunction) {}
    };

    /*
     * PIMPL-Class for RSASignaturePrivateKeyCtx
     */
    class RSASignaturePrivateKeyCtx::Impl : public RSASignatureImpl<AsymmetricPrivateKey> {
        using RSASignatureImpl<AsymmetricPrivateKey>::RSASignatureImpl;
    };

    RSASignaturePrivateKeyCtx::RSASignaturePrivateKeyCtx(const AsymmetricPrivateKey& key,
                                                         openssl::DigestTypes hashFunction,
                                                         std::shared_ptr<RSASignaturePadding> padding)
        : _impl(std::make_unique<RSASignaturePrivateKeyCtx::Impl>(key, hashFunction, padding)) {}

    RSASignaturePrivateKeyCtx::RSASignaturePrivateKeyCtx(const RSASignaturePrivateKeyCtx& other)
        : _impl(std::make_unique<RSASignaturePrivateKeyCtx::Impl>(*(other._impl))) {}

    RSASignaturePrivateKeyCtx& RSASignaturePrivateKeyCtx::operator=(const RSASignaturePrivateKeyCtx& other) {
        this->_impl = std::make_unique<RSASignaturePrivateKeyCtx::Impl>(*(other._impl));
        return *this;
    }

    RSASignaturePrivateKeyCtx::~RSASignaturePrivateKeyCtx() = default;

    std::vector<uint8_t> RSASignaturePrivateKeyCtx::signDigest(const std::vector<uint8_t> &messageDigest) {
        size_t expectedDigestSize = Hash::getDigestSize(_impl->hashFunction);
        if (messageDigest.size() != expectedDigestSize) {
            throw MoCOCrWException((boost::format{"Expected digest of size %1%"}
                                                  % expectedDigestSize).str());
        }

        try {
            auto keyCtx = _EVP_PKEY_CTX_new(_impl->key.internal());
            _EVP_PKEY_sign_init(keyCtx.get());

            _impl->padding->prepareOpenSSLContext(keyCtx, _impl->hashFunction);

            return signHelper(keyCtx, messageDigest);
        }
        catch (const OpenSSLException &e) {
            throw MoCOCrWException(e.what());
        }
    }

    std::vector<uint8_t> RSASignaturePrivateKeyCtx::signMessage(const std::vector<uint8_t> &message) {
        return signDigest(createHash(_impl->hashFunction, message));
    }

    /*
     * PIMPL-Class for RSASignaturePublicKeyCtx
     */
    class RSASignaturePublicKeyCtx::Impl : public RSASignatureImpl<AsymmetricPublicKey> {
        using RSASignatureImpl<AsymmetricPublicKey>::RSASignatureImpl;
    };

    RSASignaturePublicKeyCtx::RSASignaturePublicKeyCtx(const AsymmetricPublicKey& key,
                                                       openssl::DigestTypes hashFunction,
                                                       std::shared_ptr<RSASignaturePadding> padding)
        : _impl(std::make_unique<RSASignaturePublicKeyCtx::Impl>(key, hashFunction, padding)) {}

    RSASignaturePublicKeyCtx::RSASignaturePublicKeyCtx(const X509Certificate& cert,
                                                       openssl::DigestTypes hashFunction,
                                                       std::shared_ptr<RSASignaturePadding> padding)
        : RSASignaturePublicKeyCtx(cert.getPublicKey(), hashFunction, padding) {}

    RSASignaturePublicKeyCtx::RSASignaturePublicKeyCtx(const RSASignaturePublicKeyCtx& other)
        : _impl(std::make_unique<RSASignaturePublicKeyCtx::Impl>(*(other._impl))) {}

    RSASignaturePublicKeyCtx& RSASignaturePublicKeyCtx::operator=(const RSASignaturePublicKeyCtx& other) {
        this->_impl = std::make_unique<RSASignaturePublicKeyCtx::Impl>(*(other._impl));
        return *this;
    }

    RSASignaturePublicKeyCtx::~RSASignaturePublicKeyCtx() = default;

    void RSASignaturePublicKeyCtx::verifyDigest(const std::vector<uint8_t> &signature,
                                                const std::vector<uint8_t> &messageDigest) {

        size_t expectedDigestSize = Hash::getDigestSize(_impl->hashFunction);
        if (messageDigest.size() != expectedDigestSize) {
            throw MoCOCrWException((boost::format{"Expected digest of size %1%"}
                                                  % expectedDigestSize).str());
        }

        try {
            auto keyCtx = _EVP_PKEY_CTX_new(_impl->key.internal());
            _EVP_PKEY_verify_init(keyCtx.get());

            _impl->padding->prepareOpenSSLContext(keyCtx, _impl->hashFunction);

            _EVP_PKEY_verify(keyCtx.get(),
                             reinterpret_cast<const unsigned char *>(signature.data()),
                             signature.size(),
                             reinterpret_cast<const unsigned char *>(messageDigest.data()),
                             messageDigest.size());
        }
        catch (const OpenSSLException &e) {
            throw MoCOCrWException(e.what());
        }
    }

    void RSASignaturePublicKeyCtx::verifyMessage(const std::vector<uint8_t> &signature,
                                                 const std::vector<uint8_t> &message) {
        verifyDigest(signature, createHash(_impl->hashFunction, message));
    }

    /* ###########
     * #  ECDSA  #
     * ###########
     */

    /*
     * Common base class for all PIMPL classes of the ECDSA contexts
     *
     * Implements the check if the given key is a ECC key in the constructor.
     */
    template <class Key>
    class ECDSAImpl : public SignatureCtxImpl {
    public:
        ECDSAImpl(const Key& key, openssl::DigestTypes hashFunction) : SignatureCtxImpl(hashFunction), key(key) {
            // Not really nice but necessary since we can't get rid of the generic keypair
            if (key.getType() != AsymmetricKey::KeyTypes::ECC) {
                throw mococrw::MoCOCrWException("Expected ECC Key for ECC signatures");
            }
        }

        Key key;
    };

    /*
     * PIMPL-Class for ECDSASignaturePrivateKeyCtx
     */
    class ECDSASignaturePrivateKeyCtx::Impl : public ECDSAImpl<AsymmetricPrivateKey> {
        using ECDSAImpl<AsymmetricPrivateKey>::ECDSAImpl;
    };

    ECDSASignaturePrivateKeyCtx::ECDSASignaturePrivateKeyCtx(const AsymmetricPrivateKey& key,
                                                             openssl::DigestTypes hashFunction)
        : _impl(std::make_unique<ECDSASignaturePrivateKeyCtx::Impl>(key, hashFunction)) {}

    ECDSASignaturePrivateKeyCtx::ECDSASignaturePrivateKeyCtx(const ECDSASignaturePrivateKeyCtx& other)
        : _impl(std::make_unique<ECDSASignaturePrivateKeyCtx::Impl>(*(other._impl))) {}

    ECDSASignaturePrivateKeyCtx& ECDSASignaturePrivateKeyCtx::operator=(const ECDSASignaturePrivateKeyCtx& other) {
        this->_impl = std::make_unique<ECDSASignaturePrivateKeyCtx::Impl>(*(other._impl));
        return *this;
    }

    ECDSASignaturePrivateKeyCtx::~ECDSASignaturePrivateKeyCtx() = default;

    std::vector<uint8_t> ECDSASignaturePrivateKeyCtx::signDigest(const std::vector<uint8_t> &messageDigest) {
        size_t expectedDigestSize = Hash::getDigestSize(_impl->hashFunction);
        if (messageDigest.size() != expectedDigestSize) {
            throw MoCOCrWException((boost::format{"Expected digest of size %1%"}
                                                  % expectedDigestSize).str());
        }

        try {
            auto keyCtx = _EVP_PKEY_CTX_new(_impl->key.internal());
            _EVP_PKEY_sign_init(keyCtx.get());

            return signHelper(keyCtx, messageDigest);
        }
        catch (const OpenSSLException &e) {
            throw MoCOCrWException(e.what());
        }
    }

    std::vector<uint8_t> ECDSASignaturePrivateKeyCtx::signMessage(const std::vector<uint8_t> &message) {
        return signDigest(createHash(_impl->hashFunction, message));
    }

    /*
     * PIMPL-Class for ECDSASignaturePublicKeyCtx
     */
    class ECDSASignaturePublicKeyCtx::Impl : public ECDSAImpl<AsymmetricPublicKey> {
        using ECDSAImpl<AsymmetricPublicKey>::ECDSAImpl;
    };

    ECDSASignaturePublicKeyCtx::ECDSASignaturePublicKeyCtx(const AsymmetricPublicKey& key,
                                                           openssl::DigestTypes hashFunction)
        : _impl(std::make_unique<ECDSASignaturePublicKeyCtx::Impl>(key, hashFunction)) {}

    ECDSASignaturePublicKeyCtx::ECDSASignaturePublicKeyCtx(const X509Certificate& cert,
                                                           openssl::DigestTypes hashFunction)
        : ECDSASignaturePublicKeyCtx(cert.getPublicKey(), hashFunction) {}

    ECDSASignaturePublicKeyCtx::ECDSASignaturePublicKeyCtx(const ECDSASignaturePublicKeyCtx& other)
        : _impl(std::make_unique<ECDSASignaturePublicKeyCtx::Impl>(*(other._impl))) {}

    ECDSASignaturePublicKeyCtx& ECDSASignaturePublicKeyCtx::operator=(const ECDSASignaturePublicKeyCtx& other) {
        this->_impl = std::make_unique<ECDSASignaturePublicKeyCtx::Impl>(*(other._impl));
        return *this;
    }

    ECDSASignaturePublicKeyCtx::~ECDSASignaturePublicKeyCtx() = default;

    void ECDSASignaturePublicKeyCtx::verifyDigest(const std::vector<uint8_t> &signature,
                                                  const std::vector<uint8_t> &messageDigest) {

        size_t expectedDigestSize = Hash::getDigestSize(_impl->hashFunction);
        if (messageDigest.size() != expectedDigestSize) {
            throw MoCOCrWException((boost::format{"Expected digest of size %1%"}
                                                  % expectedDigestSize).str());
        }

        try {
            auto keyCtx = _EVP_PKEY_CTX_new(_impl->key.internal());
            _EVP_PKEY_verify_init(keyCtx.get());

            _EVP_PKEY_verify(keyCtx.get(),
                             reinterpret_cast<const unsigned char *>(signature.data()),
                             signature.size(),
                             reinterpret_cast<const unsigned char *>(messageDigest.data()),
                             messageDigest.size());
        }
        catch (const OpenSSLException &e) {
            throw MoCOCrWException(e.what());
        }
    }

    void ECDSASignaturePublicKeyCtx::verifyMessage(const std::vector<uint8_t> &signature,
                                                   const std::vector<uint8_t> &message) {
        verifyDigest(signature, createHash(_impl->hashFunction, message));
    }

}

max_stars_repo_name: vkrikun/MoCOCrW

max_issues_repo_name: vkrikun/MoCOCrW

max_forks_repo_name: vkrikun/MoCOCrW


text:
#include "server.h"
#include "adapter.h"
#include "wallet/secstring.h"
#include "core/ecc_native.h"

#include "node/node.h"
#include "utility/cli/options.h"
#include "utility/logger.h"
#include "utility/helpers.h"
#include "utility/string_helpers.h"
#include "utility/log_rotation.h"

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

#include "version.h"

using namespace beam;
using namespace std;

#define LOG_FILES_DIR "logs"
#define FILES_PREFIX "explorer-node_"
#define API_PORT_PARAMETER "api_port"

struct Options {
    std::string nodeDbFilename;
    std::string accessControlFile;
    std::string nodeConnectTo;
    io::Address nodeListenTo;
    io::Address explorerListenTo;
    int logLevel;
    Key::IPKdf::Ptr ownerKey;
    static const unsigned logRotationPeriod = 3*60*60*1000; // 3 hours
    std::vector<uint32_t> whitelist;
    uint32_t logCleanupPeriod;
};

static bool parse_cmdline(int argc, char* argv[], Options& o);
static void setup_node(Node& node, const Options& o);

int main(int argc, char* argv[]) {
    Options options;
    if (!parse_cmdline(argc, argv, options)) {
        return 1;
    }

    const auto path = boost::filesystem::system_complete(LOG_FILES_DIR);
    auto logger = Logger::create(LOG_LEVEL_INFO, options.logLevel, options.logLevel, FILES_PREFIX, path.string());

    clean_old_logfiles(LOG_FILES_DIR, FILES_PREFIX, options.logCleanupPeriod);

    int retCode = 0;
    try {
        io::Reactor::Ptr reactor = io::Reactor::create();
        io::Reactor::Scope scope(*reactor);
        io::Reactor::GracefulIntHandler gih(*reactor);
        io::Timer::Ptr logRotateTimer = io::Timer::create(*reactor);

        LogRotation logRotation(*reactor, options.logRotationPeriod, options.logCleanupPeriod);

        Node node;
        setup_node(node, options);
        explorer::IAdapter::Ptr adapter = explorer::create_adapter(node);
        node.Initialize();
        explorer::Server server(*adapter, *reactor, options.explorerListenTo, options.accessControlFile, options.whitelist);
        LOG_INFO() << "Node listens to " << options.nodeListenTo << ", explorer listens to " << options.explorerListenTo;
        reactor->run();
        LOG_INFO() << "Done";
    } catch (const std::exception& e) {
        LOG_ERROR() << "EXCEPTION: " << e.what();
        retCode = 255;
	}
	catch (const beam::CorruptionException& e) {
		LOG_ERROR() << "Corruption: " << e.m_sErr;
		retCode = 255;
    } catch (...) {
        LOG_ERROR() << "NON_STD EXCEPTION";
        retCode = 255;
    }
    return retCode;
}

bool parse_cmdline(int argc, char* argv[], Options& o) {

    po::options_description cliOptions("Node explorer options");
    cliOptions.add_options()
        (cli::HELP_FULL, "list of all options")
        (cli::NODE_PEER, po::value<string>()->default_value("eu-node03.masternet.beam.mw:8100"), "peer address")
        (cli::PORT_FULL, po::value<uint16_t>()->default_value(10000), "port to start the local node on")
        (API_PORT_PARAMETER, po::value<uint16_t>()->default_value(8888), "port to start the local api server on")
        (cli::KEY_OWNER, po::value<string>()->default_value(""), "owner viewer key")
        (cli::PASS, po::value<string>()->default_value(""), "password for owner key")
        (cli::IP_WHITELIST, po::value<std::string>()->default_value(""), "IP whitelist")
        (cli::LOG_CLEANUP_DAYS, po::value<uint32_t>()->default_value(5), "old logfiles cleanup period(days)")
    ;

    cliOptions.add(createRulesOptionsDescription());

#ifdef NDEBUG
    o.logLevel = LOG_LEVEL_INFO;
#else
    o.logLevel = LOG_LEVEL_DEBUG;
#endif

    po::variables_map vm;
    try
    {
        po::store(po::command_line_parser(argc, argv) // value stored first is preferred
            .options(cliOptions)
            .style(po::command_line_style::default_style ^ po::command_line_style::allow_guessing)
            .run(), vm);

        if (vm.count(cli::HELP))
        {
            cout << cliOptions << std::endl;
            return false;
        }

        {
            std::ifstream cfg("explorer-node.cfg");

            if (cfg)
            {
                po::store(po::parse_config_file(cfg, cliOptions), vm);
            }
        }

        vm.notify();

        o.logCleanupPeriod = vm[cli::LOG_CLEANUP_DAYS].as<uint32_t>() * 24 * 3600;
        o.nodeDbFilename = FILES_PREFIX "db";
        //o.accessControlFile = "api.keys";

        o.nodeConnectTo = vm[cli::NODE_PEER].as<string>();
        o.nodeListenTo.port(vm[cli::PORT].as<uint16_t>());
        o.explorerListenTo.port(vm[API_PORT_PARAMETER].as<uint16_t>());

        std::string keyOwner = vm[cli::KEY_OWNER].as<string>();
        if (!keyOwner.empty())
        {
            SecString pass;
            if (!beam::read_wallet_pass(pass, vm))
                throw std::runtime_error("Please, provide password for the keys.");

            KeyString ks;
            ks.SetPassword(Blob(pass.data(), static_cast<uint32_t>(pass.size())));

            {
                ks.m_sRes = keyOwner;

                std::shared_ptr<ECC::HKdfPub> kdf = std::make_shared<ECC::HKdfPub>();
                if (!ks.Import(*kdf))
                    throw std::runtime_error("view key import failed");

                o.ownerKey = kdf;
            }
        }

#ifdef WIN32
        WSADATA wsaData = { };
        WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif

        std::string whitelist = vm[cli::IP_WHITELIST].as<string>();

        if (!whitelist.empty())
        {
            const auto& items = string_helpers::split(whitelist, ',');

            for (const auto& item : items)
            {
                io::Address addr;

                if (addr.resolve(item.c_str()))
                {
                    o.whitelist.push_back(addr.ip());
                }
                else throw std::runtime_error("IP address not added to whitelist: " + item);
            }
        }

        getRulesOptions(vm);

        return true;
    }
    catch (const po::error& ex)
    {
        cout << ex.what();
        cout << cliOptions << std::endl;
    }
    catch (const exception& ex)
    {
        cout << ex.what();
    }

    return false;
}

void setup_node(Node& node, const Options& o) {
    Rules::get().UpdateChecksum();
    LOG_INFO() << "Beam Node Explorer " << PROJECT_VERSION << " (" << BRANCH_NAME << ")";
    LOG_INFO() << "Rules signature: " << Rules::get().Checksum;

    node.m_Cfg.m_sPathLocal = o.nodeDbFilename;
    node.m_Cfg.m_Listen.port(o.nodeListenTo.port());
    node.m_Cfg.m_Listen.ip(o.nodeListenTo.ip());
    node.m_Cfg.m_MiningThreads = 0;
    node.m_Cfg.m_VerificationThreads = 1;

    node.m_Keys.m_pOwner = o.ownerKey;

    auto& address = node.m_Cfg.m_Connect.emplace_back();
    address.resolve(o.nodeConnectTo.c_str());
}

max_stars_repo_name: inix/beam

max_issues_repo_name: inix/beam

max_forks_repo_name: inix/beam


text:
//==================================================================================================
/*!
  @file

    @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_RSHL_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_RSHL_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-bitwise
    This function object returns the first entry shifted left or right
    by the absolute value of the second entry,
    according to its sign.

    @see  rshr, shr, shl

    @par Header <boost/simd/function/rshl.hpp>

    @par Example:

      @snippet rshl.cpp rshl

    @par Possible output:

      @snippet rshl.txt rshl

  **/
  Value rshl(Value const& x, IntegerValue const& n);
} }
#endif

#include <boost/simd/function/scalar/rshl.hpp>
#include <boost/simd/function/simd/rshl.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#include <QtWidgets>
#include <QStringList>

#include <boost/foreach.hpp>

#include "TabResponseHeaders.h"

TabResponseHeaders::TabResponseHeaders()
{
    createHeaderTable();

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(headersTable);
    setLayout(mainLayout);
}

void TabResponseHeaders::clear()
{
    headersTable->setRowCount(2);
    headersTable->setColumnCount(2);
}

void TabResponseHeaders::processHeaders(const QList<QNetworkReply::RawHeaderPair>& pairs)
{
    headersTable->setRowCount(pairs.count());
    int row = 0;
    BOOST_FOREACH(QNetworkReply::RawHeaderPair pair, pairs)
    {
        QString content = QString::fromUtf8(pair.first.data());
        QTableWidgetItem *nameItem = new QTableWidgetItem(content);
        headersTable->setItem(row, 0, nameItem);

        content = QString::fromUtf8(pair.second.data());
        QTableWidgetItem *valueItem = new QTableWidgetItem(content);
        headersTable->setItem(row, 1, valueItem);

        row++;
    }

    headersTable->resizeColumnsToContents();
}

void TabResponseHeaders::createHeaderTable()
{
    QStringList columns;
    columns << "name" << "value";

    headersTable = new QTableWidget();
    headersTable->verticalHeader()->setVisible(false);
    headersTable->setShowGrid(false);
    headersTable->setRowCount(2);
    headersTable->setColumnCount(2);
    headersTable->setHorizontalHeaderLabels(columns);
}

max_stars_repo_name: ararog/RestInspector

max_issues_repo_name: ararog/RestInspector

max_forks_repo_name: ararog/RestInspector


text:
// MIT License
// Copyright (c) 2017 Zhuhao Wang

// 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.

#include "nekit/instance.h"

#include <boost/assert.hpp>

#include "nekit/utils/error.h"
#include "nekit/utils/log.h"
#include "nekit/utils/system_resolver.h"

#undef NECHANNEL
#define NECHANNEL "Instance"

namespace nekit {

Instance::Instance(std::string name) : name_{name} {}

void Instance::AddProxyManager(std::unique_ptr<ProxyManager> &&proxy_manager) {
  BOOST_ASSERT(proxy_manager->GetRunloop() == GetRunloop());

  proxy_managers_.emplace_back(std::move(proxy_manager));
}

void Instance::Run() {
  BOOST_ASSERT(ready_);

  BOOST_LOG_SCOPED_THREAD_ATTR(
      "Instance", boost::log::attributes::constant<std::string>(name_));

  for (auto &manager : proxy_managers_) {
    manager->Run();
  }

  NEINFO << "Start running instance.";
  runloop_.Run();

  NEINFO << "Instance stopped.";
}

void Instance::Stop() {
  runloop_.Stop();
  for (auto &manager : proxy_managers_) {
    manager->Stop();
  }
  ready_ = false;
}

utils::Runloop *Instance::GetRunloop() { return &runloop_; }

}  // namespace nekit

ext: cc

max_stars_repo_name: fossabot/libnekit

max_issues_repo_name: fossabot/libnekit

max_forks_repo_name: fossabot/libnekit


text:
//
// Created by Gianluca on 17/12/2021.
// SPDX-License-Identifier: MIT
//

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>

#include <iostream>
#include <fstream>
#include <cassert>
#include <ranges>

using graph_t = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, boost::property<boost::edge_weight_t, int>>;
using vertex_descriptor = graph_t::vertex_descriptor;

struct early_stop_visitor : boost::default_dijkstra_visitor {
  using base = boost::default_dijkstra_visitor;
  struct done{};

  explicit early_stop_visitor(vertex_descriptor vd) : destination(vd) {}

  void finish_vertex(vertex_descriptor v, const graph_t& g) {
    if (v == destination) throw done{};
    base::finish_vertex(v, g);
  }

private:
  vertex_descriptor destination;
};

int main() {
  auto file = std::ifstream("../day15/input");
  assert(file.is_open());

  std::vector<std::vector<int>> weight_matrix;

  for (std::string line; std::getline(file, line); ) {
    weight_matrix.emplace_back();
    std::ranges::for_each(line, [&](auto c){ weight_matrix.back().emplace_back(c - '0'); });
  }

  auto tile_size = weight_matrix.size();
  weight_matrix.resize(tile_size * 5);
  std::ranges::for_each(weight_matrix, [&](auto& item){ item.resize(tile_size * 5); });

  for (auto h_tile_index = 1; h_tile_index < 5; ++h_tile_index) {
    for (auto v_tile_index = 0; v_tile_index < tile_size; ++v_tile_index) {
      auto origin_view = std::ranges::take_view(weight_matrix[((h_tile_index - 1) * tile_size) + v_tile_index], tile_size);
      auto insert_view = std::ranges::take_view(weight_matrix[(h_tile_index * tile_size) + v_tile_index], tile_size);
      std::transform(origin_view.begin(), origin_view.end(), insert_view.begin(), [&](const auto &num) { return (num + 1 == 10 ? 1 : num + 1); });
    }
  }

  std::ranges::for_each(weight_matrix, [&](auto& item){
    for (auto h_tile_index = 1; h_tile_index < 5; ++h_tile_index) {
      auto origin_view = std::ranges::take_view(std::ranges::drop_view(item, (h_tile_index - 1) * tile_size), tile_size);
      auto insert_view = std::ranges::take_view(std::ranges::drop_view(item, h_tile_index * tile_size), tile_size);
      std::transform(origin_view.begin(), origin_view.end(), insert_view.begin(), [&](const auto &num) { return (num + 1 == 10 ? 1 : num + 1); });
    }
  });

  std::vector<std::pair<int, int>> edges;
  std::vector<int> weights;
  for (int i = 0; i < weight_matrix.size(); ++i) {
    for (int j = 0; j < weight_matrix[i].size(); ++j) {
      if (i > 0) {
        edges.emplace_back(std::pair(weight_matrix.size() * i + j, (weight_matrix.size() * (i-1)) + j));
        weights.emplace_back(weight_matrix[i - 1][j]);
      }
      if (i < weight_matrix.size() - 1) {
        edges.emplace_back(std::pair(weight_matrix.size() * i + j, (weight_matrix.size() * (i+1)) + j));
        weights.emplace_back(weight_matrix[i + 1][j]);
      }
      if (j > 0) {
        edges.emplace_back(std::pair(weight_matrix.size() * i + j, (weight_matrix.size() * i) + j - 1));
        weights.emplace_back(weight_matrix[i][j - 1]);
      }
      if (j < weight_matrix[i].size() - 1) {
        edges.emplace_back(std::pair(weight_matrix.size() * i + j, (weight_matrix.size() * i) + j + 1));
        weights.emplace_back(weight_matrix[i][j + 1]);
      }
    }
  }

  int start_vertex = 0;
  int end_vertex = (weight_matrix.size() * weight_matrix[0].size()) - 1;

  graph_t g(edges.begin(), edges.end(), weights.begin(), weight_matrix.size() * weight_matrix[0].size());

  std::vector<int> distances(boost::num_vertices(g));
  early_stop_visitor vis(end_vertex);

  try {
    dijkstra_shortest_paths(g, start_vertex, boost::visitor(vis).distance_map(boost::make_iterator_property_map(distances.begin(), get(boost::vertex_index, g))));
  }
  catch(early_stop_visitor::done const&) {}

  std::cout << distances[end_vertex] << std::endl;

  return 0;
}


text:
// Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.

#include "Generic/common/leak_detection.h"

#include "Generic/common/InternalInconsistencyException.h"
#include "Generic/common/UTF8OutputStream.h"
#include "Generic/common/OStringStream.h"
#include "Generic/common/OutputUtil.h"
#include "Generic/common/ParamReader.h"
#include "Generic/common/XMLUtil.h"

#include "Generic/icews/ICEWSEventMention.h"
#include "Generic/icews/ICEWSEventMentionSet.h"
#include "Generic/icews/ICEWSActorInfo.h"
#include "Generic/icews/CAMEOXMLResultCollector.h"

#include "Generic/state/XMLStrings.h"
#include "Generic/state/XMLElement.h"
#include "Generic/theories/SentenceTheory.h"
#include "Generic/theories/DocTheory.h"
#include "Generic/theories/ActorMention.h"
#include "Generic/actors/ActorInfo.h"

#include <xercesc/dom/DOM.hpp>
#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/framework/MemBufFormatTarget.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

void CAMEOXMLResultCollector::loadDocTheory(DocTheory* theory) {
	_docTheory = theory;
}

std::wstring CAMEOXMLResultCollector::produceOutputHelper() {

	// Define macros
	static const XMLCh* X_CAMEO_XML = xercesc::XMLString::transcode("CAMEO_XML");
	static const XMLCh* X_Document = xercesc::XMLString::transcode("Document");
	static const XMLCh* X_Sentences = xercesc::XMLString::transcode("Sentences");
	static const XMLCh* X_Events = xercesc::XMLString::transcode("Events");
	static const XMLCh* X_Sentence = xercesc::XMLString::transcode("Sentence");
	static const XMLCh* X_Event = xercesc::XMLString::transcode("Event");
	static const XMLCh* X_id = xercesc::XMLString::transcode("id");
	static const XMLCh* X_tense = xercesc::XMLString::transcode("tense");
	static const XMLCh* X_type = xercesc::XMLString::transcode("type");
	static const XMLCh* X_char_offsets = xercesc::XMLString::transcode("char_offsets");
	static const XMLCh* X_sentence_id = xercesc::XMLString::transcode("sentence_id");

	Symbol SOURCE_SYM(L"SOURCE");
	Symbol TARGET_SYM(L"TARGET");

	// Make top element, and beneath it Sentences and Events elemetns
	xercesc::DOMImplementation* impl = xercesc::DOMImplementationRegistry::getDOMImplementation(SerifXML::X_Core);
	xercesc::DOMDocument *xercesDOMDocument = impl->createDocument(0, X_CAMEO_XML, 0);

	const wchar_t* doc_name = _docTheory->getDocument()->getName().to_string();
	SerifXML::XMLElement rootElem(xercesDOMDocument->getDocumentElement());
	SerifXML::XMLElement docElem = rootElem.addChild(X_Document);
	docElem.setAttribute(X_id, doc_name);
	SerifXML::XMLElement sentencesElem = docElem.addChild(X_Sentences);
	SerifXML::XMLElement eventsElem = docElem.addChild(X_Events);

	// Make Sentences elements
	for (int i = 0; i < _docTheory->getNSentences(); i++) {
		const Sentence *sentence = _docTheory->getSentence(i);
		CharOffset start_offset = sentence->getStartCharOffset();
		CharOffset end_offset = sentence->getEndCharOffset();
		std::wstringstream offsets;
		offsets << start_offset << L":" << end_offset;
		SerifXML::XMLElement sentenceElem = sentencesElem.addChild(X_Sentence);
		sentenceElem.setAttribute(X_id, i);
		sentenceElem.setAttribute(X_char_offsets, offsets.str());
		sentenceElem.addText(sentence->getString()->toString());
	}

	// Make Events elements from ICEWSEventMentions
	ICEWSEventMentionSet* eventMentionSet = _docTheory->getICEWSEventMentionSet();
	int i = 0;
	if (eventMentionSet) {
		int count = 0;
		BOOST_FOREACH(ICEWSEventMention_ptr em, (*eventMentionSet)) {

			if (em->isDatabaseWorthyEvent()) {

				SerifXML::XMLElement eventElem = eventsElem.addChild(X_Event);
				eventElem.setAttribute(X_id, i);
				i++;

				// Event Type, Tense, and Sentence ID
				eventElem.setAttribute(X_type, em->getEventType()->getEventCode());

				eventElem.setAttribute(X_tense, em->getEventTense().to_string());

				// Get Source Actor and Target Actor
				ActorMention_ptr sourceActor;
				ActorMention_ptr targetActor;
				typedef std::pair<Symbol, ActorMention_ptr> ParticipantPair;
				BOOST_FOREACH(const ParticipantPair &participantPair, em->getParticipantList()) {
					if (participantPair.first == TARGET_SYM) {
						targetActor = participantPair.second;
					} else if (participantPair.first == SOURCE_SYM) {
						sourceActor = participantPair.second;
					}
				}

				// Get sentence ID and offsets
				int serif_sent_no = sourceActor->getEntityMention()->getSentenceNumber();
				eventElem.setAttribute(X_sentence_id, serif_sent_no);
				const Sentence *sentence = _docTheory->getSentence(serif_sent_no);
				CharOffset start_offset = sentence->getStartCharOffset();
				CharOffset end_offset = sentence->getEndCharOffset();
				std::wstringstream offsets;
				offsets << start_offset << L":" << end_offset;
				eventElem.setAttribute(X_char_offsets, offsets.str());

				// Add actors
				addActorElement(eventElem, sourceActor, "Source");
				addActorElement(eventElem, targetActor, "Target");
			}
		}
	}

	return rootElem.toWString();
}

void CAMEOXMLResultCollector::addActorElement(SerifXML::XMLElement& eventElem, ActorMention_ptr am, std::string role) {

	static const XMLCh* X_actor_id = xercesc::XMLString::transcode("actor_id");
	static const XMLCh* X_actor_name = xercesc::XMLString::transcode("actor_name");
	static const XMLCh* X_agent_id = xercesc::XMLString::transcode("agent_id");
	static const XMLCh* X_agent_name = xercesc::XMLString::transcode("agent_name");
	static const XMLCh* X_char_offsets = xercesc::XMLString::transcode("char_offsets");
	static const XMLCh* X_role = xercesc::XMLString::transcode("role");
	static const XMLCh* X_Participant = xercesc::XMLString::transcode("Participant");

	ActorId actorID = ActorId();
	AgentId agentID = AgentId();
	std::wstring actorName = L"";
	std::wstring agentName = L"";

	if (ProperNounActorMention_ptr pm = boost::dynamic_pointer_cast<ProperNounActorMention>(am)) {
		actorID = pm->getActorId();
		actorName = pm->getActorName();
	} else if (CompositeActorMention_ptr cm = boost::dynamic_pointer_cast<CompositeActorMention>(am)) {
		agentID = cm->getPairedAgentId();
		agentName = cm->getPairedAgentName();
		actorID = cm->getPairedActorId();
		actorName = cm->getPairedActorName();
	}

	if (!actorID.isNull()) {
		SerifXML::XMLElement actorElem = eventElem.addChild(X_Participant);
		actorElem.setAttribute(X_role, role);
		std::wstring actor_id = boost::lexical_cast<std::wstring>(actorID.getId());
		actorElem.setAttribute(X_actor_id, actor_id);
		actorElem.setAttribute(X_actor_name, actorName);
		if (!agentID.isNull()) {
			std::wstring agent_id = boost::lexical_cast<std::wstring>(agentID.getId());
			actorElem.setAttribute(X_agent_id, agent_id);
			actorElem.setAttribute(X_agent_name, agentName);
		}
		// Add in character offsets for this actor
		int start_sentence_number = am->getEntityMention()->getSentenceNumber();
		int start_token = am->getEntityMention()->getNode()->getStartToken();
		CharOffset start_offset = am->getSentence()->getTokenSequence()->getToken(start_token)->getStartCharOffset();
		int end_sentence_number = am->getEntityMention()->getSentenceNumber();
		int end_token = am->getEntityMention()->getNode()->getEndToken();
		CharOffset end_offset = am->getSentence()->getTokenSequence()->getToken(end_token)->getEndCharOffset();
		std::wstringstream offsets;
		offsets << start_offset << L":" << end_offset;
		actorElem.setAttribute(X_char_offsets, offsets.str());
	}
}

void CAMEOXMLResultCollector::produceOutput(const wchar_t *output_dir,
									     const wchar_t *doc_filename)
{
	// File name
	std::wstring output_file = std::wstring(output_dir) + LSERIF_PATH_SEP + std::wstring(doc_filename);
	if (!boost::algorithm::ends_with(output_file, L".xml")) {
		output_file += L".cameo.xml";
	} else {
		output_file = boost::algorithm::replace_last_copy(output_file, ".xml", ".cameo.xml");
	}

	// Open output stream
	UTF8OutputStream stream;
	stream.open(output_file.c_str());

	std::wstring results = produceOutputHelper();

	// Write out
	stream << results;

	stream.close();
}

void CAMEOXMLResultCollector::produceOutput(std::wstring *results) { *results = produceOutputHelper(); }

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
/*!
 * @file CommandLineParser.hpp
 *
 * @date Oct 8, 2021
 * @author Tim Spain <timothy.spain@nersc.no>
 */

#ifndef SRC_INCLUDE_COMMANDLINEPARSER_HPP
#define SRC_INCLUDE_COMMANDLINEPARSER_HPP

#include <boost/program_options.hpp>
#include <string>
#include <vector>

namespace Nextsim {

/*!
 * A class to parse the neXtSIM_DG command line.
 */
class CommandLineParser {
public:
    /*!
     * Parse the command line for command line options.
     *
     * @param argc the count of passed arguments.
     * @param argv The array of C strings passed as arguments.
     */
    CommandLineParser(int argc, char* argv[]);
    virtual ~CommandLineParser() = default;

    /*!
     * Return a std::vector of the file names declared as config files on the
     * command line, in order.
     */
    std::vector<std::string> getConfigFileNames();

private:
    CommandLineParser() = default;

    boost::program_options::variables_map m_arguments;
    std::vector<std::string> m_configFilenames;
};

} /* namespace Nextsim */

#endif /* SRC_INCLUDE_COMMANDLINEPARSER_HPP */

max_stars_repo_name: athelaf/nextsimdg

max_issues_repo_name: athelaf/nextsimdg

max_forks_repo_name: athelaf/nextsimdg


text:
//////////////////////////////////////////////////////////////////////////////
//  Boost.Assign v2                                                         //
//                                                                          //
//  Copyright (C) 2003-2004 Thorsten Ottosen                                //
//  Copyright (C) 2011 Erwann Rogard                                        //
//  Use, modification and distribution are subject to 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_ASSIGN_V2_CONVERSION_CONVERT_ER_2011_HPP
#define BOOST_ASSIGN_V2_CONVERSION_CONVERT_ER_2011_HPP
#include <boost/assign/v2/support/pp/ignore.hpp>
#include <boost/assign/v2/support/keyword.hpp>
#include <boost/assign/v2/put/csv_put.hpp>
#include <boost/range/algorithm/for_each.hpp>

namespace boost{
namespace assign{
namespace v2{
namespace convert_tag{

    struct put{};
    struct copy{};

}// convert_tag
//[syntax_conversion_convert
namespace conversion_aux{
//<-

    template<typename C, typename R>
    C csv_put_copy(C& cont, R const& range)
    {
        put( cont ).for_each( range );
        return cont;
    }

    template<typename C, typename Arg>
    Arg const& initializer( Arg const& arg )
    {
        return arg;
    }

    template<typename C, typename Arg, typename R>
    C dispatch(Arg const& arg, R const& range, convert_tag::put)
    {
        C cont( initializer<C>( arg ) );
        return csv_put_copy( cont, range );
    }

    template<typename C, typename R>
    C dispatch(kwd_nil_, R const& range, convert_tag::put)
    {
        C cont; return csv_put_copy( cont, range );
    }

    template<typename C, typename R>
    C dispatch(kwd_nil_, R const& r, convert_tag::copy)
    {
        return C( boost::begin( r ), boost::end( r ) );
    }

    template<typename C, typename R>
    struct deduce_tag;

    template<typename C, typename Arg, typename R>
    C dispatch(Arg const& arg, R const& r)/*<-*/
    {
        typedef typename deduce_tag<C, R>::type tag_;
        return dispatch<C>( arg, r, tag_() );
    }BOOST_ASSIGN_V2_IGNORE(/*->*/;/*<-*/)/*->*/

//->

    template<typename C, typename Arg = kwd_nil_>
    struct convert/*<-*/
    {

        convert(){}
        convert(Arg arg):arg_( arg ){}

        Arg const& arg()const{ return this->arg_; }

        private:
        mutable Arg arg_;

    }/*->*/;

    template<typename R, typename C, typename Arg>
    C operator|( R const& r, convert<C, Arg> const& adapter)/*<-*/
    {
        return dispatch<C>( adapter.arg(), r );
    }BOOST_ASSIGN_V2_IGNORE(/*->*/;/*<-*/)/*->*/

}// conversion_aux

    template<typename C, typename Arg = kwd_nil_>
    struct convert/*<-*/
        : conversion_aux::convert<C, Arg>
    /*->*/
    {
//<-
        typedef conversion_aux::convert<C> super_t;
//->

        convert()/*<-*/{}BOOST_ASSIGN_V2_IGNORE(/*->*/;/*<-*/)/*->*/
        convert(Arg const& arg)/*<-*/
            : super_t( arg )
        {}BOOST_ASSIGN_V2_IGNORE(/*->*/;/*<-*/)/*->*/

        template<typename Arg1>
        convert<C, Arg1>
        operator^(Arg1 const& arg1)/*<-*/
        {
            return convert<C, Arg1>( arg1 );
        }BOOST_ASSIGN_V2_IGNORE(/*->*/;/*<-*/)/*->*/

    };

//]
}// v2
}// assign
}// boost

#include <boost/assign/v2/conversion/deduce_tag.hpp>

#endif //  BOOST_ASSIGN_V2_CONVERSION_CONVERT_ER_2011_HPP


text:
//
//  searcher.cpp
//  Andrews-Curtis Conjecture
//
//  Created by Kelly Davis on 8/19/11.
//
//

#include <list>
#include <queue>
#include <memory>
#include <vector>
#include <utility>
#include <iostream>
#include <functional>

#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/scoped_array.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/mpi/nonblocking.hpp>
#include <boost/serialization/list.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <boost/mpi/collectives.hpp>
#include <boost/mpi/communicator.hpp>

#include "relator.h"
#include "globals.h"
#include "searcher.h"
#include "arguments.h"
#include "binary_tree.h"
#include "boost/threadpool.hpp"
#include "balanced_presentation.h"
#include "balanced_presentation_nursery.h"

// Mutex for in_values
static boost::mutex s_in_values_mutex;

// Mutex for queue
static boost::mutex s_queue_mutex;

// Queue to hold elements in the next level
static std::queue<andrews_curtis::Balanced_presentation*> s_balanced_presentation_queue;

namespace andrews_curtis
{
    // Typedefs
    typedef std::list<Balanced_presentation*>::iterator Itr;
  	typedef std::queue<andrews_curtis::Balanced_presentation*>::size_type queue_size_type;

  	// Utility function to obtain children
  	void obtain_children(std::vector< std::list<Balanced_presentation*> > *in_values);

  	// Utility function to clear lists
  	void clear_list(std::list<Balanced_presentation*> *list);

  	// Utility function to delete a Balanced_presentation
  	void delete_balanced_presentation(Balanced_presentation *balanced_presentation);

  	// Utility function to insert Balanced presentations
  	void insert_balanced_presentation(Balanced_presentation *balanced_presentation,bool *is_trivial,Balanced_presentation **trivial_presentation);

    Searcher::Searcher(const Arguments &arguments)
    :   m_is_trivial(false),
        m_counterexample(),
        m_arguments(arguments),
        m_trivial_presentation(0)
    {
        // New up a Balanced_presentation
        std::auto_ptr<Balanced_presentation> balanced_presentation(new Balanced_presentation());

        // Define array of Relator's
        boost::scoped_array< std::auto_ptr<Relator> > relators(new std::auto_ptr<Relator>[g_relators_count]);

        // Loop over user relators
        for(unsigned int index = 0; index < g_relators_count; ++index)
        {
            // New up a Relator with 'index' relator from m_arguments
            relators[index] = std::auto_ptr<Relator>(new Relator(m_arguments.get_relators()[index]));

            // Insert relator into balanced_presentation
            balanced_presentation->set_relator(relators[index].get(), index);
        }

        // Set m_counterexample
        m_counterexample = "Counterexample:\n";
        m_counterexample += balanced_presentation->to_string();

        // Define the world communicator in which we reside
        boost::mpi::communicator communicator;

        // Is this process the home of balanced_presentation?
        if(communicator.rank() == balanced_presentation->get_process())
        {
            // Insert Relators into scapegoat tree and give up ownership
            for(unsigned int index = 0; index < g_relators_count; ++index)
                Binary_tree<Relator>::insert(relators[index].release());

            // Push the Balanced_presentation onto the queue
            s_balanced_presentation_queue.push(balanced_presentation.get());

            // Insert Balanced_presentation into scapegoat tree and give up ownership
            Binary_tree<Balanced_presentation>::insert(balanced_presentation.release());
        }
    }

    void Searcher::search()
    {
    		// Define a thread pool with hardware_concurrency threads
    		boost::threadpool::thread_pool<> thread_pool(boost::thread::hardware_concurrency());

    		// Define variable to hold the current level
    		unsigned long level = 0;

        // Define the world communicator in which we reside
        boost::mpi::communicator communicator;

    		// Log the number of threads in the thread pool
    		std::cout << "Process: " << communicator.rank() << " Thread pool size: " << thread_pool.size() << std::endl;

        // Define vector to hold values to send
        std::vector< std::list<Balanced_presentation*> > in_values(communicator.size());

        // Define vector to hold values to receive
        std::vector< std::list<Balanced_presentation*> > out_values(communicator.size());

        // Loop forever
        while(true)
        {
      			// Obtain length of local Relator Binary_tree
      			unsigned long local_relator_length = Binary_tree<Relator>::length();

      			// Define a variable to hold the length of the global Relator Binary_tree
      			unsigned long global_relator_length;

      			// Obtain global Relator length
      			boost::mpi::reduce(communicator,local_relator_length,global_relator_length, std::plus<unsigned long>(),0);

      			// Obtain size of local Relator Binary_tree
      			unsigned long local_relator_size = Binary_tree<Relator>::size();

      			// Define a variable to hold the size of the global Relator Binary_tree
      			unsigned long global_relator_size;

      			// Obtain global Relator size
      			boost::mpi::reduce(communicator,local_relator_size,global_relator_size, std::plus<unsigned long>(),0);

      			// Obtain size of local Balanced_presentation Binary_tree
      			unsigned long local_balanced_presentation_size = Binary_tree<Balanced_presentation>::size();

      			// Define a variable to hold the size of the global Balanced_presentation Binary_tree
      			unsigned long global_balanced_presentation_size;

      			// Obtain global Balanced_presentation size
      			boost::mpi::reduce(communicator,local_balanced_presentation_size,global_balanced_presentation_size, std::plus<unsigned long>(),0);

      			// If we are process 0
      			if(!communicator.rank())
      			{
      				// Print current level
      				std::cout << std::endl << "Completed level: " << level++ << std::endl;

      				// Obtain start time
      				static boost::posix_time::ptime start_time(boost::posix_time::microsec_clock::local_time());

      				// Obtain stop time
      				boost::posix_time::ptime stop_time(boost::posix_time::microsec_clock::local_time());

      				// Obtain difference between start_time and stop_time
      				boost::posix_time::time_duration time_difference = stop_time - start_time;

      				// Print runtime
      				std::cout << "\tUptime: " << time_difference.total_milliseconds() << "ms" << std::endl;

      				// Print Relator count
      				std::cout << "\tRelators: " << global_relator_size << std::endl;

      				// Print Balanced_presentation count
      				std::cout << "\tBalanced_presentations: " << global_balanced_presentation_size << std::endl;

      				// Print Average Relator length
      				std::cout << "\tAverage Relator Length: " << (static_cast<double>(global_relator_length)/global_relator_size) << std::endl;

      				// Print Average Balanced presentation length
      				std::cout << "\tAverage Balanced presentation Length: " << g_relators_count*(static_cast<double>(global_relator_length)/global_relator_size) << std::endl;
      			}

      			// Obtain size of s_balanced_presentation_queue
      			queue_size_type queue_size = s_balanced_presentation_queue.size();

      			// Schedule tasks on thread_pool
      			for(queue_size_type index = 0; index < queue_size; ++index)
      				thread_pool.schedule(boost::bind(obtain_children,&in_values));

      			// Wait until all children have been obtained
      			thread_pool.wait();

      			// Loop over processes and do our hand rolled all to all to save on memory
      			for(unsigned int process = 0; process < communicator.size(); ++process)
      			{
      				// Determine destinaion of send
              int destinaion = (communicator.rank() + process) % communicator.size();

      				// Determine source of recieve
      				int source = (communicator.rank() - process + communicator.size()) % communicator.size();

      				// Define requests
      				boost::mpi::request requests[2];

      				// Start recieve from source
      				requests[0] = communicator.irecv(source,0,out_values[source]);

      				// Start send to destinaion
      				requests[1] = communicator.isend(destinaion,0,in_values[destinaion]);

      				// Wait on requests
      				boost::mpi::wait_all(requests, requests + 2);

      				// Delete all Balanced_presentation's in in_values[destinaion]
      				for(Itr itr = in_values[destinaion].begin(); itr != in_values[destinaion].end(); ++itr)
      					thread_pool.schedule(boost::bind(delete_balanced_presentation,(*itr)));

              // Clear in_values[destinaion] to prevent invalid pointers hanging around
      				thread_pool.schedule(boost::bind(clear_list,&in_values[destinaion]));
      			}

           // Loop over out_values
           for(int process = 0; process < communicator.size(); ++process)
           {
               // Loop over elements at index
               for(Itr itr = out_values[process].begin(); itr != out_values[process].end(); ++itr)
               {
      				     // Schedule a thread to insert the current element
      					   thread_pool.schedule(boost::bind(insert_balanced_presentation,*itr,&m_is_trivial,&m_trivial_presentation));
               }
            }

      			// Wait until all elements have been inserted
      			thread_pool.wait();

            // Define bool indicating if there exists a trivial presentation globally
            bool global_is_trivial = boost::mpi::all_reduce(communicator,m_is_trivial,std::logical_or<bool>());

            // If there is globally a trivial presentation
            if(global_is_trivial)
            {
                // Flag the search as trivial
                m_is_trivial = true;

                // Break while(true)
                break;
            }

            // Define bool indicating if there exist new local presentation's
            bool new_local_presentations = !s_balanced_presentation_queue.empty();

            // Define bool indicating if there exist new global presentation's
            bool new_global_presentations = boost::mpi::all_reduce(communicator,new_local_presentations,std::logical_or<bool>());

            // If there are globally no new presentations, the original presentation contradicts the AC conjecture
            if(!new_global_presentations)
              break;

             // Clear out_values to prevent invalid pointers hanging around
             for(unsigned int index = 0; index < out_values.size(); ++index)
      			 	 thread_pool.schedule(boost::bind(clear_list,&out_values[index]));

      			// Wait until all lists have been cleared
      			thread_pool.wait();
        }
    }

    void Searcher::print_derivation() const
    {
        // If the presentation is not AC trivial, do nothing
        if(!m_is_trivial)
            return;

    		// Define string to hold derivation
    		std::string derivation;

        // Define the world communicator in which we reside
        boost::mpi::communicator communicator;

        // Set current Balanced_presentation
        const Balanced_presentation *bp = m_trivial_presentation;

        // Loop forever
        while(true)
        {
            // Define bool to indicate if we are done
            bool done = false;

            // Define vector to hold values to send
            std::vector< std::pair<const Balanced_presentation*,std::string> > in_values(communicator.size());

            // Define vector to hold values to receive
            std::vector< std::pair<const Balanced_presentation*,std::string> > out_values(communicator.size());

            // If bp is not null
            if(bp)
            {
                // Add bp to the derivation
				        derivation = bp->to_string() + derivation;

                // If there is a parent to bp
                if(bp->get_parent())
                {
                    // Add bp to in_values
                    in_values[bp->get_parent_process()] = std::pair<const Balanced_presentation*,std::string>(bp,derivation);
                }
                else
                {
                    // Indicate we are done
                    done = true;

          					// Print out the derivation
          					std::cout << std::endl << "Derivation:" << std::endl;

          					// Print out the derivation
          					std::cout << derivation;
                }
            }

            // If we are done, break the while(true)
            if(boost::mpi::all_reduce(communicator,done,std::logical_or<bool>()))
                break;

            // Send in_values to apropos host and receive out_values
            boost::mpi::all_to_all(communicator,in_values,out_values);

            // Null out bp
            bp = 0;

            // Loop over out_values
            for(unsigned int process = 0; process < out_values.size(); ++process)
            {
                // If out_values[process] is not null
                if(out_values[process].first)
                {
                    // Set bp to the parent of the last printed bp
                    bp = out_values[process].first->get_parent();

                    // Set derivation to the current derivation
                    derivation = out_values[process].second;

                    // Delete out_values[process].first, newed up in all_to_all
                    if(communicator.rank() != out_values[process].first->get_process())
                        delete out_values[process].first;

                    // Break out of for, a child has only one parent
                    break;
                }
            }
        }
    }

  	void obtain_children(std::vector< std::list<Balanced_presentation*> > *in_values)
  	{
  		// Define Balanced_presentation
  		Balanced_presentation *parent = 0;

  		// Define scope for queue lock
  		{
  			// Lock s_queue_mutex
  			boost::lock_guard<boost::mutex> lock_guard(s_queue_mutex);

  			// Obtain the next Balanced_presentation
  			parent = s_balanced_presentation_queue.front();

  			// Pop balanced_presentation
  			s_balanced_presentation_queue.pop();
  		}

  		// Obtain children of parent
  		std::list<Balanced_presentation*> children = Balanced_presentation_nursery::get_children(parent);

  		// Loop over children
  		for(Itr itr = children.begin(); itr != children.end(); ++itr)
  		{
  			// Lock s_in_values_mutex
  			boost::lock_guard<boost::mutex> lock_guard(s_in_values_mutex);

  			// Place children in apropos place in in_values
  			(*in_values)[(*itr)->get_process()].push_back((*itr));
  		}
  	}

  	void clear_list(std::list<Balanced_presentation*> *list)
  	{
  		list->clear();
  	}

  	void delete_balanced_presentation(Balanced_presentation *balanced_presentation)
  	{
  		// Delete Relators
  		for(unsigned int relator = 0; relator < g_relators_count; ++relator)
  			delete balanced_presentation->get_relator(relator);

  		// Delete Balanced_presentation
  		delete balanced_presentation;
  	}

  	void insert_balanced_presentation(Balanced_presentation *balanced_presentation,bool *is_trivial,Balanced_presentation **trivial_presentation)
  	{
  		// Attempt to insert balanced_presentation into the tree
  		Balanced_presentation *bp = Binary_tree<Balanced_presentation>::insert(balanced_presentation);

  		// If insertion worked, i.e. if balanced_presentation was not previously in the tree
  		if(!bp)
  		{
  			// Loop over Relators
  			for(unsigned int relator = 0; relator < g_relators_count; ++relator)
  			{
  				// Attempt to insert relator into the tree
  				Relator *rel = Binary_tree<Relator>::insert(balanced_presentation->get_relator(relator));

  				// If insertion did not work, i.e. if the rel was previously in the tree
  				if(rel)
  				{
  					// Lock m_mutex as we are modifying balanced_presentation which is in the tree
  					boost::lock_guard<boost::mutex> lock_guard(Binary_tree<Balanced_presentation>::m_mutex);

  					// Delete the current relator
  					delete balanced_presentation->get_relator(relator);

  					// Replace it with rel, saving memory
  					balanced_presentation->set_relator(rel,relator);
  				}
  			}

  			// Define scope for queue lock
  			{
  				// Lock s_queue_mutex
  				boost::lock_guard<boost::mutex> lock_guard(s_queue_mutex);

  				// Push the balanced_presentation onto the queue
  				s_balanced_presentation_queue.push(balanced_presentation);
  			}

  			// Save pointer to first trivial presentation found
  			if(!(*is_trivial) && balanced_presentation->is_trivial())
  				(*trivial_presentation) = balanced_presentation;

  			// Flip m_is_trivial (TODO: Remove this CPU sink)
  			(*is_trivial) = (*is_trivial) || balanced_presentation->is_trivial();
  		}
  		// If insertion did not work, i.e. if balanced_presentation was previously in the tree
  		else
  		{
  			// Delete Relators
  			for(unsigned int relator = 0; relator < g_relators_count; ++relator)
  				delete balanced_presentation->get_relator(relator);

  			// Delete the Balanced_presentation balanced_presentation
  			delete balanced_presentation;
  		}
  	}
}

max_stars_repo_name: KellyJDavis/Andrews-Curtis

max_issues_repo_name: KellyJDavis/Andrews-Curtis

max_forks_repo_name: KellyJDavis/Andrews-Curtis


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================

#include <nt2/integration/primitive.hpp>
#include <nt2/include/functions/quad.hpp>
#include <nt2/include/functions/linspace.hpp>
#include <nt2/integration/output.hpp>
#include <nt2/table.hpp>

#include <boost/dispatch/meta/strip.hpp>

#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/tests/ulp.hpp>

struct f
{
  template<class Sig>
  struct result;

  template<class This, class X>
  struct result<This(X)>
       : boost::dispatch::meta::strip<X>
  {
  };

  template < class X > inline
  X operator()(const X & x ) const
  {
    return x;
  }
};

NT2_TEST_CASE_TPL( primitive_cplx_inout2, NT2_REAL_TYPES )
{
  using nt2::primitive;
  using nt2::options;
  using nt2::integration::output;
//  primitive<nt2::tag::quad_>(f(), nt2::linspace(T(0), T(5), 10));

   BOOST_AUTO_TPL(res, (primitive<nt2::tag::quad_>(f(), nt2::linspace(T(0), T(5)))));
   NT2_TEST_ULP_EQUAL(res.integrals(nt2::end_), T(12.5), 2);
}


text:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <random>
#include <functional>
#include <chrono>

#include <boost/geometry.hpp>
#include <boost/geometry/extensions/triangulation/triangulation.hpp>

namespace bg = boost::geometry;

int main() {
    const bool svg_out = true;
    const bool legalize = true;
    for(int i=0; i<1; ++i) {
        using point = bg::model::point<double, 2, bg::cs::cartesian>;
        using segment = bg::model::segment<point>;
        using triangulation = bg::model::triangulation<point>;
        std::default_random_engine generator(19);
        std::normal_distribution<> distribution(0.0,1.0);

        const std::size_t points_count = 1'000;
        auto gen = std::bind(distribution, generator);

        triangulation out;
        std::vector<point> in;
        for(int i=0; i < points_count; ++i)
            in.push_back(point(gen(), gen()));
        bg::delaunay_triangulation(in, out, legalize);

        if(svg_out) {
            std::ofstream svg("triangulation.svg");
            boost::geometry::svg_mapper<point> mapper(svg, 720, 720);

            for(auto const& f : bg::vertex_range(out)) {
                mapper.add(f);
            }

            for(auto const& f : bg::face_range(out)) {
                mapper.map(f, "fill-opacity:0.3;fill:rgb(51,51,153);stroke:rgb(26,26,76);stroke-with:1");
            }
            auto bv = out.boundary_vertex();
            std::size_t prev;
            do{
                prev = bv;
                bv = out.boundary_next(bv);
                segment s((out.vertices_begin()+prev)->m_p, (out.vertices_begin()+bv)->m_p);
                mapper.map(s, "opacity:1.0;fill:none;stroke:rgb(192,0,0);stroke-width:1");
            }while(bv != out.boundary_vertex());
            for(auto const& v : bg::vertex_range(out)) {
                mapper.map(v, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:1", 2);
            }
        }
    }
    return 0;
}


text:
/*
 * MIT License
 *
 * Copyright (c) 2019 Denis Kovalchuk
 *
 * 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 FTP_DATA_CONNECTION_HPP
#define FTP_DATA_CONNECTION_HPP

#include <boost/asio/ip/tcp.hpp>
#include <fstream>

namespace ftp::detail
{

class data_connection
{
public:
    data_connection(const std::string & ip, uint16_t port);

    data_connection(const data_connection &) = delete;

    data_connection & operator=(const data_connection &) = delete;

    void open();

    bool is_open() const;

    void close();

    void send(std::ifstream & file);

    void recv(std::ofstream & file);

    std::string recv();

private:
    boost::asio::io_context io_context_;
    boost::asio::ip::tcp::socket socket_;
    std::array<char, 8192> buffer_;
    std::string ip_;
    uint16_t port_;
};

} // namespace ftp::detail
#endif //FTP_DATA_CONNECTION_HPP

max_stars_repo_name: deniskovalchuk/ftp-client

max_issues_repo_name: deniskovalchuk/ftp-client

max_forks_repo_name: deniskovalchuk/ftp-client