text:
/*
 * Copyright 2017 MapD Technologies, Inc.
 *
 * 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 <glog/logging.h>
#include <gtest/gtest.h>

#include <boost/algorithm/string.hpp>
#include <boost/iterator/counting_iterator.hpp>
#include "boost/filesystem.hpp"

#include "Catalog/Catalog.h"
#include "Fragmenter/InsertOrderFragmenter.h"
#include "Import/Importer.h"
#include "Parser/parser.h"
#include "QueryEngine/ResultSet.h"
#include "QueryRunner/QueryRunner.h"
#include "Shared/UpdelRoll.h"
#include "Shared/geo_types.h"
#include "Tests/TestHelpers.h"

#include <tuple>
#ifndef BASE_PATH
#define BASE_PATH "./tmp"
#endif

#define CALCITEPORT 9093

using namespace std;
using namespace Catalog_Namespace;
using namespace TestHelpers;

namespace {

std::unique_ptr<SessionInfo> gsession;
bool g_hoist_literals{true};

inline void run_ddl_statement(const string& input_str) {
  QueryRunner::run_ddl_statement(input_str, gsession);
}

std::shared_ptr<ResultSet> run_query(const string& query_str) {
  return QueryRunner::run_multiple_agg(
      query_str, gsession, ExecutorDeviceType::CPU, g_hoist_literals, true);
}

template <typename E = std::runtime_error>
bool alter_common(const string& table,
                  const string& column,
                  const string& type,
                  const string& comp,
                  const string& val,
                  const string& val2,
                  const bool expect_throw = false) {
  std::string alter_query = "alter table " + table + " add column " + column + " " + type;
  if (val != "") {
    alter_query += " default " + val;
  }
  if (comp != "") {
    alter_query += " encoding " + comp;
  }

  if (expect_throw) {
    EXPECT_THROW(run_ddl_statement(alter_query + ";"), E);
    return true;
  } else {
    EXPECT_NO_THROW(run_ddl_statement(alter_query + ";"););
  }

  if (val2 != "") {
    std::string query_str = "SELECT " + column + " FROM " + table;
    auto rows = run_query(query_str + ";");
    int r_cnt = 0;
    while (true) {
      auto crt_row = rows->getNextRow(true, true);
      if (0 == crt_row.size()) {
        break;
      }
      auto geo = boost::get<std::string>(v<NullableString>(crt_row[0]));
#if 1
      if (geo == val2) {
        ++r_cnt;
      }
#else
      // somehow these do not work as advertised ...
      using namespace Geo_namespace;
      if (boost::iequals(type, "POINT") && GeoPoint(geo) == GeoPoint(val2))
        ++r_cnt;
      else if (boost::iequals(type, "LINESTRING") &&
               GeoLineString(geo) == GeoLineString(val2))
        ++r_cnt;
      else if (boost::iequals(type, "POLYGON") && GeoPolygon(geo) == GeoPolygon(val2))
        ++r_cnt;
      else if (boost::iequals(type, "MULTIPOLYGON") &&
               GeoMultiPolygon(geo) == GeoMultiPolygon(val2))
        ++r_cnt;
#endif
    }
    return r_cnt == 100;
  } else {
    std::string query_str =
        "SELECT count() FROM " + table + " WHERE " + column +
        ("" == val || boost::iequals("NULL", val) ? " IS NULL" : (" = " + val));
    auto rows = run_query(query_str + ";");
    auto crt_row = rows->getNextRow(true, true);
    CHECK_EQ(size_t(1), crt_row.size());
    auto r_cnt = v<int64_t>(crt_row[0]);
    return r_cnt == 100;
  }
}

void import_table_file(const string& table, const string& file) {
  std::string query_str = string("COPY trips FROM '") + "../../Tests/Import/datafiles/" +
                          file + "' WITH (header='true');";

  SQLParser parser;
  std::list<std::unique_ptr<Parser::Stmt>> parse_trees;
  std::string last_parsed;
  if (parser.parse(query_str, parse_trees, last_parsed)) {
    throw std::runtime_error("Failed to parse: " + query_str);
  }
  CHECK_EQ(parse_trees.size(), size_t(1));

  const auto& stmt = parse_trees.front();
  Parser::DDLStmt* ddl = dynamic_cast<Parser::DDLStmt*>(stmt.get());
  if (!ddl) {
    throw std::runtime_error("Not a DDLStmt: " + query_str);
  }
  ddl->execute(*gsession);
}

class SQLTestEnv : public ::testing::Environment {
 public:
  virtual void SetUp() {
    gsession.reset(QueryRunner::get_session(BASE_PATH,
                                            "gtest",
                                            "test!test!",
                                            "gtest_db",
                                            std::vector<LeafHostInfo>{},
                                            std::vector<LeafHostInfo>{},
                                            false,
                                            true,
                                            true));
  }
};

// don't use R"()" format; somehow it causes many blank lines
// to be output on console. how come?
const char* create_table_trips =
    "    CREATE TABLE trips ("
    "            medallion               TEXT ENCODING DICT,"
    "            hack_license            TEXT ENCODING DICT,"
    "            vendor_id               TEXT ENCODING DICT,"
    "            rate_code_id            SMALLINT,"
    "            store_and_fwd_flag      TEXT ENCODING DICT,"
    "            pickup_datetime         TIMESTAMP,"
    "            dropoff_datetime        TIMESTAMP,"
    "            passenger_count         SMALLINT,"
    "            trip_time_in_secs       INTEGER,"
    "            trip_distance           FLOAT,"
    "            pickup_longitude        DECIMAL(14,7),"
    "            pickup_latitude         DECIMAL(14,7),"
    "            dropoff_longitude       DOUBLE,"
    "            dropoff_latitude        DECIMAL(19,5),"
    "            deleted                 BOOLEAN"
    "            ) WITH (FRAGMENT_SIZE=50);";  // so 2 fragments here

void init_table_data(const string& table = "trips",
                     const string& create_table_cmd = create_table_trips,
                     const string& file = "trip_data_b.txt") {
  run_ddl_statement("drop table if exists " + table + ";");
  run_ddl_statement(create_table_cmd);
  if (file.size()) {
    import_table_file(table, file);
  }
}

class AlterColumnTest : public ::testing::Test {
 protected:
  virtual void SetUp() { ASSERT_NO_THROW(init_table_data();); }
  virtual void TearDown() { ASSERT_NO_THROW(run_ddl_statement("drop table trips;");); }
};

#define MT std::make_tuple
std::vector<std::tuple<std::string, std::string, std::string, std::string>> type_vals = {
    MT("text", "none", "'abc'", ""),
    MT("text", "dict(8)", "'ijk'", ""),
    MT("text", "dict(32)", "'xyz'", ""),
    MT("float", "", "1.25", ""),
    MT("double", "", "1.25", ""),
    MT("smallint", "", "123", ""),
    MT("integer", "", "123", ""),
    MT("bigint", "", "123", ""),
    MT("bigint encoding fixed(8)", "", "", ""),
    MT("bigint encoding fixed(16)", "", "", ""),
    MT("bigint encoding fixed(32)", "", "", ""),
    MT("decimal(8)", "", "123", ""),
    MT("decimal(8,2)", "", "1.23", ""),
    MT("date", "", "'2011-10-23'", ""),
    MT("time", "", "'10:23:45'", ""),
    MT("timestamp", "", "'2011-10-23 10:23:45'", ""),
    MT("POINT", "", "'POINT (1 2)'", "POINT (1 2)"),
    MT("LINESTRING", "", "'LINESTRING (1 1,2 2,3 3)'", "LINESTRING (1 1,2 2,3 3)"),
    MT("POLYGON",
       "",
       "'POLYGON((0 0,0 9,9 9,9 0),(1 1,2 2,3 3))'",
       "POLYGON ((9 0,9 9,0 9,0 0,9 0),(3 3,2 2,1 1,3 3))"),
    MT("MULTIPOLYGON",
       "",
       "'MULTIPOLYGON(((0 0,0 9,9 9,9 0),(1 1,2 2,3 3)))'",
       "MULTIPOLYGON (((9 0,9 9,0 9,0 0,9 0),(3 3,2 2,1 1,3 3)))"),
};

TEST_F(AlterColumnTest, Add_column_with_default) {
  int cid = 0;
  for (const auto& tv : type_vals) {
    EXPECT_TRUE(alter_common("trips",
                             "x" + std::to_string(++cid),
                             std::get<0>(tv),
                             std::get<1>(tv),
                             std::get<2>(tv),
                             std::get<3>(tv),
                             false));
  }
}

TEST_F(AlterColumnTest, Add_column_with_null) {
  int cid = 0;
  for (const auto& tv : type_vals) {
    if (std::get<3>(tv) == "") {
      EXPECT_TRUE(alter_common("trips",
                               "x" + std::to_string(++cid),
                               std::get<0>(tv),
                               std::get<1>(tv),
                               "",
                               "",
                               false));
    } else {
      EXPECT_TRUE(alter_common("trips",
                               "x" + std::to_string(++cid),
                               std::get<0>(tv),
                               std::get<1>(tv),
                               "",
                               std::get<3>(tv),
                               true));
    }
  }
}

TEST(AlterColumnTest2, Drop_after_fail_to_add) {
  EXPECT_NO_THROW(run_ddl_statement("drop table if exists t;"););
  EXPECT_NO_THROW(run_ddl_statement("create table t(c1 int);"););
  EXPECT_NO_THROW(run_query("insert into t values (10);"););
  EXPECT_THROW(
      run_ddl_statement("alter table t add column c2 TEXT NOT NULL ENCODING DICT;"),
      std::runtime_error);
  EXPECT_NO_THROW(run_ddl_statement("drop table t;"););
}

}  // namespace

int main(int argc, char** argv) {
  google::InitGoogleLogging(argv[0]);
  testing::InitGoogleTest(&argc, argv);
  ::testing::AddGlobalTestEnvironment(new SQLTestEnv);

  int err{0};
  try {
    err = RUN_ALL_TESTS();
  } catch (const std::exception& e) {
    LOG(ERROR) << e.what();
  }
  return err;
}

max_stars_repo_name: fenggeorgeyu/mapd-core

max_issues_repo_name: fenggeorgeyu/mapd-core

max_forks_repo_name: fenggeorgeyu/mapd-core


text:
//
//  Copyright (c) 2015, 2016 Terry Seyler
//
//  Distributed under the MIT License
//  See accompanying file LICENSE.md
//

#include <boost/bind.hpp>
#include <core/server/proto_tcp_text_session.hpp>

using namespace boost::asio::ip;

namespace proto_net
{
    namespace server
    {
        proto_tcp_text_session::proto_tcp_text_session(proto_net_service_ptr ps_service, proto_net_pipeline& ps_pipeline,
                                             size_t buffer_size /*= 4096*/)
                : proto_tcp_session(ps_service, ps_pipeline, buffer_size)
        { }

        proto_tcp_text_session::~ proto_tcp_text_session()
        {

        }

        void
        proto_tcp_text_session::ps_start(void)
        {
            ps_async_read();
        }

        void
        proto_tcp_text_session::ps_async_read(void)
        {
            stream_buffer_.prepare(buffer_size_);
            boost::asio::async_read_until(socket_, stream_buffer_, '\0',
                                          boost::bind(&proto_tcp_text_session::ps_handle_read, this,
                                                      boost::asio::placeholders::error,
                                                      boost::asio::placeholders::bytes_transferred));
        }

        void
        proto_tcp_text_session::ps_async_write(proto_net_out_data& data_out, bool no_write_complete /*= false*/)
        {
            if (data_out.data() && data_out.data_size() && data_out.data_type() == data_text) //guard against empty data getting put into the pipe in
            {
                // add pre-write pipe out call for the pipeline
                ps_pipeline_.ps_pipe_out(data_out); // (server) any changes to the out data just prior to being sent
                char *data = data_out.data();
                size_t data_size = data_out.data_size();
                if (data && data_size)
                {
                    boost::asio::async_write(socket_, boost::asio::buffer(data, data_size),
                                             boost::bind(&proto_tcp_session::ps_handle_write, this,
                                                         boost::asio::placeholders::error));
                }
                else
                    ps_async_read(); // just go back to reading
            }
            else
                ps_async_read(); // just go back to reading
        }

        void
        proto_tcp_text_session::ps_handle_read(const boost::system::error_code &error, size_t bytes_transferred)
        {
            if (session_read_error_)
                return;

            if (!error)
            {
                std::istream is(&stream_buffer_);
                is.get(buffer_, buffer_size_, '\0');

                // handle a ps_read here
                std::string request(buffer_);
                proto_net_data req_data(request);
                std::string response;
                proto_net_data res_data(response);
                if (req_data.data_size())
                {
                    ps_pipeline_.ps_pipe_in(req_data); // just prior to the pipeline execute the pipe in
                    ps_pipeline_.ps_pipeline(req_data, res_data); // all of the magic takes place inside the ps_pipeline
                }
                stream_buffer_.consume(bytes_transferred);
                ps_async_write(res_data); // set response data ptr or size to zero for a non-write
            }
            else
            {
                ps_close_session();
                session_read_error_ = true;
            }
        }

        void
        proto_tcp_text_session::ps_handle_write(const boost::system::error_code& error)
        {
            if (!error)
            {
                // handle a post write here
                ps_async_read(); // just go back to reading
            }
        }
    }

}

