text:
/*
 * Copyright (c) 2015-2016 Spotify AB
 *
 * 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.
 */

#include <string>

#include <sstream>

#include <boost/test/unit_test.hpp>

#include <spotify/json/codec/object.hpp>
#include <spotify/json/decode.hpp>
#include <spotify/json/decode_exception.hpp>
#include <spotify/json/encode.hpp>

#include <spotify/json/benchmark/benchmark.hpp>

BOOST_AUTO_TEST_SUITE(spotify)
BOOST_AUTO_TEST_SUITE(json)
BOOST_AUTO_TEST_SUITE(codec)

struct struct_t {
  int integer;
};

codec::object_t<struct_t> required_codec(size_t n) {
  auto codec = codec::object<struct_t>();
  const size_t num_letters = 'z' - 'a';
  for (size_t i = 0; i < n; i++) {
    const auto c = static_cast<char>('a' + (i % num_letters));
    const auto m = (i / num_letters);
    std::stringstream key_ss;
    key_ss << c << m;
    codec.required(key_ss.str(), &struct_t::integer);
  }
  return codec;
}

std::string make_json(size_t n) {
  std::stringstream json_ss;
  json_ss << "{";

  const size_t num_letters = 'z' - 'a';
  for (size_t i = 0; i < n; i++) {
    const auto c = static_cast<char>('a' + (i % num_letters));
    const auto m = (i / num_letters);
    std::stringstream key_ss;
    json_ss << '"' << c << m << '"' << ":0,";
  }

  json_ss << '"' << '.' << '"' << ":0}";
  return json_ss.str();
}

BOOST_AUTO_TEST_CASE(benchmark_json_codec_object_decode_with_few_required_fields) {
  const auto codec = required_codec(50);
  const auto json = make_json(50);

  JSON_BENCHMARK(1e5, [=]{
    auto context = decode_context(json.data(), json.data() + json.size());
    codec.decode(context);
  });
}

BOOST_AUTO_TEST_CASE(benchmark_json_codec_object_decode_with_many_required_fields) {
  const auto codec = required_codec(1000);
  const auto json = make_json(1000);

  JSON_BENCHMARK(1e4, [=]{
    auto context = decode_context(json.data(), json.data() + json.size());
    codec.decode(context);
  });
}

BOOST_AUTO_TEST_SUITE_END()  // codec
BOOST_AUTO_TEST_SUITE_END()  // json
BOOST_AUTO_TEST_SUITE_END()  // spotify

ext: cpp

max_stars_repo_name: ivangalkin/spotify-json

max_issues_repo_name: ivangalkin/spotify-json

max_forks_repo_name: ivangalkin/spotify-json


text:
/*
 *  YOLO against multiple files in a folder
 */
#include <opencv2/opencv.hpp>   // for commandline parser
#include "jetnet.h"
#include "create_runner.h"
//#include <boost/filesystem.hpp>
//#include <boost/algorithm/string.hpp>
#include <experimental/filesystem>
#include <curl/curl.h>

using namespace jetnet;

std::string log_detections(const std::vector<Detection>& detections, std::vector<std::string> class_labels) {
    std::ostringstream detection_str_builder;

    for (auto detection : detections) {
        auto class_label_index = std::max_element(detection.probabilities.begin(), detection.probabilities.end()) - detection.probabilities.begin();
        std::string text(std::to_string(static_cast<int>(detection.probabilities[class_label_index] * 100)) + "% " + class_labels[class_label_index]);
        std::cout << text <<std::endl;
        detection_str_builder << "_" << class_labels[class_label_index] << std::to_string(static_cast<int>(detection.probabilities[class_label_index] * 100));
    }

    return detection_str_builder.str();
}

