text:
/**
 * @file
 * @copyright This code is licensed under the 3-clause BSD license.\n
 *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
 *            See LICENSE.txt for details.
 */

#include "Tasks.h"
#include <Core/Log.h>
#include <Swoose/QMMM/QmRegionSelection/QmRegionSelector.h>
#include <Swoose/Utilities/SettingsNames.h>
#include <Utils/GeometryOptimization/QmmmGeometryOptimizer.h>
#include <Utils/IO/ChemicalFileFormats/ChemicalFileHandler.h>
#include <Utils/IO/ChemicalFileFormats/XyzStreamHandler.h>
#include <Utils/IO/FilesystemHelpers.h>
#include <Utils/IO/FormattedIOUtils.h>
#include <Utils/IO/MolecularTrajectoryIO.h>
#include <Utils/IO/NativeFilenames.h>
#include <Utils/MolecularDynamics/MolecularDynamics.h>
#include <Utils/Optimizer/GradientBased/Bfgs.h>
#include <Utils/Optimizer/GradientBased/GradientBasedCheck.h>
#include <boost/filesystem.hpp>

namespace Scine {
namespace Swoose {
namespace Tasks {

namespace {
constexpr const char* defaultOptimizationResultsDirectory = "opt_results";
constexpr const char* optimizationDirectoryKey = "results_directory";
constexpr const char* optimizationStructureFile = "opt_structure.xyz";
constexpr const char* optimizationTrajectoryFile = "opt_trajectory.xyz";
constexpr const char* hessianCsvFilename = "hessian.csv";
} // namespace

void runMMCalculationTask(Core::Calculator& calculator, const std::string& structureFile,
                          Utils::PropertyList properties, Core::Log& log) {
  Utils::AtomCollection structure = Utils::ChemicalFileHandler::read(structureFile).first;

  calculator.setStructure(structure);
  calculator.setRequiredProperties(properties);

  log.output << "Starting an MM calculation for the molecule: " << structureFile << Core::Log::nl;
  log.output << "MM model: " << calculator.name() << Core::Log::endl;
  const Utils::Results& results = calculator.calculate("MM calculation");
  double energy = results.get<Utils::Property::Energy>();
  Utils::GradientCollection gradients = results.get<Utils::Property::Gradients>() * Utils::Constants::kCalPerMol_per_hartree;

  log.output << "Calculation done. Results: " << Core::Log::endl;
  log.output << Core::Log::nl << "# Energy (kcal/mol): " << energy * Utils::Constants::kCalPerMol_per_hartree
             << Core::Log::endl;
  log.output << Core::Log::nl << "# Gradients (kcal/(mol*bohr)):" << Core::Log::endl;
  log.output << [&gradients](std::ostream& os) { Utils::matrixPrettyPrint(os, gradients); };
  log.output << Core::Log::endl;

  if (properties.containsSubSet(Utils::Property::Hessian)) {
    Utils::HessianMatrix hessian = results.get<Utils::Property::Hessian>() * Utils::Constants::kCalPerMol_per_hartree;
    std::ofstream hessianFile(hessianCsvFilename);
    Utils::matrixToCsv(hessianFile, hessian, ',');
    hessianFile.close();
    log.output << Core::Log::nl << "# Hessian (kcal/(mol*bohr^2)) has been written to file: " << hessianCsvFilename
               << Core::Log::nl << Core::Log::endl;
  }
}

void runQmmmCalculationTask(Core::Calculator& calculator, const std::string& structureFile,
                            Utils::PropertyList properties, Core::Log& log, const YAML::Node& yamlNode) {
  Utils::AtomCollection structure = Utils::ChemicalFileHandler::read(structureFile).first;

  // Set settings
  Utils::nodeToSettings(calculator.settings(), yamlNode, false);
  // Set structure
  calculator.setStructure(structure);
  // Set required properties
  calculator.setRequiredProperties(properties);

  log.output << "Starting a QM/MM calculation for the molecule: " << structureFile << Core::Log::endl;
  const Utils::Results& results = calculator.calculate("QM/MM calculation");
  double energy = results.get<Utils::Property::Energy>();
  Utils::GradientCollection gradients = results.get<Utils::Property::Gradients>() * Utils::Constants::kCalPerMol_per_hartree;

  log.output << "Calculation done. Results: " << Core::Log::endl;
  log.output << Core::Log::nl << "# Energy (Hartree): " << std::setprecision(10) << energy << Core::Log::endl;
  log.output << Core::Log::nl << "# Gradients (kcal/(mol*bohr)):" << std::setprecision(5) << Core::Log::endl;
  log.output << [&gradients](std::ostream& os) { Utils::matrixPrettyPrint(os, gradients); };
  log.output << Core::Log::endl;
}

void runSFAMParametrizationTask(Core::MMParametrizer& parametrizer, const std::string& structureFile, Core::Log& log) {
  Utils::AtomCollection structure = Utils::ChemicalFileHandler::read(structureFile).first;
  parametrizer.parametrize(structure);
  log.output << Core::Log::nl << "Parametrization done." << Core::Log::endl;
}

void runMDSimulationTask(Utils::MolecularDynamics& md, const std::string& structureFile, Core::Log& log) {
  Utils::AtomCollection startStructure = Utils::ChemicalFileHandler::read(structureFile).first;
  log.output << "Starting MD simulation..." << Core::Log::endl;
  try {
    md.performMDSimulation(startStructure, log);
  }
  catch (const std::exception& e) {
    const std::string failedTrajectoryFilename = "MD_trajectory_failed.xyz";
    auto failedTrajectory = md.getMolecularTrajectory();
    Utils::MolecularTrajectoryIO::write(Utils::MolecularTrajectoryIO::format::xyz, failedTrajectoryFilename, failedTrajectory);
    throw std::runtime_error(std::string(e.what()) + "\n" +
                             "Trajectory of failed MD has been written to: " + std::string(failedTrajectoryFilename));
  }

  log.output << "All MD steps have been successfully completed." << Core::Log::endl;

  auto trajectory = md.getMolecularTrajectory();
  const std::string trajectoryFilename = "MD_trajectory.xyz";
  Utils::MolecularTrajectoryIO::write(Utils::MolecularTrajectoryIO::format::xyz, trajectoryFilename, trajectory);
  log.output << "Trajectory has been written to the following file: " << trajectoryFilename << Core::Log::endl;

  auto energies = trajectory.getEnergies();
  const std::string energiesFilename = "MD_energies.dat";
  std::ofstream energiesFile(energiesFilename);
  energiesFile << "Energies for the MD snapshots (kcal/mol):" << Core::Log::endl;
  for (const auto& energy : energies) {
    energiesFile << energy * Utils::Constants::kCalPerMol_per_hartree << Core::Log::endl;
  }
  log.output << "Energies have been written to the following file: " << energiesFilename << Core::Log::endl;
}

void runMMOptimizationTask(Core::Calculator& calculator, Utils::GeometryOptimizerBase& optimizer,
                           const std::string& structureFile, Core::Log& log, const YAML::Node& yamlNode) {
  std::string resultsDir = defaultOptimizationResultsDirectory;
  if (yamlNode[optimizationDirectoryKey])
    resultsDir = yamlNode[optimizationDirectoryKey].as<std::string>();

  Utils::AtomCollection structure = Utils::ChemicalFileHandler::read(structureFile).first;

  Utils::FilesystemHelpers::createDirectories(resultsDir);

  // Trajectory stream
  boost::filesystem::remove(Utils::NativeFilenames::combinePathSegments(resultsDir, optimizationTrajectoryFile));
  std::ofstream trajectory(Utils::NativeFilenames::combinePathSegments(resultsDir, optimizationTrajectoryFile),
                           std::ofstream::out);
  Utils::XyzStreamHandler writer;
  // Variable for the observer
  double oldEnergy = 0.0;

  // Observer function
  auto obsFunc = [&](const int& cycle, const double& energy, const Eigen::VectorXd& /* params */) {
    if (cycle == 1) {
      log.output.printf("%s\n", "Starting optimization cycles...");
      log.output.printf("%7s %16s %16s\n", "Cycle", "Energy", "Energy Diff.");
    }
    log.output.printf("%7d %+16.9f %+16.9f\n", cycle, energy, energy - oldEnergy);
    oldEnergy = energy;
    auto currStructure = calculator.getStructure();
    writer.write(trajectory, *currStructure);
  };

  // Add observer
  optimizer.addObserver(obsFunc);

  auto cycles = optimizer.optimize(structure, log);

  trajectory.close();
  Utils::ChemicalFileHandler::write(Utils::NativeFilenames::combinePathSegments(resultsDir, optimizationStructureFile),
                                    structure);

  auto maxAllowedCycles = optimizer.getSettings().getInt(Utils::GradientBasedCheck::gconvMaxIterKey);
  if (cycles == maxAllowedCycles)
    throw std::runtime_error("The structure optimization did not converge within the maximum number of cycles. This "
                             "number can be increased with the setting: " +
                             std::string(Utils::GradientBasedCheck::gconvMaxIterKey));

  log.output << "MM structure optimization done. Results are written to directory: " << resultsDir << Core::Log::endl;
}

template<class OptimizerType>
void runQmmmOptimizationTask(Core::Calculator& calculator, Utils::QmmmGeometryOptimizer<OptimizerType>& optimizer,
                             const std::string& structureFile, Core::Log& log, const YAML::Node& yamlNode) {
  std::string resultsDir = defaultOptimizationResultsDirectory;
  if (yamlNode[optimizationDirectoryKey])
    resultsDir = yamlNode[optimizationDirectoryKey].as<std::string>();

  Utils::AtomCollection structure = Utils::ChemicalFileHandler::read(structureFile).first;

  // Set settings
  Utils::nodeToSettings(calculator.settings(), yamlNode, true);
  // Set structure
  calculator.setStructure(structure);

  Utils::FilesystemHelpers::createDirectories(resultsDir);

  // Trajectory stream
  boost::filesystem::remove(Utils::NativeFilenames::combinePathSegments(resultsDir, optimizationTrajectoryFile));
  std::ofstream trajectory(Utils::NativeFilenames::combinePathSegments(resultsDir, optimizationTrajectoryFile),
                           std::ofstream::out);
  Utils::XyzStreamHandler writer;
  // Variable for the observer
  double oldEnergy = 0.0;

  auto obsFunc = [&](const int& cycle, const double& energy, const Eigen::VectorXd& /* params */) {
    if (cycle == 1) {
      log.output.printf("%s\n", "Starting full system optimization cycles...");
      log.output.printf("%7s %16s %16s\n", "Cycle", "Energy", "Energy Diff.");
    }
    log.output.printf("%7d %+16.9f %+16.9f\n", cycle, energy, energy - oldEnergy);
    oldEnergy = energy;
    auto currStructure = calculator.getStructure();
    writer.write(trajectory, *currStructure);
  };

  // Add observer
  optimizer.addObserver(obsFunc);

  auto cycles = optimizer.optimize(structure, log);

  trajectory.close();
  Utils::ChemicalFileHandler::write(Utils::NativeFilenames::combinePathSegments(resultsDir, optimizationStructureFile),
                                    structure);

  auto maxAllowedCycles =
      optimizer.getSettings().getInt(Utils::QmmmGeometryOptimizer<Utils::Bfgs>::qmmmOptMaxMacroiterationsKey) *
      optimizer.getSettings().getInt(Utils::QmmmGeometryOptimizer<Utils::Bfgs>::qmmmOptMaxFullMicroiterationsKey);
  if (cycles == maxAllowedCycles)
    throw std::runtime_error("The structure optimization did not converge within the maximum number of cycles.");

  log.output << "QM/MM structure optimization done. Results are written to directory: " << resultsDir << Core::Log::endl;
}

void runQmRegionSelectionTask(const std::string& structureFile, Core::Log& log, YAML::Node& yamlNode,
                              std::string yamlSettingsPath) {
  log.output << "Starting automated selection of QM region..." << Core::Log::nl << Core::Log::endl;
  Qmmm::QmRegionSelector qmRegionSelector;
  Utils::AtomCollection structure = Utils::ChemicalFileHandler::read(structureFile).first;
  qmRegionSelector.setLog(log);
  Utils::nodeToSettings(qmRegionSelector.settings(), yamlNode, true);
  qmRegionSelector.settings().modifyString(SwooseUtilities::SettingsNames::yamlSettingsFilePath, yamlSettingsPath);

  // Generate QM region
  qmRegionSelector.generateQmRegion(structure);
  auto result = qmRegionSelector.getQmRegionIndices();
  log.output << "Indices of QM atoms: " << Core::Log::endl;
  log.output << "[";
  for (int i = 0; i < result.size(); ++i) {
    if (result[i] >= 0) {
      log.output << result[i];
      if (i != result.size() - 1)
        log.output << ", ";
    }
  }
  log.output << "]" << Core::Log::nl << Core::Log::endl;
  auto optimalQmRegion = qmRegionSelector.getQmRegionStructure();
  auto chargeAndMultiplicity = qmRegionSelector.getQmRegionChargeAndMultiplicity();
  log.output << "Molecular charge of QM region: " << chargeAndMultiplicity.first << Core::Log::nl;
  log.output << "Spin multiplicity of QM region: " << chargeAndMultiplicity.second << Core::Log::endl;
  log.output << "Optimal QM region is written to: optimal_qm_region.xyz" << Core::Log::endl;
  Utils::ChemicalFileHandler::write("optimal_qm_region.xyz", optimalQmRegion);
}

// Explicit instantiation such that the function implementation can stay in the .cpp file.
template void
runQmmmOptimizationTask<Utils::Bfgs>(Core::Calculator& calculator, Utils::QmmmGeometryOptimizer<Utils::Bfgs>& optimizer,
                                     const std::string& structureFile, Core::Log& log, const YAML::Node& yamlNode);

} // namespace Tasks
} // namespace Swoose
} // namespace Scine