ext: cpp

max_stars_repo_name: tseyler/proto-server

max_issues_repo_name: tseyler/proto-server

max_forks_repo_name: tseyler/proto-server


text:
// Copyright 2012 Cloudera Inc.
//
// 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 "runtime/client-cache.h"

#include <sstream>
#include <server/TServer.h>
#include <protocol/TBinaryProtocol.h>
#include <transport/TSocket.h>
#include <transport/TTransportUtils.h>
#include <memory>

#include <boost/foreach.hpp>

#include "common/logging.h"
#include "util/thrift-util.h"
#include "gen-cpp/ImpalaInternalService.h"

using namespace std;
using namespace boost;
using namespace apache::thrift;
using namespace apache::thrift::server;
using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;

namespace impala {

BackendClientCache::BackendClientCache(int max_clients, int max_clients_per_backend)
  : max_clients_(max_clients),
    max_clients_per_backend_(max_clients_per_backend) {
}

Status BackendClientCache::GetClient(
    const pair<string, int>& hostport, ImpalaInternalServiceClient** client) {
  VLOG_RPC << "GetClient("
           << hostport.first << ":" << hostport.second << ")";
  lock_guard<mutex> l(lock_);
  ClientCache::iterator cache_entry = client_cache_.find(hostport);
  if (cache_entry == client_cache_.end()) {
    cache_entry =
        client_cache_.insert(make_pair(hostport, list<BackendClient*>())).first;
    DCHECK(cache_entry != client_cache_.end());
  }

  list<BackendClient*>& info_list = cache_entry->second;
  if (!info_list.empty()) {
    *client = info_list.front()->iface();
    VLOG_RPC << "GetClient(): adding client for "
             << info_list.front()->ipaddress()
             << ":" << info_list.front()->port();
    info_list.pop_front();
  } else {
    auto_ptr<BackendClient> info(
        new BackendClient(cache_entry->first.first, cache_entry->first.second));
    RETURN_IF_ERROR(info->Open());
    client_map_[info->iface()] = info.get();
    VLOG_CONNECTION << "GetClient(): creating client for "
                    << info->ipaddress() << ":" << info->port();
    *client = info.release()->iface();
  }

  return Status::OK;
}

Status BackendClientCache::ReopenClient(ImpalaInternalServiceClient* client) {
  lock_guard<mutex> l(lock_);
  ClientMap::iterator i = client_map_.find(client);
  DCHECK(i != client_map_.end());
  BackendClient* info = i->second;
  RETURN_IF_ERROR(info->Close());
  RETURN_IF_ERROR(info->Open());
  return Status::OK;
}

void BackendClientCache::ReleaseClient(ImpalaInternalServiceClient* client) {
  lock_guard<mutex> l(lock_);
  ClientMap::iterator i = client_map_.find(client);
  DCHECK(i != client_map_.end());
  BackendClient* info = i->second;
  VLOG_RPC << "releasing client for "
           << info->ipaddress() << ":" << info->port();
  ClientCache::iterator j =
      client_cache_.find(make_pair(info->ipaddress(), info->port()));
  DCHECK(j != client_cache_.end());
  j->second.push_back(info);
}

void BackendClientCache::CloseConnections(const pair<string, int>& hostport) {
  lock_guard<mutex> l(lock_);
  ClientCache::iterator cache_entry = client_cache_.find(hostport);
  if (cache_entry == client_cache_.end()) return;
  VLOG_RPC << "Invalidating all " << cache_entry->second.size() << " clients for: "
           << hostport.first << ":" << hostport.second;
  BOOST_FOREACH(BackendClient* client, cache_entry->second) {
    client->Close();
  }
}

string BackendClientCache::DebugString() {
  lock_guard<mutex> l(lock_);
  stringstream out;
  out << "BackendClientCache(#hosts=" << client_cache_.size()
      << " [";
  for (ClientCache::iterator i = client_cache_.begin(); i != client_cache_.end(); ++i) {
    if (i != client_cache_.begin()) out << " ";
    out << i->first.first << ":" << i->first.second << ":" << i->second.size();
  }
  out << "])";
  return out.str();
}

}

ext: cc

max_stars_repo_name: RalfBarkow/impala

max_issues_repo_name: RalfBarkow/impala

max_forks_repo_name: RalfBarkow/impala