int main(int argc, char** argv)
{
    std::string keys =
            "{help h usage ? |      | print this message                        }"
            "{@type          |<none>| Network type (yolov2, yolov3)             }"
            "{@modelfile     |<none>| Built and serialized TensorRT model file  }"
            "{@nameslist     |<none>| Class names list file                     }"
            "{@infolder      |<none>| Folder to read inputs from                }"
            "{outfolder      |      | Folder to write annotated outputs to      }"
            "{profile        |      | Enable profiling                          }"
            "{t thresh       | 0.24 | Detection threshold                       }"
            "{nt nmsthresh   | 0.45 | Non-maxima suppression threshold          }"
            "{batch          | 1    | Batch size                                }"
            "{anchors        |      | Anchor prior file name                    }";

    cv::CommandLineParser parser(argc, argv, keys);
    parser.about("Jetnet YOLO Folder runner");

    if (parser.has("help")) {
        parser.printMessage();
        return -1;
    }

    auto network_type = parser.get<std::string>("@type");
    auto input_model_file = parser.get<std::string>("@modelfile");
    auto input_names_file = parser.get<std::string>("@nameslist");
    auto input_folder = parser.get<std::string>("@infolder");
    auto output_folder = parser.get<std::string>("outfolder");
    auto threshold = parser.get<float>("thresh");
    auto nms_threshold = parser.get<float>("nmsthresh");
    auto batch_size = parser.get<int>("batch");
    auto anchors_file = parser.get<std::string>("anchors");

    if (!parser.check()) {
        parser.printErrors();
        return 0;
    }

    std::vector<std::string> class_names;
    if (!read_text_file(class_names, input_names_file)) {
        std::cerr << "Failed to read names file" << std::endl;
        return -1;
    }

    // read anchors file
    std::vector<std::string> anchor_priors_str;
    std::vector<float> anchor_priors;

    if (!anchors_file.empty()) {
        if (!read_text_file(anchor_priors_str, anchors_file)) {
            std::cerr << "Failed to read anchor priors file" << std::endl;
            return -1;
        }

        for (auto str : anchor_priors_str)
            anchor_priors.push_back(std::stof(str));
    }

    YoloRunnerFactory runner_fact(class_names.size(), threshold, nms_threshold, batch_size,
                                  anchor_priors, false);
    YoloRunnerFactory::PreType pre;
    YoloRunnerFactory::RunnerType runner;
    YoloRunnerFactory::PostType post;

    std::tie(pre, runner, post) = runner_fact.create(network_type);

    if (!pre || !runner || !post) {
        std::cerr << "Failed to create runner" << std::endl;
        return -1;
    }

    if (!runner->init(input_model_file)) {
        std::cerr << "Failed to init runner" << std::endl;
        return -1;
    }

    // TODO list files in input folder and write to inputs vector

    for(auto& input: std::experimental::filesystem::recursive_directory_iterator(input_folder))
    {
        //if (!boost::iequals(input.path().extension().string(), ".jpg"))
        if (input.path().extension().string() != ".jpg")
            continue;

        std::string input_str = input.path().string();

        std::vector<cv::Mat> images;

        std::cout << "Reading from: " << input_str << std::endl;

        cv::Mat img = read_image(input_str);
        if (img.empty()) {
            std::cerr << "Failed to read image:: " << input_str << std::endl;
            return -1;
        }

        images.push_back(img);

        // register images to the preprocessor
        pre->register_images(images);

        if (!(*runner)()) {
            std::cerr << "Failed to run network" << std::endl;
            return -1;
        }

        // get detections
        auto detections = post->get_detections();

        // Log the detections to the console & write to str
        std::string detection_str = log_detections(detections[0], class_names);

        if (!detection_str.empty() && !output_folder.empty()) {
            std::experimental::filesystem::path inputPath(input_str);

            std::ostringstream output_filename_builder;
            output_filename_builder << output_folder << "/" << inputPath.stem() << detection_str << ".jpg";
            std::string output_filename = output_filename_builder.str();

            // Optionally output an image file
            std::cout << "Writing annotated image to " << output_filename << std::endl;
            cv::Mat out;
            // image is read in RGB, convert to BGR for display with imshow and bbox rendering
            cv::cvtColor(images[0], out, cv::COLOR_RGB2BGR);
            draw_detections(detections[0], class_names, out);
            write_image(output_filename, out);
            out.release();
        }

        images[0].release();
        img.release();
    }

    std::cout << "Complete" << std::endl;
    return 0;
}

max_stars_repo_name: petergeneric/jetnet-detect

max_issues_repo_name: petergeneric/jetnet-detect