max_stars_repo_name: qcscine/swoose

max_issues_repo_name: qcscine/swoose

max_forks_repo_name: qcscine/swoose


#include "message.h++"
#include <boost/thread/detail/singleton.hpp>
#include "commondomfeatures.h++"
#include "xftpcommons.h++"
#include <iostream>
#include "servercontrol.h++"
#include "clientcontrol.h++"

using namespace xftp;

streamcon::Mutex Message::GlobalSetupLock;

Message::Message(size_t _ID, ProcessImplType *_PI): ProcessImpl(_PI)
{
	ID=_ID;
}

size_t Message::GetID()
{
	return ID;
}

void Message::Process(ControlThread&t)
{
	(*ProcessImpl)(&t,*this);
}
Message::~Message()
{
}

Message::DOMSerializedMessage Message::InitializeSerialization(
				xercesc::DOMDocument & document)
{
	DOMSerializedMessage Result(document.createElement (this->GetName()));
	return Result;
}

Message::ProcessImplBaseType Message::GetProcessImpl()
{
	return ProcessImpl->GetFunction();
}

ServerMessage::ServerMessage(size_t ID, ProcessImplType *_PI) : Message(ID, _PI)
{
	;
}

//void ServerMessage::Process(ControlThread &control)
//{
//	Process(dynamic_cast<ClientControl&>(control));
//}

ClientMessage::ClientMessage(size_t ID, ProcessImplType *_PI) : Message(ID,_PI)
{
	;
}
//
//void ClientMessage::Process(ControlThread &control)
//{
//	Process(dynamic_cast<ServerControl&>(control));
//}


text:
#include <boost/serialization/export.hpp>
#include "StochasticGradientDescent.hpp"
#include "../layer/neuron/RecurrentNeuron.hpp"
#include "../layer/neuron/SimpleNeuron.hpp"

using namespace std;
using namespace snn;
using namespace internal;

BOOST_CLASS_EXPORT(StochasticGradientDescent)

StochasticGradientDescent::StochasticGradientDescent(const float learningRate, const float momentum)
    : learningRate(learningRate), momentum(momentum)
{
}

shared_ptr<NeuralNetworkOptimizer> StochasticGradientDescent::clone() const
{
    return make_shared<StochasticGradientDescent>(*this);
}