text:
/**

Copyright (c) 2016, Hanselmann Fabian, Heller Florian, Heizmann Heinrich, Kübler Marcel, Mehlhaus Jonas, Meißner Pascal, Qattan Mohamad, Reckling Reno, Stroh Daniel
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#pragma once

#include <boost/shared_ptr.hpp>
#include <random>
#include "OptimizationAlgorithm.hpp"
#include "NeighbourhoodFunction.hpp"

namespace ISM {

template <class InstanceType>
class HillClimbingAlogrithm : public OptimizationAlgorithm<InstanceType>
{
	public:
		HillClimbingAlogrithm(NeighbourhoodFunctionPtr<InstanceType> neighbourhoodFunction,
			CostFunctionPtr<InstanceType> costFunction, bool randomWalkProbability = 0.0)
			: OptimizationAlgorithm<InstanceType>(neighbourhoodFunction, costFunction)
			, mRandomWalkProbability(randomWalkProbability)
		{}

		InstanceType optimize(InstanceType startInstance)
		{
			InstanceType selectedInstance = startInstance;

			double lowestCost = this->mCostFunction->calculateCost(selectedInstance);
			bool keepOptimizing = true;

			while (keepOptimizing)
			{
				keepOptimizing = false;

				this->mNeighbourhoodFunction->setReferenceInstance(selectedInstance);

				if (this->mNeighbourhoodFunction->hasNextNeighbour())
				{
					//Check if random walk shuld be performed
					if (mDistribution(mGenerator) < mRandomWalkProbability)
					{
							selectedInstance = this->mNeighbourhoodFunction->getNextNeighbour();
							lowestCost = this->mCostFunction->calculateCost(selectedInstance);
							keepOptimizing = true;
					}
					else
					{
						do
						{
							InstanceType nextInstance = this->mNeighbourhoodFunction->getNextNeighbour();
							double nextInstanceCost = this->mCostFunction->calculateCost(nextInstance);

							if (nextInstanceCost < lowestCost)
							{
								selectedInstance = nextInstance;
								lowestCost = nextInstanceCost;
								keepOptimizing = true;
							}
						} while (this->mNeighbourhoodFunction->hasNextNeighbour());
					}
				}
				else
				{
					//The selected instance has no neighbours, we can't continue the optimization
					return selectedInstance;
				}

			}

			return selectedInstance;
		}

	  private:
		bool mRandomWalkProbability;
		std::default_random_engine mGenerator;
		std::uniform_real_distribution<double> mDistribution = std::uniform_real_distribution<double>(0.0, 1.0);
};

template<class InstanceType>
using HillClimbingAlogrithmPtr = boost::shared_ptr<HillClimbingAlogrithm<InstanceType>>;

}

ext: hpp


text:
// Copyright David Abrahams, Daniel Wallin 2003.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PARAMETER_AUX_PACK_DEDUCED_ITEM_HPP
#define BOOST_PARAMETER_AUX_PACK_DEDUCED_ITEM_HPP

#include <boost/parameter/aux_/void.hpp>

namespace boost { namespace parameter { namespace aux {

    // A typelist that stored deduced parameter specs.
    template <
        typename ParameterSpec
      , typename Tail = ::boost::parameter::void_
    >
    struct deduced_item
    {
        typedef ParameterSpec spec;
        typedef Tail tail;
    };

    // Evaluate Tail and construct deduced_item list.
    template <typename Spec, typename Tail>
    struct make_deduced_item
    {
        typedef ::boost::parameter::aux
        ::deduced_item<Spec,typename Tail::type> type;
    };
}}} // namespace boost::parameter::aux

#endif  // include guard


text:
#include <iostream>

using std::cout;
using std::endl;

#include "viennagrid/forwards.hpp"

#include "viennagrid/storage/view.hpp"
#include "viennagrid/storage/container_collection.hpp"
#include "viennagrid/storage/inserter.hpp"
#include "viennagrid/storage/id_generator.hpp"
#include "viennagrid/storage/hidden_key_map.hpp"
#include "viennagrid/storage/range.hpp"

#include "viennagrid/topology/vertex.hpp"
#include "viennagrid/topology/line.hpp"
#include "viennagrid/topology/simplex.hpp"

#include "viennagrid/element/element_key.hpp"
#include "viennagrid/element/element_orientation.hpp"
#include "viennagrid/element/element_view.hpp"
#include "viennagrid/point.hpp"

#include "viennagrid/config/element_config.hpp"
#include "viennagrid/config/mesh_config.hpp"

#include "viennagrid/mesh/mesh.hpp"
#include "viennagrid/mesh/element_creation.hpp"

#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
namespace ublas = boost::numeric::ublas;

// struct test_tag {};
// VIENNADATA_ENABLE_TYPE_BASED_KEY_DISPATCH(test_tag)

typedef ublas::vector<double> vector_type;

class my_mesh_config
{
  private:
    //typedef viennagrid::storage::pointer_handle_tag handle_tag;
    //typedef viennagrid::storage::iterator_handle_tag handle_tag;
    typedef viennagrid::storage::id_handle_tag          handle_tag;

  public:

    typedef viennagrid::config::result_of::full_mesh_config< viennagrid::tetrahedron_tag, vector_type, handle_tag >::type     type;
};

int main()
{
    //
    // typedefing and setting up the geometric mesh
    //

    typedef viennagrid::mesh<my_mesh_config> mesh_type;
    mesh_type mesh;

    //
    // typedefs for the element types
    //

    typedef viennagrid::result_of::element<mesh_type, viennagrid::vertex_tag>::type vertex_type;
    typedef viennagrid::result_of::handle<mesh_type, viennagrid::vertex_tag>::type vertex_handle_type;

    typedef viennagrid::result_of::element<mesh_type, viennagrid::line_tag>::type line_type;
    typedef viennagrid::result_of::element<mesh_type, viennagrid::triangle_tag>::type triangle_type;

    typedef viennagrid::result_of::element<mesh_type, viennagrid::tetrahedron_tag>::type tetrahedron_type;
    typedef viennagrid::result_of::handle<mesh_type, viennagrid::tetrahedron_tag>::type tetrahedron_handle_type;

    //
    // Adding a tetrahedron
    //

    // creates four vertices within the mesh, vh is short vor vertex handle
    // make_element is responsible for resizing all meta-info container which are associated with vertex_type
    vertex_handle_type vh0 = viennagrid::make_vertex( mesh );
    vertex_handle_type vh1 = viennagrid::make_vertex( mesh );
    vertex_handle_type vh2 = viennagrid::make_vertex( mesh );
    vertex_handle_type vh3 = viennagrid::make_vertex( mesh );

//     viennagrid::tagging::tag<test_tag>( viennagrid::dereference_handle(mesh, vh1) );
//     viennagrid::tagging::tag<test_tag>( viennagrid::dereference_handle(mesh, vh2) );

    // create geometric information for the vertices
    vector_type p0(3);
    p0[0] = 0.0; p0[1] = 0.0; p0[2] = 0.0;
    vector_type p1(3);
    p1[0] = 1.0; p1[1] = 0.0; p1[2] = 0.0;
    vector_type p2(3);
    p2[0] = 0.0; p2[1] = 1.0; p2[2] = 0.0;
    vector_type p3(3);
    p3[0] = 0.0; p3[1] = 0.0; p3[2] = 1.0;

    // set the geometric information for the vertices
    // is equivalent to viennagrid::look_up<vector_type>(mesh, vhX)
    viennagrid::point(mesh, vh0) = p0;
    viennagrid::point(mesh, vh1) = p1;
    viennagrid::point(mesh, vh2) = p2;
    viennagrid::point(mesh, vh3) = p3;

    // creates a handle buffer for the vertex handles of the tetdrahedron
    std::vector<vertex_handle_type> handles(4);
    handles[0] = vh0; handles[1] = vh1; handles[2] = vh2; handles[3] = vh3;

    // creates the tetrahedron within the mesh, all boundary cell generation is done here implicit
    tetrahedron_handle_type tet = viennagrid::make_element<tetrahedron_type>( mesh, handles.begin(), handles.end() );
    std::cout << tet << std::endl;

    // set a double value to a tetdrahedron

    const mesh_type & test = mesh;

    typedef viennagrid::result_of::const_element_range<mesh_type, viennagrid::vertex_tag>::type const_vertex_range;
    typedef viennagrid::result_of::iterator<const_vertex_range>::type const_vertex_iterator;

    cout << "All vertices of the mesh using point_range" << endl;
    const_vertex_range r = viennagrid::elements<viennagrid::vertex_tag>(test);
    for (const_vertex_iterator i = r.begin(); i != r.end(); ++i)
        cout << *i << " " << viennagrid::point(test, *i) << endl;
    cout << endl;

//     cout << "All points of the mesh using point_range" << endl;
//     viennagrid::result_of::metainfo_range<mesh_type, vertex_type, vector_type>::type point_range = viennagrid::metainfo_range<vertex_type, vector_type>(mesh);
//     for (viennagrid::result_of::metainfo_range<mesh_type, vertex_type, vector_type>::type::iterator it = point_range.begin(); it != point_range.end(); ++it)
//         cout << (*it) << endl;
//     cout << endl;
//
//
//
//     cout << "All points of the mesh using point_range and std::copy" << endl;
//     std::copy( point_range.begin(), point_range.end(), std::ostream_iterator<vector_type>(std::cout, "\n") );
//     cout << endl;

//     cout << "All points of the mesh using point_range using const mesh" << endl;
//     viennagrid::result_of::const_metainfo_range<mesh_type, vertex_type, vector_type>::type const_point_range =
//             viennagrid::metainfo_range<vertex_type, vector_type>( test );
//
//     for (viennagrid::result_of::const_metainfo_range<mesh_type, vertex_type, vector_type>::type::iterator it = const_point_range.begin(); it != const_point_range.end(); ++it)
//         cout << it.element() << " " << it.metainfo() << endl;
//     cout << endl;

//     cout << "All tagged points of the mesh using point_range and std::copy" << endl;
//     typedef viennagrid::result_of::element_view<mesh_type, vertex_type>::type VertexView;
//     VertexView view = viennagrid::tagged_elements<vertex_type>(mesh, test_tag());
//     viennagrid::result_of::metainfo_view<VertexView, viennagrid::result_of::metainfo_container<mesh_type, vertex_type, vector_type>::type>::type
//         point_range2 = viennagrid::metainfo_view<vector_type>( view, mesh );
//     std::copy( point_range2.begin(), point_range2.end(), std::ostream_iterator< vector_type >(std::cout, "\n") );

    return 0;
}

max_stars_repo_name: viennagrid/viennagrid-dev

max_issues_repo_name: viennagrid/viennagrid-dev

max_forks_repo_name: viennagrid/viennagrid-dev


text:
//
// Copyright (c) 2018 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_CORE_IMPL_TIMEOUT_SERVICE_HPP
#define BOOST_BEAST_CORE_IMPL_TIMEOUT_SERVICE_HPP

#include <boost/beast/experimental/core/detail/timeout_service.hpp>

namespace boost {
namespace beast {

inline
void
set_timeout_service_options(
    boost::asio::io_context& ioc,
    std::chrono::seconds interval)
{
    boost::asio::use_service<
        detail::timeout_service>(ioc).set_option(interval);
}

} // beast
} // boost

#endif

ext: ipp


text:
// Copyright 2012 Cloudera, Inc.
//
// 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 <boost/thread/locks.hpp>
#include <string>

#include "kudu/gutil/stringprintf.h"
#include "kudu/util/oid_generator.h"

namespace kudu {

string ObjectIdGenerator::Next() {
  boost::lock_guard<LockType> l(oid_lock_);
  boost::uuids::uuid oid = oid_generator_();
  const uint8_t *uuid = oid.data;
  return StringPrintf("%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
               uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
               uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
}

} // namespace kudu

max_stars_repo_name: kv-zuiwanyuan/kudu

max_issues_repo_name: kv-zuiwanyuan/kudu

max_forks_repo_name: kv-zuiwanyuan/kudu


text:
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>

#include "util.h"

BOOST_AUTO_TEST_SUITE(getarg_tests)

static void
ResetArgs(const std::string& strArg)
{
    std::vector<std::string> vecArg;
    boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on);

    // Insert dummy executable name:
    vecArg.insert(vecArg.begin(), "testbitcoin");

    // Convert to char*:
    std::vector<const char*> vecChar;
    BOOST_FOREACH(std::string& s, vecArg)
        vecChar.push_back(s.c_str());

    ParseParameters(vecChar.size(), &vecChar[0]);
}

BOOST_AUTO_TEST_CASE(boolarg)
{
    ResetArgs("-exc");
    BOOST_CHECK(GetBoolArg("-exc"));
    BOOST_CHECK(GetBoolArg("-exc", false));
    BOOST_CHECK(GetBoolArg("-exc", true));

    BOOST_CHECK(!GetBoolArg("-fo"));
    BOOST_CHECK(!GetBoolArg("-fo", false));
    BOOST_CHECK(GetBoolArg("-fo", true));

    BOOST_CHECK(!GetBoolArg("-exco"));
    BOOST_CHECK(!GetBoolArg("-exco", false));
    BOOST_CHECK(GetBoolArg("-exco", true));

    ResetArgs("-exc=0");
    BOOST_CHECK(!GetBoolArg("-exc"));
    BOOST_CHECK(!GetBoolArg("-exc", false));
    BOOST_CHECK(!GetBoolArg("-exc", true));

    ResetArgs("-exc=1");
    BOOST_CHECK(GetBoolArg("-exc"));
    BOOST_CHECK(GetBoolArg("-exc", false));
    BOOST_CHECK(GetBoolArg("-exc", true));

    // New 0.6 feature: auto-map -nosomething to !-something:
    ResetArgs("-noexc");
    BOOST_CHECK(!GetBoolArg("-exc"));
    BOOST_CHECK(!GetBoolArg("-exc", false));
    BOOST_CHECK(!GetBoolArg("-exc", true));

    ResetArgs("-noexc=1");
    BOOST_CHECK(!GetBoolArg("-exc"));
    BOOST_CHECK(!GetBoolArg("-exc", false));
    BOOST_CHECK(!GetBoolArg("-exc", true));

    ResetArgs("-exc -noexc");  // -exc should win
    BOOST_CHECK(GetBoolArg("-exc"));
    BOOST_CHECK(GetBoolArg("-exc", false));
    BOOST_CHECK(GetBoolArg("-exc", true));

    ResetArgs("-exc=1 -noexc=1");  // -exc should win
    BOOST_CHECK(GetBoolArg("-exc"));
    BOOST_CHECK(GetBoolArg("-exc", false));
    BOOST_CHECK(GetBoolArg("-exc", true));

    ResetArgs("-exc=0 -noexc=0");  // -exc should win
    BOOST_CHECK(!GetBoolArg("-exc"));
    BOOST_CHECK(!GetBoolArg("-exc", false));
    BOOST_CHECK(!GetBoolArg("-exc", true));

    // New 0.6 feature: treat -- same as -:
    ResetArgs("--exc=1");
    BOOST_CHECK(GetBoolArg("-exc"));
    BOOST_CHECK(GetBoolArg("-exc", false));
    BOOST_CHECK(GetBoolArg("-exc", true));

    ResetArgs("--noexc=1");
    BOOST_CHECK(!GetBoolArg("-exc"));
    BOOST_CHECK(!GetBoolArg("-exc", false));
    BOOST_CHECK(!GetBoolArg("-exc", true));

}

BOOST_AUTO_TEST_CASE(stringarg)
{
    ResetArgs("");
    BOOST_CHECK_EQUAL(GetArg("-exc", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-exc", "eleven"), "eleven");

    ResetArgs("-exc -bar");
    BOOST_CHECK_EQUAL(GetArg("-exc", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-exc", "eleven"), "");

    ResetArgs("-exc=");
    BOOST_CHECK_EQUAL(GetArg("-exc", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-exc", "eleven"), "");

    ResetArgs("-exc=11");
    BOOST_CHECK_EQUAL(GetArg("-exc", ""), "11");
    BOOST_CHECK_EQUAL(GetArg("-exc", "eleven"), "11");

    ResetArgs("-exc=eleven");
    BOOST_CHECK_EQUAL(GetArg("-exc", ""), "eleven");
    BOOST_CHECK_EQUAL(GetArg("-exc", "eleven"), "eleven");

}

BOOST_AUTO_TEST_CASE(intarg)
{
    ResetArgs("");
    BOOST_CHECK_EQUAL(GetArg("-exc", 11), 11);
    BOOST_CHECK_EQUAL(GetArg("-exc", 0), 0);

    ResetArgs("-exc -bar");
    BOOST_CHECK_EQUAL(GetArg("-exc", 11), 0);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);

    ResetArgs("-exc=11 -bar=12");
    BOOST_CHECK_EQUAL(GetArg("-exc", 0), 11);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 12);

    ResetArgs("-exc=NaN -bar=NotANumber");
    BOOST_CHECK_EQUAL(GetArg("-exc", 1), 0);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);
}

BOOST_AUTO_TEST_CASE(doubledash)
{
    ResetArgs("--exc");
    BOOST_CHECK_EQUAL(GetBoolArg("-exc"), true);

    ResetArgs("--exc=verbose --bar=1");
    BOOST_CHECK_EQUAL(GetArg("-exc", ""), "verbose");
    BOOST_CHECK_EQUAL(GetArg("-bar", 0), 1);
}

BOOST_AUTO_TEST_CASE(boolargno)
{
    ResetArgs("-noexc");
    BOOST_CHECK(!GetBoolArg("-exc"));
    BOOST_CHECK(!GetBoolArg("-exc", true));
    BOOST_CHECK(!GetBoolArg("-exc", false));

    ResetArgs("-noexc=1");
    BOOST_CHECK(!GetBoolArg("-exc"));
    BOOST_CHECK(!GetBoolArg("-exc", true));
    BOOST_CHECK(!GetBoolArg("-exc", false));

    ResetArgs("-noexc=0");
    BOOST_CHECK(GetBoolArg("-exc"));
    BOOST_CHECK(GetBoolArg("-exc", true));
    BOOST_CHECK(GetBoolArg("-exc", false));

    ResetArgs("-exc --noexc");
    BOOST_CHECK(GetBoolArg("-exc"));

    ResetArgs("-noexc -exc"); // exc always wins:
    BOOST_CHECK(GetBoolArg("-exc"));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: CaptChadd/Extremecoin

max_issues_repo_name: CaptChadd/Extremecoin

max_forks_repo_name: CaptChadd/Extremecoin


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifdef _MSC_VER
#pragma warning (disable : 4512)
#endif

#include <boost/container/allocator.hpp>

#define BOOST_CONTAINER_VECTOR_ALLOC_STATS

#include <boost/container/vector.hpp>

#undef BOOST_CONTAINER_VECTOR_ALLOC_STATS

#include <memory>    //std::allocator
#include <iostream>  //std::cout, std::endl
#include <cassert>   //assert

#include <boost/timer/timer.hpp>
using boost::timer::cpu_timer;
using boost::timer::cpu_times;
using boost::timer::nanosecond_type;

namespace bc = boost::container;

typedef std::allocator<int>   StdAllocator;
typedef bc::allocator<int, 2> AllocatorPlusV2;
typedef bc::allocator<int, 1> AllocatorPlusV1;

template<class Allocator> struct get_allocator_name;

template<> struct get_allocator_name<StdAllocator>
{  static const char *get() {  return "StdAllocator";  } };

template<> struct get_allocator_name<AllocatorPlusV2>
{  static const char *get() {  return "AllocatorPlusV2";  } };

template<> struct get_allocator_name<AllocatorPlusV1>
{  static const char *get() {  return "AllocatorPlusV1";  } };

class MyInt
{
   std::size_t int_; //Use a type that will grow on 64 bit machines

   public:
   MyInt(int i = 0) : int_(i){}

   MyInt(const MyInt &other)
      :  int_(other.int_)
   {}

   MyInt & operator=(const MyInt &other)
   {
      int_ = other.int_;
      return *this;
   }
};

void print_header()
{
   std::cout   << "Allocator" << ";" << "Iterations" << ";" << "Size" << ";"
               << "num_shrink" << ";" << "shrink_to_fit(ns)" << std::endl;
}

template<class Allocator>
void vector_test_template(unsigned int num_iterations, unsigned int num_elements, bool csv_output)
{
   typedef typename Allocator::template rebind<MyInt>::other IntAllocator;

   unsigned int capacity = 0;
   const std::size_t Step = 5;
   unsigned int num_shrink = 0;
   (void)capacity;

   cpu_timer timer;
   timer.resume();

   #ifndef NDEBUG
   typedef bc::dtl::integral_constant
      <unsigned, bc::dtl::version<Allocator>::value> alloc_version;
   #endif

   for(unsigned int r = 0; r != num_iterations; ++r){
      bc::vector<MyInt, IntAllocator> v(num_elements);
      v.reset_alloc_stats();
      num_shrink = 0;
      for(unsigned int e = num_elements; e != 0; e -= Step){
         v.erase(v.end() - Step, v.end());
         v.shrink_to_fit();
         assert( (alloc_version::value != 2) || (e == Step) || (v.num_shrink > num_shrink) );
         num_shrink = v.num_shrink;
      }
      assert(v.empty());
      assert(0 == v.capacity());
   }

   timer.stop();
   nanosecond_type nseconds = timer.elapsed().wall;

   if(csv_output){
      std::cout   << get_allocator_name<Allocator>::get()
                  << ";"
                  << num_iterations
                  << ";"
                  << num_elements
                  << ";"
                  << num_shrink
                  << ";"
                  << float(nseconds)/(num_iterations*num_elements)
                  << std::endl;
   }
   else{
      std::cout   << std::endl
                  << "Allocator: " << get_allocator_name<Allocator>::get()
                  << std::endl
                  << "  num_shrink:         " << num_shrink
                  << std::endl
                  << "  shrink_to_fit ns:   "
                  << float(nseconds)/(num_iterations*num_elements)
                  << std::endl << std::endl;
   }
   bc::dlmalloc_trim(0);
}

int main(int argc, const char *argv[])
{
   //#define SINGLE_TEST
   #define SIMPLE_IT
   #ifdef SINGLE_TEST
      #ifdef NDEBUG
      unsigned int numit [] =  { 10 };
      #else
      unsigned int numit [] =  { 50 };
      unsigned int numele[] = { 2000 };
      #endif
   #elif defined SIMPLE_IT
      unsigned int numit [] =  { 3 };
      unsigned int numele[] = { 2000 };
   #else
      #ifdef NDEBUG
      unsigned int numit [] =  { 100,   1000, 10000 };
      #else
      unsigned int numit [] =  { 10,   100, 1000 };
      #endif
      unsigned int numele [] = { 10000, 2000, 500   };
   #endif

   bool csv_output = argc == 2 && (strcmp(argv[1], "--csv-output") == 0);

   if(csv_output){
      print_header();
      for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){
         vector_test_template<StdAllocator>(numit[i], numele[i], csv_output);
      }
      for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){
         vector_test_template<AllocatorPlusV1>(numit[i], numele[i], csv_output);
      }
      for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){
         vector_test_template<AllocatorPlusV2>(numit[i], numele[i], csv_output);
      }
   }
   else{
      for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){
         std::cout   << "\n    -----------------------------------    \n"
                     <<   "  Iterations/Elements:         " << numit[i] << "/" << numele[i]
                     << "\n    -----------------------------------    \n";
         vector_test_template<StdAllocator>(numit[i], numele[i], csv_output);
         vector_test_template<AllocatorPlusV1>(numit[i], numele[i], csv_output);
         vector_test_template<AllocatorPlusV2>(numit[i], numele[i], csv_output);
      }
   }
   return 0;
}

max_stars_repo_name: cpp-pm/boost

max_issues_repo_name: cpp-pm/boost

max_forks_repo_name: cpp-pm/boost


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://kylelutz.github.com/compute for more information.
//---------------------------------------------------------------------------//

#include <iostream>
#include <algorithm>

#include <QtGlobal>
#if QT_VERSION >= 0x050000
#include <QtWidgets>
#else
#include <QtGui>
#endif
#include <QtOpenGL>

#ifndef Q_MOC_RUN
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>
#include <boost/compute/utility/dim.hpp>
#include <boost/compute/utility/source.hpp>
#endif // Q_MOC_RUN

namespace compute = boost::compute;

// opencl source code
const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
    // map value to color
    float4 color(uint i)
    {
        uchar c = i;
        uchar x = 35;
        uchar y = 25;
        uchar z = 15;
        uchar max = 255;

        if(i == 256)
            return (float4)(0, 0, 0, 255);
        else
            return (float4)(max-x*i, max-y*i, max-z*i, max) / 255.f;
    }

    __kernel void mandelbrot(__write_only image2d_t image)
    {
        const uint x_coord = get_global_id(0);
        const uint y_coord = get_global_id(1);
        const uint width = get_global_size(0);
        const uint height = get_global_size(1);

        float x_origin = ((float) x_coord / width) * 3.25f - 2.0f;
        float y_origin = ((float) y_coord / height) * 2.5f - 1.25f;

        float x = 0.0f;
        float y = 0.0f;

        uint i = 0;
        while(x*x + y*y <= 4.f && i < 256){
            float tmp = x*x - y*y + x_origin;
            y = 2*x*y + y_origin;
            x = tmp;
            i++;
        }

        int2 coord = { x_coord, y_coord };
        write_imagef(image, coord, color(i));
    };
);

class MandelbrotWidget : public QGLWidget
{
    Q_OBJECT

public:
    MandelbrotWidget(QWidget *parent = 0);
    ~MandelbrotWidget();

    void initializeGL();
    void resizeGL(int width, int height);
    void paintGL();
    void keyPressEvent(QKeyEvent* event);

private:
    compute::context context_;
    compute::command_queue queue_;
    compute::program program_;
    GLuint gl_texture_;
    compute::opengl_texture cl_texture_;
};

MandelbrotWidget::MandelbrotWidget(QWidget *parent)
    : QGLWidget(parent)
{
    gl_texture_ = 0;
}

MandelbrotWidget::~MandelbrotWidget()
{
}

void MandelbrotWidget::initializeGL()
{
    // setup opengl
    glDisable(GL_LIGHTING);

    // create the OpenGL/OpenCL shared context
    context_ = compute::opengl_create_shared_context();

    // get gpu device
    compute::device gpu = context_.get_device();
    std::cout << "device: " << gpu.name() << std::endl;

    // setup command queue
    queue_ = compute::command_queue(context_, gpu);

    // build mandelbrot program
    program_ = compute::program::create_with_source(source, context_);
    program_.build();
}

void MandelbrotWidget::resizeGL(int width, int height)
{
    // resize viewport
    glViewport(0, 0, width, height);

    // delete old texture
    if(gl_texture_){
      glDeleteTextures(1, &gl_texture_);
      gl_texture_ = 0;
    }

    // generate new texture
    glGenTextures(1, &gl_texture_);
    glBindTexture(GL_TEXTURE_2D, gl_texture_);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(
        GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0
    );

    // create opencl object for the texture
    cl_texture_ = compute::opengl_texture(
        context_, GL_TEXTURE_2D, 0, gl_texture_, CL_MEM_WRITE_ONLY
    );
}

void MandelbrotWidget::paintGL()
{
    using compute::dim;

    float w = width();
    float h = height();

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0, w, 0.0, h, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // setup the mandelbrot kernel
    compute::kernel kernel(program_, "mandelbrot");
    kernel.set_arg(0, cl_texture_);

    // acquire the opengl texture so it can be used in opencl
    compute::opengl_enqueue_acquire_gl_objects(1, &cl_texture_.get(), queue_);

    // execute the mandelbrot kernel
    queue_.enqueue_nd_range_kernel(
        kernel, dim(0, 0), dim(width(), height()), dim(1, 1)
    );

    // release the opengl texture so it can be used by opengl
    compute::opengl_enqueue_release_gl_objects(1, &cl_texture_.get(), queue_);

    // ensure opencl is finished before rendering in opengl
    queue_.finish();

    // draw a single quad with the mandelbrot image texture
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, gl_texture_);

    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(0, 0);
    glTexCoord2f(0, 1); glVertex2f(0, h);
    glTexCoord2f(1, 1); glVertex2f(w, h);
    glTexCoord2f(1, 0); glVertex2f(w, 0);
    glEnd();
}

void MandelbrotWidget::keyPressEvent(QKeyEvent* event)
{
    if(event->key() == Qt::Key_Escape) {
        this->close();
    }
}

// the mandelbrot example shows how to create a mandelbrot image in
// OpenCL and render the image as a texture in OpenGL
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    MandelbrotWidget widget;
    widget.show();

    return app.exec();
}

#include "mandelbrot.moc"

max_stars_repo_name: bastiankoe/compute

max_issues_repo_name: bastiankoe/compute

max_forks_repo_name: bastiankoe/compute


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

#include "graph.hh"
#include "graph_filtering.hh"
#include "graph_properties.hh"

#include "graph_search.hh"

#include <boost/python.hpp>

using namespace std;
using namespace boost;
using namespace graph_tool;

// find vertices which match a certain (inclusive) property range
python::list
find_vertex_range(python::object g, GraphInterface::deg_t deg,
                  python::tuple range)
{
    GraphInterface& gi = python::extract<GraphInterface&>(g().attr("_Graph__graph"));
    python::list ret;
    run_action<>()(gi, std::bind(find_vertices(), placeholders::_1, std::ref(g),
                                 placeholders::_2, std::ref(range),
                                 std::ref(ret)),
                   all_selectors())(degree_selector(deg));
    return ret;
}

// find edges which match a certain (inclusive) property range
python::list
find_edge_range(python::object g, boost::any eprop,
                python::tuple range)
{
    GraphInterface& gi = python::extract<GraphInterface&>(g().attr("_Graph__graph"));
    python::list ret;
    typedef property_map_types::apply<value_types,
                                      GraphInterface::edge_index_map_t,
                                      mpl::bool_<true> >::type
        all_edge_props;

    GraphInterface::edge_index_map_t eindex =
        any_cast<GraphInterface::edge_index_map_t>(gi.GetEdgeIndex());
    run_action<>()(gi, std::bind(find_edges(), placeholders::_1, std::ref(g), eindex,
                                 placeholders::_2, std::ref(range), std::ref(ret)),
                   all_edge_props())(eprop);
    return ret;
}

using namespace boost::python;

void export_search()
{
    def("find_vertex_range", &find_vertex_range);
    def("find_edge_range", &find_edge_range);
}

max_stars_repo_name: johankaito/fufuka

max_issues_repo_name: johankaito/fufuka

max_forks_repo_name: johankaito/fufuka


text:
//
// Copyright (c) 2018-2019 Christian Mazakas (christian dot mazakas at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/LeonineKing1199/foxy
//

#include <foxy/listener.hpp>
#include <foxy/client_session.hpp>
#include <foxy/server_session.hpp>
#include <foxy/utility.hpp>

#include <foxy/test/helpers/ssl_ctx.hpp>

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

#include <boost/asio/coroutine.hpp>

#include <boost/asio/executor.hpp>
#include <boost/asio/post.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/strand.hpp>

#include <boost/system/error_code.hpp>

#include <boost/beast/http.hpp>

#include <thread>
#include <atomic>
#include <memory>
#include <iostream>
#include <cassert>

namespace asio = boost::asio;
namespace http = boost::beast::http;
namespace ssl  = boost::asio::ssl;

using boost::asio::ip::tcp;

static constexpr int num_client_requests = 10;
static constexpr int num_clients         = 128;

#include <boost/asio/yield.hpp>

struct request_handler : asio::coroutine
{
  struct frame
  {
    http::request<http::empty_body>   request;
    http::response<http::string_body> response;
  };

  foxy::server_session&  server;
  std::unique_ptr<frame> frame_ptr;

  request_handler(foxy::server_session& server_)
    : server(server_)
    , frame_ptr(std::make_unique<frame>())
  {
  }

  template <class Self>
  auto operator()(Self&                     self,
                  boost::system::error_code ec                = {},
                  std::size_t const         bytes_transferred = 0) -> void
  {
    assert(server.stream.is_ssl());

    auto& f = *frame_ptr;
    reenter(*this)
    {
      while (true) {
        f.response = {};
        f.request  = {};

        yield server.async_read(f.request, std::move(self));
        if (ec) { break; }

        f.response.result(http::status::ok);
        f.response.version(11);
        f.response.body() = "
Hello, world!
";
        f.response.prepare_payload();

        yield server.async_write(f.response, std::move(self));
        if (ec) { break; }

        if (!f.request.keep_alive()) { break; }
      }

      return self.complete({}, 0);
    }
  }
};

struct client_op : asio::coroutine
{
  using executor_type = asio::strand<asio::executor>;

  struct frame
  {
    foxy::client_session              client;
    http::request<http::empty_body>   request;
    http::response<http::string_body> response;

    int       req_count    = 0;
    int const max_requests = num_client_requests;

    frame(asio::executor executor, ssl::context& ctx)
      : client(executor, foxy::session_opts{ctx, std::chrono::seconds(30), true})
    {
    }
  };

  std::unique_ptr<frame> frame_ptr;
  executor_type          strand;
  std::atomic_int&       req_count;
  foxy::listener&        l;

  client_op(asio::executor   executor,
            std::atomic_int& req_count_,
            foxy::listener&  l_,
            ssl::context&    ctx)
    : frame_ptr(std::make_unique<frame>(executor, ctx))
    , strand(asio::make_strand(executor))
    , req_count(req_count_)
    , l(l_)
  {
  }

  auto
  operator()(boost::system::error_code ec, tcp::endpoint) -> void
  {
    (*this)(ec);
  }

  auto operator()(boost::system::error_code ec = {}) -> void
  {
    assert(strand.running_in_this_thread());

    auto& f = *frame_ptr;
    reenter(*this)
    {
      assert(f.client.stream.is_ssl());

      yield f.client.async_connect("127.0.0.1", "1337", std::move(*this));
      if (ec) { break; }

      for (f.req_count = 0; f.req_count < f.max_requests; ++f.req_count) {
        f.request  = {};
        f.response = {};

        f.request.method(http::verb::get);
        f.request.target("/");
        f.request.version(11);
        f.request.keep_alive(f.req_count < (f.max_requests - 1));

        yield f.client.async_request(f.request, f.response, std::move(*this));
        if (ec) { break; }

        {
          auto const curr_req_count = ++req_count;
          if (curr_req_count == num_clients * num_client_requests) { l.shutdown(); }
        }
      }

      yield f.client.async_shutdown(std::move(*this));
    }
  }

  auto
  get_executor() const noexcept -> executor_type
  {
    return strand;
  }
};

int
main()
{
  auto server_ctx = foxy::test::make_server_ssl_ctx();
  auto client_ctx = foxy::test::make_client_ssl_ctx();

  auto const num_client_threads = 4;
  auto const num_server_threads = 4;

  // For the sake of performance, we give our client and server separate threadpools
  //
  asio::io_context client_io{num_client_threads};
  asio::io_context server_io{num_server_threads};

  std::atomic_int req_count{0};

  auto s = foxy::listener(
    server_io.get_executor(),
    tcp::endpoint(asio::ip::make_address("127.0.0.1"), static_cast<unsigned short>(1337)),
    std::move(server_ctx));

  s.async_accept([](auto& server_session) { return request_handler(server_session); });

  for (auto idx = 0; idx < num_clients; ++idx) {
    asio::post(client_op(client_io.get_executor(), req_count, s, client_ctx));
  }

  auto threads = std::vector<std::thread>();
  threads.reserve(num_client_threads + num_server_threads);

  for (auto idx = 0; idx < num_client_threads; ++idx) {
    threads.emplace_back([&] { client_io.run(); });
  }

  for (auto idx = num_client_threads; idx < (num_client_threads + num_server_threads); ++idx) {
    threads.emplace_back([&] { server_io.run(); });
  }

  for (auto& thread : threads) { thread.join(); }

  return 0;
}

max_stars_repo_name: Olipro/foxy

max_issues_repo_name: Olipro/foxy

max_forks_repo_name: Olipro/foxy


text:
#include "PressureProjection.h"

#include <Eigen/Core>
#include <iostream>

#include "LevelSet.h"
#include "tbb/tbb.h"

namespace FluidSim3D
{
PressureProjection::PressureProjection(const LevelSet& surface,
                                        const VectorGrid<double>& cutCellWeights,
                                        const VectorGrid<double>& ghostFluidWeights,
                                        const VectorGrid<double>& solidVelocity)
    : mySurface(surface),
      myCutCellWeights(cutCellWeights),
      myGhostFluidWeights(ghostFluidWeights),
      mySolidVelocity(solidVelocity),
      myUseInitialGuessPressure(false),
      myInitialGuessPressure(nullptr)
{
    // For efficiency sake, this should only take in velocity on a staggered grid
    // that matches the center sampled surface and collision

    assert(solidVelocity.sampleType() == VectorGridSettings::SampleType::STAGGERED);

#if !defined(NDEBUG)
    for (int axis : {0, 1, 2})
    {
        Vec3i faceCount = solidVelocity.size(axis);

        Vec3i cellSize = faceCount;
        --cellSize[axis];

        assert(cellSize == surface.size());
    }
#endif

    assert(solidVelocity.isGridMatched(cutCellWeights) && solidVelocity.isGridMatched(ghostFluidWeights));

    myPressure = ScalarGrid<double>(surface.xform(), surface.size(), 0);
    myValidFaces = VectorGrid<VisitedCellLabels>(surface.xform(), surface.size(), Vec3t<VisitedCellLabels>::Constant(VisitedCellLabels::UNVISITED_CELL),
                                                 VectorGridSettings::SampleType::STAGGERED);
}

void PressureProjection::project(VectorGrid<double>& velocity)
{
    assert(velocity.isGridMatched(mySolidVelocity));

    enum class MaterialLabels
    {
        SOLID_CELL,
        AIR_CELL,
        LIQUID_CELL
    };

    UniformGrid<MaterialLabels> materialCellLabels(mySurface.size(), MaterialLabels::SOLID_CELL);

    tbb::parallel_for(tbb::blocked_range<int>(0, materialCellLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)
    {
        for (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)
        {
            Vec3i cell = materialCellLabels.unflatten(cellIndex);

            bool isFluidCell = false;

            for (int axis = 0; axis < 3 && !isFluidCell; ++axis)
                for (int direction : {0, 1})
                {
                    Vec3i face = cellToFace(cell, axis, direction);

                    if (myCutCellWeights(face, axis) > 0)
                    {
                        isFluidCell = true;
                        break;
                    }
                }

            if (isFluidCell)
            {
                if (mySurface(cell) <= 0)
                    materialCellLabels(cell) = MaterialLabels::LIQUID_CELL;
                else
                    materialCellLabels(cell) = MaterialLabels::AIR_CELL;
            }
        }
    });

    constexpr int UNLABELLED_CELL = -1;

    UniformGrid<int> liquidCellIndices(mySurface.size(), UNLABELLED_CELL);

    int liquidCellCount = 0;

    forEachVoxelRange(Vec3i::Zero(), liquidCellIndices.size(), [&](const Vec3i& cell)
    {
        if (materialCellLabels(cell) == MaterialLabels::LIQUID_CELL) liquidCellIndices(cell) = liquidCellCount++;
    });

    Vector rhsVector = Vector::Zero(liquidCellCount);
    Vector initialGuessVector = Vector::Zero(liquidCellCount);

    tbb::enumerable_thread_specific<std::vector<Eigen::Triplet<SolveReal>>> parallelSparseMatrixElements;

    tbb::parallel_for(tbb::blocked_range<int>(0, liquidCellIndices.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)
    {
        auto& localSparseMatrixElements = parallelSparseMatrixElements.local();

        for (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)
        {
            Vec3i cell = liquidCellIndices.unflatten(cellIndex);

            int liquidIndex = liquidCellIndices(cell);

            if (liquidIndex >= 0)
            {
                assert(materialCellLabels(cell) == MaterialLabels::LIQUID_CELL);

                // Compute divergence to add to RHS
                SolveReal divergence = 0;

                for (int axis : {0, 1, 2})
                    for (int direction : {0, 1})
                    {
                        Vec3i face = cellToFace(cell, axis, direction);

                        SolveReal weight = myCutCellWeights(face, axis);

                        SolveReal sign = (direction == 0) ? 1 : -1;

                        // Add divergence from faces
                        if (weight > 0) divergence += sign * weight * velocity(face, axis);
                        if (weight < 1.) divergence += sign * (1. - weight) * mySolidVelocity(face, axis);
                    }

                rhsVector(liquidIndex) = divergence;

                SolveReal diagonal = 0;

                for (int axis : {0, 1, 2})
                    for (int direction : {0, 1})
                    {
                        Vec3i adjacentCell = cellToCell(cell, axis, direction);

                        // Bounds check. If out-of-bounds, treat like a stationary grid-aligned solid.
                        if (adjacentCell[axis] < 0 || adjacentCell[axis] >= mySurface.size()[axis]) continue;

                        Vec3i face = cellToFace(cell, axis, direction);

                        SolveReal weight = myCutCellWeights(face, axis);

                        if (weight > 0)
                        {
                            int adjacentLiquidIndex = liquidCellIndices(adjacentCell);
                            if (adjacentLiquidIndex >= 0)
                            {
                                assert(materialCellLabels(adjacentCell) == MaterialLabels::LIQUID_CELL);

                                localSparseMatrixElements.emplace_back(liquidIndex, adjacentLiquidIndex, -weight);
                                diagonal += weight;
                            }
                            else
                            {
                                assert(materialCellLabels(adjacentCell) == MaterialLabels::AIR_CELL);

                                SolveReal theta = myGhostFluidWeights(face, axis);

                                theta = std::clamp(theta, SolveReal(.01), SolveReal(1));
                                diagonal += weight / theta;
                            }
                        }
                        else
                            assert(materialCellLabels(adjacentCell) == MaterialLabels::SOLID_CELL);
                    }

                assert(diagonal > 0);
                localSparseMatrixElements.emplace_back(liquidIndex, liquidIndex, diagonal);

                if (myUseInitialGuessPressure)
                {
                    assert(myInitialGuessPressure != nullptr);
                    initialGuessVector(liquidIndex) = (*myInitialGuessPressure)(cell);
                }
            }
            else
                assert(materialCellLabels(cell) != MaterialLabels::LIQUID_CELL);
        }
    });

    std::vector<Eigen::Triplet<SolveReal>> sparseMatrixElements;
    mergeLocalThreadVectors(sparseMatrixElements, parallelSparseMatrixElements);

    Eigen::SparseMatrix<SolveReal, Eigen::RowMajor> sparseMatrix(liquidCellCount, liquidCellCount);
    sparseMatrix.setFromTriplets(sparseMatrixElements.begin(), sparseMatrixElements.end());

    Eigen::ConjugateGradient<Eigen::SparseMatrix<SolveReal, Eigen::RowMajor>, Eigen::Upper | Eigen::Lower> solver;
    solver.compute(sparseMatrix);

    if (solver.info() != Eigen::Success)
    {
        std::cout << "   Solver failed to build" << std::endl;
        return;
    }

    solver.setTolerance(1E-6);

    if ((rhsVector - sparseMatrix * initialGuessVector).squaredNorm() > rhsVector.squaredNorm())
    {
        initialGuessVector.setZero();
    }

    Vector solutionVector = solver.solveWithGuess(rhsVector, initialGuessVector);

    if (solver.info() != Eigen::Success)
    {
        std::cout << "   Solver failed to converge" << std::endl;
        return;
    }
    else
    {
        std::cout << "    Solver iterations:     " << solver.iterations() << std::endl;
        std::cout << "    Solver error: " << solver.error() << std::endl;
    }

    // Copy resulting vector to pressure grid
    tbb::parallel_for(tbb::blocked_range<int>(0, liquidCellIndices.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)
    {
        for (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)
        {
            Vec3i cell = liquidCellIndices.unflatten(cellIndex);

            int liquidIndex = liquidCellIndices(cell);

            if (liquidIndex >= 0)
            {
                assert(materialCellLabels(cell) == MaterialLabels::LIQUID_CELL);
                myPressure(cell) = solutionVector(liquidIndex);
            }
            else
                assert(materialCellLabels(cell) != MaterialLabels::LIQUID_CELL);
        }
    });

    // Build valid faces
    for (int axis : {0, 1, 2})
    {
        tbb::parallel_for(tbb::blocked_range<int>(0, myValidFaces.grid(axis).voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)
        {
            for (int faceIndex = range.begin(); faceIndex != range.end(); ++faceIndex)
            {
                Vec3i face = myValidFaces.grid(axis).unflatten(faceIndex);

                if (myCutCellWeights(face, axis) > 0)
                {
                    Vec3i backwardCell = faceToCell(face, axis, 0);
                    Vec3i forwardCell = faceToCell(face, axis, 1);

                    if (!(backwardCell[axis] < 0 || forwardCell[axis] >= mySurface.size()[axis]))
                    {
                        if (liquidCellIndices(backwardCell) >= 0 || liquidCellIndices(forwardCell) >= 0)
                        {
                            assert(materialCellLabels(backwardCell) == MaterialLabels::LIQUID_CELL ||
                                    materialCellLabels(forwardCell) == MaterialLabels::LIQUID_CELL);

                            myValidFaces(face, axis) = VisitedCellLabels::FINISHED_CELL;
                        }
                        else
                            myValidFaces(face, axis) = VisitedCellLabels::UNVISITED_CELL;
                    }
                    else
                        myValidFaces(face, axis) = VisitedCellLabels::UNVISITED_CELL;
                }
            }
        });
    }

    // Apply pressure update
    for (int axis : {0, 1, 2})
    {
        tbb::parallel_for(tbb::blocked_range<int>(0, myValidFaces.grid(axis).voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)
        {
            for (int faceIndex = range.begin(); faceIndex != range.end(); ++faceIndex)
            {
                Vec3i face = myValidFaces.grid(axis).unflatten(faceIndex);

                if (myValidFaces(face, axis) == VisitedCellLabels::FINISHED_CELL)
                {
                    Vec3i backwardCell = faceToCell(face, axis, 0);
                    Vec3i forwardCell = faceToCell(face, axis, 1);

                    assert(myCutCellWeights(face, axis) > 0);
                    assert(backwardCell[axis] >= 0 && forwardCell[axis] <= mySurface.size()[axis]);
                    assert(materialCellLabels(backwardCell) == MaterialLabels::LIQUID_CELL ||
                            materialCellLabels(forwardCell) == MaterialLabels::LIQUID_CELL);

                    SolveReal gradient = myPressure(forwardCell) - myPressure(backwardCell);

                    if (materialCellLabels(backwardCell) == MaterialLabels::AIR_CELL ||
                        materialCellLabels(forwardCell) == MaterialLabels::AIR_CELL)
                    {
                        SolveReal theta = myGhostFluidWeights(face, axis);
                        theta = std::clamp(theta, SolveReal(.01), SolveReal(1));

                        gradient /= theta;
                    }

                    velocity(face, axis) -= gradient;
                }
                else
                {
                    velocity(face, axis) = 0;
                }
            }
        });
    }
}

}


text:
#include "googletest/googletest/include/gtest/gtest.h"

#include <boost/algorithm/hex.hpp>
#include <string>
#include <vector>

#include "SerializationTester.h"
#include "serialize.h"

TEST(serialize_tests, varints)
{
    // encode

    CDataStream            ss(SER_DISK, 0);
    CDataStream::size_type size = 0;
    for (int i = 0; i < 100000; i++) {
        ss << VARINT(i);
        size += ::GetSerializeSize(VARINT(i), 0, 0);
        EXPECT_TRUE(size == ss.size());
    }

    for (uint64_t i = 0; i < 100000000000ULL; i += 999999937) {
        ss << VARINT(i);
        size += ::GetSerializeSize(VARINT(i), 0, 0);
        EXPECT_TRUE(size == ss.size());
    }

    // decode
    for (int i = 0; i < 100000; i++) {
        int j = 0;
        ss >> VARINT(j);
        EXPECT_TRUE(i == j) << "decoded:" << j << " expected:" << i;
    }

    for (uint64_t i = 0; i < 100000000000ULL; i += 999999937) {
        uint64_t j = 0;
        ss >> VARINT(j);
        EXPECT_TRUE(i == j) << "decoded:" << j << " expected:" << i;
    }
}

TEST(serialize_tests, cross_platform_consistency) { RunCrossPlatformSerializationTests(); }

TEST(serialize_tests, ser_compact_size)
{
    {
        std::string s = boost::algorithm::unhex(std::string("81"));
        CDataStream ssValue(s.c_str(), s.c_str() + s.size(), SER_NETWORK, PROTOCOL_VERSION);
        auto        val = ReadCompactSize(ssValue);
        EXPECT_EQ(val, static_cast<decltype(val)>(129));
    }
    {
        std::string s = boost::algorithm::unhex(std::string("fd3401"));
        CDataStream ssValue(s.c_str(), s.c_str() + s.size(), SER_NETWORK, PROTOCOL_VERSION);
        auto        val = ReadCompactSize(ssValue);
        EXPECT_EQ(val, static_cast<decltype(val)>(308));
    }
    {
        std::string s = boost::algorithm::unhex(std::string("fd0490"));
        CDataStream ssValue(s.c_str(), s.c_str() + s.size(), SER_NETWORK, PROTOCOL_VERSION);
        auto        val = ReadCompactSize(ssValue);
        EXPECT_EQ(val, static_cast<decltype(val)>(36868));
    }
    {
        std::string s = boost::algorithm::unhex(std::string("fefd0f0100"));
        CDataStream ssValue(s.c_str(), s.c_str() + s.size(), SER_NETWORK, PROTOCOL_VERSION);
        auto        val = ReadCompactSize(ssValue);
        EXPECT_EQ(val, static_cast<decltype(val)>(69629));
    }
}

// TEST(serialize_tests,vector_bool)
//{
//    std::vector<uint8_t> vec1{1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1,
//    0, 0, 1}; std::vector<bool> vec2{1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1,
//    0, 1, 0, 0, 1};

//    EXPECT_TRUE(vec1 == std::vector<uint8_t>(vec2.begin(), vec2.end()));
//    EXPECT_TRUE(SerializeHash(vec1) == SerializeHash(vec2));
//}

TEST(serialize_tests, sizes)
{
    EXPECT_EQ(sizeof(char), GetSerializeSize(char(0), 0));
    EXPECT_EQ(sizeof(int8_t), GetSerializeSize(int8_t(0), 0));
    EXPECT_EQ(sizeof(uint8_t), GetSerializeSize(uint8_t(0), 0));
    EXPECT_EQ(sizeof(int16_t), GetSerializeSize(int16_t(0), 0));
    EXPECT_EQ(sizeof(uint16_t), GetSerializeSize(uint16_t(0), 0));
    EXPECT_EQ(sizeof(int32_t), GetSerializeSize(int32_t(0), 0));
    EXPECT_EQ(sizeof(uint32_t), GetSerializeSize(uint32_t(0), 0));
    EXPECT_EQ(sizeof(int64_t), GetSerializeSize(int64_t(0), 0));
    EXPECT_EQ(sizeof(uint64_t), GetSerializeSize(uint64_t(0), 0));
    EXPECT_EQ(sizeof(float), GetSerializeSize(float(0), 0));
    EXPECT_EQ(sizeof(double), GetSerializeSize(double(0), 0));
    // Bool is serialized as char
    EXPECT_EQ(sizeof(char), GetSerializeSize(bool(0), 0));

    // Sanity-check GetSerializeSize and c++ type matching
    EXPECT_EQ(GetSerializeSize(char(0), 0), 1U);
    EXPECT_EQ(GetSerializeSize(int8_t(0), 0), 1U);
    EXPECT_EQ(GetSerializeSize(uint8_t(0), 0), 1U);
    EXPECT_EQ(GetSerializeSize(int16_t(0), 0), 2U);
    EXPECT_EQ(GetSerializeSize(uint16_t(0), 0), 2U);
    EXPECT_EQ(GetSerializeSize(int32_t(0), 0), 4U);
    EXPECT_EQ(GetSerializeSize(uint32_t(0), 0), 4U);
    EXPECT_EQ(GetSerializeSize(int64_t(0), 0), 8U);
    EXPECT_EQ(GetSerializeSize(uint64_t(0), 0), 8U);
    EXPECT_EQ(GetSerializeSize(float(0), 0), 4U);
    EXPECT_EQ(GetSerializeSize(double(0), 0), 8U);
    EXPECT_EQ(GetSerializeSize(bool(0), 0), 1U);
}

/*
Python code to generate the below hashes:

    def reversed_hex(x):
        return binascii.hexlify(''.join(reversed(x)))
    def dsha256(x):
        return hashlib.sha256(hashlib.sha256(x).digest()).digest()

    reversed_hex(dsha256(''.join(struct.pack('<f', x) for x in range(0,1000)))) ==
'8e8b4cf3e4df8b332057e3e23af42ebc663b61e0495d5e7e32d85099d7f3fe0c'
    reversed_hex(dsha256(''.join(struct.pack('<d', x) for x in range(0,1000)))) ==
'43d0c82591953c4eafe114590d392676a01585d25b25d433557f0d7878b23f96'
*/
TEST(serialize_tests, floats)
{
    CDataStream ss(SER_DISK, 0);
    // encode
    for (int i = 0; i < 1000; i++) {
        ss << float(i);
    }
    EXPECT_TRUE(Hash(ss.begin(), ss.end()) ==
                uint256("8e8b4cf3e4df8b332057e3e23af42ebc663b61e0495d5e7e32d85099d7f3fe0c"));

    // decode
    for (int i = 0; i < 1000; i++) {
        float j;
        ss >> j;
        EXPECT_TRUE(i == j) << "decoded:" << j << " expected:" << i;
    }
}