max_forks_repo_name: petergeneric/jetnet-detect


text:
// -------------------------------------------------------------------------------------------------
//                              Copyright 2016 - NumScale SAS
//
//                   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
// -------------------------------------------------------------------------------------------------

/// bench for functor is_not_less_equal in simd mode for float type with no decorator (regular call).
#include <simd_bench.hpp>
#include <boost/simd/function/is_not_less_equal.hpp>

namespace nsb = ns::bench;
namespace bs =  boost::simd;

DEFINE_BENCH_MAIN()
{
  using T = bs::pack<float>;
  run<T>(bs::is_not_less_equal, nsbg::rand<T>(-10, 10), nsbg::rand<T>(-10, 10));
}


text:
#include <llvm/ADT/STLExtras.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/TargetSelect.h>

#include "foundations/Database.hpp"
#include "queryCompiler/queryCompiler.hpp"
#include "utils/general.hpp"

#include "native/sql/SqlTuple.hpp"
#include "foundations/InformationUnit.hpp"
#include "semanticAnalyser/SemanticAnalyser.hpp"
#include "queryCompiler/QueryContext.hpp"

#include <boost/algorithm/string.hpp>

#include <unistd.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <atomic>
#include <unordered_map>
// pistache
#include "pistache/endpoint.h"
#include "pistache/http_header.h"
#include "pistache/http_headers.h"
using namespace Pistache;

static std::string escapeEscapes(const std::string& in) {
    std::stringstream ss;
    size_t idx = 0;
    while (idx < in.size()) {
        if (in[idx] == '\n') {
            ss << '\\' << 'r' << '\\' << 'n';
        } else {
            ss << in[idx];
        }
        ++idx;
    }
    return ss.str();
}
static std::string escapeQuote(const std::string& in) {
    std::stringstream ss;
    size_t idx = 0;
    while (idx < in.size()) {
        if (in[idx] == '"') {
            ss << '\\' << '"';
        } else {
            ss << in[idx];
        }
        ++idx;
    }
    return ss.str();
}

std::unordered_map<uint64_t, std::unique_ptr<Database>> dbs;
std::atomic<uint64_t> dbcounter = 0;
char lectures[] = "{\"content\": [{\"No\": 4052, \"title\": \"logic\", \"ECTS\": 4}]}";
char branches[] = "{\"nodes\": [{\"name\": \"master\", \"id\": 0, \"tuples\": 4}, {\"name\": \"mybranch1\",\"id\": 1,\"tuples\": 15}, {\"name\": \"mybranch2\",\"id\": 2, \"tuples\": 15}, {\"name\": \"mybranch3\",\"id\": 3,\"tuples\": 5}], \"links\": [{\"source\": 0,\"target\": 2,\"weight\": 1},{\"source\": 0,\"target\": 1,\"weight\": 1},{\"source\": 1,\"target\": 3,\"weight\": 1} ]}";

std::stringstream ss;
bool first;

void jsonStreamingCallback(Native::Sql::SqlTuple *tuple) {
  if(!first)
     ss << ",";
  ss << "{";
  first = false;
  int column=0; // TODO: replace by real column name
  for (const auto & value : tuple->values) {
      if (column)
         ss << ", ";
      ss << "\""<< column++ << "\":"  "\"" << escapeQuote(toString(*value)) << "\"" ;
  }
  ss << "}";
}

std::string printLineage(std::unique_ptr<Database>& db){
  QueryContext queryContext(*db);
  return semanticalAnalysis::BranchAnalyser(queryContext.analyzingContext).returnJSON();
}