void StochasticGradientDescent::updateWeights(SimpleNeuron& neuron, float error) const
{
    for (size_t w = 0; w < neuron.weights.size(); ++w)
    {
        auto deltaWeights = this->learningRate * error * neuron.lastInputs[w];
        deltaWeights += this->momentum * neuron.previousDeltaWeights[w];
        neuron.weights[w] += deltaWeights;
        neuron.previousDeltaWeights[w] = deltaWeights;
    }
}

void StochasticGradientDescent::updateWeights(RecurrentNeuron& neuron, float error) const
{
    size_t w;
    for (w = 0; w < neuron.lastInputs.size(); ++w)
    {
        auto deltaWeights = this->learningRate * error * neuron.lastInputs[w];
        deltaWeights += this->momentum * neuron.previousDeltaWeights[w];
        neuron.weights[w] += deltaWeights;
        neuron.previousDeltaWeights[w] = deltaWeights;
    }
    neuron.recurrentError = error + neuron.recurrentError * neuron.outputFunction->derivative(neuron.previousSum) *
        neuron.weights[w];

    auto deltaWeights = this->learningRate * neuron.recurrentError * neuron.previousOutput;
    deltaWeights += this->momentum * neuron.previousDeltaWeights[w];
    neuron.weights[w] += deltaWeights;
    neuron.previousDeltaWeights[w] = deltaWeights;
}

int StochasticGradientDescent::isValid()
{
    if (this->learningRate <= 0.0f || this->learningRate >= 1.0f)
        return 103;
    if (this->momentum < 0.0f || this->momentum > 1.0f)
        return 104;
    return 0;
}

bool StochasticGradientDescent::operator==(const NeuralNetworkOptimizer& optimizer) const
{
    try
    {
        const auto& o = dynamic_cast<const StochasticGradientDescent&>(optimizer);
        return this->NeuralNetworkOptimizer::operator==(optimizer)
            && this->learningRate == o.learningRate
            && this->momentum == o.momentum;
    }
    catch (bad_cast&)
    {
        return false;
    }
}

bool StochasticGradientDescent::operator!=(const NeuralNetworkOptimizer& optimizer) const
{
    return !(*this == optimizer);
}

ext: cpp

max_stars_repo_name: sehe/StraightforwardNeuralNetwork

max_issues_repo_name: sehe/StraightforwardNeuralNetwork

max_forks_repo_name: sehe/StraightforwardNeuralNetwork


text:
#define BOOST_NUMPY_INTERNAL_MAIN
#include <boost/numpy/internal.hpp>

namespace boost
{
namespace numpy
{

void initialize()
{
  import_array();
  import_ufunc();
}

}
}

max_stars_repo_name: maartenbreddels/mab

max_issues_repo_name: maartenbreddels/mab

max_forks_repo_name: maartenbreddels/mab


text:
// graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

// based on code written by Alexandre Hannud Abdo <abdo@member.fsf.org>

#ifndef GRAPH_EXTENDED_CLUSTERING_HH
#define GRAPH_EXTENDED_CLUSTERING_HH

#include <unordered_set>

#include <boost/graph/breadth_first_search.hpp>

namespace graph_tool
{

using namespace std;
using namespace boost;

// graph filter to remove a single vertex

template <class Vertex>
struct single_vertex_filter
{
    single_vertex_filter() {}
    single_vertex_filter(Vertex v):_v(v) {}

    bool operator()(Vertex v) const { return v != _v; }

    Vertex _v;
};

class bfs_stop_exception {};

// this will abort the BFS search when no longer useful

template <class TargetSet, class DistanceMap>
struct bfs_max_depth_watcher
{
    typedef on_tree_edge event_filter;

    bfs_max_depth_watcher(TargetSet& targets, size_t max_depth,
                          DistanceMap distance)
        : _targets(targets), _max_depth(max_depth), _distance(distance) {}

    template <class Graph>
    void operator()(typename graph_traits<Graph>::edge_descriptor e,
                    const Graph& g)
    {
        typename graph_traits<Graph>::vertex_descriptor v = target(e,g);
        if (get(_distance, v) > _max_depth)
            throw bfs_stop_exception();
        if (_targets.find(v) != _targets.end())
            _targets.erase(v);
        if (_targets.empty())
            throw bfs_stop_exception();
    }

    TargetSet& _targets;
    size_t _max_depth;
    DistanceMap _distance;
};

// abstract target collecting so algorithm works for bidirectional and
// undirected graphs

template<class Graph, class Vertex, class Targets, class DirectedCategory>
void collect_targets(Vertex v, Graph& g, Targets& t, DirectedCategory)
{
    typename graph_traits<Graph>::in_edge_iterator ei, ei_end;
    typename graph_traits<Graph>::vertex_descriptor u;
    for(tie(ei, ei_end) = in_edges(v, g); ei != ei_end; ++ei)
    {
        u = source(*ei, g);
        if (u == v) // no self-loops
            continue;
        if (t.find(u) != t.end()) // avoid parallel edges
            continue;
        t.insert(u);
    }
}

template<class Graph, class Vertex, class Targets>
void collect_targets(Vertex v, Graph& g, Targets& t, undirected_tag)
{
    typename graph_traits<Graph>::out_edge_iterator ei, ei_end;
    typename graph_traits<Graph>::vertex_descriptor u;
    for(tie(ei, ei_end) = out_edges(v, g); ei != ei_end; ++ei)
    {
        u = target(*ei, g);
        if (u == v) // no self-loops
            continue;
        if (t.find(u) != t.end()) // avoid parallel edges
            continue;
        t.insert(u);
    }
}

// get_extended_clustering

struct get_extended_clustering
{
    template <class Graph, class IndexMap, class ClusteringMap>
    void operator()(const Graph& g, IndexMap vertex_index,
                    vector<ClusteringMap> cmaps) const
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;

        int i, N = num_vertices(g);

        #pragma omp parallel for default(shared) private(i) schedule(runtime) if (N > 100)
        for (i = 0; i < N; ++i)
        {
            vertex_t v = vertex(i, g);
            if (v == graph_traits<Graph>::null_vertex())
                continue;

            // We must disconsider paths through the original vertex
            typedef single_vertex_filter<vertex_t> filter_t;
            typedef filtered_graph<Graph, keep_all, filter_t> fg_t;
            fg_t fg(g, keep_all(), filter_t(v));

            typedef DescriptorHash<IndexMap> hasher_t;
            typedef std::unordered_set<vertex_t,hasher_t> neighbour_set_t;
            neighbour_set_t neighbours(0, hasher_t(vertex_index));
            neighbour_set_t targets(0, hasher_t(vertex_index));
            typename neighbour_set_t::iterator ni, ti;

            // collect targets, neighbours and calculate normalization factor
            collect_targets(v, g, targets,
                            typename graph_traits<Graph>::directed_category());
            size_t k_in = targets.size(), k_out, k_inter=0, z;
            typename graph_traits<Graph>::adjacency_iterator a, a_end;
            for (tie(a, a_end) = adjacent_vertices(v, g); a != a_end; ++a)
            {
                if (*a == v) // no self-loops
                    continue;
                if (neighbours.find(*a) != neighbours.end()) // avoid parallel
                    continue;                                // edges

                neighbours.insert(*a);
                if (targets.find(*a) != targets.end())
                    ++k_inter;
            }
            k_out = neighbours.size();
            z = (k_in*k_out) - k_inter;

            // And now we setup and start the BFS bonanza
            for (ni = neighbours.begin(); ni != neighbours.end(); ++ni)
            {
                typedef std::unordered_map<vertex_t,size_t,
                                           DescriptorHash<IndexMap> > dmap_t;
                dmap_t dmap(0, DescriptorHash<IndexMap>(vertex_index));
                InitializedPropertyMap<dmap_t>
                    distance_map(dmap, numeric_limits<size_t>::max());

                typedef std::unordered_map<vertex_t,default_color_type,
                                           DescriptorHash<IndexMap> > cmap_t;
                cmap_t cmap(0, DescriptorHash<IndexMap>(vertex_index));
                InitializedPropertyMap<cmap_t>
                    color_map(cmap, color_traits<default_color_type>::white());

                try
                {
                    distance_map[*ni] = 0;
                    neighbour_set_t specific_targets = targets;
                    specific_targets.erase(*ni);
                    bfs_max_depth_watcher<neighbour_set_t,
                                          InitializedPropertyMap<dmap_t> >
                        watcher(specific_targets, cmaps.size(), distance_map);
                    breadth_first_visit(fg, *ni,
                                        visitor
                                        (make_bfs_visitor
                                         (make_pair(record_distances
                                                    (distance_map,
                                                     boost::on_tree_edge()),
                                                    watcher))).
                                        color_map(color_map));
                }
                catch (bfs_stop_exception) {}

                for (ti = targets.begin(); ti != targets.end(); ++ti)
                {
                    if (*ti == *ni) // no self-loops
                        continue;
                    if (distance_map[*ti] <= cmaps.size())
                        cmaps[distance_map[*ti]-1][v] += 1.0/z;
                }
            }
        }
    }
};

} // graph_tool namespace