TEST(serialize_tests, doubles)
{
    CDataStream ss(SER_DISK, 0);
    // encode
    for (int i = 0; i < 1000; i++) {
        ss << double(i);
    }
    EXPECT_TRUE(Hash(ss.begin(), ss.end()) ==
                uint256("43d0c82591953c4eafe114590d392676a01585d25b25d433557f0d7878b23f96"));

    // decode
    for (int i = 0; i < 1000; i++) {
        double j;
        ss >> j;
        EXPECT_TRUE(i == j) << "decoded:" << j << " expected:" << i;
    }
}

TEST(serialize_tests, compactsize)
{
    CDataStream                  ss(SER_DISK, 0);
    std::vector<char>::size_type i, j;

    for (i = 1; i <= MAX_SIZE; i *= 2) {
        WriteCompactSize(ss, i - 1);
        WriteCompactSize(ss, i);
    }
    for (i = 1; i <= MAX_SIZE; i *= 2) {
        j = ReadCompactSize(ss);
        EXPECT_TRUE((i - 1) == j) << "decoded:" << j << " expected:" << (i - 1);
        j = ReadCompactSize(ss);
        EXPECT_TRUE(i == j) << "decoded:" << j << " expected:" << i;
    }
}

TEST(serialize_tests, noncanonical)
{
    // Write some non-canonical CompactSize encodings, and
    // make sure an exception is thrown when read back.
    CDataStream                  ss(SER_DISK, 0);
    std::vector<char>::size_type n;

    // zero encoded with three bytes:
    ss.write("\xfd\x00\x00", 3);
    EXPECT_THROW(ReadCompactSize(ss), std::ios_base::failure);

    // 0xfc encoded with three bytes:
    ss.write("\xfd\xfc\x00", 3);
    EXPECT_THROW(ReadCompactSize(ss), std::ios_base::failure);

    // 0xfd encoded with three bytes is OK:
    ss.write("\xfd\xfd\x00", 3);
    n = ReadCompactSize(ss);
    EXPECT_TRUE(n == 0xfd);

    // zero encoded with five bytes:
    ss.write("\xfe\x00\x00\x00\x00", 5);
    EXPECT_THROW(ReadCompactSize(ss), std::ios_base::failure);

    // 0xffff encoded with five bytes:
    ss.write("\xfe\xff\xff\x00\x00", 5);
    EXPECT_THROW(ReadCompactSize(ss), std::ios_base::failure);

    // zero encoded with nine bytes:
    ss.write("\xff\x00\x00\x00\x00\x00\x00\x00\x00", 9);
    EXPECT_THROW(ReadCompactSize(ss), std::ios_base::failure);

    // 0x01ffffff encoded with nine bytes:
    ss.write("\xff\xff\xff\xff\x01\x00\x00\x00\x00", 9);
    EXPECT_THROW(ReadCompactSize(ss), std::ios_base::failure);
}