class RestHandler : public Http::Handler {
public:
  HTTP_PROTOTYPE(RestHandler)
  void onRequest(const Http::Request &request, Http::ResponseWriter response) {
    response.headers()
        .add<Http::Header::AccessControlAllowOrigin>("*")
        .add<Http::Header::AccessControlAllowMethods>("GET, POST, PUT, DELETE")
        .add<Http::Header::AccessControlAllowHeaders>("content-type")
        .add<Http::Header::ContentType>(MIME(Application, Json));

    // parse resources for correct db
    std::vector<std::string> resources;
    uint64_t dbindex=0;
    boost::split(resources, request.resource(), boost::is_any_of("/"));
    if (resources.size()>=2)
      dbindex=std::atoi(resources[1].c_str());
    if(dbs.find(dbindex) == dbs.end())
      dbindex=0; //fallback to standard

    // switch over request method
    switch(request.method()){
      case Http::Method::Options:
        // it's a preflight request
        response.send(Http::Code::Ok);
        return;
      case Http::Method::Get:
        response.send(Http::Code::Ok, printLineage(dbs[dbindex]).c_str());
        return;
      case Http::Method::Put:
        dbindex = ++dbcounter;
        dbs.emplace(dbindex,std::make_unique<Database>());
        response.send(Http::Code::Ok,std::to_string(dbindex).c_str());
        return;
      case Http::Method::Post:
        break;
      case Http::Method::Delete:
        fprintf(stderr, "delete: %ld\n", dbindex);
        if(dbindex > 0) dbs.erase(dbindex);
        response.send(Http::Code::Ok);
        return;
      default:
        response.send(Http::Code::Bad_Request, "not supported method");
        return;
    }

    std::string input = request.body(), error="", columnsstring;
    std::vector<std::string> inputs;
    boost::split(inputs, input, boost::is_any_of(";"));
    struct QueryCompiler::BenchmarkResult result;
    for(auto& s: inputs){
      try {
        if(s.size()==0) continue; // no input
        s+=";"; // add terminate symbol
        // reset json printers
        ss.str("");
        first=true;
        result += QueryCompiler::compileAndBenchmark(s,*dbs[dbindex], (void*) jsonStreamingCallback);
        // print result
        columnsstring="";
        int column=0;
        for (auto& i: result.columns){
           if(column>0) columnsstring += ", ";
           columnsstring+= "{\"" + std::to_string(column++) + "\": \"" + i->columnInformation->columnName + "\"}";
        }
      } catch (const std::exception & e) {
        fprintf(stderr, "Exception: %s\n", e.what());
        error += e.what();
        error += "; ";
      } catch (...) {
      }
    }
    std::string output = "{\"columns\": [" + columnsstring + "], \"content\": [" + ss.str() + "]";
    if(error.size()>0)
       output +=", \"errormsg\": \"" + error + "\"";
    output+= ", \"compilationtime\": " + std::to_string(result.llvmCompilationTime/1000) + ", \"executiontime\": " + std::to_string(result.executionTime/1000) +
        ", \"parsingtime\": " + std::to_string(result.parsingTime/1000) + ", \"analysingtime\": " + std::to_string(result.analysingTime/1000) + ", \"translationtime\": "+ std::to_string(result.translationTime/1000) + "}";
    fprintf(stderr, "response: %s\n", output.c_str());
    response.send(Http::Code::Ok, output.c_str());
  }
};

int main(int argc, char **argv) {
  unsigned port = 5000;
  int opt;
  while ((opt = getopt(argc, argv, "p:")) != -1) {
    switch (opt) {
    case 'p':
      port = atoi(optarg);
      break;
    default:
      break;
    }
  }
  // necessary for the LLVM JIT compiler
  llvm::InitializeNativeTarget();
  llvm::InitializeNativeTargetAsmPrinter();
  llvm::InitializeNativeTargetAsmParser();
  dbs.emplace(0,std::make_unique<Database>()); // add a default db

  Pistache::Address addr(Pistache::Ipv4::any(), Pistache::Port(port));
  auto opts = Pistache::Http::Endpoint::options().threads(1).maxRequestSize(1024 * 1024);
  Http::Endpoint server(addr);
  server.init(opts);
  server.setHandler(Http::make_handler<RestHandler>());
  server.serve();
  server.shutdown();

  llvm::llvm_shutdown();

  return 0;
}

max_stars_repo_name: josefschmeisser/TardisDB

max_issues_repo_name: josefschmeisser/TardisDB

max_forks_repo_name: josefschmeisser/TardisDB


text:
// This file is part of the dune-xt-functions project:
//   https://github.com/dune-community/dune-xt-functions
// Copyright 2009-2018 dune-xt-functions developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2014 - 2018)
//   René Fritze     (2015 - 2018)
//   TiKeil          (2018)
//   Tobias Leibner  (2017)