#endif // GRAPH_EXTENDED_CLUSTERING_HH

ext: hh

max_stars_repo_name: johankaito/fufuka

max_issues_repo_name: johankaito/fufuka

max_forks_repo_name: johankaito/fufuka


text:
#include "slot.h"

#include <cassert>
#include <cmath>

#include <boost/algorithm/clamp.hpp>
#include <boost/optional.hpp>

#include "../shader_core/config.h"
#include "../shader_core/rect.h"
#include "../shader_core/vector.h"

static bool set_curve(csg::Curve& curve, const csg::Curve& new_value)
{
	if (new_value.min() != curve.min() || new_value.max() != curve.max()) {
		return false;
	}
	curve = new_value;
	return true;
}

bool csg::ColorSlotValue::operator==(const ColorSlotValue& other) const
{
	return value.similar(other.value, FLOAT_COMPARE_DIFF);
}

void csg::EnumSlotValue::set(const size_t new_value)
{
	if (new_value <= max_value) {
		value = new_value;
	}
}

const char* csg::EnumSlotValue::internal_name() const
{
	boost::optional<NodeEnumOptionInfo> opt_info{ NodeEnumOptionInfo::from(meta_enum, value) };
	if (opt_info) {
		return opt_info->internal_name();
	}
	return "NAME ERROR";
}

bool csg::EnumSlotValue::operator==(const EnumSlotValue& other) const
{
	return (value == other.value && meta_enum == other.meta_enum);
}

void csg::FloatSlotValue::set(const float new_value)
{
	value = boost::algorithm::clamp(new_value, min, max);
}

bool csg::FloatSlotValue::operator==(const FloatSlotValue& other) const
{
	return (fabs(value - other.value) < FLOAT_COMPARE_DIFF) && min == other.min && max == other.max && _precision == other._precision;
}

void csg::IntSlotValue::set(const int new_value)
{
	value = boost::algorithm::clamp(new_value, min, max);
}

bool csg::IntSlotValue::operator==(const IntSlotValue& other) const
{
	return value == other.value && min == other.min && max == other.max;
}

void csg::VectorSlotValue::set(const csc::Float3 new_value)
{
	const float x{ boost::algorithm::clamp(new_value.x, min.x, max.x) };
	const float y{ boost::algorithm::clamp(new_value.y, min.y, max.y) };
	const float z{ boost::algorithm::clamp(new_value.z, min.z, max.z) };
	value = csc::Float3{ x, y, z };
}

bool csg::VectorSlotValue::operator==(const VectorSlotValue& other) const
{
	return value.similar(other.value, FLOAT_COMPARE_DIFF);
}

csg::RGBCurveSlotValue::RGBCurveSlotValue() :
	curve_all{ csc::Float2{ 0.0f, 0.0f }, csc::Float2{ 1.0f, 1.0f } },
	curve_r{ csc::Float2{ 0.0f, 0.0f }, csc::Float2{ 1.0f, 1.0f } },
	curve_g{ csc::Float2{ 0.0f, 0.0f }, csc::Float2{ 1.0f, 1.0f } },
	curve_b{ csc::Float2{ 0.0f, 0.0f }, csc::Float2{ 1.0f, 1.0f } }
{

}

bool csg::RGBCurveSlotValue::set_all(const Curve& value)
{
	return set_curve(curve_all, value);
}

bool csg::RGBCurveSlotValue::set_r(const Curve& value)
{
	return set_curve(curve_r, value);
}

bool csg::RGBCurveSlotValue::set_g(const Curve& value)
{
	return set_curve(curve_g, value);
}

bool csg::RGBCurveSlotValue::set_b(const Curve& value)
{
	return set_curve(curve_b, value);
}

bool csg::RGBCurveSlotValue::operator==(const RGBCurveSlotValue& other) const
{
	return (
		curve_all.similar(other.curve_all , FLOAT_COMPARE_DIFF) &&
		curve_r.similar(other.curve_r, FLOAT_COMPARE_DIFF) &&
		curve_g.similar(other.curve_g, FLOAT_COMPARE_DIFF) &&
		curve_b.similar(other.curve_b, FLOAT_COMPARE_DIFF)
		);
}

csg::VectorCurveSlotValue::VectorCurveSlotValue(const csc::Float2 min, const csc::Float2 max) :
	curve_x{ min, max },
	curve_y{ min, max },
	curve_z{ min, max },
	min{ min },
	max{ max }
{

}

bool csg::VectorCurveSlotValue::set_x(const Curve& value)
{
	return set_curve(curve_x, value);
}

bool csg::VectorCurveSlotValue::set_y(const Curve& value)
{
	return set_curve(curve_y, value);
}

bool csg::VectorCurveSlotValue::set_z(const Curve& value)
{
	return set_curve(curve_z, value);
}

bool csg::VectorCurveSlotValue::set_bounds(const csc::FloatRect bounds_rect)
{
	const bool valid_x{ curve_x.bounds_valid(bounds_rect) };
	const bool valid_y{ curve_y.bounds_valid(bounds_rect) };
	const bool valid_z{ curve_z.bounds_valid(bounds_rect) };
	if (valid_x && valid_y && valid_z) {
		curve_x.set_bounds(bounds_rect);
		curve_y.set_bounds(bounds_rect);
		curve_z.set_bounds(bounds_rect);
		min = bounds_rect.begin();
		max = bounds_rect.end();
		return true;
	}
	else {
		return false;
	}
}

bool csg::VectorCurveSlotValue::operator==(const VectorCurveSlotValue& other) const
{
	return (
		curve_x.similar(other.curve_x, FLOAT_COMPARE_DIFF) &&
		curve_y.similar(other.curve_y, FLOAT_COMPARE_DIFF) &&
		curve_z.similar(other.curve_z, FLOAT_COMPARE_DIFF) &&
		min.similar(other.min, FLOAT_COMPARE_DIFF) &&
		max.similar(other.max, FLOAT_COMPARE_DIFF)
	);
}

bool csg::ColorRampSlotValue::operator==(const ColorRampSlotValue& other) const
{
	return ramp.similar(other.ramp, FLOAT_COMPARE_DIFF);
}

bool csg::ImageSlotValue::operator==(const ImageSlotValue& other) const
{
    return strcmp(filePath, other.filePath) ==0;
}

csg::SlotValue& csg::SlotValue::operator=(const SlotValue& other)
{
	_type = other._type;
	value_union = other.value_union;

	if (other.curve_rgb_value) {
		curve_rgb_value = std::make_unique<RGBCurveSlotValue>(*other.curve_rgb_value);
	}
	else {
		curve_vector_value = std::unique_ptr<VectorCurveSlotValue>();
	}

	if (other.curve_vector_value) {
		curve_vector_value = std::make_unique<VectorCurveSlotValue>(*other.curve_vector_value);
	}
	else {
		curve_vector_value = std::unique_ptr<VectorCurveSlotValue>();
	}

	if (other.color_ramp_value) {
		color_ramp_value = std::make_unique<ColorRampSlotValue>(*other.color_ramp_value);
	}
	else {
		color_ramp_value = std::unique_ptr<ColorRampSlotValue>();
	}

    if (other.image_path_value) {
        image_path_value = std::make_unique<ImageSlotValue>(*other.image_path_value);
    }
    else {
        image_path_value = std::unique_ptr<ImageSlotValue>();
    }

	return *this;
}