TEST(serialize_tests, insert_delete)
{
    // Test inserting/deleting bytes.
    CDataStream ss(SER_DISK, 0);
    EXPECT_EQ(ss.size(), 0U);

    ss.write("\x00\x01\x02\xff", 4);
    EXPECT_EQ(ss.size(), 4U);

    char c = (char)11;

    // Inserting at beginning/end/middle:
    ss.insert(ss.begin(), c);
    EXPECT_EQ(ss.size(), 5U);
    EXPECT_EQ(ss[0], c);
    EXPECT_EQ(ss[1], 0);

    ss.insert(ss.end(), c);
    EXPECT_EQ(ss.size(), 6U);
    EXPECT_EQ(ss[4], (char)0xff);
    EXPECT_EQ(ss[5], c);

    ss.insert(ss.begin() + 2, c);
    EXPECT_EQ(ss.size(), 7U);
    EXPECT_EQ(ss[2], c);

    // Delete at beginning/end/middle
    ss.erase(ss.begin());
    EXPECT_EQ(ss.size(), 6U);
    EXPECT_EQ(ss[0], 0);

    ss.erase(ss.begin() + ss.size() - 1);
    EXPECT_EQ(ss.size(), 5U);
    EXPECT_EQ(ss[4], (char)0xff);

    ss.erase(ss.begin() + 1);
    EXPECT_EQ(ss.size(), 4U);
    EXPECT_EQ(ss[0], 0);
    EXPECT_EQ(ss[1], 1);
    EXPECT_EQ(ss[2], 2);
    EXPECT_EQ(ss[3], (char)0xff);

    // Make sure GetAndClear does the right thing:
    CSerializeData d;
    ss.GetAndClear(d);
    EXPECT_EQ(ss.size(), 0U);
}