#ifndef DUNE_XT_FUNCTIONS_BASE_DERIVED_HH
#define DUNE_XT_FUNCTIONS_BASE_DERIVED_HH

#include <memory>
#include <type_traits>

#include <boost/numeric/conversion/cast.hpp>

#include <dune/common/typetraits.hh>

#include <dune/xt/common/exceptions.hh>
#include <dune/xt/common/memory.hh>

#include <dune/xt/functions/interfaces/grid-function.hh>
#include <dune/xt/functions/interfaces/function.hh>

namespace Dune {
namespace XT {
namespace Functions {
namespace internal {

enum class Derivative
{
  divergence
};

template <class FunctionType, Derivative derivative>
class SelectDerived
{
  static_assert(is_grid_function<FunctionType>::value, "FunctionType has to be a GridFunction!");

public:
  typedef typename FunctionType::ElementType E;
  typedef typename FunctionType::DomainFieldType D;
  static const size_t d = FunctionType::domain_dim;
  typedef typename FunctionType::RangeFieldType R;

private:
  template <class F>
  class Choose
  {
    template <size_t d, size_t r, size_t rC, Derivative der, bool anything = true>
    class Dimension
    {
      static_assert(!anything, "No derivative for these dimensions available!");
    };

    template <size_t d, bool anything>
    class Dimension<d, d, 1, Derivative::divergence, anything>
    {
    public:
      static const size_t r = 1;
      static const size_t rC = 1;
    };

  public:
    static const size_t r = Dimension<d, F::range_dim, F::range_dim_cols, derivative>::r;
    static const size_t rC = Dimension<d, F::range_dim, F::range_dim_cols, derivative>::rC;
  }; // class SelectDerived

public:
  static const size_t r = Choose<FunctionType>::r;
  static const size_t rC = Choose<FunctionType>::rC;

  using FunctionLocalFunctionType = typename FunctionType::LocalFunctionType;
  using DomainType = typename ElementFunctionInterface<E, r, rC, R>::DomainType;
  using RangeType = typename ElementFunctionInterface<E, r, rC, R>::RangeType;
  using DerivativeRangeType = typename ElementFunctionInterface<E, r, rC, R>::DerivativeRangeType;

private:
  template <Derivative der, bool anything = true>
  class Call
  {
    static_assert(!anything, "Nothing available for this derivative!");
  }; // class Call

  template <bool anything>
  class Call<Derivative::divergence, anything>
  {
  public:
    static std::string type()
    {
      return "divergence";
    }

    static int order(const size_t ord)
    {
      return boost::numeric_cast<size_t>(std::max(boost::numeric_cast<ssize_t>(ord) - 1, ssize_t(0)));
    }

    static RangeType
    evaluate(const FunctionLocalFunctionType& func_local, const DomainType& xx, const Common::Parameter& param)
    {
      return func_local.jacobian(xx, param);
    } // ... evaluate(...)

    static DerivativeRangeType jacobian(const FunctionLocalFunctionType& /*func_local*/,
                                        const DomainType& /*xx*/,
                                        const Common::Parameter& /*param*/)
    {
      DUNE_THROW(NotImplemented, "for divergence!");
    }
  }; // class Call< ..., divergence >

public:
  static std::string type()
  {
    return Call<derivative>::type();
  }

  static int order(const size_t ord)
  {
    return Call<derivative>::order(ord);
  }

  static RangeType
  evaluate(const FunctionLocalFunctionType& func_local, const DomainType& xx, const Common::Parameter& param)
  {
    return Call<derivative>::evaluate(func_local, xx, param);
  }