template <> boost::optional<csg::BoolSlotValue> csg::SlotValue::as() const {
	return (type() != SlotType::BOOL) ? boost::none : boost::optional<csg::BoolSlotValue>{ value_union.bool_value };
}
template <> boost::optional<csg::ColorSlotValue> csg::SlotValue::as() const {
	return (type() != SlotType::COLOR) ? boost::none : boost::optional<csg::ColorSlotValue>{ value_union.color_value };
}
template <> boost::optional<csg::EnumSlotValue> csg::SlotValue::as() const {
	return (type() != SlotType::ENUM) ? boost::none : boost::optional<csg::EnumSlotValue>{ value_union.enum_value };
}
template <> boost::optional<csg::FloatSlotValue> csg::SlotValue::as() const {
	return (type() != SlotType::FLOAT) ? boost::none : boost::optional<csg::FloatSlotValue>{ value_union.float_value };
}
template <> boost::optional<csg::IntSlotValue> csg::SlotValue::as() const {
	return (type() != SlotType::INT) ? boost::none : boost::optional<csg::IntSlotValue>{ value_union.int_value };
}
template <> boost::optional<csg::VectorSlotValue> csg::SlotValue::as() const {
	return (type() != SlotType::VECTOR) ? boost::none : boost::optional<csg::VectorSlotValue>{ value_union.vector_value };
}
template <> boost::optional<csg::RGBCurveSlotValue> csg::SlotValue::as() const {
	return (type() != SlotType::CURVE_RGB || static_cast<bool>(curve_rgb_value) == false) ? boost::none : boost::optional<csg::RGBCurveSlotValue>{ *curve_rgb_value };
}
template <> boost::optional<csg::VectorCurveSlotValue> csg::SlotValue::as() const {
	return (type() != SlotType::CURVE_VECTOR || static_cast<bool>(curve_vector_value) == false) ? boost::none : boost::optional<csg::VectorCurveSlotValue>{ *curve_vector_value };
}
template <> boost::optional<csg::ColorRampSlotValue> csg::SlotValue::as() const {
	return (type() != SlotType::COLOR_RAMP || static_cast<bool>(color_ramp_value) == false) ? boost::none : boost::optional<csg::ColorRampSlotValue>{ *color_ramp_value };
}

template <> boost::optional<csg::ImageSlotValue> csg::SlotValue::as() const {
    return (type() != SlotType::IMAGE || static_cast<bool>(image_path_value) == false) ? boost::none : boost::optional<csg::ImageSlotValue>{ *image_path_value };
}

bool csg::SlotValue::operator==(const SlotValue& other) const
{
	if (_type != other._type) {
		return false;
	}

	switch (_type) {
		case SlotType::BOOL:
		{
			if (value_union.bool_value != other.value_union.bool_value) {
				return false;
			}
			break;
		}
		case SlotType::COLOR:
		{
			if (value_union.color_value != other.value_union.color_value) {
				return false;
			}
			break;
		}
		case SlotType::ENUM:
		{
			if (value_union.enum_value != other.value_union.enum_value) {
				return false;
			}
			break;
		}
		case SlotType::FLOAT:
		{
			if (value_union.float_value != other.value_union.float_value) {
				return false;
			}
			break;
		}
		case SlotType::INT:
		{
			if (value_union.int_value != other.value_union.int_value) {
				return false;
			}
			break;
		}
		case SlotType::VECTOR:
		{
			if (value_union.vector_value != other.value_union.vector_value) {
				return false;
			}
			break;
		}
		case SlotType::CURVE_RGB:
		{
			assert(curve_rgb_value.get() != nullptr);
			assert(other.curve_rgb_value.get() != nullptr);
			if (*curve_rgb_value != *other.curve_rgb_value) {
				return false;
			}
			break;
		}
		case SlotType::CURVE_VECTOR:
		{
			assert(curve_vector_value.get() != nullptr);
			assert(other.curve_vector_value.get() != nullptr);
			if (*curve_vector_value != *other.curve_vector_value) {
				return false;
			}
			break;
		}
		case SlotType::COLOR_RAMP:
		{
			assert(color_ramp_value.get() != nullptr);
			assert(other.color_ramp_value.get() != nullptr);
			if (*color_ramp_value != *other.color_ramp_value) {
				return false;
			}
			break;
		}
        case SlotType::IMAGE:
        {
            assert(image_path_value.get() != nullptr);
            assert(other.image_path_value.get() != nullptr);
            if (*image_path_value != *other.image_path_value) {
                return false;
            }
            break;
        }
		default:
			// This should only happen when a new unsupported type is added
			assert(false);
	}

	return true;
}

bool csg::Slot::operator==(const Slot& other) const
{
	if (_name != other._name) {
		return false;
	}

	if (_dir != other._dir) {
		return false;
	}

	if (_type != other._type) {
		return false;
	}

	if (value.has_value() != other.value.has_value()) {
		return false;
	}

	if (value.has_value()) {
		if (*value != *(other.value)) {
			return false;
		}
	}

	return true;
}

max_stars_repo_name: zwluoqi/mobile-visual-shader-editor

max_issues_repo_name: zwluoqi/mobile-visual-shader-editor

max_forks_repo_name: zwluoqi/mobile-visual-shader-editor


text:
//==================================================================================================
/**
  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)
**/
//==================================================================================================
#include <boost/simd/function/shuffle.hpp>
#include <boost/simd/function/deinterleave_first.hpp>
#include <boost/simd/function/deinterleave_second.hpp>
#include <boost/simd/constant/valmin.hpp>
#include <boost/simd/constant/valmax.hpp>
#include <boost/simd/pack.hpp>
#include <simd_test.hpp>

namespace bs = boost::simd;

STF_CASE_TPL( "Direct deinterleave shuffle", STF_NUMERIC_TYPES)
{
  // cardinal 2
  {
    bs::pack<T,2> a{ bs::Valmax<T>(), T(42) };
    bs::pack<T,2> b{ T(13), bs::Valmin<T>() };

    STF_ALL_EQUAL( (bs::shuffle<0,2>(a,b)), (bs::deinterleave_first (a,b)) );
    STF_ALL_EQUAL( (bs::shuffle<1,3>(a,b)), (bs::deinterleave_second(a,b)) );
    STF_ALL_EQUAL( (bs::shuffle<2,0>(a,b)), (bs::deinterleave_first (b,a)) );
    STF_ALL_EQUAL( (bs::shuffle<3,1>(a,b)), (bs::deinterleave_second(b,a)) );
  }

 // cardinal 4
  {
    bs::pack<T,4> a{ bs::Valmax<T>(), T(42), T(69), bs::Valmin<T>() };
    bs::pack<T,4> b{ T(13), bs::Valmin<T>(), T(37), bs::Valmax<T>() };

    STF_ALL_EQUAL( (bs::shuffle<0,2,4,6>(a,b)), (bs::deinterleave_first (a,b)) );
    STF_ALL_EQUAL( (bs::shuffle<1,3,5,7>(a,b)), (bs::deinterleave_second(a,b)) );
    STF_ALL_EQUAL( (bs::shuffle<4,6,0,2>(a,b)), (bs::deinterleave_first (b,a)) );
    STF_ALL_EQUAL( (bs::shuffle<5,7,1,3>(a,b)), (bs::deinterleave_second(b,a)) );
  }

  // cardinal 8
  {
    bs::pack<T,8> a { bs::Valmax<T>(),T(66),T(99),T(55), T(-1),T(77), T(23), bs::Valmin<T>()};
    bs::pack<T,8> b{ T(13), bs::Valmin<T>(), T(37), bs::Valmax<T>(), T(54),T(13),T(37),T(69) };

    STF_ALL_EQUAL( (bs::shuffle<0,2,4,6,8,10,12,14>(a,b)), (bs::deinterleave_first (a,b)) );
    STF_ALL_EQUAL( (bs::shuffle<1,3,5,7,9,11,13,15>(a,b)), (bs::deinterleave_second(a,b)) );
    STF_ALL_EQUAL( (bs::shuffle<8,10,12,14,0,2,4,6>(a,b)), (bs::deinterleave_first (b,a)) );
    STF_ALL_EQUAL( (bs::shuffle<9,11,13,15,1,3,5,7>(a,b)), (bs::deinterleave_second(b,a)) );
  }
}


text:
//
//  Copyright (c) 2012 Artyom Beilis (Tonkikh)
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//

#include <boost/nowide/cstdlib.hpp>
#include <cstring>