max_stars_repo_name: NeblioTeam/neblio

max_issues_repo_name: NeblioTeam/neblio

max_forks_repo_name: NeblioTeam/neblio


text:
//
//  JacobianPseudoInverse.cpp
//  Eigen_test
//
//  Created by Emil Iliev on 19.10.19.
//  Copyright © 2019 Emil Iliev. All rights reserved.
//

#include "JacobianPseudoInverse.hpp"
#include "Jacobian.hpp"
#include <iostream>
#include <Eigen/StdVector>

JacobianPseudoInverse::JacobianPseudoInverse(std::shared_ptr<Robot> robot):
    mtxinstance(MatrixFactory::getInstance()),
    _robot(robot) {

    _desired_position = Eigen::VectorXf(6);
    current_position.resize(6);
}

void JacobianPseudoInverse::setDesiredPosistion(Eigen::VectorXf& desired_position) {
    this->_desired_position = desired_position;
}

Eigen::VectorXf JacobianPseudoInverse::calculateData() {
    //Result vector
    Eigen::VectorXf delta_theta(_robot->giveMeMatrixHolder().size());
    //Vector for delta moving in space
    Eigen::VectorXf delta_translation(6);
    Eigen::VectorXf _temp = _desired_position;

    Jacobian* jac = Jacobian::getInstance();
    //MARK: - TODO
    //should be a parameter of function
    //Desired accuracy
    float epsilon = 0.1f;

    for (;;)
    {
        jac->calculateJacobian(_robot->giveMeMatrixHolder(),
                               _robot->giveMeJoints(),
                               _robot->giveMeFullHM());
        //calculation delta
        current_position << _robot->giveMeFullHM()(0,3) ,    //X
                            _robot->giveMeFullHM()(1,3) ,    //Y
                            _robot->giveMeFullHM()(2,3) ,    //Z
                            0.0f,                           //Orientation
                            0.0f,                           //Orientation
                            0.0f;                           //Orientation

        delta_translation = _desired_position - current_position;

        //compare delta with desired accuracy
        float n = delta_translation.norm();
        if (n < epsilon) {
            //Done
            break;
        }
        //Algo
        delta_theta = jac->psevdoInverse() * delta_translation;
        updateJoints(delta_theta);
    }
    _robot->notifyUpdatedJoints();
    return _temp;
}