  static DerivativeRangeType
  jacobian(const FunctionLocalFunctionType& func_local, const DomainType& xx, const Common::Parameter& param)
  {
    return Call<derivative>::jacobian(func_local, xx, param);
  }
}; // class SelectDerived

template <class FunctionType, Derivative derivative>
class DerivedLocalFunction
  : public ElementFunctionInterface<typename SelectDerived<FunctionType, derivative>::E,
                                    SelectDerived<FunctionType, derivative>::r,
                                    SelectDerived<FunctionType, derivative>::rC,
                                    typename SelectDerived<FunctionType, derivative>::R>
{
  using BaseType = ElementFunctionInterface<typename SelectDerived<FunctionType, derivative>::E,
                                            SelectDerived<FunctionType, derivative>::r,
                                            SelectDerived<FunctionType, derivative>::rC,
                                            typename SelectDerived<FunctionType, derivative>::R>;

  using Select = SelectDerived<FunctionType, derivative>;

public:
  using ElementType = typename BaseType::ElementType;
  using DomainType = typename BaseType::DomainType;
  using RangeType = typename BaseType::RangeType;
  using DerivativeRangeType = typename BaseType::DerivativeRangeType;

  DerivedLocalFunction(const FunctionType& func)
    : BaseType()
    , func_local_(func.local_function())
  {}

  int order(const XT::Common::Parameter& param = {}) const override final
  {
    return Select::order(func_local_->order(param));
  }

  RangeType evaluate(const DomainType& xx, const Common::Parameter& param = {}) const override final
  {
    return Select::evaluate(*func_local_, xx, param);
  }

  DerivativeRangeType jacobian(const DomainType& xx, const Common::Parameter& param = {}) const override final
  {
    return Select::jacobian(*func_local_, xx, param);
  }

protected:
  void post_bind(const ElementType& element)
  {
    func_local_->bind(element);
  }

private:
  std::unique_ptr<typename FunctionType::LocalFunctionType> func_local_;
}; // class DerivedLocalFunction

template <class FunctionType, Derivative derivative>
class Derived
  : public GridFunctionInterface<typename SelectDerived<FunctionType, derivative>::E,
                                 SelectDerived<FunctionType, derivative>::r,
                                 SelectDerived<FunctionType, derivative>::rC,
                                 typename SelectDerived<FunctionType, derivative>::R>
{
  using BaseType = GridFunctionInterface<typename SelectDerived<FunctionType, derivative>::E,
                                         SelectDerived<FunctionType, derivative>::r,
                                         SelectDerived<FunctionType, derivative>::rC,
                                         typename SelectDerived<FunctionType, derivative>::R>;
  using FunctionStorageType = Common::ConstStorageProvider<FunctionType>;
  using ThisType = Derived<FunctionType, derivative>;

public:
  using ElementType = typename BaseType::ElementType;
  using LocalFunctionType = typename BaseType::LocalFunctionType;

  Derived(const FunctionType& func, const std::string nm = "")
    : func_(Common::make_unique<FunctionStorageType>(func))
    , name_(nm.empty() ? SelectDerived<FunctionType, derivative>::type() + " of '" + func.name() + "'" : nm)
  {}

  Derived(const std::shared_ptr<const FunctionType> func, const std::string nm = "")
    : func_(Common::make_unique<FunctionStorageType>(func))
    , name_(nm.empty() ? SelectDerived<FunctionType, derivative>::type() + " of '" + func_->access().name() + "'" : nm)
  {}

  Derived(ThisType&& source) = default;
  Derived(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;
  ThisType& operator=(ThisType&& other) = delete;

  virtual std::unique_ptr<LocalFunctionType> local_function() const override final
  {
    typedef DerivedLocalFunction<FunctionType, derivative> RealLocalFunctionType;
    assert(func_);
    return Common::make_unique<RealLocalFunctionType>(func_->access());
  } // ... local_function(...)

  virtual ThisType* copy() const
  {
    DUNE_THROW(NotImplemented, "Are you kidding me?");
  }

  virtual std::string name() const override final
  {
    return name_;
  }

private:
  std::unique_ptr<const FunctionStorageType> func_;
  const std::string name_;
}; // class Derived

} // namespace internal

template <class FunctionType>
class DivergenceFunction : public internal::Derived<FunctionType, internal::Derivative::divergence>
{
  typedef internal::Derived<FunctionType, internal::Derivative::divergence> BaseType;

public:
  template <class... Args>
  DivergenceFunction(Args&&... args)
    : BaseType(std::forward<Args>(args)...)
  {}
}; // class DivergenceFunction

template <class T, class... Args>
std::shared_ptr<DivergenceFunction<T>> make_divergence(const T& func, Args&&... args)
{
  return std::make_shared<DivergenceFunction<T>>(func, std::forward<Args>(args)...);
}

template <class T, class... Args>
std::shared_ptr<DivergenceFunction<T>> make_divergence(std::shared_ptr<T> func, Args&&... args)
{
  return std::make_shared<DivergenceFunction<T>>(func, std::forward<Args>(args)...);
}

} // namespace Functions
} // namespace XT
} // namespace Dune

#endif // DUNE_XT_FUNCTIONS_DERIVED_HH

ext: hh

max_stars_repo_name: renefritze/dune-xt-functions

max_issues_repo_name: renefritze/dune-xt-functions

max_forks_repo_name: TiKeil/dune-xt-functions


text:
#include <bunsan/runtime/stacktrace.hpp>

#include <bunsan/runtime/demangle.hpp>
#include <bunsan/runtime/detail/format.hpp>

#include <boost/assert.hpp>
#include <boost/optional.hpp>
#include <boost/scope_exit.hpp>

#include <iomanip>

#include <cstdlib>
#include <cstring>

#include <dbghelp.h>
#include <psapi.h>
#include <windows.h>

namespace bunsan {
namespace runtime {

std::ostream &operator<<(std::ostream &out, const stacktrace &trace) {
  struct msvc_context {
    HANDLE hProcess = 0;
    bool syms_ready = false;
  };
  static const msvc_context context = []() {
    SymSetOptions(SYMOPT_DEFERRED_LOADS);
    msvc_context context = {
        .hProcess = GetCurrentProcess(),
        .syms_ready = SymInitialize(hProcess, nullptr, true)};
    return context;
  }();
  for (void *const function : trace) {
    if (context.syms_ready) {
      DWORD64 dwDisplacement = 0;
      DWORD64 dwAddress = reinterpret_cast<DWORD64>(function);
      std::vector<char> buffer(sizeof(SYMBOL_INFO) + MAX_SYM_NAME);
      PSYMBOL_INFO pSymbol = reinterpret_cast<PSYMBOL_INFO>(buffer.data());
      pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
      pSymbol->MaxNameLen = MAX_SYM_NAME;
      if (SymFromAddr(context.hProcess, dwAddress, &dwDisplacement, pSymbol)) {
        detail::format(out, nullptr, nullptr, 0, pSymbol->Name,
                       pSymbol->Address, dwDisplacement, function);
      } else {
        detail::format_fallback(out, function);
      }
    } else {
      detail::format_fallback(out, function);
    }
  }
  return out;
}

}  // namespace runtime
}  // namespace bunsan


text:
/*
ID: septicmk
LANG: C++
TASK: Kmeans.cpp
*/

#include "Kmeans.h"
#include "../Core/Core.h"
#include <boost/serialization/vector.hpp>
#include <boost/serialization/queue.hpp>
#include <boost/serialization/export.hpp>
#include <vector>
#include <queue>
#include <fstream>

BOOST_CLASS_EXPORT(kmeans::Kmeans)
namespace kmeans{