#if defined(BOOST_NOWIDE_TEST_INCLUDE_WINDOWS) && defined(BOOST_WINDOWS)
#include <windows.h>
#endif

#include "test.hpp"

// "Safe" strcpy version with NULL termination to make MSVC runtime happy
// which warns when using strncpy
template<size_t size>
void strcpy_safe(char (&dest)[size], const char* src)
{
    size_t len = std::strlen(src);
    if(len >= size)
        len = size - 1u;
    std::memcpy(dest, src, len);
    dest[len] = 0;
}

void test_main(int, char**, char**)
{
    std::string example = "\xd7\xa9-\xd0\xbc-\xce\xbd";
    char penv[256] = {0};
    strcpy_safe(penv, ("BOOST_TEST2=" + example + "x").c_str());

    TEST(boost::nowide::setenv("BOOST_TEST1", example.c_str(), 1) == 0);
    TEST(boost::nowide::getenv("BOOST_TEST1"));
    TEST(boost::nowide::getenv("BOOST_TEST1") == example);
    TEST(boost::nowide::setenv("BOOST_TEST1", "xx", 0) == 0);
    TEST(boost::nowide::getenv("BOOST_TEST1") == example);
    TEST(boost::nowide::putenv(penv) == 0);
    TEST(boost::nowide::getenv("BOOST_TEST2"));
    TEST(boost::nowide::getenv("BOOST_TEST_INVALID") == 0);
    TEST(boost::nowide::getenv("BOOST_TEST2") == example + "x");
#ifdef BOOST_WINDOWS
    // Passing a variable without an equals sign (before \0) is an error
    // But GLIBC has an extension that unsets the env var instead
    char penv2[256] = {0};
    const char* sPenv2 = "BOOST_TEST1SOMEGARBAGE=";
    strcpy_safe(penv2, sPenv2);
    // End the string before the equals sign -> Expect fail
    penv2[strlen("BOOST_TEST1")] = '\0';
    TEST(boost::nowide::putenv(penv2) == -1);
    TEST(boost::nowide::getenv("BOOST_TEST1"));
    TEST(boost::nowide::getenv("BOOST_TEST1") == example);
#endif
}

max_stars_repo_name: DouglasHeriotDesign/nowide

max_issues_repo_name: DouglasHeriotDesign/nowide


text:
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Helmet Software Framework
//
// Copyright (C) 2018 Hat Boy Software, Inc.
//
//  @author Matthew Alan Gray - <mgray@hatboysoftware.com>
//  @author Tony Richards - <trichards@indiezen.com>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#pragma once

#include <Helmet/Enterprise/Configuration.hpp>

#include <memory>

#include <boost/noncopyable.hpp>

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Helmet {
namespace Enterprise {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
class I_Request;
class I_ResponseHandler;

class HELMET_ENTERPRISE_DLL_LINK I_RequestHandler
:   boost::noncopyable
{
    /// @name Types
    /// @{
public:
    typedef std::shared_ptr<I_Request>                  pRequest_type;
    typedef std::shared_ptr<I_ResponseHandler>          pResponseHandler_type;
    /// @}

    /// @name I_RequestHandler interface.
    /// @{
public:
    /// Handle a request asynchronously
    /// @param _responseHandler dispatch object that will handle the reponse to this request.
    virtual void handleRequest(pRequest_type _pRequest, pResponseHandler_type _pResponseHandler) = 0;
    /// @}

    /// @name Events
    /// @{
public:
    /// @}

    /// @name 'Structors
    /// @{
protected:
             I_RequestHandler();
    virtual ~I_RequestHandler();
    /// @}

};  // interface I_RequestHandler

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
}   // namespace Enterprise
}   // namespace Helmet
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~

ext: hpp

max_stars_repo_name: hatboysoftware/helmet

max_issues_repo_name: hatboysoftware/helmet

max_forks_repo_name: hatboysoftware/helmet


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#include "kudu/cfile/cfile_writer.h"

#include <functional>
#include <numeric>
#include <ostream>
#include <utility>

#include <boost/optional/optional.hpp>
#include <gflags/gflags.h>
#include <glog/logging.h>

#include "kudu/cfile/block_compression.h"
#include "kudu/cfile/block_encodings.h"
#include "kudu/cfile/block_pointer.h"
#include "kudu/cfile/cfile.pb.h"
#include "kudu/cfile/cfile_util.h"
#include "kudu/cfile/index_btree.h"
#include "kudu/cfile/type_encodings.h"
#include "kudu/common/common.pb.h"
#include "kudu/common/key_encoder.h"
#include "kudu/common/schema.h"
#include "kudu/common/types.h"
#include "kudu/gutil/port.h"
#include "kudu/util/array_view.h" // IWYU pragma: keep
#include "kudu/util/coding.h"
#include "kudu/util/coding-inl.h"
#include "kudu/util/compression/compression_codec.h"
#include "kudu/util/crc.h"
#include "kudu/util/debug/trace_event.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/hexdump.h"
#include "kudu/util/logging.h"
#include "kudu/util/pb_util.h"

DEFINE_int32(cfile_default_block_size, 256*1024, "The default block size to use in cfiles");
TAG_FLAG(cfile_default_block_size, advanced);

DEFINE_string(cfile_default_compression_codec, "no_compression",
              "Default cfile block compression codec.");
TAG_FLAG(cfile_default_compression_codec, advanced);

DEFINE_bool(cfile_write_checksums, true,
            "Write CRC32 checksums for each block");
TAG_FLAG(cfile_write_checksums, evolving);

using google::protobuf::RepeatedPtrField;
using kudu::fs::BlockCreationTransaction;
using kudu::fs::BlockManager;
using kudu::fs::WritableBlock;
using std::accumulate;
using std::pair;
using std::string;
using std::unique_ptr;
using std::vector;