void JacobianPseudoInverse::updateJoints(Eigen::VectorXf& delta_theta ) {
    JointHandler& joints = _robot->giveMeJoints();

    for (int i = 0 ; i < delta_theta.size() ; i++) {
        //TODO ADD CONSTRAINTS
        //new var = old var + delta var
        float res = delta_theta[i] + joints[i].giveMeVariableParametr();

        if ( res > 180) {
            res = -180;
        } else if (res < -180) {
            res = 180;
        }
        _robot->setJointVariable(i, res);
    }
    _robot->caclulateFullTransormationMatrix();
}

max_stars_repo_name: emiliev/RoboticArm

max_issues_repo_name: emiliev/RoboticArm

max_forks_repo_name: emiliev/RoboticArm


text:
// [===========================================================================]
// [                               C r y p t o x                               ]
// [---------------------------------------------------------------------------]
// [                                                                           ]
// [                          Copyright (C) 2016-2017                          ]
// [                      Rodrigo Madera <madera@acm.org>                      ]
// [                                                                           ]
// [---------------------------------------------------------------------------]
// [         Distributed under the Boost Software License, Version 1.0         ]
// [ Read accompanying LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt ]
// [===========================================================================]

#pragma once

//
// Boost
//
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>

//
// Std
//
#include <iostream>
#include <vector>
#include <string>

ext: hxx

max_stars_repo_name: madera/cryptox

max_issues_repo_name: madera/cryptox

max_forks_repo_name: madera/cryptox


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2005-2013.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_CONTAINER_CONTAINER_DETAIL_MPL_HPP
#define BOOST_CONTAINER_CONTAINER_DETAIL_MPL_HPP

#ifndef BOOST_CONFIG_HPP
#  include <boost/config.hpp>
#endif

#if defined(BOOST_HAS_PRAGMA_ONCE)
#  pragma once
#endif

#include <boost/container/detail/config_begin.hpp>
#include <boost/container/detail/workaround.hpp>
#include <boost/move/detail/type_traits.hpp>
#include <boost/intrusive/detail/mpl.hpp>

#include <cstddef>

namespace network_boost {
namespace container {
namespace container_detail {

using network_boost::move_detail::integral_constant;
using network_boost::move_detail::true_type;
using network_boost::move_detail::false_type;
using network_boost::move_detail::enable_if_c;
using network_boost::move_detail::enable_if;
using network_boost::move_detail::enable_if_convertible;
using network_boost::move_detail::disable_if_c;
using network_boost::move_detail::disable_if;
using network_boost::move_detail::disable_if_convertible;
using network_boost::move_detail::is_convertible;
using network_boost::move_detail::if_c;
using network_boost::move_detail::if_;
using network_boost::move_detail::identity;
using network_boost::move_detail::bool_;
using network_boost::move_detail::true_;
using network_boost::move_detail::false_;
using network_boost::move_detail::yes_type;
using network_boost::move_detail::no_type;
using network_boost::move_detail::bool_;
using network_boost::move_detail::true_;
using network_boost::move_detail::false_;
using network_boost::move_detail::unvoid_ref;
using network_boost::move_detail::and_;
using network_boost::move_detail::or_;
using network_boost::move_detail::not_;
using network_boost::move_detail::enable_if_and;
using network_boost::move_detail::disable_if_and;
using network_boost::move_detail::enable_if_or;
using network_boost::move_detail::disable_if_or;

template <class Pair>
struct select1st
{
   typedef Pair                        argument_type;
   typedef typename Pair::first_type   result_type;

   template<class OtherPair>
   const typename Pair::first_type& operator()(const OtherPair& x) const
   {  return x.first;   }

   const typename Pair::first_type& operator()(const typename Pair::first_type& x) const
   {  return x;   }
};

}  //namespace container_detail {
}  //namespace container {
}  //namespace network_boost {

#include <boost/container/detail/config_end.hpp>

#endif   //#ifndef BOOST_CONTAINER_CONTAINER_DETAIL_MPL_HPP

max_stars_repo_name: Liastre/uri

max_issues_repo_name: Liastre/uri

max_forks_repo_name: Liastre/uri


text: #include <boost/hana/lazy.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Setup the X11 window and event propagation
// TODO: We should probable do this using XCB instead of Xlib

#include <iostream>

#include "KeyboardController.h"
#include "XWindow.h"

#include <rocket/Log.h>
#include <rocket/ThreadPool.h>

#include <boost/chrono.hpp>
#include <boost/thread.hpp>

#include "../../common/Application.h"
#include "../../common/resource/FSResourcePackage.h"

#ifdef USE_GLES2
#include "../gles2/EglContextManager.h"
#elif USE_GLEW
#include "../glx/GlxContextManager.h"
#endif

#include "../../common/input/PointerEvent.h"
#include "../openal/OpenAlPlayer.h"

#include "GamepadManager.h"

using namespace std;

using namespace rocket;
using namespace rocket::resource;
using namespace rocket::resource::audio;
using namespace rocket::input;
using namespace rocket::linux;
using namespace rocket::game2d;

namespace rocket {
	extern void gameInit();
}

void postPointerEvent(PointerEvent::ActionType actionType,
		int windowWidth, int windowHeight, int mouseX, int mouseY) {
	float nx = static_cast<float>(2*mouseX-windowWidth)/static_cast<float>(windowWidth);
	float ny = static_cast<float>(windowHeight-2*mouseY)/static_cast<float>(windowHeight);

	Application::getApplication().post(
			PointerEvent(0, PointerEvent::PointerType::MOUSE,
			actionType, nx, ny));
}