    void Matrix::init (size_t nrow, size_t ncol){
        this->nrow = nrow;
        this->ncol = ncol;
        data.resize(nrow*ncol);
        std::fill(data.begin(), data.end(), 0.0f);
    }

    void Matrix::add (std::vector<double> record, size_t i){
        for(size_t j = 0; j < record.size(); ++j){
            data[ i*ncol + j ] += record[j];
        }
    }

    std::vector<double> Matrix::get_value(size_t i){
        std::vector<double> ret;
        for (size_t j = 0; j < ncol; ++j){
            ret.push_back(data[ i*ncol + j ]);
        }
        return ret;
    }

    Kmeans* Kmeans::operator +(Kmeans &rhs){
        Kmeans *pret = new Kmeans();
        pret->mat.init(mat.nrow, mat.ncol);
        for(size_t i = 0; i< mat.data.size() ; ++i)
            pret->mat.data[i] = mat.data[i] + rhs.mat.data[i];
        return pret;
    }

    void Kmeans::beginDataScan(std::vector<double> records, size_t feat_dim){
        std::priority_queue<int> q;
        std::vector<int> weight;
        size_t n_records = records.size();
        size_t n_cluster = mat.nrow;
        for (size_t i = 0; i < n_records; ++ i){
            int x = core::Random(10007);
            weight.push_back(x);
            if (q.size() < n_cluster){
                q.push(i);
            }else if (x < weight[q.top()]){
                q.pop();
                q.push(i);
            }
        }
        while(!q.empty()){
            std::vector<double> record;
            record.clear();
            size_t i = q.top();
            for(size_t j = 0; j < feat_dim ; ++j){
                record.push_back(records[i*feat_dim+j]);
            }
            mat.add(record, n_cluster - q.size());
            q.pop();
        }
    }