namespace kudu {
namespace cfile {

const char kMagicStringV1[] = "kuducfil";
const char kMagicStringV2[] = "kuducfl2";
const int kMagicLength = 8;
const size_t kChecksumSize = sizeof(uint32_t);

static const size_t kMinBlockSize = 512;

////////////////////////////////////////////////////////////
// CFileWriter
////////////////////////////////////////////////////////////

CFileWriter::CFileWriter(WriterOptions options,
                         const TypeInfo* typeinfo,
                         bool is_nullable,
                         unique_ptr<WritableBlock> block)
  : block_(std::move(block)),
    off_(0),
    value_count_(0),
    options_(std::move(options)),
    is_nullable_(is_nullable),
    typeinfo_(typeinfo),
    state_(kWriterInitialized) {
  EncodingType encoding = options_.storage_attributes.encoding;
  Status s = TypeEncodingInfo::Get(typeinfo_, encoding, &type_encoding_info_);
  if (!s.ok()) {
    // TODO: we should somehow pass some contextual info about the
    // tablet here.
    WARN_NOT_OK(s, "Falling back to default encoding");
    s = TypeEncodingInfo::Get(typeinfo,
                              TypeEncodingInfo::GetDefaultEncoding(typeinfo_),
                              &type_encoding_info_);
    CHECK_OK(s);
  }

  compression_ = options_.storage_attributes.compression;
  if (compression_ == DEFAULT_COMPRESSION) {
    compression_ = GetCompressionCodecType(FLAGS_cfile_default_compression_codec);
  }

  if (options_.storage_attributes.cfile_block_size <= 0) {
    options_.storage_attributes.cfile_block_size = FLAGS_cfile_default_block_size;
  }
  if (options_.storage_attributes.cfile_block_size < kMinBlockSize) {
    LOG(WARNING) << "Configured block size " << options_.storage_attributes.cfile_block_size
                 << " smaller than minimum allowed value " << kMinBlockSize
                 << ": using minimum.";
    options_.storage_attributes.cfile_block_size = kMinBlockSize;
  }

  if (options_.write_posidx) {
    posidx_builder_.reset(new IndexTreeBuilder(&options_, this));
  }

  if (options_.write_validx) {
    if (!options_.validx_key_encoder) {
      auto key_encoder = &GetKeyEncoder<faststring>(typeinfo_);
      options_.validx_key_encoder = [key_encoder] (const void* value, faststring* buffer) {
        key_encoder->ResetAndEncode(value, buffer);
      };
    }

    validx_builder_.reset(new IndexTreeBuilder(&options_, this));
  }
}

CFileWriter::~CFileWriter() {
}

Status CFileWriter::Start() {
  TRACE_EVENT0("cfile", "CFileWriter::Start");
  CHECK(state_ == kWriterInitialized) <<
    "bad state for Start(): " << state_;

  if (compression_ != NO_COMPRESSION) {
    const CompressionCodec* codec;
    RETURN_NOT_OK(GetCompressionCodec(compression_, &codec));
    block_compressor_.reset(new CompressedBlockBuilder(codec));
  }

  CFileHeaderPB header;
  FlushMetadataToPB(header.mutable_metadata());

  uint32_t pb_size = header.ByteSize();

  faststring header_str;
  // First the magic.
  header_str.append(kMagicStringV2);
  // Then Length-prefixed header.
  PutFixed32(&header_str, pb_size);
  pb_util::AppendToString(header, &header_str);

  vector<Slice> header_slices;
  header_slices.emplace_back(header_str);

  // Append header checksum.
  uint8_t checksum_buf[kChecksumSize];
  if (FLAGS_cfile_write_checksums) {
    uint32_t header_checksum = crc::Crc32c(header_str.data(), header_str.size());
    InlineEncodeFixed32(checksum_buf, header_checksum);
    header_slices.emplace_back(checksum_buf, kChecksumSize);
  }

  RETURN_NOT_OK_PREPEND(WriteRawData(header_slices), "Couldn't write header");

  BlockBuilder *bb;
  RETURN_NOT_OK(type_encoding_info_->CreateBlockBuilder(&bb, &options_));
  data_block_.reset(bb);

  if (is_nullable_) {
    size_t nrows = ((options_.storage_attributes.cfile_block_size + typeinfo_->size() - 1) /
                    typeinfo_->size());
    non_null_bitmap_builder_.reset(new NullBitmapBuilder(nrows * 8));
  }

  state_ = kWriterWriting;

  return Status::OK();
}

Status CFileWriter::Finish() {
  TRACE_EVENT0("cfile", "CFileWriter::Finish");
  BlockManager* bm = block_->block_manager();
  unique_ptr<BlockCreationTransaction> transaction = bm->NewCreationTransaction();
  RETURN_NOT_OK(FinishAndReleaseBlock(transaction.get()));
  return transaction->CommitCreatedBlocks();
}

Status CFileWriter::FinishAndReleaseBlock(BlockCreationTransaction* transaction) {
  TRACE_EVENT0("cfile", "CFileWriter::FinishAndReleaseBlock");
  CHECK(state_ == kWriterWriting) <<
    "Bad state for Finish(): " << state_;

  // Write out any pending values as the last data block.
  RETURN_NOT_OK(FinishCurDataBlock());

  state_ = kWriterFinished;

  uint32_t incompatible_features = 0;
  if (FLAGS_cfile_write_checksums) {
    incompatible_features |= IncompatibleFeatures::CHECKSUM;
  }

  // Start preparing the footer.
  CFileFooterPB footer;
  footer.set_data_type(typeinfo_->type());
  footer.set_is_type_nullable(is_nullable_);
  footer.set_encoding(type_encoding_info_->encoding_type());
  footer.set_num_values(value_count_);
  footer.set_compression(compression_);
  footer.set_incompatible_features(incompatible_features);

  // Write out any pending positional index blocks.
  if (options_.write_posidx) {
    BTreeInfoPB posidx_info;
    RETURN_NOT_OK_PREPEND(posidx_builder_->Finish(&posidx_info),
                          "Couldn't write positional index");
    footer.mutable_posidx_info()->CopyFrom(posidx_info);
  }

  if (options_.write_validx) {
    BTreeInfoPB validx_info;
    RETURN_NOT_OK_PREPEND(validx_builder_->Finish(&validx_info), "Couldn't write value index");
    footer.mutable_validx_info()->CopyFrom(validx_info);
  }

  // Optionally append extra information to the end of cfile.
  // Example: dictionary block for dictionary encoding
  RETURN_NOT_OK(data_block_->AppendExtraInfo(this, &footer));

  // Flush metadata.
  FlushMetadataToPB(footer.mutable_metadata());

  faststring footer_str;
  pb_util::SerializeToString(footer, &footer_str);

  footer_str.append(kMagicStringV2);
  PutFixed32(&footer_str, footer.GetCachedSize());

  // Prepend the footer checksum.
  vector<Slice> footer_slices;
  uint8_t checksum_buf[kChecksumSize];
  if (FLAGS_cfile_write_checksums) {
    uint32_t footer_checksum = crc::Crc32c(footer_str.data(), footer_str.size());
    InlineEncodeFixed32(checksum_buf, footer_checksum);
    footer_slices.emplace_back(checksum_buf, kChecksumSize);
  }

  footer_slices.emplace_back(footer_str);
  RETURN_NOT_OK_PREPEND(WriteRawData(footer_slices), "Couldn't write footer");

  // Done with this block.
  RETURN_NOT_OK(block_->Finalize());
  transaction->AddCreatedBlock(std::move(block_));
  return Status::OK();
}

void CFileWriter::AddMetadataPair(const Slice &key, const Slice &value) {
  CHECK_NE(state_, kWriterFinished);

  unflushed_metadata_.emplace_back(key.ToString(), value.ToString());
}

string CFileWriter::GetMetaValueOrDie(Slice key) const {
  typedef pair<string, string> ss_pair;
  for (const ss_pair& entry : unflushed_metadata_) {
    if (Slice(entry.first) == key) {
      return entry.second;
    }
  }
  LOG(FATAL) << "Missing metadata entry: " << KUDU_REDACT(key.ToDebugString());
}

void CFileWriter::FlushMetadataToPB(RepeatedPtrField<FileMetadataPairPB> *field) {
  typedef pair<string, string> ss_pair;
  for (const ss_pair &entry : unflushed_metadata_) {
    FileMetadataPairPB *pb = field->Add();
    pb->set_key(entry.first);
    pb->set_value(entry.second);
  }
  unflushed_metadata_.clear();
}

Status CFileWriter::AppendEntries(const void *entries, size_t count) {
  DCHECK(!is_nullable_);

  int rem = count;

  const uint8_t *ptr = reinterpret_cast<const uint8_t *>(entries);

  while (rem > 0) {
    int n = data_block_->Add(ptr, rem);
    DCHECK_GE(n, 0);

    ptr += typeinfo_->size() * n;
    rem -= n;
    value_count_ += n;

    if (data_block_->IsBlockFull()) {
      RETURN_NOT_OK(FinishCurDataBlock());
    }
  }

  DCHECK_EQ(rem, 0);
  return Status::OK();
}

Status CFileWriter::AppendNullableEntries(const uint8_t *bitmap,
                                          const void *entries,
                                          size_t count) {
  DCHECK(is_nullable_ && bitmap != nullptr);

  const uint8_t *ptr = reinterpret_cast<const uint8_t *>(entries);

  size_t nitems;
  bool is_non_null = false;
  BitmapIterator bmap_iter(bitmap, count);
  while ((nitems = bmap_iter.Next(&is_non_null)) > 0) {
    if (is_non_null) {
      size_t rem = nitems;
      do {
        int n = data_block_->Add(ptr, rem);
        DCHECK_GE(n, 0);

        non_null_bitmap_builder_->AddRun(true, n);
        ptr += n * typeinfo_->size();
        value_count_ += n;
        rem -= n;

        if (data_block_->IsBlockFull()) {
          RETURN_NOT_OK(FinishCurDataBlock());
        }

      } while (rem > 0);
    } else {
      non_null_bitmap_builder_->AddRun(false, nitems);
      ptr += nitems * typeinfo_->size();
      value_count_ += nitems;
    }
  }

  return Status::OK();
}

Status CFileWriter::FinishCurDataBlock() {
  uint32_t num_elems_in_block = data_block_->Count();
  if (is_nullable_) {
    num_elems_in_block = non_null_bitmap_builder_->nitems();
  }

  if (PREDICT_FALSE(num_elems_in_block == 0)) {
    return Status::OK();
  }

  rowid_t first_elem_ord = value_count_ - num_elems_in_block;
  VLOG(1) << "Appending data block for values " <<
    first_elem_ord << "-" << value_count_;

  // The current data block is full, need to push it
  // into the file, and add to index
  Slice data = data_block_->Finish(first_elem_ord);
  VLOG(2) << " actual size=" << data.size();

  uint8_t key_tmp_space[typeinfo_->size()];
  if (validx_builder_ != nullptr) {
    // If we're building an index, we need to copy the first
    // key from the block locally, so we can write it into that index.
    RETURN_NOT_OK(data_block_->GetFirstKey(key_tmp_space));
    VLOG(1) << "Appending validx entry\n" <<
      kudu::HexDump(Slice(key_tmp_space, typeinfo_->size()));
  }

  vector<Slice> v;
  faststring null_headers;
  if (is_nullable_) {
    Slice non_null_bitmap = non_null_bitmap_builder_->Finish();
    PutVarint32(&null_headers, num_elems_in_block);
    PutVarint32(&null_headers, non_null_bitmap.size());
    v.emplace_back(null_headers.data(), null_headers.size());
    v.push_back(non_null_bitmap);
  }
  v.push_back(data);
  Status s = AppendRawBlock(v, first_elem_ord,
                            reinterpret_cast<const void *>(key_tmp_space),
                            Slice(last_key_),
                            "data block");

  if (is_nullable_) {
    non_null_bitmap_builder_->Reset();
  }

  if (validx_builder_ != nullptr) {
    RETURN_NOT_OK(data_block_->GetLastKey(key_tmp_space));
    (*options_.validx_key_encoder)(key_tmp_space, &last_key_);
  }
  data_block_->Reset();

  return s;
}

Status CFileWriter::AppendRawBlock(const vector<Slice>& data_slices,
                                   size_t ordinal_pos,
                                   const void *validx_curr,
                                   const Slice& validx_prev,
                                   const char *name_for_log) {
  CHECK_EQ(state_, kWriterWriting);

  BlockPointer ptr;
  Status s = AddBlock(data_slices, &ptr, name_for_log);
  if (!s.ok()) {
    LOG(WARNING) << "Unable to append block to file: " << s.ToString();
    return s;
  }

  // Now add to the index blocks
  if (posidx_builder_ != nullptr) {
    tmp_buf_.clear();
    KeyEncoderTraits<UINT32, faststring>::Encode(ordinal_pos, &tmp_buf_);
    RETURN_NOT_OK(posidx_builder_->Append(Slice(tmp_buf_), ptr));
  }

  if (validx_builder_ != nullptr) {
    CHECK(validx_curr != nullptr) <<
      "must pass a key for raw block if validx is configured";

    (*options_.validx_key_encoder)(validx_curr, &tmp_buf_);
    Slice idx_key = Slice(tmp_buf_);
    if (options_.optimize_index_keys) {
      GetSeparatingKey(validx_prev, &idx_key);
    }
    VLOG(1) << "Appending validx entry\n" <<
            kudu::HexDump(idx_key);
    s = validx_builder_->Append(idx_key, ptr);
    if (!s.ok()) {
      LOG(WARNING) << "Unable to append to value index: " << s.ToString();
      return s;
    }
  }

  return s;
}

Status CFileWriter::AddBlock(const vector<Slice> &data_slices,
                             BlockPointer *block_ptr,
                             const char *name_for_log) {
  uint64_t start_offset = off_;
  vector<Slice> out_slices;

  if (block_compressor_ != nullptr) {
    // Write compressed block
    Status s = block_compressor_->Compress(data_slices, &out_slices);
    if (!s.ok()) {
      LOG(WARNING) << "Unable to compress block at offset " << off_
                   << ": " << s.ToString();
      return s;
    }
  } else {
    out_slices = data_slices;
  }

  // Calculate and append a data checksum.
  uint8_t checksum_buf[kChecksumSize];
  if (FLAGS_cfile_write_checksums) {
    uint32_t checksum = 0;
    for (const Slice &data : out_slices) {
      checksum = crc::Crc32c(data.data(), data.size(), checksum);
    }
    InlineEncodeFixed32(checksum_buf, checksum);
    out_slices.emplace_back(checksum_buf, kChecksumSize);
  }

  RETURN_NOT_OK(WriteRawData(out_slices));

  uint64_t total_size = off_ - start_offset;

  *block_ptr = BlockPointer(start_offset, total_size);
  VLOG(1) << "Appended " << name_for_log
          << " with " << total_size << " bytes at " << start_offset;
  return Status::OK();
}

Status CFileWriter::WriteRawData(const vector<Slice>& data) {
  size_t data_size = accumulate(data.begin(), data.end(), static_cast<size_t>(0),
                                [&](int sum, const Slice& curr) {
                                  return sum + curr.size();
                                });
  Status s = block_->AppendV(data);
  if (!s.ok()) {
    LOG(WARNING) << "Unable to append data of size "
                 << data_size << " at offset " << off_
                 << ": " << s.ToString();
  }
  off_ += data_size;
  return s;
}

} // namespace cfile
} // namespace kudu