int main() {
	LOGD("Hello rocket!");
	Director::getDirector().setInitFunction(rocket::gameInit);

	XApplication app;
	#ifdef USE_GLEW
		GlxContextManager glContextManager {app.getDisplay()};
	#else
	#ifdef USE_GLES2
		EglContextManager glContextManager {app.getDisplay()};
	#else
	#error "Neither USE_GLES2 or USE_GLEW defined"
	#endif
	#endif

	auto eventMask = PointerMotionMask| ButtonPressMask| ButtonReleaseMask | FocusChangeMask |
			KeyPressMask | KeyReleaseMask | StructureNotifyMask;

	#ifdef USE_GLEW
	XWindow *window = app.createWindow(glContextManager.getVisualInfo(), eventMask);
	#else
	XWindow *window = app.createSimpleWindow(eventMask);
	#endif

	int windowWidth = 0;
	int windowHeight = 0;

	// Pointer events.
	bool mousePointerPressed = false;
	int mouseX = 0;
	int mouseY = 0;
	int mouseButton = -1;

	boost::mutex windowFocusedMutex;
	boost::condition_variable windowFocusedCondition;
	boost::atomic<bool> windowFocused{true};
	window->setEventHandler(MotionNotify, [&] (XEvent const& event) {
		mouseX = event.xmotion.x;
		mouseY = event.xmotion.y;
		if (mousePointerPressed) {
			postPointerEvent(PointerEvent::ActionType::MOVED, windowWidth, windowHeight, mouseX, mouseY);
		}
	});
	window->setEventHandler(ButtonPress, [&] (XEvent const& event) {
		if (mouseButton == -1) {
			mousePointerPressed = true;
			postPointerEvent(PointerEvent::ActionType::PRESSED, windowWidth, windowHeight, mouseX, mouseY);
			mouseButton = event.xbutton.button;
		}
	});
	window->setEventHandler(ButtonRelease, [&] (XEvent const& event) {
		if (mouseButton == static_cast<int>(event.xbutton.button)) {
			mousePointerPressed = false;
			postPointerEvent(PointerEvent::ActionType::RELEASED, windowWidth, windowHeight, mouseX, mouseY);
			mouseButton = -1;
		}
	});
	window->setEventHandler(FocusIn, [&] (XEvent const&) {
		boost::unique_lock<boost::mutex> lock(windowFocusedMutex);
		if (!windowFocused) {
			LOGD("Window focused");
			Application::getApplication().resume();
		}
		windowFocused.store(true);
		windowFocusedCondition.notify_all();
	});

	window->setEventHandler(FocusOut, [&] (XEvent const&) {
		boost::unique_lock<boost::mutex> lock(windowFocusedMutex);
		if (windowFocused) {
			LOGD("Window not focused");
			Application::getApplication().pause();
		}
		windowFocused.store(false);
		windowFocusedCondition.notify_all();
	});

	// Keyboard controller
	KeyboardController keyboardController;
	window->setEventHandler(KeyPress, [&] (XEvent const& event) {
	//	LOGD(boost::format("KeyPress state: %d, keycode: %d") % event.xkey.state % event.xkey.keycode);
		keyboardController.onKeyPressed(event.xkey);
	});
	window->setEventHandler(KeyRelease, [&] (XEvent const& event) {
	//	LOGD(boost::format("KeyPress state: %d, keycode: %d") % event.xkey.state % event.xkey.keycode);
		keyboardController.onKeyReleased(event.xkey);
	});

	// Window control, bring down application and destroy window on close.
	window->setEventHandler(ClientMessage, [&] (XEvent const& event) {
		if (strcmp("WM_PROTOCOLS", app.getAtomName(event.xclient.message_type).get()) == 0) {
			if (static_cast<unsigned long>(event.xclient.data.l[0]) == app.getDeleteWindowAtom()) {
				LOGD("Shutting down application");

				Application::getApplication().pause();
				Application::getApplication().surfaceDestroyed();
				Application::getApplication().destroy();
				app.destroyWindow(window);
			}
		}
	});

	window->setEventHandler(ConfigureNotify, [&] (XEvent const& event) {
		if ((event.xconfigure.width != windowWidth) || (event.xconfigure.height != windowHeight)) {
			windowWidth = event.xconfigure.width;
			windowHeight = event.xconfigure.height;

			Application::getApplication().surfaceChanged(0, windowWidth, windowHeight);
		}
	});

	std::shared_ptr<ResourcePackage> rp = std::make_shared<FSResourcePackage>("./assets");
	ResourceManager rm {"assets"};
	rm.addResourcePackage("assets", rp);

	Application::init(std::move(rm), std::unique_ptr<PlatformAudioPlayer>(new OpenAlPlayer()));

	window->setFullscreen(false);
	window->setVisible(true);

	Application::getApplication().create(&glContextManager);
	Application::getApplication().resume();
	glContextManager.setSurfaceWindow(window->getWindow());
	Application::getApplication().surfaceCreated();

	// Gamepad management.
	ThreadPool gamepadControllerThread{1};
	boost::atomic<bool> pollControllerEvents{true};

	gamepadControllerThread.submit([&] {
		GamepadManager manager;
		while (pollControllerEvents.load()) {
			bool dropEvents = false;
			if (!windowFocused.load()) {
				boost::unique_lock<boost::mutex> lock(windowFocusedMutex);
				LOGD("Wait for focus");
				boost::system_time const timeout=boost::get_system_time()+ boost::posix_time::milliseconds(2000);
				windowFocusedCondition.timed_wait(lock, timeout);
				LOGD("Received focus");
				dropEvents = true;
			}

			auto event = manager.pollControllers();
			if (event) {
				if (!dropEvents) {
					Application::getApplication().post(event.get());
				}
			} else { // No events lets sleep for a while
				boost::this_thread::sleep_for(ticks{1});
			}
		}
	});

	// Since this is blocking and is responsible for dispatching the above
	// lambdas are allowed to capture scope by reference.
	app.runEventDispatcher();
	pollControllerEvents.store(false);
	windowFocusedCondition.notify_all();
	return 0;
}


text:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#include "picker.h"
#include "Python.h"
#include "numpy/arrayobject.h"

using std::vector;

void PyArrayToVector (PyArrayObject* arr, vector<double>& out, int n) {
    int i;
    double* p;
    out.resize(n);
    for (i = 0; i < n; i++) {
        p = (double*) PyArray_GETPTR1(arr, i);
        out[i] = *p;
    }
    return;
}

static PyObject* dbshear (PyObject *dummy, PyObject *args) {

    int i, p_pick;
    double s1_pick, s2_pick, snr_s1, snr_s2, dt, cov_len, k_len;
    double sta(1.0), lta(5.0);
    vector<double> N, E, Z;

    // Python wrapper declarations
    PyObject *arg1=NULL, *arg2=NULL, *arg3=NULL;
    PyArrayObject *PZ=NULL, *PN=NULL, *PE=NULL;
    PyArrayObject *filter, *K1, *K2, *S1, *S2;

    if (!PyArg_ParseTuple(args, "OOOddd", &PZ, &PN,
                          &PE, &cov_len, &dt, &k_len)) {
        return NULL;
    }

    // Various output related definitions for Python wrapper
    // Find the number of elements in the spectrum
    npy_intp *nz = PyArray_DIMS(PZ);
    npy_intp *nn = PyArray_DIMS(PN);
    npy_intp *ne = PyArray_DIMS(PE);

    PyArrayToVector(PZ, Z, *nz);
    PyArrayToVector(PN, N, *nn);
    PyArrayToVector(PE, E, *ne);

    // Check that all three traces are the same length
    if ((*nz != *ne) || (*nz != *nn) || (*ne != *nn)) return NULL;
    vector<double> pol_fltr,  cftK1(*nz), cftK2(*nz);
    vector<double> cftS1(*nz), cftS2(*nz), snr;

    // Begin picking algorithm & calculate polarization filter
    Polarizer polar_fltr(cov_len, dt);
    pol_fltr = polar_fltr.filter(Z, N, E);

    // Calculate STA/LTA and try to find correct trigger window
    int start, stop;
    double peak_snr;
    snr = lstalta(Z, int(sta/dt), int(lta/dt));
    trigger(snr, 5.0, 2.5, 2.0, dt, start, stop, peak_snr);
    if (start == -1 || stop == -1) {
        p_pick = -1;
    }
    else {
        p_pick = start;
    }
    vector<double> kurt;
    kurt = kurtosis(Z, int(k_len/dt));
    // Window around trial P-pick to refine through k-rate
    start = p_pick - int(1.0/dt);
    stop = p_pick + int(1.0/dt);
    if (stop > kurt.size()) stop = kurt.size()-1;
    vector<double>::iterator it = kurt.begin();
    p_pick = std::distance(it, std::max_element(it+start, it+stop));

    // Attempt to pick S-waves on both horizontals
    ShearPicker SPicker(dt, k_len, sta, lta, 5.0, 2.5, 2, p_pick, pol_fltr);
    SPicker.pick(N, s1_pick, snr_s1);
    SPicker.pick(E, s2_pick, snr_s2);

    //Py_DECREF(PZ);
    //Py_DECREF(PN);
    //Py_DECREF(PE);

    return Py_BuildValue("ffff", s1_pick, s2_pick, snr_s1, snr_s2);
}

static struct PyMethodDef methods[] =
{
    {"dbshear", dbshear, METH_VARARGS, "Polarization filters recursively"},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef dbshear_moddef = {
    PyModuleDef_HEAD_INIT,
    "dbshear", /* name of module */
    "",        /* module documentation */
    -1,        /* size of per-interpreter state of the module, or -1 if the moduel keeps state in global variables */
    methods
};

PyMODINIT_FUNC PyInit_dbshear (void)
{
    return PyModule_Create(&dbshear_moddef);
}


text:
#include "logic_intr.hpp"

#include <libraries/core/comm_intr.hpp>
#include <llpm/module.hpp>
#include <util/llvm_type.hpp>

#include <boost/foreach.hpp>

#include <llvm/IR/Constants.h>

using namespace std;

namespace llpm {
using namespace llvm;

BooleanLogic::BooleanLogic(unsigned,
                           llvm::Type* inputType,
                           llvm::Type* outputType) :
    Function(inputType, outputType)
{
}

std::string Constant::print() const {
    if (this->_value == NULL)
        return "(null)";
    return valuestr(this->_value);
}

std::string Once::print() const {
    if (this->_value == NULL)
        return "(null)";
    return valuestr(this->_value);
}

static llvm::Constant* getLLVMEquivalent(OutputPort* op);
static llvm::Constant* getLLVMEquivalent(InputPort* ip) {
    auto op = ip->owner()->module()->conns()->findSource(ip);
    return getLLVMEquivalent(op);
}

static llvm::Constant* getLLVMEquivalent(OutputPort* op) {
    assert(op != nullptr);
    auto block = op->owner();
    if (block->is<Constant>())
        return block->as<Constant>()->value();

    if (block->is<Join>()) {
        auto join = block->as<Join>();
        vector<llvm::Constant*> vec;
        for (unsigned i=0; i<join->din_size(); i++) {
            auto ip = join->din(i);
            auto eq = getLLVMEquivalent(ip);
            if (eq == nullptr)
                return nullptr;
            vec.push_back(eq);
        }
        if (join->dout()->type()->isStructTy()) {
            return llvm::ConstantStruct::get(
                llvm::dyn_cast<llvm::StructType>(op->type()),
                vec);
        } else if (join->dout()->type()->isVectorTy()) {
            return llvm::ConstantVector::get(vec);
        } else {
            assert(false && "Unknown join type! Fixme or return null.");
        }
    }

    if (block->is<Identity>()) {
        return getLLVMEquivalent(block->as<Identity>()->din());
    }
    if (block->is<Wait>()) {
        return getLLVMEquivalent(block->as<Wait>()->din());
    }

    if (block->is<Extract>()) {
        auto e = block->as<Extract>();
        auto c = getLLVMEquivalent(e->din());
        if (c == nullptr)
            return nullptr;

        for (auto idx: e->path()) {
            c = c->getAggregateElement(idx);
            if (c == nullptr)
                return nullptr;
        }
        return c;
    }

    if (block->is<Split>()) {
        auto s = block->as<Split>();
        auto c = getLLVMEquivalent(s->din());
        if (c == nullptr)
            return nullptr;
        for (unsigned i=0; i<s->dout_size(); i++) {
            if (op == s->dout(i)) {
                return c->getAggregateElement(i);
            }
        }
        return nullptr;
    }

    return nullptr;
}

Constant* Constant::getEquivalent(OutputPort* op) {
    if (op->owner()->is<Constant>())
        return op->owner()->as<Constant>();
    auto eq = getLLVMEquivalent(op);
    if (eq == nullptr)
        return nullptr;
    return new Constant(eq);
}

} // namespace llpm

max_stars_repo_name: llpm/llpm

max_issues_repo_name: llpm/llpm

max_forks_repo_name: llpm/llpm