    void Kmeans::endDataScan(){
        for(size_t i = 0; i < mat.nrow; ++i){
            for(size_t j = 0; j < mat.ncol; ++j){
                mat.data[i*mat.ncol+j] /= mat.data[i*mat.ncol + mat.ncol-1];
            }
            mat.data[i*mat.ncol + mat.ncol-1] = 1;
        }

        //for(size_t i = 0; i < nrow; ++i){
        //for(size_t j = 0; j < ncol; ++j){
        //std::cout << data[i*ncol+j] << " ";
        //}
        //std::puts("");
        //}
    }

    Kmeans* Kmeans::processRecord(std::vector<double> records, size_t feat_dim){
        Kmeans* pret = new Kmeans();
        //std::cout << this->test << std::endl;
        pret->mat.init(this->mat.nrow, this->mat.ncol);
        size_t n_records = records.size()/feat_dim;
        for (size_t i = 0 ; i < n_records ; i++){
            std::vector<double> record;
            record.clear();
            for(size_t j = 0; j < feat_dim ; j ++){
                record.push_back(records[i*feat_dim+j]);
            }
            double dis = (1L<<16)-1;
            int who = -1;
            //std::cout<<"bp"<<std::endl;
            for(size_t k = 0; k < mat.nrow; k++){
                std::vector<double> centroid = mat.get_value(k);
                double tmp = 0;
                for (size_t u = 0; u < record.size(); ++u){
                    tmp += (centroid[u] - record[u])*(centroid[u] - record[u]);
                }

                if (tmp < dis){
                    who = k;
                    dis = tmp;
                }
            }
            record.push_back(1);
            pret->mat.add(record, who);
        }
        return pret;
    }

    bool Kmeans::isConverged(Kmeans* rhs, size_t feat_dim, double eps){
        double diff = 0;
        for(size_t i = 0; i < mat.nrow; i ++){
            double tmp = 0;
            for(size_t j = 0;  j < feat_dim; j++){
                tmp += (mat.data[i*mat.ncol+j] - rhs->mat.data[i*mat.ncol+j]) * (mat.data[i*mat.ncol+j] - rhs->mat.data[i*mat.ncol+j]);
            }
            tmp = sqrt(tmp);
            diff += tmp;
        }
        if (diff <= eps) return true;
        else return false;

    }

    void Kmeans::finish(std::vector<double> records, size_t feat_dim){
        std::ofstream file;
        file.open("./ans.txt");
        std::vector<float> record;
        size_t n_records = records.size()/feat_dim;
        for(size_t i = 0; i < n_records; ++i){
            std::vector<double> record;
            record.clear();
            for(size_t j = 0; j < feat_dim; ++ j){
                record.push_back(records[i*feat_dim+j]);
            }
            double dis = (1<<16)-1;
            int who = -1;
            for(size_t k = 0; k < this->mat.nrow; k++){
                std::vector<double> centroid = this->mat.get_value(k);
                double tmp = 0;
                for (size_t u = 0; u < record.size(); ++u){
                    tmp += (centroid[u] - record[u])*(centroid[u] - record[u]);
                }

                if (tmp < dis){
                    who = k;
                    dis = tmp;
                }
            }
            file << who << std::endl;

        }

    }

}

max_stars_repo_name: NCIC-PARALLEL/Graphine-LIB

max_issues_repo_name: PAA-NCIC/HPML

max_forks_repo_name: PAA-NCIC/HPML