ext: cc

max_stars_repo_name: plusplusjiajia/kudu

max_issues_repo_name: plusplusjiajia/kudu

max_forks_repo_name: plusplusjiajia/kudu


text:
#include "CommandAttack.h"
#include <boost/algorithm/string.hpp>
#include <iostream>

using internationalization::Internationalization;

void CommandAttack::executeInHeartbeat(const std::string& username, const std::vector<std::string>& fullCommand) {
    auto& currentCombat = combatManager.getCombatWithPlayer(username);

    if(currentCombat.hasPlayer(username)){

        currentCombat.queueCommand(username, fullCommand);
        //handle npc opponent. does nothing if character is user controlled
        auto opponentName = currentCombat.getOpponent(username);
        auto opponentResponse = characterManager.getAttackReply(opponentName);
        //if response is empty then non-ai opponent
        if(!opponentResponse.empty()) {
            onlineUserManager.addMessageToUser(username, opponentName + " prepares a(n) " + opponentResponse + "\n");
            std::vector<std::string> opponentCommand;
            opponentCommand.push_back(opponentResponse);
            currentCombat.queueCommand(opponentName, opponentCommand);
        }

    } else { //player is not in a combat
        onlineUserManager.addMessageToUser(username, stringManager.getString(Internationalization::STRING_CODE::NOT_IN_COMBAT));
    }
}

void CommandAttack::executeCombatRound(const std::string& username, const std::vector<std::string>& fullCommand) {
    auto& currentCombat = combatManager.getCombatWithPlayer(username);

    auto attackValue = characterManager.getCharacterAttack(username);
    auto opponentName = currentCombat.getOpponent(username);

    if(characterManager.isDecoy(opponentName)){
        onlineUserManager.addMessageToUser(username, "You missed your opponent and hit their decoy.\n");
        onlineUserManager.addMessageToUser(opponentName, "Your opponent hit your decoy\n");
    } else {
        characterManager.damageCharacter(opponentName, attackValue);
        onlineUserManager.addMessageToUser(
                username,
                stringManager.getString(Internationalization::STRING_CODE::YOU_ATTACKED) +
                opponentName +
                stringManager.getString(Internationalization::STRING_CODE::FOR) +
                std::to_string(attackValue) +
                ".\n"
        );
        onlineUserManager.addMessageToUser(
                opponentName,
                stringManager.getString(Internationalization::STRING_CODE::YOU_WERE_ATTACKED_FOR) +
                std::to_string(attackValue) +
                ".\n" + stringManager.getString(Internationalization::STRING_CODE::CURRENT_HP) +
                std::to_string(characterManager.getCharacterHealth(opponentName)) +
                "\n"
        );
    }

    if(characterManager.getCharacterHealth(opponentName) <= 0){
        //end combat & respawn opponent if user
    }
}

std::vector<std::string> CommandAttack::reassembleCommand(std::string& fullCommand, bool& commandIsValid) {
    std::vector<std::string> processedCommand;

    //Format: attack
    boost::trim_if(fullCommand, boost::is_any_of(" \t"));

    //split by " " and compress all long spaces
    boost::split(processedCommand, fullCommand, boost::is_any_of(" \t"), boost::token_compress_on);
    commandIsValid = (processedCommand.size() == 1 || processedCommand.size() == 2);

    return processedCommand;
}