blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5a6b298c7e2470121c4644ee17ef63c15b5c3f4e | e32869b01445590bc9247558bc92ee1ae2699cce | /2000/2700/2702.cpp | 011ed0fde50285cce58bd5ef6c68f09915162d7d | [] | no_license | jgm0710/BOJ | 294ae89df58dea887997472f1a25ac915befb635 | a870632899720260b186d4432d1a9f79b9f80beb | refs/heads/master | 2021-05-23T00:30:23.008388 | 2020-09-03T10:10:20 | 2020-09-03T10:10:20 | 253,155,744 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 387 | cpp | #include <iostream>
using namespace std;
int main() {
//최소 공배수 lcm
//최대 공약수 Gcf
int t;
cin >> t;
while (t--) {
int a, b;
int gcf = 0;
int lcm=0;
cin >> a >> b;
for (int i = 1; i<1100; i++) {
if (a % i == 0 && b % i == 0) {
gcf = i;
}
}
lcm = (a / gcf) * (b / gcf) * gcf;
cout << lcm << " " << gcf<<endl;
}
} | [
"62986636+jgm0710@users.noreply.github.com"
] | 62986636+jgm0710@users.noreply.github.com |
b0b197dbf130789a1751137ff1b160c34cd8a054 | 5ae53e2ac9558b6b27ee5df6bccf89786176873c | /inc/e57reader.hpp | d0401172648560de69d810bcd5be69e9158e3c00 | [] | no_license | jessesun-cloud/e57toPtx | 6b6f9d390c3303a09af78b17c06d53eca20178c5 | e63c66ce85dd664a22cf9d2aab0f2b452f23c7cb | refs/heads/main | 2023-03-31T18:25:04.905400 | 2021-04-05T20:02:26 | 2021-04-05T20:02:26 | 317,743,796 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 658 | hpp | #pragma once
#include <vector>
#include <string>
#include <functional>
using namespace std;
typedef std::function<void(int numPoint, float* pos,
float* rIntensity,
int* rgbColor)> PointsCB;
class E57Reader
{
public:
E57Reader();
~E57Reader();
bool Open(const char* pFilename);
bool GetSize(int& columns, int& rows);
std::string GetScanName();
bool GetHeader(double scannerPos[12], double ucs[16]);
bool MoveNextScan();
size_t ReadPoints(PointsCB pFun);
int GetNumScan();
void Reset();
size_t GetPointCount();
private:
struct Impl;
Impl* mpImpl;
}; | [
"75183234+jessesun-cloud@users.noreply.github.com"
] | 75183234+jessesun-cloud@users.noreply.github.com |
d37951b044bae5cbbe31c3c49409e6b9d8022169 | 8db996a9a1f6c1231b50452273b0cea06dd572b3 | /Plugin/Test/usdiTestExport.cpp | 62ca10fc9b578e3d26b26469e626a0963c2b0798 | [
"MIT"
] | permissive | microcompunics/USDForUnity | 4f64802c07ff1f42fd6763e265c217c29bd0a96d | c54d8dbb9e64ed534354aec095c6c7ef8417b4aa | refs/heads/master | 2021-01-11T12:29:51.163929 | 2016-12-09T08:49:18 | 2016-12-09T08:49:18 | 76,308,973 | 1 | 0 | null | 2016-12-13T00:54:42 | 2016-12-13T00:54:41 | null | UTF-8 | C++ | false | false | 9,847 | cpp | #include <type_traits>
#include <cstdio>
#include <cmath>
#include <vector>
#include <string>
#include "../usdi/usdi.h"
using usdi::float2;
using usdi::float3;
using usdi::float4;
using usdi::quatf;
template<class T> void* ToPtr(const T& v) { return (void*)&v; }
template<class T> void* ToPtr(const T* v) { return (void*)v; }
template<class T>
static void AddAttribute(usdi::Schema *schema, const char *name, usdi::AttributeType type, const T& v, int num_samples = 5)
{
auto *attr = usdiPrimCreateAttribute(schema, name, type);
usdi::AttributeData data;
data.data = ToPtr(v);
data.num_elements = 1;
if (num_samples == 1) {
usdiAttrWriteSample(attr, &data, usdiDefaultTime());
}
else {
for (int i = 0; i < num_samples; ++i) {
usdi::Time t = 1.0 / 30.0 * i;
usdiAttrWriteSample(attr, &data, t);
}
}
}
template<class T, size_t N>
static void AddAttribute(usdi::Schema *schema, const char *name, usdi::AttributeType type, const T (&v)[N], int num_samples = 5)
{
auto *attr = usdiPrimCreateAttribute(schema, name, type);
usdi::AttributeData data;
data.data = (void*)v;
data.num_elements = N;
if (num_samples == 1) {
usdiAttrWriteSample(attr, &data, usdiDefaultTime());
}
else {
for (int i = 0; i < num_samples; ++i) {
usdi::Time t = 1.0 / 30.0 * i;
usdiAttrWriteSample(attr, &data, t);
}
}
}
static void TestAttributes(usdi::Schema *schema)
{
{
int v = 123;
AddAttribute(schema, "int_scalar", usdi::AttributeType::Int, v);
}
{
float v = 1.23f;
AddAttribute(schema, "float_scalar", usdi::AttributeType::Float, v);
}
{
float2 v = {1.23f, 2.34f};
AddAttribute(schema, "float2_scalar", usdi::AttributeType::Float2, v);
}
{
float3 v = { 1.23f, 2.34f, 3.45f };
AddAttribute(schema, "float3_scalar", usdi::AttributeType::Float3, v);
}
{
float4 v = { 1.23f, 2.34f, 3.45f, 4.56f };
AddAttribute(schema, "float4_scalar", usdi::AttributeType::Float4, v);
}
{
quatf v = { 1.23f, 2.34f, 3.45f, 4.56f };
AddAttribute(schema, "quaternion_scalar", usdi::AttributeType::Quaternion, v);
}
{
const char *v = "test_token";
AddAttribute(schema, "token_scalar", usdi::AttributeType::Token, v);
}
{
const char *v = "test_string";
AddAttribute(schema, "string_scalar", usdi::AttributeType::String, v);
}
{
int v[] = { 123, 234, 345 };
AddAttribute(schema, "int_array", usdi::AttributeType::IntArray, v);
}
{
float v[] = { 1.23f, 2.34f, 3.45f };
AddAttribute(schema, "float_array", usdi::AttributeType::FloatArray, v);
}
{
float2 v[] = { { 1.23f, 2.34f } ,{ 3.45f, 4.56f } ,{ 5.67f, 6.78f } };
AddAttribute(schema, "float2_array", usdi::AttributeType::Float2Array, v);
}
{
float3 v[] = { { 1.23f, 2.34f, 3.45f } ,{ 4.56f, 5.67f, 6.78f } ,{ 7.89f, 8.90f, 9.01f} };
AddAttribute(schema, "float3_array", usdi::AttributeType::Float3Array, v);
}
{
float4 v[] = { { 1.23f, 2.34f, 3.45f, 4.56f } ,{ 5.67f, 6.78f, 7.89f, 8.90f } ,{ 9.01f, 0.12f, 1.23f, 2.34f } };
AddAttribute(schema, "float4_array", usdi::AttributeType::Float4Array, v);
}
{
quatf v[] = { { 1.23f, 2.34f, 3.45f, 4.56f } ,{ 5.67f, 6.78f, 7.89f, 8.90f } ,{ 9.01f, 0.12f, 1.23f, 2.34f } };
AddAttribute(schema, "quaternion_array", usdi::AttributeType::QuaternionArray, v);
}
{
const char *v[] = { "test_token0", "test_token1", "test_token2" };
AddAttribute(schema, "token_array", usdi::AttributeType::TokenArray, v);
}
{
const char *v[] = { "test_string0", "test_string1", "test_string2" };
AddAttribute(schema, "string_array", usdi::AttributeType::StringArray, v);
}
}
void TestExport(const char *filename)
{
auto *ctx = usdiCreateContext();
usdi::ExportSettings settings;
settings.instanceable_by_default = true;
usdiSetExportSettings(ctx, &settings);
usdiCreateStage(ctx, filename);
auto *root = usdiGetRoot(ctx);
{
auto *xf = usdiCreateXform(ctx, root, "Child");
for (int i = 0; i < 5; ++i) {
usdi::Time t = (1.0 / 30.0) * i;
usdi::XformData data;
data.position.x = 0.2f * i;
usdiXformWriteSample(xf, &data, t);
}
TestAttributes(xf);
{
auto *mesh = usdiCreateMesh(ctx, xf, "TestMesh");
float3 points[] = {
{ -0.5f, -0.5f, 0.0f },
{ 0.5f, -0.5f, 0.0f },
{ 0.5f, 0.5f, 0.0f },
{ -0.5f, 0.5f, 0.0f },
};
float3 normals[] = {
{ 0.0f, 0.0f, 1.0f },
{ 0.0f, 0.0f, 1.0f },
{ 0.0f, 0.0f, 1.0f },
{ 0.0f, 0.0f, 1.0f },
};
float4 tangents[] = {
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
};
float2 uvs[] = {
{ 0.0f, 0.0f },
{ 1.0f, 0.0f },
{ 1.0f, 1.0f },
{ 0.0f, 1.0f },
};
int counts[] = { 4 };
int indices[] = { 0, 1, 2, 3 };
usdi::MeshData data;
data.points = points;
data.normals = normals;
data.tangents = tangents;
data.uvs = uvs;
data.indices = indices;
data.num_points = std::extent<decltype(points)>::value;
data.num_counts = std::extent<decltype(counts)>::value;
data.num_indices = std::extent<decltype(indices)>::value;
for (int i = 0; i < 5; ++i) {
usdi::Time t = (1.0 / 30.0) * i;
usdiMeshWriteSample(mesh, &data, t);
}
}
}
{
auto *mesh2 = usdiCreateMesh(ctx, root, "TestRootMesh");
float3 vertices[] = {
{ -0.5f, -0.5f, 0.0f },
{ 0.5f, -0.5f, 0.0f },
{ 0.5f, 0.5f, 0.0f },
{ -0.5f, 0.5f, 0.0f },
};
int counts[] = { 3, 3 };
int indices[] = { 0, 1, 2, 0, 2, 3 };
usdi::MeshData data;
data.points = vertices;
data.counts = counts;
data.indices = indices;
data.num_points = std::extent<decltype(vertices)>::value;
data.num_counts = std::extent<decltype(counts)>::value;
data.num_indices = std::extent<decltype(indices)>::value;
for (int i = 0; i < 5; ++i) {
usdi::Time t = (1.0 / 30.0) * i;
usdiMeshWriteSample(mesh2, &data, t);
}
AddAttribute(mesh2, "TestImageAsset", usdi::AttributeType::Asset, "USDAssets/test.exr", 1);
AddAttribute(mesh2, "TestFBXAsset", usdi::AttributeType::Asset, "USDAssets/test.fbx", 1);
AddAttribute(mesh2, "TestMDLAsset", usdi::AttributeType::Asset, "USDAssets/test.mdl", 1);
}
{
auto CreateTestXformTree = [](usdi::Context *ctx, usdi::Schema *parent, std::vector<std::string> names)
{
for (auto& name : names) {
parent = usdiCreateXform(ctx, parent, name.c_str());
}
};
auto *xf = usdiCreateXform(ctx, root, "TestVariants");
int vset[] = {
usdiPrimCreateVariantSet(xf, "VariantSet0"),
usdiPrimCreateVariantSet(xf, "VariantSet1"),
};
usdiPrimCreateVariant(xf, vset[0], "Variant0-0");
usdiPrimCreateVariant(xf, vset[0], "Variant0-1");
usdiPrimCreateVariant(xf, vset[1], "Variant1-0");
usdiPrimCreateVariant(xf, vset[1], "Variant1-1");
usdiPrimCreateVariant(xf, vset[1], "Variant1-2");
usdiPrimBeginEditVariant(xf, 0, 0);
xf = usdiAsXform(usdiFindSchema(ctx, "/TestVariants"));
for (int i = 0; i < 5; ++i) {
usdi::Time t = (1.0 / 30.0) * i;
usdi::XformData data;
data.position.x = 0.2f * i;
usdiXformWriteSample(xf, &data, t);
}
CreateTestXformTree(ctx, xf, { "Variant0-0", "Hoge" });
usdiPrimEndEditVariant(xf);
usdiPrimBeginEditVariant(xf, 1, 1);
xf = usdiAsXform(usdiFindSchema(ctx, "/TestVariants"));
for (int i = 0; i < 5; ++i) {
usdi::Time t = (1.0 / 30.0) * i;
usdi::XformData data;
data.position.y = 0.4f * i;
usdiXformWriteSample(xf, &data, t);
}
CreateTestXformTree(ctx, xf, { "Variant1-1", "Hage", "Hige" });
usdiPrimEndEditVariant(xf);
}
// create internal reference
auto *ref = usdiCreateOverride(ctx, "/Ref");
usdiPrimAddReference(ref, nullptr, "/Child");
// create payload
auto *pl = usdiCreateOverride(ctx, "/TestPayload");
usdiPrimSetPayload(pl, "HelloWorld.usda", "/hello");
usdiSave(ctx);
usdiFlatten(ctx);
usdiSaveAs(ctx, "Hoge.usda");
usdiDestroyContext(ctx);
}
void TestExportReference(const char *filename, const char *flatten)
{
auto *ctx = usdiCreateContext();
usdiCreateStage(ctx, filename);
// create external reference
auto *ref = usdiCreateOverride(ctx, "/Test");
usdiPrimAddReference(ref, "TestExport.usda", "/Child");
usdiSave(ctx);
usdiFlatten(ctx);
usdiSaveAs(ctx, flatten);
usdiDestroyContext(ctx);
}
| [
"saint.skr@gmail.com"
] | saint.skr@gmail.com |
8aaa1e722ec4687cf05e184e6da1878718596c7d | 55d560fe6678a3edc9232ef14de8fafd7b7ece12 | /boost/test/unit_test_suite.hpp | 579091c456626b930ef2cca5ff9b16621c77bd8e | [
"BSL-1.0"
] | permissive | stardog-union/boost | ec3abeeef1b45389228df031bf25b470d3d123c5 | caa4a540db892caa92e5346e0094c63dea51cbfb | refs/heads/stardog/develop | 2021-06-25T02:15:10.697006 | 2020-11-17T19:50:35 | 2020-11-17T19:50:35 | 148,681,713 | 0 | 0 | BSL-1.0 | 2020-11-17T19:50:36 | 2018-09-13T18:38:54 | C++ | UTF-8 | C++ | false | false | 19,059 | hpp | // (C) Copyright Gennadiy Rozental 2001.
// 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/test for the library home page.
//
/// @file
/// @brief Defines Unit Test Framework public API
// ***************************************************************************
#ifndef BOOST_TEST_UNIT_TEST_SUITE_HPP_071894GER
#define BOOST_TEST_UNIT_TEST_SUITE_HPP_071894GER
// Boost.Test
#include <boost/test/framework.hpp>
#include <boost/test/tree/auto_registration.hpp>
#include <boost/test/tree/test_case_template.hpp>
#include <boost/test/tree/global_fixture.hpp>
#include <boost/test/detail/suppress_warnings.hpp>
#include <boost/test/detail/pp_variadic.hpp>
//____________________________________________________________________________//
// ************************************************************************** //
// ************** Non-auto (explicit) test case interface ************** //
// ************************************************************************** //
#define BOOST_TEST_CASE( test_function ) \
boost::unit_test::make_test_case( boost::function<void ()>(test_function), \
BOOST_TEST_STRINGIZE( test_function ), \
__FILE__, __LINE__ )
#define BOOST_CLASS_TEST_CASE( test_function, tc_instance ) \
boost::unit_test::make_test_case( (test_function), \
BOOST_TEST_STRINGIZE( test_function ), \
__FILE__, __LINE__, tc_instance )
// ************************************************************************** //
// ************** BOOST_TEST_SUITE ************** //
// ************************************************************************** //
#define BOOST_TEST_SUITE( testsuite_name ) \
( new boost::unit_test::test_suite( testsuite_name, __FILE__, __LINE__ ) )
// ************************************************************************** //
// ************** BOOST_AUTO_TEST_SUITE ************** //
// ************************************************************************** //
#define BOOST_AUTO_TEST_SUITE_WITH_DECOR( suite_name, decorators ) \
namespace suite_name { \
BOOST_AUTO_TU_REGISTRAR( suite_name )( \
BOOST_STRINGIZE( suite_name ), \
__FILE__, __LINE__, \
decorators ); \
/**/
#define BOOST_AUTO_TEST_SUITE_NO_DECOR( suite_name ) \
BOOST_AUTO_TEST_SUITE_WITH_DECOR( \
suite_name, \
boost::unit_test::decorator::collector::instance() ) \
/**/
#if BOOST_PP_VARIADICS
#define BOOST_AUTO_TEST_SUITE( ... ) \
BOOST_TEST_INVOKE_IF_N_ARGS( 1, \
BOOST_AUTO_TEST_SUITE_NO_DECOR, \
BOOST_AUTO_TEST_SUITE_WITH_DECOR, \
__VA_ARGS__) \
/**/
#else /* BOOST_PP_VARIADICS */
#define BOOST_AUTO_TEST_SUITE( suite_name ) \
BOOST_AUTO_TEST_SUITE_NO_DECOR( suite_name ) \
/**/
#endif /* BOOST_PP_VARIADICS */
// ************************************************************************** //
// ************** BOOST_FIXTURE_TEST_SUITE ************** //
// ************************************************************************** //
#define BOOST_FIXTURE_TEST_SUITE_WITH_DECOR(suite_name, F, decorators) \
BOOST_AUTO_TEST_SUITE_WITH_DECOR( suite_name, decorators ) \
typedef F BOOST_AUTO_TEST_CASE_FIXTURE; \
/**/
#define BOOST_FIXTURE_TEST_SUITE_NO_DECOR( suite_name, F ) \
BOOST_AUTO_TEST_SUITE_NO_DECOR( suite_name ) \
typedef F BOOST_AUTO_TEST_CASE_FIXTURE; \
/**/
#if BOOST_PP_VARIADICS
#define BOOST_FIXTURE_TEST_SUITE( ... ) \
BOOST_TEST_INVOKE_IF_N_ARGS( 2, \
BOOST_FIXTURE_TEST_SUITE_NO_DECOR, \
BOOST_FIXTURE_TEST_SUITE_WITH_DECOR, \
__VA_ARGS__) \
/**/
#else /* BOOST_PP_VARIADICS */
#define BOOST_FIXTURE_TEST_SUITE( suite_name, F ) \
BOOST_FIXTURE_TEST_SUITE_NO_DECOR( suite_name, F ) \
/**/
#endif /* BOOST_PP_VARIADICS */
// ************************************************************************** //
// ************** BOOST_AUTO_TEST_SUITE_END ************** //
// ************************************************************************** //
#define BOOST_AUTO_TEST_SUITE_END() \
BOOST_AUTO_TU_REGISTRAR( end_suite )( 1 ); \
} \
/**/
// ************************************************************************** //
// ************** BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES ************** //
// ************************************************************************** //
/// @deprecated use decorator instead
#define BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( test_name, n ) \
BOOST_TEST_DECORATOR( * boost::unit_test::expected_failures( n ) ) \
/**/
// ************************************************************************** //
// ************** BOOST_FIXTURE_TEST_CASE ************** //
// ************************************************************************** //
#define BOOST_FIXTURE_TEST_CASE_WITH_DECOR( test_name, F, decorators ) \
struct test_name : public F { void test_method(); }; \
\
static void BOOST_AUTO_TC_INVOKER( test_name )() \
{ \
BOOST_TEST_CHECKPOINT('"' << #test_name << "\" fixture ctor"); \
test_name t; \
BOOST_TEST_CHECKPOINT('"' << #test_name << "\" fixture setup"); \
boost::unit_test::setup_conditional(t); \
BOOST_TEST_CHECKPOINT('"' << #test_name << "\" test entry"); \
t.test_method(); \
BOOST_TEST_CHECKPOINT('"' << #test_name << "\" fixture teardown"); \
boost::unit_test::teardown_conditional(t); \
BOOST_TEST_CHECKPOINT('"' << #test_name << "\" fixture dtor"); \
} \
\
struct BOOST_AUTO_TC_UNIQUE_ID( test_name ) {}; \
\
BOOST_AUTO_TU_REGISTRAR( test_name )( \
boost::unit_test::make_test_case( \
&BOOST_AUTO_TC_INVOKER( test_name ), \
#test_name, __FILE__, __LINE__ ), \
decorators ); \
\
void test_name::test_method() \
/**/
#define BOOST_FIXTURE_TEST_CASE_NO_DECOR( test_name, F ) \
BOOST_FIXTURE_TEST_CASE_WITH_DECOR( test_name, F, \
boost::unit_test::decorator::collector::instance() ) \
/**/
#if BOOST_PP_VARIADICS
#define BOOST_FIXTURE_TEST_CASE( ... ) \
BOOST_TEST_INVOKE_IF_N_ARGS( 2, \
BOOST_FIXTURE_TEST_CASE_NO_DECOR, \
BOOST_FIXTURE_TEST_CASE_WITH_DECOR, \
__VA_ARGS__) \
/**/
#else /* BOOST_PP_VARIADICS */
#define BOOST_FIXTURE_TEST_CASE( test_name, F ) \
BOOST_FIXTURE_TEST_CASE_NO_DECOR(test_name, F) \
/**/
#endif /* BOOST_PP_VARIADICS */
// ************************************************************************** //
// ************** BOOST_AUTO_TEST_CASE ************** //
// ************************************************************************** //
#define BOOST_AUTO_TEST_CASE_NO_DECOR( test_name ) \
BOOST_FIXTURE_TEST_CASE_NO_DECOR( test_name, \
BOOST_AUTO_TEST_CASE_FIXTURE ) \
/**/
#define BOOST_AUTO_TEST_CASE_WITH_DECOR( test_name, decorators ) \
BOOST_FIXTURE_TEST_CASE_WITH_DECOR( test_name, \
BOOST_AUTO_TEST_CASE_FIXTURE, decorators ) \
/**/
#if BOOST_PP_VARIADICS
#define BOOST_AUTO_TEST_CASE( ... ) \
BOOST_TEST_INVOKE_IF_N_ARGS( 1, \
BOOST_AUTO_TEST_CASE_NO_DECOR, \
BOOST_AUTO_TEST_CASE_WITH_DECOR, \
__VA_ARGS__) \
/**/
#else /* BOOST_PP_VARIADICS */
#define BOOST_AUTO_TEST_CASE( test_name ) \
BOOST_AUTO_TEST_CASE_NO_DECOR( test_name ) \
/**/
#endif /* BOOST_PP_VARIADICS */
// ************************************************************************** //
// ************** BOOST_FIXTURE_TEST_CASE_TEMPLATE ************** //
// ************************************************************************** //
#define BOOST_FIXTURE_TEST_CASE_TEMPLATE( test_name, type_name, TL, F ) \
template<typename type_name> \
struct test_name : public F \
{ void test_method(); }; \
\
struct BOOST_AUTO_TC_INVOKER( test_name ) { \
template<typename TestType> \
static void run( boost::type<TestType>* = 0 ) \
{ \
BOOST_TEST_CHECKPOINT('"' << #test_name <<"\" fixture entry."); \
test_name<TestType> t; boost::unit_test::setup_conditional(t); \
BOOST_TEST_CHECKPOINT('"' << #test_name << "\" entry."); \
t.test_method(); \
BOOST_TEST_CHECKPOINT('"' << #test_name << "\" exit."); \
boost::unit_test::teardown_conditional(t); \
} \
}; \
\
BOOST_AUTO_TU_REGISTRAR( test_name )( \
boost::unit_test::ut_detail::template_test_case_gen< \
BOOST_AUTO_TC_INVOKER( test_name ),TL >( \
BOOST_STRINGIZE( test_name ), __FILE__, __LINE__ ), \
boost::unit_test::decorator::collector::instance() ); \
\
template<typename type_name> \
void test_name<type_name>::test_method() \
/**/
// ************************************************************************** //
// ************** BOOST_AUTO_TEST_CASE_TEMPLATE ************** //
// ************************************************************************** //
#define BOOST_AUTO_TEST_CASE_TEMPLATE( test_name, type_name, TL ) \
BOOST_FIXTURE_TEST_CASE_TEMPLATE( test_name, type_name, TL, \
BOOST_AUTO_TEST_CASE_FIXTURE ) \
/**/
// ************************************************************************** //
// ************** BOOST_TEST_CASE_TEMPLATE ************** //
// ************************************************************************** //
#define BOOST_TEST_CASE_TEMPLATE( name, typelist ) \
boost::unit_test::ut_detail::template_test_case_gen<name,typelist>( \
BOOST_TEST_STRINGIZE( name ), __FILE__, __LINE__ ) \
/**/
// ************************************************************************** //
// ************** BOOST_TEST_CASE_TEMPLATE_FUNCTION ************** //
// ************************************************************************** //
#define BOOST_TEST_CASE_TEMPLATE_FUNCTION( name, type_name ) \
template<typename type_name> \
void BOOST_JOIN( name, _impl )( boost::type<type_name>* ); \
\
struct name { \
template<typename TestType> \
static void run( boost::type<TestType>* frwrd = 0 ) \
{ \
BOOST_JOIN( name, _impl )( frwrd ); \
} \
}; \
\
template<typename type_name> \
void BOOST_JOIN( name, _impl )( boost::type<type_name>* ) \
/**/
// ************************************************************************** //
// ************** BOOST_GLOBAL_FIXTURE ************** //
// ************************************************************************** //
#define BOOST_GLOBAL_FIXTURE( F ) \
static boost::unit_test::ut_detail::global_configuration_impl<F> BOOST_JOIN( gf_, F ) \
/**/
// ************************************************************************** //
// ************** BOOST_TEST_GLOBAL_CONFIGURATION ************** //
// ************************************************************************** //
#define BOOST_TEST_GLOBAL_CONFIGURATION( F ) \
static boost::unit_test::ut_detail::global_configuration_impl<F> BOOST_JOIN( gf_, F ) \
/**/
// ************************************************************************** //
// ************** BOOST_TEST_GLOBAL_FIXTURE ************** //
// ************************************************************************** //
#define BOOST_TEST_GLOBAL_FIXTURE( F ) \
static boost::unit_test::ut_detail::global_fixture_impl<F> BOOST_JOIN( gf_, F ) \
/**/
// ************************************************************************** //
// ************** BOOST_TEST_DECORATOR ************** //
// ************************************************************************** //
#define BOOST_TEST_DECORATOR( D ) \
static boost::unit_test::decorator::collector const& \
BOOST_TEST_APPEND_UNIQUE_ID(decorator_collector) = D; \
/**/
// ************************************************************************** //
// ************** BOOST_AUTO_TEST_CASE_FIXTURE ************** //
// ************************************************************************** //
namespace boost { namespace unit_test { namespace ut_detail {
struct nil_t {};
} // namespace ut_detail
} // unit_test
} // namespace boost
// Intentionally is in global namespace, so that FIXTURE_TEST_SUITE can reset it in user code.
typedef ::boost::unit_test::ut_detail::nil_t BOOST_AUTO_TEST_CASE_FIXTURE;
// ************************************************************************** //
// ************** Auto registration facility helper macros ************** //
// ************************************************************************** //
// Facility for having a unique name based on __LINE__ and __COUNTER__ (later if available)
#if defined(__COUNTER__)
#define BOOST_TEST_INTERNAL_HAS_COUNTER
#endif
#if defined(BOOST_TEST_INTERNAL_HAS_COUNTER)
#define BOOST_TEST_APPEND_UNIQUE_ID( name ) \
BOOST_JOIN( BOOST_JOIN( name, __LINE__ ), __COUNTER__)
/**/
#else
#define BOOST_TEST_APPEND_UNIQUE_ID( name ) \
BOOST_JOIN( name, __LINE__ )
/**/
#endif
/**/
#define BOOST_AUTO_TU_REGISTRAR( test_name ) \
static boost::unit_test::ut_detail::auto_test_unit_registrar \
BOOST_TEST_APPEND_UNIQUE_ID( BOOST_JOIN( test_name, _registrar ) ) \
/**/
#define BOOST_AUTO_TC_INVOKER( test_name ) BOOST_JOIN( test_name, _invoker )
#define BOOST_AUTO_TC_UNIQUE_ID( test_name ) BOOST_JOIN( test_name, _id )
// ************************************************************************** //
// ************** BOOST_TEST_MAIN ************** //
// ************************************************************************** //
#if defined(BOOST_TEST_MAIN)
#ifdef BOOST_TEST_ALTERNATIVE_INIT_API
bool init_unit_test() {
#else
::boost::unit_test::test_suite*
init_unit_test_suite( int, char* [] ) {
#endif
#ifdef BOOST_TEST_MODULE
using namespace ::boost::unit_test;
assign_op( framework::master_test_suite().p_name.value, BOOST_TEST_STRINGIZE( BOOST_TEST_MODULE ).trim( "\"" ), 0 );
#endif
#ifdef BOOST_TEST_ALTERNATIVE_INIT_API
return true;
}
#else
return 0;
}
#endif
#endif
//____________________________________________________________________________//
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_UNIT_TEST_SUITE_HPP_071894GER
| [
"james.pack@stardog.com"
] | james.pack@stardog.com |
b259436a83ae7aa1f9a9fb76d1f6df8422eba225 | 97763df96bc21d91e46e3a98f9ee2b55f557035e | /src/wallet/test/crypto_tests.cpp | 6bd9d62d14839d94b68527f84c26e81175b37f36 | [
"MIT"
] | permissive | jaagcoin/JAAGCoin-Core | 2f0138c38e28b98878bbcd5f011ab84d1441bb57 | 87073dbff406e2d95a6e9d81521973c3c8cef350 | refs/heads/master | 2020-03-26T05:34:39.790028 | 2018-08-30T15:46:16 | 2018-08-30T15:46:16 | 144,563,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,022 | cpp | // Copyright (c) 2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "test/test_random.h"
#include "utilstrencodings.h"
#include "test/test_jaag.h"
#include "wallet/crypter.h"
#include <vector>
#include <boost/test/unit_test.hpp>
#include <openssl/aes.h>
#include <openssl/evp.h>
BOOST_FIXTURE_TEST_SUITE(wallet_crypto, BasicTestingSetup)
bool OldSetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod, unsigned char* chKey, unsigned char* chIV)
{
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
return false;
int i = 0;
if (nDerivationMethod == 0)
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
(unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
{
memory_cleanse(chKey, sizeof(chKey));
memory_cleanse(chIV, sizeof(chIV));
return false;
}
return true;
}
bool OldEncrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext, const unsigned char chKey[32], const unsigned char chIV[16])
{
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCK_SIZE - 1 bytes
int nLen = vchPlaintext.size();
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
vchCiphertext = std::vector<unsigned char> (nCLen);
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) return false;
bool fOk = true;
EVP_CIPHER_CTX_init(ctx);
if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0;
if (fOk) fOk = EVP_EncryptUpdate(ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen) != 0;
if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (&vchCiphertext[0]) + nCLen, &nFLen) != 0;
EVP_CIPHER_CTX_cleanup(ctx);
EVP_CIPHER_CTX_free(ctx);
if (!fOk) return false;
vchCiphertext.resize(nCLen + nFLen);
return true;
}
bool OldDecrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext, const unsigned char chKey[32], const unsigned char chIV[16])
{
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = vchCiphertext.size();
int nPLen = nLen, nFLen = 0;
vchPlaintext = CKeyingMaterial(nPLen);
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) return false;
bool fOk = true;
EVP_CIPHER_CTX_init(ctx);
if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0;
if (fOk) fOk = EVP_DecryptUpdate(ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen) != 0;
if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (&vchPlaintext[0]) + nPLen, &nFLen) != 0;
EVP_CIPHER_CTX_cleanup(ctx);
EVP_CIPHER_CTX_free(ctx);
if (!fOk) return false;
vchPlaintext.resize(nPLen + nFLen);
return true;
}
// General secure AES 256 CBC encryption routine
bool OldEncryptAES256(const SecureString& sKey, const SecureString& sPlaintext, const std::string& sIV, std::string& sCiphertext)
{
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCK_SIZE - 1 bytes
int nLen = sPlaintext.size();
int nCLen = nLen + AES_BLOCK_SIZE;
int nFLen = 0;
// Verify key sizes
if(sKey.size() != 32 || sIV.size() != AES_BLOCK_SIZE) {
LogPrintf("crypter EncryptAES256 - Invalid key or block size: Key: %d sIV:%d\n", sKey.size(), sIV.size());
return false;
}
// Prepare output buffer
sCiphertext.resize(nCLen);
// Perform the encryption
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) return false;
bool fOk = true;
EVP_CIPHER_CTX_init(ctx);
if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char*) &sKey[0], (const unsigned char*) &sIV[0]);
if (fOk) fOk = EVP_EncryptUpdate(ctx, (unsigned char*) &sCiphertext[0], &nCLen, (const unsigned char*) &sPlaintext[0], nLen);
if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (unsigned char*) (&sCiphertext[0])+nCLen, &nFLen);
EVP_CIPHER_CTX_cleanup(ctx);
EVP_CIPHER_CTX_free(ctx);
if (!fOk) return false;
sCiphertext.resize(nCLen + nFLen);
return true;
}
bool OldDecryptAES256(const SecureString& sKey, const std::string& sCiphertext, const std::string& sIV, SecureString& sPlaintext)
{
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = sCiphertext.size();
int nPLen = nLen, nFLen = 0;
// Verify key sizes
if(sKey.size() != 32 || sIV.size() != AES_BLOCK_SIZE) {
LogPrintf("crypter DecryptAES256 - Invalid key or block size\n");
return false;
}
sPlaintext.resize(nPLen);
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) return false;
bool fOk = true;
EVP_CIPHER_CTX_init(ctx);
if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char*) &sKey[0], (const unsigned char*) &sIV[0]);
if (fOk) fOk = EVP_DecryptUpdate(ctx, (unsigned char *) &sPlaintext[0], &nPLen, (const unsigned char *) &sCiphertext[0], nLen);
if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (unsigned char *) (&sPlaintext[0])+nPLen, &nFLen);
EVP_CIPHER_CTX_cleanup(ctx);
EVP_CIPHER_CTX_free(ctx);
if (!fOk) return false;
sPlaintext.resize(nPLen + nFLen);
return true;
}
void TestAES256CBC(const std::string &hexkey, const std::string &hexiv, const std::string &hexin, const std::string &hexout)
{
std::vector<unsigned char> key = ParseHex(hexkey);
std::vector<unsigned char> iv = ParseHex(hexiv);
std::vector<unsigned char> in = ParseHex(hexin);
std::vector<unsigned char> correctout = ParseHex(hexout);
SecureString sKey(key.begin(), key.end()), sPlaintextIn(in.begin(), in.end()), sPlaintextOut, sPlaintextOutOld;
std::string sIv(iv.begin(), iv.end()), sCiphertextIn(correctout.begin(), correctout.end()), sCiphertextOut, sCiphertextOutOld;
BOOST_CHECK_MESSAGE(EncryptAES256(sKey, sPlaintextIn, sIv, sCiphertextOut), "EncryptAES256: " + HexStr(sCiphertextOut) + std::string(" != ") + hexout);
BOOST_CHECK_MESSAGE(OldEncryptAES256(sKey, sPlaintextIn, sIv, sCiphertextOutOld), "OldEncryptAES256: " + HexStr(sCiphertextOutOld) + std::string(" != ") + hexout);
BOOST_CHECK(sCiphertextOut == sCiphertextOutOld);
BOOST_CHECK_MESSAGE(DecryptAES256(sKey, sCiphertextIn, sIv, sPlaintextOut), "DecryptAES256: " + HexStr(sPlaintextOut) + std::string(" != ") + hexin);
BOOST_CHECK_MESSAGE(OldDecryptAES256(sKey, sCiphertextIn, sIv, sPlaintextOutOld), "OldDecryptAES256: " + HexStr(sPlaintextOutOld) + std::string(" != ") + hexin);
BOOST_CHECK(sPlaintextOut == sPlaintextOutOld);
}
class TestCrypter
{
public:
static void TestPassphraseSingle(const std::vector<unsigned char>& vchSalt, const SecureString& passphrase, uint32_t rounds,
const std::vector<unsigned char>& correctKey = std::vector<unsigned char>(),
const std::vector<unsigned char>& correctIV=std::vector<unsigned char>())
{
unsigned char chKey[WALLET_CRYPTO_KEY_SIZE];
unsigned char chIV[WALLET_CRYPTO_IV_SIZE];
CCrypter crypt;
crypt.SetKeyFromPassphrase(passphrase, vchSalt, rounds, 0);
OldSetKeyFromPassphrase(passphrase, vchSalt, rounds, 0, chKey, chIV);
BOOST_CHECK_MESSAGE(memcmp(chKey, crypt.vchKey.data(), crypt.vchKey.size()) == 0, \
HexStr(chKey, chKey+sizeof(chKey)) + std::string(" != ") + HexStr(crypt.vchKey));
BOOST_CHECK_MESSAGE(memcmp(chIV, crypt.vchIV.data(), crypt.vchIV.size()) == 0, \
HexStr(chIV, chIV+sizeof(chIV)) + std::string(" != ") + HexStr(crypt.vchIV));
if(!correctKey.empty())
BOOST_CHECK_MESSAGE(memcmp(chKey, &correctKey[0], sizeof(chKey)) == 0, \
HexStr(chKey, chKey+sizeof(chKey)) + std::string(" != ") + HexStr(correctKey.begin(), correctKey.end()));
if(!correctIV.empty())
BOOST_CHECK_MESSAGE(memcmp(chIV, &correctIV[0], sizeof(chIV)) == 0,
HexStr(chIV, chIV+sizeof(chIV)) + std::string(" != ") + HexStr(correctIV.begin(), correctIV.end()));
}
static void TestPassphrase(const std::vector<unsigned char>& vchSalt, const SecureString& passphrase, uint32_t rounds,
const std::vector<unsigned char>& correctKey = std::vector<unsigned char>(),
const std::vector<unsigned char>& correctIV=std::vector<unsigned char>())
{
TestPassphraseSingle(vchSalt, passphrase, rounds, correctKey, correctIV);
for(SecureString::const_iterator i(passphrase.begin()); i != passphrase.end(); ++i)
TestPassphraseSingle(vchSalt, SecureString(i, passphrase.end()), rounds);
}
static void TestDecrypt(const CCrypter& crypt, const std::vector<unsigned char>& vchCiphertext, \
const std::vector<unsigned char>& vchPlaintext = std::vector<unsigned char>())
{
CKeyingMaterial vchDecrypted1;
CKeyingMaterial vchDecrypted2;
int result1, result2;
result1 = crypt.Decrypt(vchCiphertext, vchDecrypted1);
result2 = OldDecrypt(vchCiphertext, vchDecrypted2, crypt.vchKey.data(), crypt.vchIV.data());
BOOST_CHECK(result1 == result2);
// These two should be equal. However, OpenSSL 1.0.1j introduced a change
// that would zero all padding except for the last byte for failed decrypts.
// This behavior was reverted for 1.0.1k.
if (vchDecrypted1 != vchDecrypted2 && vchDecrypted1.size() >= AES_BLOCK_SIZE && SSLeay() == 0x100010afL)
{
for(CKeyingMaterial::iterator it = vchDecrypted1.end() - AES_BLOCK_SIZE; it != vchDecrypted1.end() - 1; it++)
*it = 0;
}
BOOST_CHECK_MESSAGE(vchDecrypted1 == vchDecrypted2, HexStr(vchDecrypted1.begin(), vchDecrypted1.end()) + " != " + HexStr(vchDecrypted2.begin(), vchDecrypted2.end()));
if (vchPlaintext.size())
BOOST_CHECK(CKeyingMaterial(vchPlaintext.begin(), vchPlaintext.end()) == vchDecrypted2);
}
static void TestEncryptSingle(const CCrypter& crypt, const CKeyingMaterial& vchPlaintext,
const std::vector<unsigned char>& vchCiphertextCorrect = std::vector<unsigned char>())
{
std::vector<unsigned char> vchCiphertext1;
std::vector<unsigned char> vchCiphertext2;
int result1 = crypt.Encrypt(vchPlaintext, vchCiphertext1);
int result2 = OldEncrypt(vchPlaintext, vchCiphertext2, crypt.vchKey.data(), crypt.vchIV.data());
BOOST_CHECK(result1 == result2);
BOOST_CHECK(vchCiphertext1 == vchCiphertext2);
if (!vchCiphertextCorrect.empty())
BOOST_CHECK(vchCiphertext2 == vchCiphertextCorrect);
const std::vector<unsigned char> vchPlaintext2(vchPlaintext.begin(), vchPlaintext.end());
if(vchCiphertext1 == vchCiphertext2)
TestDecrypt(crypt, vchCiphertext1, vchPlaintext2);
}
static void TestEncrypt(const CCrypter& crypt, const std::vector<unsigned char>& vchPlaintextIn, \
const std::vector<unsigned char>& vchCiphertextCorrect = std::vector<unsigned char>())
{
TestEncryptSingle(crypt, CKeyingMaterial(vchPlaintextIn.begin(), vchPlaintextIn.end()), vchCiphertextCorrect);
for(std::vector<unsigned char>::const_iterator i(vchPlaintextIn.begin()); i != vchPlaintextIn.end(); ++i)
TestEncryptSingle(crypt, CKeyingMaterial(i, vchPlaintextIn.end()));
}
};
BOOST_AUTO_TEST_CASE(passphrase) {
// These are expensive.
TestCrypter::TestPassphrase(ParseHex("0000deadbeef0000"), "test", 25000, \
ParseHex("fc7aba077ad5f4c3a0988d8daa4810d0d4a0e3bcb53af662998898f33df0556a"), \
ParseHex("cf2f2691526dd1aa220896fb8bf7c369"));
std::string hash(GetRandHash().ToString());
std::vector<unsigned char> vchSalt(8);
GetRandBytes(&vchSalt[0], vchSalt.size());
uint32_t rounds = insecure_rand();
if (rounds > 30000)
rounds = 30000;
TestCrypter::TestPassphrase(vchSalt, SecureString(hash.begin(), hash.end()), rounds);
}
BOOST_AUTO_TEST_CASE(encrypt) {
std::vector<unsigned char> vchSalt = ParseHex("0000deadbeef0000");
BOOST_CHECK(vchSalt.size() == WALLET_CRYPTO_SALT_SIZE);
CCrypter crypt;
crypt.SetKeyFromPassphrase("passphrase", vchSalt, 25000, 0);
TestCrypter::TestEncrypt(crypt, ParseHex("22bcade09ac03ff6386914359cfe885cfeb5f77ff0d670f102f619687453b29d"));
for (int i = 0; i != 100; i++)
{
uint256 hash(GetRandHash());
TestCrypter::TestEncrypt(crypt, std::vector<unsigned char>(hash.begin(), hash.end()));
}
}
BOOST_AUTO_TEST_CASE(decrypt) {
std::vector<unsigned char> vchSalt = ParseHex("0000deadbeef0000");
BOOST_CHECK(vchSalt.size() == WALLET_CRYPTO_SALT_SIZE);
CCrypter crypt;
crypt.SetKeyFromPassphrase("passphrase", vchSalt, 25000, 0);
// Some corner cases the came up while testing
TestCrypter::TestDecrypt(crypt,ParseHex("795643ce39d736088367822cdc50535ec6f103715e3e48f4f3b1a60a08ef59ca"));
TestCrypter::TestDecrypt(crypt,ParseHex("de096f4a8f9bd97db012aa9d90d74de8cdea779c3ee8bc7633d8b5d6da703486"));
TestCrypter::TestDecrypt(crypt,ParseHex("32d0a8974e3afd9c6c3ebf4d66aa4e6419f8c173de25947f98cf8b7ace49449c"));
TestCrypter::TestDecrypt(crypt,ParseHex("e7c055cca2faa78cb9ac22c9357a90b4778ded9b2cc220a14cea49f931e596ea"));
TestCrypter::TestDecrypt(crypt,ParseHex("b88efddd668a6801d19516d6830da4ae9811988ccbaf40df8fbb72f3f4d335fd"));
TestCrypter::TestDecrypt(crypt,ParseHex("8cae76aa6a43694e961ebcb28c8ca8f8540b84153d72865e8561ddd93fa7bfa9"));
for (int i = 0; i != 100; i++)
{
uint256 hash(GetRandHash());
TestCrypter::TestDecrypt(crypt, std::vector<unsigned char>(hash.begin(), hash.end()));
}
}
BOOST_AUTO_TEST_CASE(aes_256_cbc_testvectors) {
// NIST AES CBC 256-bit encryption test-vectors with padding enabled
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"000102030405060708090A0B0C0D0E0F", "6bc1bee22e409f96e93d7e117393172a", \
"f58c4c04d6e5f1ba779eabfb5f7bfbd6485a5c81519cf378fa36d42b8547edc0");
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"F58C4C04D6E5F1BA779EABFB5F7BFBD6", "ae2d8a571e03ac9c9eb76fac45af8e51", \
"9cfc4e967edb808d679f777bc6702c7d3a3aa5e0213db1a9901f9036cf5102d2");
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"9CFC4E967EDB808D679F777BC6702C7D", "30c81c46a35ce411e5fbc1191a0a52ef",
"39f23369a9d9bacfa530e263042314612f8da707643c90a6f732b3de1d3f5cee");
TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \
"39F23369A9D9BACFA530E26304231461", "f69f2445df4f9b17ad2b417be66c3710", \
"b2eb05e2c39be9fcda6c19078c6a9d1b3f461796d6b0d6b2e0c2a72b4d80e644");
}
BOOST_AUTO_TEST_SUITE_END()
| [
"dmitriy@Dmitriys-iMac.local"
] | dmitriy@Dmitriys-iMac.local |
48d55f1e66a998ce4551816934b1cd84d08b97e3 | 27cc1f42abe141bb4904da58a58e760ced937dde | /potdoga.cpp | 624c9f139cd930e9d4fa859cfc2c0253cfe70f61 | [] | no_license | Berci99/elsoCPP | 040c728c6aa08f5b5931e18c47d60e628ca0038a | e7e43c2e83b1e7cbbed09b4ad3938181da9a7af8 | refs/heads/master | 2020-03-19T03:10:08.986787 | 2019-03-25T12:45:46 | 2019-03-25T12:45:46 | 135,701,583 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,067 | cpp | /******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <iostream>
using namespace std;
class Dino{
int meret;
public:
Dino(){}
Dino(int _meret){
meret=_meret;
}
int getMeret(){return meret;}
void setMeret(int ujmeret){meret=ujmeret;}
void toString(){
std::cout << getMeret() << " meter " << std::endl;
}
};
class Futodino : public Dino{
int labak;
public:
Futodino(){}
Futodino(int meret, int _labak):Dino(meret){
labak=_labak;
}
int getLabak(){return labak;}
void setLabak(int ujlabak){labak=ujlabak;}
void toString(){
std::cout << "meret: " << getMeret() << " labak: " << getLabak() << std::endl;
}
};
class Repulodino : public Dino{
int szarnyak;
public:
Repulodino(){}
Repulodino(int meret, int _szarnyak):Dino(meret){
szarnyak=_szarnyak;
}
int getSzarnyak(){return szarnyak;}
void setSzarnyak(int ujszarnyak){szarnyak=ujszarnyak;}
void toString(){
std::cout << "meret: " << getMeret() << " szarnyak: " << getSzarnyak() << std::endl;
}
};
class Ketrec{
Dino lako;
int szam;
public:
Ketrec (int _meret, int _szam){
szam=_szam;
lako.setMeret(_meret);
}
int getSzam(){return szam;}
void setSzam(int ujszam){szam=ujszam;}
void toString (){
std::cout << "meret: " << lako.getMeret()<< " szam: " << getSzam() << std::endl;
}
};
int main()
{
Futodino fold(20, 3);
fold.toString();
Repulodino eg(15, 2);
eg.toString();
Dino l(30);
l.toString();
Ketrec ket(4,6);
ket.toString();
}
| [
"noreply@github.com"
] | noreply@github.com |
29279fc2a5dbcd117a3381b7599fd878806f054e | d0214e3209449b2e4875c532e72b34de447683e1 | /autotype.cpp | c1c9a4b9917f3828e45b224444c053aed88521e9 | [] | no_license | gergalerg/cloaked-octo-nemesis | b3bf04adb208beff1c0fc912a0c335881ffcdeb0 | 72ddad9a00c03dbd7991407a2d6850e7496fba6c | refs/heads/master | 2020-06-05T05:36:02.628733 | 2015-10-07T23:48:27 | 2015-10-07T23:48:27 | 12,652,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 804 | cpp | #include <iostream>
#include <vector>
using namespace std;
template<typename T>
void printall(vector<T> v)
{
for (auto p = v.begin(); p != v.end(); ++p)
cout << *p << "\t";
cout << "\n";
}
template<typename T, typename U>
void multiply(const vector<T>& vt, const vector<U>& vu)
{
vector<T> vtemp;
for (int i=0; i < vt.size(); ++i)
{
auto tmp = vt[i] * vu[i];
vtemp.push_back(tmp);
}
for (auto x: vtemp) cout << x << "\t";
}
struct X {
int x,y;
int operator()(int t) { return t; }
void f() {
[=]() -> int {
return operator()(this->x + y);
};
}
};
int main()
{
vector<double> h = {1,2,3,4,5};
printall(h);
multiply(h,h);
cout << "\n";
X x;
x.x = 3;
x.y = 4;
x.f();
} | [
"gregspace@gmail.com"
] | gregspace@gmail.com |
4f99cf04b43e9fd71847b86de630c32c5ffabfe3 | b301ab714ad4d4625d4a79005a1bda6456a283ec | /UVa/10596.cpp | 21aa22d513bd4a254ea200188f303ef7f1a6611f | [] | no_license | askeySnip/OJ_records | 220fd83d406709328e8450df0f6da98ae57eb2d9 | 4b77e3bb5cf19b98572fa6583dff390e03ff1a7c | refs/heads/master | 2022-06-26T02:14:34.957580 | 2022-06-11T13:56:33 | 2022-06-11T13:56:33 | 117,955,514 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,330 | cpp | /*
ID: leezhen
TASK: practice
LANG: C++11
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
#include <bitset>
#include <list>
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<pair<int, int> > vii;
typedef long long ll;
// struct
#define inf 1e9
// data
int n, r;
int deg[205];
vi edges[205];
int vist[205];
void dfs(int u) {
vist[u] = 1;
for(int i=0; i<(int)edges[u].size(); i++) {
int v = edges[u][i];
if(!vist[v]) dfs(v);
}
}
int main() {
while(scanf("%d %d", &n, &r) == 2) {
int a, b;
memset(deg, 0, sizeof deg);
for(int i=0; i<205; i++) edges[i].clear();
memset(vist, 0, sizeof vist);
for(int i=0; i<r; i++) {
scanf("%d %d", &a, &b);
deg[a]++; deg[b]++;
edges[a].push_back(b);
edges[b].push_back(a);
}
int c = 0;
for(int i=0; i<n; i++) {
if(deg[i]&1) {
c++;
}
}
bool flag = true;
dfs(a);
for(int i=0; i<n; i++) {
if(!vist[i] && deg[i] > 0) {
flag = false;
break;
}
}
if(r > 0 && c == 0 && flag) printf("Possible\n");
else printf("Not Possible\n");
}
return 0;
}
| [
"296181278@qq.com"
] | 296181278@qq.com |
e781a0955c41c02af5db98448e213288171dfb8a | b0673fad76139aba3153353ce83c5718e9409952 | /src/main.cpp | 2d500ebd14a8f61e0cff0f2ae6fe0f549178fc0e | [
"MIT"
] | permissive | franklee1/lastday | 175add084cb47399f2ff85313653b86cb68ba639 | dff92d05f40eac3ea676d86c007de25748b8e859 | refs/heads/master | 2020-03-16T02:27:18.038778 | 2018-05-07T13:34:30 | 2018-05-07T13:34:30 | 132,465,292 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 134,064 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "alert.h"
#include "checkpoints.h"
#include "db.h"
#include "txdb.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include "kernel.h"
#include "zerocoin/Zerocoin.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace std;
using namespace boost;
//
// Global state
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
map<uint256, CBlockIndex*> mapBlockIndex;
set<pair<COutPoint, unsigned int> > setStakeSeen;
libzerocoin::Params* ZCParams;
CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
CBigNum bnProofOfStakeLimit(~uint256(0) >> 20);
CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
unsigned int nTargetSpacing = 1 * 60; // 10 minutes
unsigned int nTargetSpacing_v2 = 5 * 60; // 5 minutes
unsigned int nStakeMinAge = 24 * 60 * 60;
unsigned int nStakeMaxAge = 96 * 60 * 60;
unsigned int nModifierInterval = 10 * 60; // time to elapse before new modifier is computed
int nCoinbaseMaturity = 10;
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
uint256 nBestChainTrust = 0;
uint256 nBestInvalidTrust = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64_t nTimeBestReceived = 0;
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
map<uint256, CTransaction> mapOrphanTransactions;
map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "bigboxcoin Signed Message:\n";
// Settings
int64_t nTransactionFee = MIN_TX_FEE;
int64_t nReserveBalance = 0;
int64_t nMinimumInputValue = 0;
extern enum Checkpoints::CPMode CheckpointsMode;
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
void RegisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.insert(pwalletIn);
}
}
void UnregisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.erase(pwalletIn);
}
}
// check whether the passed transaction is from us
bool static IsFromMe(CTransaction& tx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
return true;
return false;
}
// get the wallet transaction with the given hash (if it exists)
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->GetTransaction(hashTx,wtx))
return true;
return false;
}
// erases transaction with the given hash from all wallets
void static EraseFromWallets(uint256 hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->EraseFromWallet(hash);
}
// make sure all wallets know about the given transaction, in the given block
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
{
if (!fConnect)
{
// ppcoin: wallets need to refund inputs when disconnecting coinstake
if (tx.IsCoinStake())
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
pwallet->DisableTransaction(tx);
}
return;
}
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
}
// notify wallets about a new best chain
void static SetBestChain(const CBlockLocator& loc)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->SetBestChain(loc);
}
// notify wallets about an updated transaction
void static UpdatedTransaction(const uint256& hashTx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->UpdatedTransaction(hashTx);
}
// dump all wallets
void static PrintWallets(const CBlock& block)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->PrintWallet(block);
}
// notify wallets about an incoming inventory (for request counts)
void static Inventory(const uint256& hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->Inventory(hash);
}
// ask wallets to resend their transactions
void ResendWalletTransactions(bool fForce)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions(fForce);
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CTransaction& tx)
{
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (nSize > 5000)
{
printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
return false;
}
mapOrphanTransactions[hash] = tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
if (!mapOrphanTransactions.count(hash))
return;
const CTransaction& tx = mapOrphanTransactions[hash];
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
}
mapOrphanTransactions.erase(hash);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction and CTxIndex
//
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
{
SetNull();
if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
return false;
if (!ReadFromDisk(txindexRet.pos))
return false;
if (prevout.n >= vout.size())
{
SetNull();
return false;
}
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
{
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::ReadFromDisk(COutPoint prevout)
{
CTxDB txdb("r");
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool IsStandardTx(const CTransaction& tx)
{
if (tx.nVersion > CTransaction::CURRENT_VERSION)
return false;
// Treat non-final transactions as non-standard to prevent a specific type
// of double-spend attack, as well as DoS attacks. (if the transaction
// can't be mined, the attacker isn't expending resources broadcasting it)
// Basically we don't want to propagate transactions that can't included in
// the next block.
//
// However, IsFinalTx() is confusing... Without arguments, it uses
// chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height()
// is set to the value of nHeight in the block. However, when IsFinalTx()
// is called within CBlock::AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a transaction can
// be part of the *next* block, we need to call IsFinalTx() with one more
// than chainActive.Height().
//
// Timestamps on the other hand don't get any special treatment, because we
// can't know what timestamp the next block will have, and there aren't
// timestamp applications where it matters.
if (!IsFinalTx(tx, nBestHeight + 1)) {
return false;
}
// nTime has different purpose from nLockTime but can be used in similar attacks
if (tx.nTime > FutureDrift(GetAdjustedTime())) {
return false;
}
// Extremely large transactions with lots of inputs can cost the network
// almost as much to process as they cost the sender in fees, because
// computing signature hashes is O(ninputs*txsize). Limiting transactions
// to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (sz >= MAX_STANDARD_TX_SIZE)
return false;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
// pay-to-script-hash, which is 3 ~80-byte signatures, 3
// ~65-byte public keys, plus a few script ops.
if (txin.scriptSig.size() > 500)
return false;
if (!txin.scriptSig.IsPushOnly())
return false;
if (fEnforceCanonical && !txin.scriptSig.HasCanonicalPushes()) {
return false;
}
}
unsigned int nDataOut = 0;
txnouttype whichType;
BOOST_FOREACH(const CTxOut& txout, tx.vout) {
if (!::IsStandard(txout.scriptPubKey, whichType))
return false;
if (whichType == TX_NULL_DATA)
nDataOut++;
if (txout.nValue == 0)
return false;
if (fEnforceCanonical && !txout.scriptPubKey.HasCanonicalPushes()) {
return false;
}
}
// only one OP_RETURN txout is permitted
if (nDataOut > 1) {
return false;
}
return true;
}
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
{
AssertLockHeld(cs_main);
// Time based nLockTime implemented in 0.1.6
if (tx.nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = nBestHeight;
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
if (!txin.IsFinal())
return false;
return true;
}
//
// Check transaction inputs, and make sure any
// pay-to-script-hash transactions are evaluating IsStandard scripts
//
// Why bother? To avoid denial-of-service attacks; an attacker
// can submit a standard HASH... OP_EQUAL transaction,
// which will get accepted into blocks. The redemption
// script can be anything; an attacker could use a very
// expensive-to-check-upon-redemption script like:
// DUP CHECKSIG DROP ... repeated 100 times... OP_1
//
bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
{
if (IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
return false;
if (whichType == TX_SCRIPTHASH)
{
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (!Solver(subscript, whichType2, vSolutions2))
return false;
if (whichType2 == TX_SCRIPTHASH)
return false;
int tmpExpected;
tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int
CTransaction::GetLegacySigOpCount() const
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
AssertLockHeld(cs_main);
CBlock blockTmp;
if (pblock == NULL)
{
// Load the block this tx is in
CTxIndex txindex;
if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
return 0;
if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
return 0;
pblock = &blockTmp;
}
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CTransaction::CheckTransaction() const
{
// Basic checks that don't depend on any context
if (vin.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64_t nValueOut = 0;
for (unsigned int i = 0; i < vout.size(); i++)
{
const CTxOut& txout = vout[i];
if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
if (txout.nValue < 0)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
if (txout.nValue > MAX_MONEY)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return false;
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
int64_t CTransaction::GetMinFee(unsigned int nBlockSize, enum GetMinFee_mode mode, unsigned int nBytes) const
{
// Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
int64_t nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
unsigned int nNewBlockSize = nBlockSize + nBytes;
int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
// To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
if (nMinFee < nBaseFee)
{
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT)
nMinFee = nBaseFee;
}
// Raise the price as the block approaches full
if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
{
if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
return MAX_MONEY;
nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
}
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}
bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx,
bool* pfMissingInputs)
{
AssertLockHeld(cs_main);
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("AcceptToMemoryPool : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("AcceptToMemoryPool : coinbase as individual tx"));
// ppcoin: coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return tx.DoS(100, error("AcceptToMemoryPool : coinstake as individual tx"));
// Rather not work on nonstandard transactions (unless -testnet)
if (!fTestNet && !IsStandardTx(tx))
return error("AcceptToMemoryPool : nonstandard transaction type");
// is it already in the memory pool?
uint256 hash = tx.GetHash();
if (pool.exists(hash))
return false;
// Check for conflicts with in-memory transactions
CTransaction* ptxOld = NULL;
{
LOCK(pool.cs); // protect pool.mapNextTx
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (pool.mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
// Allow replacing with a newer version of the same transaction
if (i != 0)
return false;
ptxOld = pool.mapNextTx[outpoint].ptx;
if (IsFinalTx(*ptxOld))
return false;
if (!tx.IsNewerThan(*ptxOld))
return false;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (!pool.mapNextTx.count(outpoint) || pool.mapNextTx[outpoint].ptx != ptxOld)
return false;
}
break;
}
}
}
{
CTxDB txdb("r");
// do we already have it?
if (txdb.ContainsTx(hash))
return false;
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("AcceptToMemoryPool : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
// Check for non-standard pay-to-script-hash in inputs
if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
return error("AcceptToMemoryPool : nonstandard transaction input");
// Note: if you modify this code to accept non-standard transactions, then
// you should add code here to check that the transaction does a
// reasonable number of ECDSA signature verifications.
int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
int64_t txMinFee = tx.GetMinFee(1000, GMF_RELAY, nSize);
if (nFees < txMinFee)
return error("AcceptToMemoryPool : not enough fees %s, %"PRId64" < %"PRId64,
hash.ToString().c_str(),
nFees, txMinFee);
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection cs;
static double dFreeCount;
static int64_t nLastTime;
int64_t nNow = GetTime();
{
LOCK(pool.cs);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
return error("AcceptToMemoryPool : free transaction rejected by rate limiter");
if (fDebug)
printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
{
return error("AcceptToMemoryPool : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
}
}
// Store transaction in memory
{
LOCK(pool.cs);
if (ptxOld)
{
printf("AcceptToMemoryPool : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
pool.remove(*ptxOld);
}
pool.addUnchecked(hash, tx);
}
///// are we sure this is ok when loading transactions or restoring block txes
// If updated, erase old tx from wallet
if (ptxOld)
EraseFromWallets(ptxOld->GetHash());
printf("AcceptToMemoryPool : accepted %s (poolsz %"PRIszu")\n",
hash.ToString().substr(0,10).c_str(),
pool.mapTx.size());
return true;
}
bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
{
// Add to memory pool without checking anything. Don't call this directly,
// call AcceptToMemoryPool to properly check the transaction first.
{
mapTx[hash] = tx;
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
nTransactionsUpdated++;
}
return true;
}
bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive)
{
// Remove transaction from memory pool
{
LOCK(cs);
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
{
if (fRecursive) {
for (unsigned int i = 0; i < tx.vout.size(); i++) {
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
if (it != mapNextTx.end())
remove(*it->second.ptx, true);
}
}
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
return true;
}
bool CTxMemPool::removeConflicts(const CTransaction &tx)
{
// Remove transactions which depend on inputs of tx, recursively
LOCK(cs);
BOOST_FOREACH(const CTxIn &txin, tx.vin) {
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
if (it != mapNextTx.end()) {
const CTransaction &txConflict = *it->second.ptx;
if (txConflict != tx)
remove(txConflict, true);
}
}
return true;
}
void CTxMemPool::clear()
{
LOCK(cs);
mapTx.clear();
mapNextTx.clear();
++nTransactionsUpdated;
}
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
int CMerkleTx::GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
AssertLockHeld(cs_main);
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
AssertLockHeld(cs_main);
int nResult = GetDepthInMainChainINTERNAL(pindexRet);
if (nResult == 0 && !mempool.exists(GetHash()))
return -1; // Not in chain, not in mempool
return nResult;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
return max(0, (nCoinbaseMaturity+0) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool()
{
return ::AcceptToMemoryPool(mempool, *this, NULL);
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb)
{
{
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
tx.AcceptToMemoryPool();
}
}
return AcceptToMemoryPool();
}
return false;
}
bool CWalletTx::AcceptWalletTransaction()
{
CTxDB txdb("r");
return AcceptWalletTransaction(txdb);
}
int CTxIndex::GetDepthInMainChain() const
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return 1 + nBestHeight - pindex->nHeight;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
{
{
LOCK(cs_main);
{
if (mempool.lookup(hash, tx))
{
return true;
}
}
CTxDB txdb("r");
CTxIndex txindex;
if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
{
CBlock block;
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
hashBlock = block.GetHash();
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
static CBlockIndex* pblockindexFBBHLast;
CBlockIndex* FindBlockByHeight(int nHeight)
{
CBlockIndex *pblockindex;
if (nHeight < nBestHeight / 2)
pblockindex = pindexGenesisBlock;
else
pblockindex = pindexBest;
if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
pblockindex = pblockindexFBBHLast;
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
while (pblockindex->nHeight < nHeight)
pblockindex = pblockindex->pnext;
pblockindexFBBHLast = pblockindex;
return pblockindex;
}
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
{
if (!fReadTransactions)
{
*this = pindex->GetBlockHeader();
return true;
}
if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
uint256 static GetOrphanRoot(const CBlock* pblock)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
return pblock->GetHash();
}
// ppcoin: find block wanted by given orphan block
uint256 WantedByOrphan(const CBlock* pblockOrphan)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
return pblockOrphan->hashPrevBlock;
}
// miner's coin base reward
int64_t GetProofOfWorkReward(int nHeight, int64_t nFees)
{
int64_t nSubsidy = 1 * COIN;
if(nBestHeight <= 15)
{
nSubsidy = 999999997 * COIN;
}
else if(nBestHeight <= 10000)
{
nSubsidy = 1 * COIN;
}
else if(nBestHeight <= 10001)
{
nSubsidy >>= nSubsidy /10000;
}
else if(nBestHeight > 10001)
{
nSubsidy >>= (nHeight / 10000); //
}
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfWorkReward() : create=%s nSubsidy=%"PRId64"\n", FormatMoney(nSubsidy).c_str(), nSubsidy);
return nSubsidy + nFees;
}
// miner's coin stake reward based on coin age spent (coin-days)
int64_t GetProofOfStakeReward(int nHeight, int64_t nCoinAge, int64_t nFees)
{
int64_t nSubsidy = nCoinAge * COIN_YEAR_REWARD * 33 / (365 * 33 + 8);
if(nBestHeight <= 10)
{
nSubsidy >>= nSubsidy /100000; //no pos
}
else if(nBestHeight <= 1000000001)
{
nSubsidy = nSubsidy * 1/2 ; //
}
if (fDebug && GetBoolArg("-printcreation"))
printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRId64"\n", FormatMoney(nSubsidy).c_str(), nCoinAge);
return nSubsidy + nFees;
}
static const int64_t nTargetTimespan_v1 = 16 * 60; // 16 mins
static const int64_t nTargetTimespan_v2 = 60 * 60; // 60 mins
unsigned int nTargetTimespan = nTargetTimespan_v1;
//
// maximum nBits value could possible be required nTime after
//
unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
{
CBigNum bnResult;
bnResult.SetCompact(nBase);
bnResult *= 2;
while (nTime > 0 && bnResult < bnTargetLimit)
{
// Maximum 200% adjustment per day...
bnResult *= 2;
nTime -= 24 * 60 * 60;
}
if (bnResult > bnTargetLimit)
bnResult = bnTargetLimit;
return bnResult.GetCompact();
}
//
// minimum amount of work that could possibly be required nTime after
// minimum proof-of-work required was nBase
//
unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
{
return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
}
//
// minimum amount of stake that could possibly be required nTime after
// minimum proof-of-stake required was nBase
//
unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
{
return ComputeMaxBits(bnProofOfStakeLimit, nBase, nTime);
}
// ppcoin: find last block index up to pindex
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
{
while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
pindex = pindex->pprev;
return pindex;
}
static unsigned int GetNextTargetRequiredV1(const CBlockIndex* pindexLast, bool fProofOfStake)
{
CBigNum bnTargetLimit = fProofOfStake ? bnProofOfStakeLimit : bnProofOfWorkLimit;
if (pindexLast == NULL)
return bnTargetLimit.GetCompact(); // genesis block
const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
if (pindexPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // first block
const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
if (pindexPrevPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // second block
int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
// ppcoin: target change every block
// ppcoin: retarget with exponential moving toward target spacing
CBigNum bnNew;
bnNew.SetCompact(pindexPrev->nBits);
int64_t nInterval = nTargetTimespan / nTargetSpacing;
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
bnNew /= ((nInterval + 1) * nTargetSpacing);
if (bnNew > bnTargetLimit)
bnNew = bnTargetLimit;
return bnNew.GetCompact();
}
static unsigned int GetNextTargetRequiredV2(const CBlockIndex* pindexLast, bool fProofOfStake)
{
if (pindexBest->nHeight+1 >= 10000)
{
nTargetSpacing = nTargetSpacing_v2;
}
else
{
nTargetSpacing = nTargetSpacing;
}
if (pindexBest->nHeight+1 >= 10000)
{
nTargetTimespan = nTargetTimespan_v2;
}
else
{
nTargetTimespan = nTargetTimespan_v1;
}
CBigNum bnTargetLimit = fProofOfStake ? bnProofOfStakeLimit : bnProofOfWorkLimit;
if (pindexLast == NULL)
return bnTargetLimit.GetCompact(); // genesis block
const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
if (pindexPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // first block
const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
if (pindexPrevPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // second block
int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
if (nActualSpacing < 0)
nActualSpacing = nTargetSpacing;
// ppcoin: target change every block
// ppcoin: retarget with exponential moving toward target spacing
CBigNum bnNew;
bnNew.SetCompact(pindexPrev->nBits);
int64_t nInterval = nTargetTimespan / nTargetSpacing;
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
bnNew /= ((nInterval + 1) * nTargetSpacing);
if (bnNew <= 0 || bnNew > bnTargetLimit)
bnNew = bnTargetLimit;
return bnNew.GetCompact();
}
unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
{
if (pindexLast->nHeight < 10000)
return GetNextTargetRequiredV1(pindexLast, fProofOfStake);
else
return GetNextTargetRequiredV2(pindexLast, fProofOfStake);
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
// Return maximum amount of blocks that other nodes claim to have
int GetNumBlocksOfPeers()
{
return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
}
bool IsInitialBlockDownload()
{
LOCK(cs_main);
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64_t nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 15 &&
pindexBest->GetBlockTime() < GetTime() - 8 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->nChainTrust > nBestInvalidTrust)
{
nBestInvalidTrust = pindexNew->nChainTrust;
CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
uiInterface.NotifyBlocksChanged();
}
uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRId64" date=%s\n",
pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRId64" date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
CBigNum(pindexBest->nChainTrust).ToString().c_str(),
nBestBlockTrust.Get64(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(GetBlockTime(), GetAdjustedTime());
}
bool CTransaction::DisconnectInputs(CTxDB& txdb)
{
// Relinquish previous transactions' spent pointers
if (!IsCoinBase())
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
COutPoint prevout = txin.prevout;
// Get prev txindex from disk
CTxIndex txindex;
if (!txdb.ReadTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : ReadTxIndex failed");
if (prevout.n >= txindex.vSpent.size())
return error("DisconnectInputs() : prevout.n out of range");
// Mark outpoint as not spent
txindex.vSpent[prevout.n].SetNull();
// Write back
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : UpdateTxIndex failed");
}
}
// Remove transaction from index
// This can fail if a duplicate of this transaction was in a chain that got
// reorganized away. This is only possible if this transaction was completely
// spent, so erasing it would be a no-op anyway.
txdb.EraseTxIndex(*this);
return true;
}
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
{
// FetchInputs can return false either because we just haven't seen some inputs
// (in which case the transaction should be stored as an orphan)
// or because the transaction is malformed (in which case the transaction should
// be dropped). If tx is definitely invalid, fInvalid will be set to true.
fInvalid = false;
if (IsCoinBase())
return true; // Coinbase transactions have no inputs to fetch.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
if (inputsRet.count(prevout.hash))
continue; // Got it already
// Read txindex
CTxIndex& txindex = inputsRet[prevout.hash].first;
bool fFound = true;
if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
{
// Get txindex from current proposed changes
txindex = mapTestPool.find(prevout.hash)->second;
}
else
{
// Read txindex from txdb
fFound = txdb.ReadTxIndex(prevout.hash, txindex);
}
if (!fFound && (fBlock || fMiner))
return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
// Read txPrev
CTransaction& txPrev = inputsRet[prevout.hash].second;
if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
{
// Get prev tx from single transactions in memory
if (!mempool.lookup(prevout.hash, txPrev))
return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
if (!fFound)
txindex.vSpent.resize(txPrev.vout.size());
}
else
{
// Get prev tx from disk
if (!txPrev.ReadFromDisk(txindex.pos))
return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
}
}
// Make sure all prevout.n indexes are valid:
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint prevout = vin[i].prevout;
assert(inputsRet.count(prevout.hash) != 0);
const CTxIndex& txindex = inputsRet[prevout.hash].first;
const CTransaction& txPrev = inputsRet[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
{
// Revisit this if/when transaction replacement is implemented and allows
// adding inputs:
fInvalid = true;
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
}
}
return true;
}
const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
{
MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
if (mi == inputs.end())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
const CTransaction& txPrev = (mi->second).second;
if (input.prevout.n >= txPrev.vout.size())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
return txPrev.vout[input.prevout.n];
}
int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
int64_t nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
nResult += GetOutputFor(vin[i], inputs).nValue;
}
return nResult;
}
unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prevout = GetOutputFor(vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
}
return nSigOps;
}
bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner)
{
// Take over previous transactions' spent pointers
// fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
// fMiner is true when called from the internal bitcoin miner
// ... both are false when called from CTransaction::AcceptToMemoryPool
if (!IsCoinBase())
{
int64_t nValueIn = 0;
int64_t nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
// If prev is coinbase or coinstake, check that it's matured
if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
// ppcoin: check transaction timestamp
if (txPrev.nTime > nTime)
return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
// Check for negative or overflow input values
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return DoS(100, error("ConnectInputs() : txin values out of range"));
}
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
// Check for conflicts (double-spend)
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!txindex.vSpent[prevout.n].IsNull())
return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
// Skip ECDSA signature verification when connecting blocks (fBlock=true)
// before the last blockchain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
{
// Verify signature
if (!VerifySignature(txPrev, *this, i, 0))
{
return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
}
}
// Mark outpoints as spent
txindex.vSpent[prevout.n] = posThisTx;
// Write back
if (fBlock || fMiner)
{
mapTestPool[prevout.hash] = txindex;
}
}
if (!IsCoinStake())
{
if (nValueIn < GetValueOut())
return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
// Tally transaction fees
int64_t nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
// enforce transaction fees for every block
if (nTxFee < GetMinFee())
return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false;
nFees += nTxFee;
if (!MoneyRange(nFees))
return DoS(100, error("ConnectInputs() : nFees out of range"));
}
}
return true;
}
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Disconnect in reverse order
for (int i = vtx.size()-1; i >= 0; i--)
if (!vtx[i].DisconnectInputs(txdb))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = 0;
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("DisconnectBlock() : WriteBlockIndex failed");
}
// ppcoin: clean up wallet after disconnecting coinstake
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, false, false);
return true;
}
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
{
// Check it again in case a previous version let a bad block in, but skip BlockSig checking
if (!CheckBlock(!fJustCheck, !fJustCheck, false))
return false;
//// issue here: it doesn't know the version
unsigned int nTxPos;
if (fJustCheck)
// FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
// Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from
nTxPos = 1;
else
nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
int64_t nFees = 0;
int64_t nValueIn = 0;
int64_t nValueOut = 0;
int64_t nStakeReward = 0;
unsigned int nSigOps = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
{
uint256 hashTx = tx.GetHash();
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes in their
// initial block download.
CTxIndex txindexOld;
if (txdb.ReadTxIndex(hashTx, txindexOld)) {
BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
if (pos.IsNull())
return false;
}
nSigOps += tx.GetLegacySigOpCount();
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
if (!fJustCheck)
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
MapPrevTx mapInputs;
if (tx.IsCoinBase())
nValueOut += tx.GetValueOut();
else
{
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
return false;
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
int64_t nTxValueIn = tx.GetValueIn(mapInputs);
int64_t nTxValueOut = tx.GetValueOut();
nValueIn += nTxValueIn;
nValueOut += nTxValueOut;
if (!tx.IsCoinStake())
nFees += nTxValueIn - nTxValueOut;
if (tx.IsCoinStake())
nStakeReward = nTxValueOut - nTxValueIn;
if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false))
return false;
}
mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
}
if (IsProofOfWork())
{
int64_t nReward = GetProofOfWorkReward(pindex->nHeight, nFees);
// Check coinbase reward
if (vtx[0].GetValueOut() > nReward)
return DoS(50, error("ConnectBlock() : coinbase reward exceeded (actual=%"PRId64" vs calculated=%"PRId64")",
vtx[0].GetValueOut(),
nReward));
}
if (IsProofOfStake())
{
// ppcoin: coin stake tx earns reward instead of paying fee
uint64_t nCoinAge;
if (!vtx[1].GetCoinAge(txdb, nCoinAge))
return error("ConnectBlock() : %s unable to get coin age for coinstake", vtx[1].GetHash().ToString().substr(0,10).c_str());
int64_t nCalculatedStakeReward = GetProofOfStakeReward(pindex->nHeight, nCoinAge, nFees);
if (nStakeReward > nCalculatedStakeReward)
return DoS(100, error("ConnectBlock() : coinstake pays too much(actual=%"PRId64" vs calculated=%"PRId64")", nStakeReward, nCalculatedStakeReward));
}
// ppcoin: track money supply and mint amount info
pindex->nMint = nValueOut - nValueIn + nFees;
pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
return error("Connect() : WriteBlockIndex for pindex failed");
if (fJustCheck)
return true;
// Write queued txindex changes
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
{
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
return error("ConnectBlock() : UpdateTxIndex failed");
}
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = pindex->GetBlockHash();
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("ConnectBlock() : WriteBlockIndex failed");
}
// Watch for transactions paying to me
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, true);
return true;
}
bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
{
printf("REORGANIZE\n");
// Find the fork
CBlockIndex* pfork = pindexBest;
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return error("Reorganize() : plonger->pprev is null");
if (pfork == plonger)
break;
if (!(pfork = pfork->pprev))
return error("Reorganize() : pfork->pprev is null");
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
// Disconnect shorter branch
list<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for disconnect failed");
if (!block.DisconnectBlock(txdb, pindex))
return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
// Queue memory transactions to resurrect.
// We only do this for blocks after the last checkpoint (reorganisation before that
// point should only happen with -reindex/-loadblock, or a misbehaving peer.
BOOST_REVERSE_FOREACH(const CTransaction& tx, block.vtx)
if (!(tx.IsCoinBase() || tx.IsCoinStake()) && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
vResurrect.push_front(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
for (unsigned int i = 0; i < vConnect.size(); i++)
{
CBlockIndex* pindex = vConnect[i];
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for connect failed");
if (!block.ConnectBlock(txdb, pindex))
{
// Invalid block
return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
}
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
return error("Reorganize() : WriteHashBestChain failed");
// Make sure it's successfully written to disk before changing memory structure
if (!txdb.TxnCommit())
return error("Reorganize() : TxnCommit failed");
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect)
AcceptToMemoryPool(mempool, tx, NULL);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete) {
mempool.remove(tx);
mempool.removeConflicts(tx);
}
printf("REORGANIZE: done\n");
return true;
}
// Called from inside SetBestChain: attaches a block to the new best chain being built
bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
{
uint256 hash = GetHash();
// Adding to current best branch
if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return false;
}
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
// Add to current best branch
pindexNew->pprev->pnext = pindexNew;
// Delete redundant memory transactions
BOOST_FOREACH(CTransaction& tx, vtx)
mempool.remove(tx);
return true;
}
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
{
uint256 hash = GetHash();
if (!txdb.TxnBegin())
return error("SetBestChain() : TxnBegin failed");
if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
{
txdb.WriteHashBestChain(hash);
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
pindexGenesisBlock = pindexNew;
}
else if (hashPrevBlock == hashBestChain)
{
if (!SetBestChainInner(txdb, pindexNew))
return error("SetBestChain() : SetBestChainInner failed");
}
else
{
// the first block in the new chain that will cause it to become the new best chain
CBlockIndex *pindexIntermediate = pindexNew;
// list of blocks that need to be connected afterwards
std::vector<CBlockIndex*> vpindexSecondary;
// Reorganize is costly in terms of db load, as it works in a single db transaction.
// Try to limit how much needs to be done inside
while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
{
vpindexSecondary.push_back(pindexIntermediate);
pindexIntermediate = pindexIntermediate->pprev;
}
if (!vpindexSecondary.empty())
printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return error("SetBestChain() : Reorganize failed");
}
// Connect further blocks
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
{
printf("SetBestChain() : ReadFromDisk failed\n");
break;
}
if (!txdb.TxnBegin()) {
printf("SetBestChain() : TxnBegin 2 failed\n");
break;
}
// errors now are not fatal, we still did a reorganisation to a new chain in a valid way
if (!block.SetBestChainInner(txdb, pindex))
break;
}
}
// Update best block in wallet (so we can detect restored wallets)
bool fIsInitialDownload = IsInitialBlockDownload();
if (!fIsInitialDownload)
{
const CBlockLocator locator(pindexNew);
::SetBestChain(locator);
}
// New best block
hashBestChain = hash;
pindexBest = pindexNew;
pblockindexFBBHLast = NULL;
nBestHeight = pindexBest->nHeight;
nBestChainTrust = pindexNew->nChainTrust;
nTimeBestReceived = GetTime();
nTransactionsUpdated++;
uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRId64" date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
CBigNum(nBestChainTrust).ToString().c_str(),
nBestBlockTrust.Get64(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
// Check the version of the last 100 blocks to see if we need to upgrade:
if (!fIsInitialDownload)
{
int nUpgraded = 0;
const CBlockIndex* pindex = pindexBest;
for (int i = 0; i < 100 && pindex != NULL; i++)
{
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
if (nUpgraded > 100/2)
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
}
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
// ppcoin: total coin age spent in transaction, in the unit of coin-days.
// Only those coins meeting minimum age requirement counts. As those
// transactions not in main chain are not currently indexed so we
// might not find out about their coin age. Older transactions are
// guaranteed to be in main chain by sync-checkpoint. This rule is
// introduced to help nodes establish a consistent view of the coin
// age (trust score) of competing branches.
bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
{
CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
nCoinAge = 0;
if (IsCoinBase())
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// First try finding the previous transaction in database
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
continue; // previous transaction not in main chain
if (nTime < txPrev.nTime)
return false; // Transaction timestamp violation
// Read block header
CBlock block;
if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
return false; // unable to read block of previous transaction
if (block.GetBlockTime() + nStakeMinAge > nTime)
continue; // only count coins meeting min age requirement
int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age nValueIn=%"PRId64" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
}
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
nCoinAge = bnCoinDay.getuint64();
return true;
}
// ppcoin: total coin age spent in block, in the unit of coin-days.
bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
{
nCoinAge = 0;
CTxDB txdb("r");
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uint64_t nTxCoinAge;
if (tx.GetCoinAge(txdb, nTxCoinAge))
nCoinAge += nTxCoinAge;
else
return false;
}
if (nCoinAge == 0) // block coin age minimum 1 coin-day
nCoinAge = 1;
if (fDebug && GetBoolArg("-printcoinage"))
printf("block coin age total nCoinDays=%"PRId64"\n", nCoinAge);
return true;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, const uint256& hashProof)
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
pindexNew->phashBlock = &hash;
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
// ppcoin: compute chain trust score
pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
// ppcoin: compute stake entropy bit for stake modifier
if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit()))
return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
// Record proof hash value
pindexNew->hashProof = hashProof;
// ppcoin: compute stake modifier
uint64_t nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRIx64, pindexNew->nHeight, nStakeModifier);
// Add to mapBlockIndex
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
// Write to disk block index
CTxDB txdb;
if (!txdb.TxnBegin())
return false;
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
if (!txdb.TxnCommit())
return false;
LOCK(cs_main);
// New best
if (pindexNew->nChainTrust > nBestChainTrust)
if (!SetBestChain(txdb, pindexNew))
return false;
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = vtx[0].GetHash();
}
uiInterface.NotifyBlocksChanged();
return true;
}
bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CheckBlock() : size limits failed"));
// Check proof of work matches claimed amount
if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetPoWHash(), nBits))
return DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
return error("CheckBlock() : block timestamp too far in the future");
// First transaction must be coinbase, the rest must not be
if (vtx.empty() || !vtx[0].IsCoinBase())
return DoS(100, error("CheckBlock() : first tx is not coinbase"));
for (unsigned int i = 1; i < vtx.size(); i++)
if (vtx[i].IsCoinBase())
return DoS(100, error("CheckBlock() : more than one coinbase"));
// Check coinbase timestamp
if (GetBlockTime() > FutureDrift((int64_t)vtx[0].nTime))
return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
if (IsProofOfStake())
{
// Coinbase output should be empty if proof-of-stake block
if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
// Second transaction must be coinstake, the rest must not be
if (vtx.empty() || !vtx[1].IsCoinStake())
return DoS(100, error("CheckBlock() : second tx is not coinstake"));
for (unsigned int i = 2; i < vtx.size(); i++)
if (vtx[i].IsCoinStake())
return DoS(100, error("CheckBlock() : more than one coinstake"));
// Check coinstake timestamp
if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64_t)vtx[1].nTime))
return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRId64" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
// NovaCoin: check proof-of-stake block signature
if (fCheckSig && !CheckBlockSignature())
return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
}
// Check transactions
BOOST_FOREACH(const CTransaction& tx, vtx)
{
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
// ppcoin: check transaction timestamp
if (GetBlockTime() < (int64_t)tx.nTime)
return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
}
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
set<uint256> uniqueTx;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uniqueTx.insert(tx.GetHash());
}
if (uniqueTx.size() != vtx.size())
return DoS(100, error("CheckBlock() : duplicate transaction"));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
nSigOps += tx.GetLegacySigOpCount();
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkle root
if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
return true;
}
bool CBlock::AcceptBlock()
{
AssertLockHeld(cs_main);
if (nVersion > CURRENT_VERSION)
return DoS(100, error("AcceptBlock() : reject unknown block version %d", nVersion));
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
int nHeight = pindexPrev->nHeight+1;
if (IsProofOfWork() && nHeight > LAST_POW_BLOCK_V1 && nHeight < POW_RE_ENABLE)
return DoS(100, error("AcceptBlock() : reject proof-of-work at height %d", nHeight));
// Check proof-of-work or proof-of-stake
if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetPastTimeLimit() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!IsFinalTx(tx, nHeight, GetBlockTime()))
return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckHardened(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
uint256 hashProof;
// Verify hash target and signature of coinstake tx
if (IsProofOfStake())
{
uint256 targetProofOfStake;
if (!CheckProofOfStake(vtx[1], nBits, hashProof, targetProofOfStake))
{
printf("WARNING: AcceptBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
return false; // do not error here as we expect this during initial block download
}
}
// PoW is checked in CheckBlock()
if (IsProofOfWork())
{
hashProof = GetPoWHash();
}
bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
// Check that the block satisfies synchronized checkpoint
if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
return error("AcceptBlock() : rejected by synchronized checkpoint");
if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
// Enforce rule that the coinbase starts with serialized block height
CScript expect = CScript() << nHeight;
if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
// Write block to history file
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
return error("AcceptBlock() : out of disk space");
unsigned int nFile = -1;
unsigned int nBlockPos = 0;
if (!WriteToDisk(nFile, nBlockPos))
return error("AcceptBlock() : WriteToDisk failed");
if (!AddToBlockIndex(nFile, nBlockPos, hashProof))
return error("AcceptBlock() : AddToBlockIndex failed");
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
// ppcoin: check pending sync-checkpoint
Checkpoints::AcceptPendingSyncCheckpoint();
return true;
}
uint256 CBlockIndex::GetBlockTrust() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
return ((CBigNum(1)<<256) / (bnTarget+1)).getuint256();
}
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
{
unsigned int nFound = 0;
for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
if (mapOrphanBlocks.count(hash))
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
// ppcoin: check proof-of-stake
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
// Preliminary checks
if (!pblock->CheckBlock())
return error("ProcessBlock() : CheckBlock FAILED");
CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
CBigNum bnNewBlock;
bnNewBlock.SetCompact(pblock->nBits);
CBigNum bnRequired;
if (pblock->IsProofOfStake())
bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
else
bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
if (bnNewBlock > bnRequired)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
}
}
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
// If don't already have its previous block, shunt it off to holding area until we get it
if (!mapBlockIndex.count(pblock->hashPrevBlock))
{
printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
// ppcoin: check proof-of-stake
if (pblock->IsProofOfStake())
{
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
else
setStakeSeenOrphan.insert(pblock->GetProofOfStake());
}
CBlock* pblock2 = new CBlock(*pblock);
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
// Ask this guy to fill in what we're missing
if (pfrom)
{
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
// ppcoin: getblocks may not obtain the ancestor block rejected
// earlier by duplicate-stake check so we ask for it again directly
if (!IsInitialBlockDownload())
pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
}
return true;
}
// Store to disk
if (!pblock->AcceptBlock())
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
CBlock* pblockOrphan = (*mi).second;
if (pblockOrphan->AcceptBlock())
vWorkQueue.push_back(pblockOrphan->GetHash());
mapOrphanBlocks.erase(pblockOrphan->GetHash());
setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
delete pblockOrphan;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
printf("ProcessBlock: ACCEPTED\n");
// ppcoin: if responsible for sync-checkpoint send it
if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
return true;
}
// novacoin: attempt to generate suitable proof-of-stake
bool CBlock::SignBlock(CWallet& wallet, int64_t nFees)
{
// if we are trying to sign
// something except proof-of-stake block template
if (!vtx[0].vout[0].IsEmpty())
return false;
// if we are trying to sign
// a complete proof-of-stake block
if (IsProofOfStake())
return true;
static int64_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
CKey key;
CTransaction txCoinStake;
int64_t nSearchTime = txCoinStake.nTime; // search to current time
if (nSearchTime > nLastCoinStakeSearchTime)
{
if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, nFees, txCoinStake, key))
{
if (txCoinStake.nTime >= max(pindexBest->GetPastTimeLimit()+1, PastDrift(pindexBest->GetBlockTime())))
{
// make sure coinstake would meet timestamp protocol
// as it would be the same as the block timestamp
vtx[0].nTime = nTime = txCoinStake.nTime;
nTime = max(pindexBest->GetPastTimeLimit()+1, GetMaxTransactionTime());
nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
// we have to make sure that we have no future timestamps in
// our transactions set
for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
vtx.insert(vtx.begin() + 1, txCoinStake);
hashMerkleRoot = BuildMerkleTree();
// append a signature to our block
return key.Sign(GetHash(), vchBlockSig);
}
}
nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
nLastCoinStakeSearchTime = nSearchTime;
}
return false;
}
bool CBlock::CheckBlockSignature() const
{
if (IsProofOfWork())
return vchBlockSig.empty();
vector<valtype> vSolutions;
txnouttype whichType;
const CTxOut& txout = vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
valtype& vchPubKey = vSolutions[0];
CKey key;
if (!key.SetPubKey(vchPubKey))
return false;
if (vchBlockSig.empty())
return false;
return key.Verify(GetHash(), vchBlockSig);
}
return false;
}
bool CheckDiskSpace(uint64_t nAdditionalBytes)
{
uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
{
fShutdown = true;
string strMessage = _("Warning: Disk space is low!");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "bigboxcoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
StartShutdown();
return false;
}
return true;
}
static filesystem::path BlockFilePath(unsigned int nFile)
{
string strBlockFn = strprintf("blk%04u.dat", nFile);
return GetDataDir() / strBlockFn;
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if ((nFile < 1) || (nFile == (unsigned int) -1))
return NULL;
FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
if (!file)
return NULL;
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
{
if (fseek(file, nBlockPos, SEEK_SET) != 0)
{
fclose(file);
return NULL;
}
}
return file;
}
static unsigned int nCurrentBlockFile = 1;
FILE* AppendBlockFile(unsigned int& nFileRet)
{
nFileRet = 0;
while (true)
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
bool LoadBlockIndex(bool fAllowNew)
{
LOCK(cs_main);
CBigNum bnTrustedModulus;
if (fTestNet)
{
pchMessageStart[0] = 0x85;
pchMessageStart[1] = 0xfa;
pchMessageStart[2] = 0x03;
pchMessageStart[3] = 0x71;
bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
nStakeMinAge = 1 * 60 * 60; // test net min age is 1 hour
nCoinbaseMaturity = 10; // test maturity is 10 blocks
}
else
{
bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
}
#if 0
// Set up the Zerocoin Params object
ZCParams = new libzerocoin::Params(bnTrustedModulus);
#endif
//
// Load block index
//
CTxDB txdb("cr+");
if (!txdb.LoadBlockIndex())
return false;
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
const char* pszTimestamp = "Big Box Coin 2018 really";
CTransaction txNew;
txNew.nTime = 1525695833;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].SetEmpty();
CBlock block;
block.vtx.push_back(txNew);
block.hashPrevBlock = 0;
block.hashMerkleRoot = block.BuildMerkleTree();
block.nVersion = 1;
block.nTime = 1525695833;
block.nBits = bnProofOfWorkLimit.GetCompact();
block.nNonce = !fTestNet ? 696716 : 696716;
if (true && (block.GetHash() != hashGenesisBlock)) {
// This will figure out a valid hash and Nonce if you're
// creating a different genesis block:
uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256();
while (block.GetHash() > hashTarget)
{
++block.nNonce;
if (block.nNonce == 0)
{
printf("NONCE WRAPPED, incrementing time");
++block.nTime;
}
}
}
//// debug print
block.print();
printf("block.GetHash() == %s\n", block.GetHash().ToString().c_str());
printf("block.hashMerkleRoot == %s\n", block.hashMerkleRoot.ToString().c_str());
printf("block.nTime = %u \n", block.nTime);
printf("block.nNonce = %u \n", block.nNonce);
assert(block.hashMerkleRoot == uint256("0xc6f05f6ac5098c45b95705c0cfeccbbd28db82655fe7988398a0851bdeb2e480"));
assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
assert(block.CheckBlock());
// Start new block file
unsigned int nFile;
unsigned int nBlockPos;
if (!block.WriteToDisk(nFile, nBlockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(nFile, nBlockPos, hashGenesisBlock))
return error("LoadBlockIndex() : genesis block not accepted");
// ppcoin: initialize synchronized checkpoint
if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
return error("LoadBlockIndex() : failed to init sync checkpoint");
}
string strPubKey = "";
// if checkpoint master key changed must reset sync-checkpoint
if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
{
// write checkpoint master key to db
txdb.TxnBegin();
if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
if (!txdb.TxnCommit())
return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
return error("LoadBlockIndex() : failed to reset sync-checkpoint");
}
return true;
}
void PrintBlockTree()
{
AssertLockHeld(cs_main);
// pre-compute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
printf("| ");
printf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
printf("| ");
printf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
printf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
block.GetHash().ToString().c_str(),
block.nBits,
DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
FormatMoney(pindex->nMint).c_str(),
block.vtx.size());
PrintWallets(block);
// put the main time-chain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
bool LoadExternalBlockFile(FILE* fileIn)
{
int64_t nStart = GetTimeMillis();
int nLoaded = 0;
{
LOCK(cs_main);
try {
CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
unsigned int nPos = 0;
while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
{
unsigned char pchData[65536];
do {
fseek(blkdat, nPos, SEEK_SET);
int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
if (nRead <= 8)
{
nPos = (unsigned int)-1;
break;
}
void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
if (nFind)
{
if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
{
nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
break;
}
nPos += ((unsigned char*)nFind - pchData) + 1;
}
else
nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
} while(!fRequestShutdown);
if (nPos == (unsigned int)-1)
break;
fseek(blkdat, nPos, SEEK_SET);
unsigned int nSize;
blkdat >> nSize;
if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
{
CBlock block;
blkdat >> block;
if (ProcessBlock(NULL,&block))
{
nLoaded++;
nPos += 4 + nSize;
}
}
}
}
catch (std::exception &e) {
printf("%s() : Deserialize or I/O error caught during load\n",
__PRETTY_FUNCTION__);
}
}
printf("Loaded %i blocks from external file in %"PRId64"ms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
extern map<uint256, CAlert> mapAlerts;
extern CCriticalSection cs_mapAlerts;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode"))
strRPC = "test";
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// if detected invalid checkpoint enter safe mode
if (Checkpoints::hashInvalidCheckpoint != 0)
{
nPriority = 3000;
strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
if (nPriority > 1000)
strRPC = strStatusBar;
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
txInMap = mempool.exists(inv.hash);
return txInMap ||
mapOrphanTransactions.count(inv.hash) ||
txdb.ContainsTx(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
unsigned char pchMessageStart[4] = { 0x71, 0xae, 0x76, 0x64 };
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
static map<CService, CPubKey> mapReuseKey;
RandAddSeedPerfmon();
if (fDebug)
printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->Misbehaving(1);
return false;
}
int64_t nTime;
CAddress addrMe;
CAddress addrFrom;
uint64_t nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
{
// disconnect from peers older than this proto version
printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty())
vRecv >> pfrom->strSubVer;
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (pfrom->fInbound && addrMe.IsRoutable())
{
pfrom->addrLocal = addrMe;
SeenLocal(addrMe);
}
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
pfrom->fDisconnect = true;
return true;
}
// record my external IP reported by peer
if (addrFrom.IsRoutable() && addrMe.IsRoutable())
addrSeenByPeer = addrMe;
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
if (GetBoolArg("-synctime", true))
AddTimeData(pfrom->addr, nTime);
// Change version
pfrom->PushMessage("verack");
pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
pfrom->PushAddress(addr);
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
{
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Ask the first connected node for block updates
static int nAskedForBlocks = 0;
if (!pfrom->fClient && !pfrom->fOneShot &&
(pfrom->nStartingHeight > (nBestHeight - 144)) &&
(pfrom->nVersion < NOBLKS_VERSION_START ||
pfrom->nVersion >= NOBLKS_VERSION_END) &&
(nAskedForBlocks < 1 || vNodes.size() <= 1))
{
nAskedForBlocks++;
pfrom->PushGetBlocks(pindexBest, uint256(0));
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
// Relay sync-checkpoint
{
LOCK(Checkpoints::cs_hashSyncCheckpoint);
if (!Checkpoints::checkpointMessage.IsNull())
Checkpoints::checkpointMessage.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
cPeerBlockCounts.input(pfrom->nStartingHeight);
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %"PRIszu"", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
if (fShutdown)
return true;
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64_t hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message inv size() = %"PRIszu"", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
CTxDB txdb("r");
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
if (fShutdown)
return true;
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(txdb, inv);
if (fDebug)
printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave)
pfrom->AskFor(inv);
else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
} else if (nInv == nLastBlock) {
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
printf("force request: %s\n", inv.ToString().c_str());
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %"PRIszu"", vInv.size());
}
if (fDebugNet || (vInv.size() != 1))
printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
BOOST_FOREACH(const CInv& inv, vInv)
{
if (fShutdown)
return true;
if (fDebugNet || (vInv.size() == 1))
printf("received getdata for: %s\n", inv.ToString().c_str());
if (inv.type == MSG_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
pfrom->PushMessage("block", block);
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// ppcoin: send latest proof-of-work block to allow the
// download node to accept as orphan (proof-of-stake
// block might be rejected by stake connection check)
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
bool pushed = false;
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end()) {
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TX) {
CTransaction tx;
if (mempool.lookup(inv.hash, tx)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << tx;
pfrom->PushMessage("tx", ss);
}
}
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 500;
printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
// ppcoin: tell downloading node about the latest block if it's
// without risk being rejected due to stake connection check
if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "checkpoint")
{
CSyncCheckpoint checkpoint;
vRecv >> checkpoint;
if (checkpoint.ProcessSyncCheckpoint(pfrom))
{
// Relay
pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
checkpoint.RelayTo(pnode);
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
int nLimit = 2000;
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
bool fMissingInputs = false;
if (AcceptToMemoryPool(mempool, tx, &fMissingInputs))
{
SyncWithWallets(tx, NULL, true);
RelayTransaction(tx, inv.hash);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
const uint256& orphanTxHash = *mi;
CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
bool fMissingInputs2 = false;
if (AcceptToMemoryPool(mempool, orphanTx, &fMissingInputs2))
{
printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
SyncWithWallets(tx, NULL, true);
RelayTransaction(orphanTx, orphanTxHash);
mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
vWorkQueue.push_back(orphanTxHash);
vEraseQueue.push_back(orphanTxHash);
}
else if (!fMissingInputs2)
{
// invalid orphan
vEraseQueue.push_back(orphanTxHash);
printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(tx);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
if (nEvicted > 0)
printf("mapOrphan overflow, removed %u tx\n", nEvicted);
}
if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
}
else if (strCommand == "block")
{
CBlock block;
vRecv >> block;
uint256 hashBlock = block.GetHash();
printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
CInv inv(MSG_BLOCK, hashBlock);
pfrom->AddInventoryKnown(inv);
if (ProcessBlock(pfrom, &block))
mapAlreadyAskedFor.erase(inv);
if (block.nDoS) pfrom->Misbehaving(block.nDoS);
}
else if (strCommand == "getaddr")
{
// Don't return addresses older than nCutOff timestamp
int64_t nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
if(addr.nTime > nCutOff)
pfrom->PushAddress(addr);
}
else if (strCommand == "mempool")
{
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
vector<CInv> vInv;
for (unsigned int i = 0; i < vtxid.size(); i++) {
CInv inv(MSG_TX, vtxid[i]);
vInv.push_back(inv);
if (i == (MAX_INV_SZ - 1))
break;
}
if (vInv.size() > 0)
pfrom->PushMessage("inv", vInv);
}
else if (strCommand == "checkorder")
{
uint256 hashReply;
vRecv >> hashReply;
if (!GetBoolArg("-allowreceivebyip"))
{
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
return true;
}
CWalletTx order;
vRecv >> order;
/// we have a chance to check the order here
// Keep giving the same key to the same ip until they use it
if (!mapReuseKey.count(pfrom->addr))
pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
// Send back approval of order and pubkey to use
CScript scriptPubKey;
scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
}
else if (strCommand == "reply")
{
uint256 hashReply;
vRecv >> hashReply;
CRequestTracker tracker;
{
LOCK(pfrom->cs_mapRequests);
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
if (mi != pfrom->mapRequests.end())
{
tracker = (*mi).second;
pfrom->mapRequests.erase(mi);
}
}
if (!tracker.IsNull())
tracker.fn(tracker.param1, vRecv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64_t nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "alert")
{
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0)
{
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
pfrom->Misbehaving(10);
}
}
}
else
{
// Ignore unknown commands for extensibility
}
// Update the last seen time for this node's address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
// requires LOCK(cs_vRecvMsg)
bool ProcessMessages(CNode* pfrom)
{
//if (fDebug)
// printf("ProcessMessages(%zu messages)\n", pfrom->vRecvMsg.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
bool fOk = true;
std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
// get next message
CNetMessage& msg = *it;
//if (fDebug)
// printf("ProcessMessages(message %u msgsz, %zu bytes, complete:%s)\n",
// msg.hdr.nMessageSize, msg.vRecv.size(),
// msg.complete() ? "Y" : "N");
// end, if an incomplete message is found
if (!msg.complete())
break;
// at this point, any failure means we can delete the current message
it++;
// Scan for message start
if (memcmp(msg.hdr.pchMessageStart, pchMessageStart, sizeof(pchMessageStart)) != 0) {
printf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
fOk = false;
break;
}
// Read header
CMessageHeader& hdr = msg.hdr;
if (!hdr.IsValid())
{
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
// Checksum
CDataStream& vRecv = msg.vRecv;
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Process message
bool fRet = false;
try
{
{
LOCK(cs_main);
fRet = ProcessMessage(pfrom, strCommand, vRecv);
}
if (fShutdown)
break;
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
}
// In case the connection got shut down, its receive buffer was wiped
if (!pfrom->fDisconnect)
pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
return fOk;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
// Keep-alive ping. We send a nonce of zero because we don't use it anywhere
// right now.
if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSendMsg.empty()) {
uint64_t nonce = 0;
if (pto->nVersion > BIP0031_VERSION)
pto->PushMessage("ping", nonce);
else
pto->PushMessage("ping");
}
// Resend wallet transactions that haven't gotten in a block yet
ResendWalletTransactions();
// Address refresh broadcast
static int64_t nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
if (!fNoListen)
{
CAddress addr = GetLocalAddress(&pnode->addr);
if (addr.IsRoutable())
pnode->PushAddress(addr);
}
}
}
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second)
{
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle)
{
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
// always trickle our own transactions
if (!fTrickleWait)
{
CWalletTx wtx;
if (GetTransaction(inv.hash, wtx))
if (wtx.fFromMe)
fTrickleWait = true;
}
if (fTrickleWait)
{
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second)
{
vInv.push_back(inv);
if (vInv.size() >= 1000)
{
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
//
// Message: getdata
//
vector<CInv> vGetData;
int64_t nNow = GetTime() * 1000000;
CTxDB txdb("r");
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(txdb, inv))
{
if (fDebugNet)
printf("sending getdata: %s\n", inv.ToString().c_str());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
mapAlreadyAskedFor[inv] = nNow;
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
| [
"you@example.com"
] | you@example.com |
b9ba7113adfb625fb0015f55cde1c8fccc66fd4f | 64f7330b04d108050da1a2640e8a031168c620b2 | /assignement_2/googletest/googlemock/include/gmock/internal/gmock-internal-utils.h | 3edb03102b9d48806a09d88eee38d6eaafbdcc62 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | alexZajac/CS014_assignements | 1c641ff4e9096c40088e95dc1a89e03761da0f3f | b20fade1cb1c86382463f530e58ded8ee2254efc | refs/heads/master | 2023-07-07T05:34:34.008957 | 2021-08-05T17:25:17 | 2021-08-05T17:25:17 | 212,858,344 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,415 | h | // Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file defines some utilities useful for implementing Google
// Mock. They are subject to change without notice, so please DO NOT
// USE THEM IN USER CODE.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
#include <stdio.h>
#include <ostream> // NOLINT
#include <string>
#include <type_traits>
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
namespace testing {
template <typename>
class Matcher;
namespace internal {
// Silence MSVC C4100 (unreferenced formal parameter) and
// C4805('==': unsafe mix of type 'const int' and type 'const bool')
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
# pragma warning(disable:4805)
#endif
// Joins a vector of strings as if they are fields of a tuple; returns
// the joined string.
GTEST_API_ std::string JoinAsTuple(const Strings& fields);
// Converts an identifier name to a space-separated list of lower-case
// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
// treated as one word. For example, both "FooBar123" and
// "foo_bar_123" are converted to "foo bar 123".
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
// PointeeOf<Pointer>::type is the type of a value pointed to by a
// Pointer, which can be either a smart pointer or a raw pointer. The
// following default implementation is for the case where Pointer is a
// smart pointer.
template <typename Pointer>
struct PointeeOf {
// Smart pointer classes define type element_type as the type of
// their pointees.
typedef typename Pointer::element_type type;
};
// This specialization is for the raw pointer case.
template <typename T>
struct PointeeOf<T*> { typedef T type; }; // NOLINT
// GetRawPointer(p) returns the raw pointer underlying p when p is a
// smart pointer, or returns p itself when p is already a raw pointer.
// The following default implementation is for the smart pointer case.
template <typename Pointer>
inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
return p.get();
}
// This overloaded version is for the raw pointer case.
template <typename Element>
inline Element* GetRawPointer(Element* p) { return p; }
// MSVC treats wchar_t as a native type usually, but treats it as the
// same as unsigned short when the compiler option /Zc:wchar_t- is
// specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
// is a native type.
#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
// wchar_t is a typedef.
#else
# define GMOCK_WCHAR_T_IS_NATIVE_ 1
#endif
// In what follows, we use the term "kind" to indicate whether a type
// is bool, an integer type (excluding bool), a floating-point type,
// or none of them. This categorization is useful for determining
// when a matcher argument type can be safely converted to another
// type in the implementation of SafeMatcherCast.
enum TypeKind {
kBool, kInteger, kFloatingPoint, kOther
};
// KindOf<T>::value is the kind of type T.
template <typename T> struct KindOf {
enum { value = kOther }; // The default kind.
};
// This macro declares that the kind of 'type' is 'kind'.
#define GMOCK_DECLARE_KIND_(type, kind) \
template <> struct KindOf<type> { enum { value = kind }; }
GMOCK_DECLARE_KIND_(bool, kBool);
// All standard integer types.
GMOCK_DECLARE_KIND_(char, kInteger);
GMOCK_DECLARE_KIND_(signed char, kInteger);
GMOCK_DECLARE_KIND_(unsigned char, kInteger);
GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(int, kInteger);
GMOCK_DECLARE_KIND_(unsigned int, kInteger);
GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
#if GMOCK_WCHAR_T_IS_NATIVE_
GMOCK_DECLARE_KIND_(wchar_t, kInteger);
#endif
// Non-standard integer types.
GMOCK_DECLARE_KIND_(Int64, kInteger);
GMOCK_DECLARE_KIND_(UInt64, kInteger);
// All standard floating-point types.
GMOCK_DECLARE_KIND_(float, kFloatingPoint);
GMOCK_DECLARE_KIND_(double, kFloatingPoint);
GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
#undef GMOCK_DECLARE_KIND_
// Evaluates to the kind of 'type'.
#define GMOCK_KIND_OF_(type) \
static_cast< ::testing::internal::TypeKind>( \
::testing::internal::KindOf<type>::value)
// Evaluates to true if and only if integer type T is signed.
#define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
// is true if and only if arithmetic type From can be losslessly converted to
// arithmetic type To.
//
// It's the user's responsibility to ensure that both From and To are
// raw (i.e. has no CV modifier, is not a pointer, and is not a
// reference) built-in arithmetic types, kFromKind is the kind of
// From, and kToKind is the kind of To; the value is
// implementation-defined when the above pre-condition is violated.
template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
struct LosslessArithmeticConvertibleImpl : public std::false_type {};
// Converting bool to bool is lossless.
template <>
struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>
: public std::true_type {};
// Converting bool to any integer type is lossless.
template <typename To>
struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>
: public std::true_type {};
// Converting bool to any floating-point type is lossless.
template <typename To>
struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>
: public std::true_type {};
// Converting an integer to bool is lossy.
template <typename From>
struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>
: public std::false_type {};
// Converting an integer to another non-bool integer is lossless
// if and only if the target type's range encloses the source type's range.
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
: public bool_constant<
// When converting from a smaller size to a larger size, we are
// fine as long as we are not converting from signed to unsigned.
((sizeof(From) < sizeof(To)) &&
(!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) ||
// When converting between the same size, the signedness must match.
((sizeof(From) == sizeof(To)) &&
(GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT
#undef GMOCK_IS_SIGNED_
// Converting an integer to a floating-point type may be lossy, since
// the format of a floating-point number is implementation-defined.
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
: public std::false_type {};
// Converting a floating-point to bool is lossy.
template <typename From>
struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
: public std::false_type {};
// Converting a floating-point to an integer is lossy.
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
: public std::false_type {};
// Converting a floating-point to another floating-point is lossless
// if and only if the target type is at least as big as the source type.
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<
kFloatingPoint, From, kFloatingPoint, To>
: public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT
// LosslessArithmeticConvertible<From, To>::value is true if and only if
// arithmetic type From can be losslessly converted to arithmetic type To.
//
// It's the user's responsibility to ensure that both From and To are
// raw (i.e. has no CV modifier, is not a pointer, and is not a
// reference) built-in arithmetic types; the value is
// implementation-defined when the above pre-condition is violated.
template <typename From, typename To>
struct LosslessArithmeticConvertible
: public LosslessArithmeticConvertibleImpl<
GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT
// This interface knows how to report a Google Mock failure (either
// non-fatal or fatal).
class FailureReporterInterface {
public:
// The type of a failure (either non-fatal or fatal).
enum FailureType {
kNonfatal, kFatal
};
virtual ~FailureReporterInterface() {}
// Reports a failure that occurred at the given source file location.
virtual void ReportFailure(FailureType type, const char* file, int line,
const std::string& message) = 0;
};
// Returns the failure reporter used by Google Mock.
GTEST_API_ FailureReporterInterface* GetFailureReporter();
// Asserts that condition is true; aborts the process with the given
// message if condition is false. We cannot use LOG(FATAL) or CHECK()
// as Google Mock might be used to mock the log sink itself. We
// inline this function to prevent it from showing up in the stack
// trace.
inline void Assert(bool condition, const char* file, int line,
const std::string& msg) {
if (!condition) {
GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
file, line, msg);
}
}
inline void Assert(bool condition, const char* file, int line) {
Assert(condition, file, line, "Assertion failed.");
}
// Verifies that condition is true; generates a non-fatal failure if
// condition is false.
inline void Expect(bool condition, const char* file, int line,
const std::string& msg) {
if (!condition) {
GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
file, line, msg);
}
}
inline void Expect(bool condition, const char* file, int line) {
Expect(condition, file, line, "Expectation failed.");
}
// Severity level of a log.
enum LogSeverity {
kInfo = 0,
kWarning = 1
};
// Valid values for the --gmock_verbose flag.
// All logs (informational and warnings) are printed.
const char kInfoVerbosity[] = "info";
// Only warnings are printed.
const char kWarningVerbosity[] = "warning";
// No logs are printed.
const char kErrorVerbosity[] = "error";
// Returns true if and only if a log with the given severity is visible
// according to the --gmock_verbose flag.
GTEST_API_ bool LogIsVisible(LogSeverity severity);
// Prints the given message to stdout if and only if 'severity' >= the level
// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
// 0, also prints the stack trace excluding the top
// stack_frames_to_skip frames. In opt mode, any positive
// stack_frames_to_skip is treated as 0, since we don't know which
// function calls will be inlined by the compiler and need to be
// conservative.
GTEST_API_ void Log(LogSeverity severity, const std::string& message,
int stack_frames_to_skip);
// A marker class that is used to resolve parameterless expectations to the
// correct overload. This must not be instantiable, to prevent client code from
// accidentally resolving to the overload; for example:
//
// ON_CALL(mock, Method({}, nullptr))...
//
class WithoutMatchers {
private:
WithoutMatchers() {}
friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
};
// Internal use only: access the singleton instance of WithoutMatchers.
GTEST_API_ WithoutMatchers GetWithoutMatchers();
// Disable MSVC warnings for infinite recursion, since in this case the
// the recursion is unreachable.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4717)
#endif
// Invalid<T>() is usable as an expression of type T, but will terminate
// the program with an assertion failure if actually run. This is useful
// when a value of type T is needed for compilation, but the statement
// will not really be executed (or we don't care if the statement
// crashes).
template <typename T>
inline T Invalid() {
Assert(false, "", -1, "Internal error: attempt to return invalid value");
// This statement is unreachable, and would never terminate even if it
// could be reached. It is provided only to placate compiler warnings
// about missing return statements.
return Invalid<T>();
}
#ifdef _MSC_VER
# pragma warning(pop)
#endif
// Given a raw type (i.e. having no top-level reference or const
// modifier) RawContainer that's either an STL-style container or a
// native array, class StlContainerView<RawContainer> has the
// following members:
//
// - type is a type that provides an STL-style container view to
// (i.e. implements the STL container concept for) RawContainer;
// - const_reference is a type that provides a reference to a const
// RawContainer;
// - ConstReference(raw_container) returns a const reference to an STL-style
// container view to raw_container, which is a RawContainer.
// - Copy(raw_container) returns an STL-style container view of a
// copy of raw_container, which is a RawContainer.
//
// This generic version is used when RawContainer itself is already an
// STL-style container.
template <class RawContainer>
class StlContainerView {
public:
typedef RawContainer type;
typedef const type& const_reference;
static const_reference ConstReference(const RawContainer& container) {
static_assert(!std::is_const<RawContainer>::value,
"RawContainer type must not be const");
return container;
}
static type Copy(const RawContainer& container) { return container; }
};
// This specialization is used when RawContainer is a native array type.
template <typename Element, size_t N>
class StlContainerView<Element[N]> {
public:
typedef typename std::remove_const<Element>::type RawElement;
typedef internal::NativeArray<RawElement> type;
// NativeArray<T> can represent a native array either by value or by
// reference (selected by a constructor argument), so 'const type'
// can be used to reference a const native array. We cannot
// 'typedef const type& const_reference' here, as that would mean
// ConstReference() has to return a reference to a local variable.
typedef const type const_reference;
static const_reference ConstReference(const Element (&array)[N]) {
static_assert(std::is_same<Element, RawElement>::value,
"Element type must not be const");
return type(array, N, RelationToSourceReference());
}
static type Copy(const Element (&array)[N]) {
return type(array, N, RelationToSourceCopy());
}
};
// This specialization is used when RawContainer is a native array
// represented as a (pointer, size) tuple.
template <typename ElementPointer, typename Size>
class StlContainerView< ::std::tuple<ElementPointer, Size> > {
public:
typedef typename std::remove_const<
typename internal::PointeeOf<ElementPointer>::type>::type RawElement;
typedef internal::NativeArray<RawElement> type;
typedef const type const_reference;
static const_reference ConstReference(
const ::std::tuple<ElementPointer, Size>& array) {
return type(std::get<0>(array), std::get<1>(array),
RelationToSourceReference());
}
static type Copy(const ::std::tuple<ElementPointer, Size>& array) {
return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());
}
};
// The following specialization prevents the user from instantiating
// StlContainer with a reference type.
template <typename T> class StlContainerView<T&>;
// A type transform to remove constness from the first part of a pair.
// Pairs like that are used as the value_type of associative containers,
// and this transform produces a similar but assignable pair.
template <typename T>
struct RemoveConstFromKey {
typedef T type;
};
// Partially specialized to remove constness from std::pair<const K, V>.
template <typename K, typename V>
struct RemoveConstFromKey<std::pair<const K, V> > {
typedef std::pair<K, V> type;
};
// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
// reduce code size.
GTEST_API_ void IllegalDoDefault(const char* file, int line);
template <typename F, typename Tuple, size_t... Idx>
auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(
std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
}
// Apply the function to a tuple of arguments.
template <typename F, typename Tuple>
auto Apply(F&& f, Tuple&& args)
-> decltype(ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size<Tuple>::value>())) {
return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size<Tuple>::value>());
}
// Template struct Function<F>, where F must be a function type, contains
// the following typedefs:
//
// Result: the function's return type.
// Arg<N>: the type of the N-th argument, where N starts with 0.
// ArgumentTuple: the tuple type consisting of all parameters of F.
// ArgumentMatcherTuple: the tuple type consisting of Matchers for all
// parameters of F.
// MakeResultVoid: the function type obtained by substituting void
// for the return type of F.
// MakeResultIgnoredValue:
// the function type obtained by substituting Something
// for the return type of F.
template <typename T>
struct Function;
template <typename R, typename... Args>
struct Function<R(Args...)> {
using Result = R;
static constexpr size_t ArgumentCount = sizeof...(Args);
template <size_t I>
using Arg = ElemFromList<I, Args...>;
using ArgumentTuple = std::tuple<Args...>;
using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
using MakeResultVoid = void(Args...);
using MakeResultIgnoredValue = IgnoredValue(Args...);
};
template <typename R, typename... Args>
constexpr size_t Function<R(Args...)>::ArgumentCount;
#ifdef _MSC_VER
# pragma warning(pop)
#endif
} // namespace internal
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
| [
"zajac.alexandre@gmail.com"
] | zajac.alexandre@gmail.com |
0dbae84bd9ab89979c31c94088cdb91aa7654fe1 | a4106a12c81180880a34fd401b4537179fadb26a | /Source/Player.cpp | 5f1ba1d33ec54cb46987ffea7553c5e9a684fc81 | [] | no_license | Vocchi/TestShoot | b052565ff7ebf55a3e99458d731331f594b46a68 | b172d80b188640b201049ccf0e52c068ed56fecc | refs/heads/master | 2021-08-30T13:47:01.939451 | 2017-12-15T14:39:39 | 2017-12-15T14:39:39 | 113,001,608 | 0 | 0 | null | 2017-12-15T14:39:40 | 2017-12-04T06:02:50 | C++ | UTF-8 | C++ | false | false | 519 | cpp | /*
==============================================================================
Player.cpp
Created: 21 Nov 2017 6:48:41pm
Author: next2
==============================================================================
*/
#include "Player.h"
Player::Player() {
position = 30 + 60 * 5;
shootFlag = 0;
}
Player::~Player() {
}
void Player::move(Graphics& g) {
g.setColour(Colours::red);
g.drawEllipse(position, 200.0, 30.0, 30.0, 15.0);
g.setColour(Colours::white);
}
void Player::shoot() {
}
| [
"33412263+Vocchi@users.noreply.github.com"
] | 33412263+Vocchi@users.noreply.github.com |
7ec4ac751ef7a3c25e25eb4f82f438f7d53cd002 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_6377668744314880_0/C++/NAFIS/A.cpp | 0aa9d8b7d58e4d0d4df19d076838093ee27ead01 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 4,133 | cpp | /*********************************************************************\
|--\ --- /\ |-----------| ----- /-------| |
| \ | / \ | | / |
| \ | / \ | | | |
| \ | / \ | | |----| |
| \ | / ------ \ |-------| | |-----| |
| \ | / \ | | | |
| \ | / \ | | / |
--- ------- ------ ----- |---------/ |
|
codeforces = nfssdq || topcoder = nafis007 |
mail = nafis_sadique@yahoo.com || nfssdq@gmail.com |
IIT,Jahangirnagar University(41) |
|
**********************************************************************/
#include <bits/stdc++.h>
using namespace std;
#define xx first
#define yy second
#define pb push_back
#define mp make_pair
#define LL long long
#define inf INT_MAX/3
#define mod 1000000007ll
#define PI acos(-1.0)
#define linf (1ll<<60)-1
#define FOR(I,A,B) for(int I = (A); I < (B); ++I)
#define REP(I,N) FOR(I,0,N)
#define ALL(A) ((A).begin(), (A).end())
#define set0(ar) memset(ar,0,sizeof ar)
#define vsort(v) sort(v.begin(),v.end())
#define setinf(ar) memset(ar,126,sizeof ar)
//cout << fixed << setprecision(20) << p << endl;
template <class T> inline T bigmod(T p,T e,T M){
LL ret = 1;
for(; e > 0; e >>= 1){
if(e & 1) ret = (ret * p) % M;
p = (p * p) % M;
} return (T)ret;
}
template <class T> inline T gcd(T a,T b){if(b==0)return a;return gcd(b,a%b);}
template <class T> inline T modinverse(T a,T M){return bigmod(a,M-2,M);}
typedef pair<double, double> P;
#define EPS 1e-9
double polarAngle( P p )
{
if( fabs( p.xx ) <= EPS && fabs( p.yy ) <= EPS ) return -1.0;
if( fabs( p.xx ) <= EPS ) return ( p.yy > EPS ? 1.0 : 3.0 ) * acos( 0 );
double theta = atan( 1.0 * p.yy / p.xx );
if( p.xx > EPS ) return( p.yy >= -EPS ? theta : ( 4 * acos( 0 ) + theta ) );
return( 2 * acos( 0 ) + theta );
}
P ar[3333];
double tmp[6666];
pair<double,int> tmp1[6666];
int main() {
freopen("a.in", "r", stdin);
freopen("a.out", "w", stdout);
ios_base::sync_with_stdio(0); cin.tie(0);
int T; cin >> T;
FOR(ts, 1, T+1){
int n; cin >> n;
REP(i, n){
cin >> ar[i].xx >> ar[i].yy;
}
cout << "Case #" << ts << ":" << endl;
cerr << "Case #" << ts << ":" << endl;
REP(i, n){
int cnt1 = 0, cnt = 0;
REP(j, n){
if(i == j) continue;
tmp[cnt1++] = polarAngle(mp(ar[j].xx-ar[i].xx, ar[j].yy-ar[i].yy));
}
sort(tmp, tmp + cnt1);
REP(j, cnt1){
if(j == 0 || abs(tmp[j]-tmp[j-1])>EPS) tmp1[cnt++] = mp(tmp[j], 1);
else tmp1[cnt-1].yy++;
}
REP(j, cnt) {
tmp1[j+cnt] = tmp1[j];
tmp1[j+cnt].xx += PI*2.0;
}
int last = -1, res = n-1, cur = n-1;
while(tmp1[last+1].xx <= tmp1[cnt].xx-PI+EPS) {
last++;
cur -= tmp1[last].yy;
}
// REP(j, cnt+cnt) cout << tmp1[j].xx << " " << tmp1[j].yy << " " ;
// cout << endl;
for(int j = cnt; j < cnt+cnt; j++){
cur += tmp1[j].yy;
while(tmp1[last+1].xx <= tmp1[j].xx-PI+EPS) {
last++;
cur -= tmp1[last].yy;
}
// cout << cur << " " << last << " ";
res = min(res, cur-tmp1[j].yy);
res = min(res, n-1-cur);
}
cout << res << endl;
cerr << res << endl;
}
}
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
86cb0f233b0b3968dc8e0501799764954b6b0d9e | b4ab2a1c532ab0275aca35719d3dba3250c961ab | /CodeforcesContest/Div2/round 646/a.cpp | 902d5a8cfa762c7085f58a837c8293caf6893a25 | [] | no_license | m-ibrahim-khalil/Algorithm | 8a0944c7898979af57e8a745b0a2f3d6462b865b | e30d57b6430c6ad15cd3953594c1d11bccc350a7 | refs/heads/master | 2023-04-03T23:53:40.835281 | 2020-08-06T07:54:42 | 2020-08-06T07:54:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,560 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pf printf
#define pi acos(-1.0)
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define pb push_back
#define mp make_pair
#define sz(v) ((int)(v).size())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n) FORE(i,0,n)
#define REPSZ(i,v) REP(i,SZ(v))
#define pll pair <ll, ll>
ll gcd(ll a,ll b) { return b==0?a:gcd(b,a%b); }
const int MAXN = 200000;
ll n,m;
ll arr[MAXN];
vector<ll> v;
vector<pll>v2;
void print(vector <ll> &v){cout << v.size() << endl;for(int i = 0; i < v.size(); i++){pf("%lld ", v[i]);}pf("\n");}
void print(vector <pll> &v){ cout << v.size() << endl; for(int i = 0; i < v.size(); i++){pf("%lld %lld\n", v[i].first, v[i].second);}}
void print(set<ll> s){set <ll> :: iterator itr;for (itr = s.begin(); itr != s.end(); ++itr){cout << *itr << " ";}cout << endl;}
void print(double d){cout << fixed << setprecision(10) << d << endl;}
void from_file(void){ freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);}
/* ------------------main section-------------! */
ll solve() {
ll ans = 0;
return ans;
}
void run() {
fastio;
int tc;
cin >> tc;
while(tc--)
{
cin >> n;
REP(i,n)
{
ll a,b;
cin >> a >> b;
v.pb(a);
v.pb(b);
v2.pb(mp(a,b));
}
cout << solve() << endl;
}
}
int main() {
run();
return 0;
}
| [
"mik858692@gmail.com"
] | mik858692@gmail.com |
48f9a1f58df98be5afcaae69030145c1446f21ff | 1ec6e6eb7782a36e0b32e616662ee2c2b00fe448 | /src/base58.cpp | b75dc8517fb205552f1a4ad0b7d487d076447583 | [
"MIT"
] | permissive | Voyacoin/Voyacoin | 4e804de68fde47a5f98990f7e80a22f39d871259 | 4030c52983749f0e0ff3a20c0d67ced3f5b35b14 | refs/heads/master | 2021-03-12T23:40:55.998354 | 2015-02-22T00:20:42 | 2015-02-22T00:20:42 | 31,138,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,069 | cpp | // Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "hash.h"
#include "uint256.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
// Skip leading spaces.
while (*psz && isspace(*psz))
psz++;
// Skip and count leading '1's.
int zeroes = 0;
while (*psz == '1') {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
// Process the characters.
while (*psz && !isspace(*psz)) {
// Decode base58 character
const char* ch = strchr(pszBase58, *psz);
if (ch == NULL)
return false;
// Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
psz++;
}
// Skip trailing spaces.
while (isspace(*psz))
psz++;
if (*psz != 0)
return false;
// Skip leading zeroes in b256.
std::vector<unsigned char>::iterator it = b256.begin();
while (it != b256.end() && *it == 0)
it++;
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
}
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
// Skip & count leading zeroes.
int zeroes = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up.
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
pbegin++;
}
// Skip leading zeroes in base58 result.
std::vector<unsigned char>::iterator it = b58.begin();
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + (b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet) ||
(vchRet.size() < 4)) {
vchRet.clear();
return false;
}
// re-calculate the checksum, insure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size() - 4);
return true;
}
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
CBase58Data::CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
std::vector<unsigned char> vchTemp;
bool rc58 = DecodeBase58Check(psz, vchTemp);
if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
OPENSSL_cleanse(&vchTemp[0], vchData.size());
return true;
}
bool CBase58Data::SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string CBase58Data::ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CBase58Data::CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion)
return -1;
if (vchVersion > b58.vchVersion)
return 1;
if (vchData < b58.vchData)
return -1;
if (vchData > b58.vchData)
return 1;
return 0;
}
namespace
{
class CVoyacoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CVoyacoinAddress* addr;
public:
CVoyacoinAddressVisitor(CVoyacoinAddress* addrIn) : addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
bool operator()(const CNoDestination& no) const { return false; }
};
} // anon namespace
bool CVoyacoinAddress::Set(const CKeyID& id)
{
SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool CVoyacoinAddress::Set(const CScriptID& id)
{
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
bool CVoyacoinAddress::Set(const CTxDestination& dest)
{
return boost::apply_visitor(CVoyacoinAddressVisitor(this), dest);
}
bool CVoyacoinAddress::IsValid() const
{
return IsValid(Params());
}
bool CVoyacoinAddress::IsValid(const CChainParams& params) const
{
bool fCorrectSize = vchData.size() == 20;
bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CTxDestination CVoyacoinAddress::Get() const
{
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, &vchData[0], 20);
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
bool CVoyacoinAddress::GetKeyID(CKeyID& keyID) const
{
if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return false;
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
bool CVoyacoinAddress::IsScript() const
{
return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}
void CVoyacoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey CVoyacoinSecret::GetKey()
{
CKey ret;
assert(vchData.size() >= 32);
ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool CVoyacoinSecret::IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
return fExpectedFormat && fCorrectVersion;
}
bool CVoyacoinSecret::SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool CVoyacoinSecret::SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
| [
"dev@voyacoin.com"
] | dev@voyacoin.com |
238323c4f8d13792d7cf0eb73563bcbe526a1efb | 5b4954cc4c11d95331863ea2c02829517af45e28 | /VulkanTestVL/src/ResourcesAndMemory/17 Destroying an image view.h | 2e6b9831ccaa7c63fe42ba8207419ef66e336ac1 | [] | no_license | PilgrimBomber/Vulkan | 2dc39d77f4018ce67c589d4856d3d62fde3d1b37 | 9fa433b9e35da91d10bc0d8901c0c3638447683c | refs/heads/master | 2022-04-09T03:12:23.022075 | 2020-03-18T19:30:18 | 2020-03-18T19:30:18 | 244,940,822 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | h |
#ifndef DESTROYING_AN_IMAGE_VIEW
#define DESTROYING_AN_IMAGE_VIEW
#include "common.h"
namespace VulkanLibrary {
void DestroyImageView( VkDevice logical_device,
VkImageView & image_view );
} // namespace VulkanLibrary
#endif // DESTROYING_AN_IMAGE_VIEW | [
"timonitsch@t-online.de"
] | timonitsch@t-online.de |
400918b017b486664cb2b144eb5cb4fe7d027e64 | d84bcfcbd33ec52f4df5e7ad396862e9c657ae85 | /Source/modules/donottrack/NavigatorDoNotTrack.cpp | d6035267627f385f4d91124e354e8fd5e1935582 | [] | no_license | leviw/Blink | fdf50bfd37d49e5de5bf5d82473d5dce103c00cc | 4ebc49b6020d0184d162401edf62e09bb4d335c0 | refs/heads/master | 2023-03-18T12:31:05.788463 | 2013-04-13T01:00:10 | 2013-04-13T01:00:10 | 9,402,789 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,666 | cpp | /*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "NavigatorDoNotTrack.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameLoaderClient.h"
#include "Navigator.h"
#include <wtf/PassOwnPtr.h>
namespace WebCore {
NavigatorDoNotTrack::NavigatorDoNotTrack(Frame* frame)
: DOMWindowProperty(frame)
{
}
NavigatorDoNotTrack::~NavigatorDoNotTrack()
{
}
const char* NavigatorDoNotTrack::supplementName()
{
return "NavigatorDoNotTrack";
}
NavigatorDoNotTrack* NavigatorDoNotTrack::from(Navigator* navigator)
{
NavigatorDoNotTrack* supplement = static_cast<NavigatorDoNotTrack*>(Supplement<Navigator>::from(navigator, supplementName()));
if (!supplement) {
supplement = new NavigatorDoNotTrack(navigator->frame());
provideTo(navigator, supplementName(), adoptPtr(supplement));
}
return supplement;
}
String NavigatorDoNotTrack::doNotTrack(Navigator* navigator)
{
return NavigatorDoNotTrack::from(navigator)->doNotTrack();
}
String NavigatorDoNotTrack::doNotTrack()
{
return frame() ? frame()->loader()->client()->doNotTrackValue() : String();
}
} // namespace WebCore
| [
"jochen@chromium.org@bbb929c8-8fbe-4397-9dbb-9b2b20218538"
] | jochen@chromium.org@bbb929c8-8fbe-4397-9dbb-9b2b20218538 |
248e5c8ded9a588e28cd1bc1fbf1fe2e48ec5464 | dc096ae8c8268934e14451e74a78152781186466 | /CplusplusPrimer_5thEd_2012/chapter09/Exercise9.20.cpp | 22bfa473ec9402aa0bf1e99f703210e129952af6 | [] | no_license | georgiosdoumas/ProgrammingCplusplus- | e9d7420cd8c69377c63e222e090a9ee60642964e | 9f37fe8ddbdb905ed6e27c13841b6ca5d0ef244c | refs/heads/master | 2023-07-09T21:05:14.636387 | 2023-07-01T17:44:39 | 2023-07-01T17:44:39 | 59,301,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 937 | cpp | // Exercise 9.20: Write a program to copy elements from a list<int> into two deques.
// The even-valued elements should go into one deque and the odd ones into the other.
#include <deque>
#include <list>
#include <iostream>
using namespace std;
int main()
{
list<int> ilist { 1, 2, 30, 4, 5, 6, 7, 8 };
deque<int> evendeq, odd_deq;
for(auto listelement : ilist)
{
if( (listelement%2) == 0 ) //even-value element
evendeq.insert( evendeq.begin(), listelement ); // or: evendeq.push_front( listelement );
else
// odd_deq.insert( odd_deq.begin(), listelement ); //this works of course, putting elements in reverse order
odd_deq.push_back( listelement ); // so I wanted to see also this
}
for(auto qel: evendeq) cout << qel << " ";
cout << endl;
for(auto qel: odd_deq) cout << qel << " ";
cout << endl;
return 0;
}
// /usr/bin/g++ -Wall -std=c++11 -o Exercise9.20 Exercise9.20.cpp
| [
"noreply@github.com"
] | noreply@github.com |
00a59f040677f1d73d3680e6c0cb762d183da129 | 60247ddbc4ffc0bf0577ce065490ce9eca535fbd | /Term2/Project5/src/MPC.cpp | 10f69aaca521c4af9dd132beb7b9375cc770b86f | [
"Apache-2.0"
] | permissive | DavidObando/carnd | 8a81b18d94ee69f9f427367f26b2ac8cbb98fba0 | f611066d9ff6d01c997bd9722ff233d9c0962cfa | refs/heads/master | 2023-05-28T23:25:58.044301 | 2022-10-04T19:54:22 | 2022-10-04T19:54:22 | 76,624,437 | 8 | 5 | Apache-2.0 | 2023-05-01T20:15:06 | 2016-12-16T05:30:35 | Jupyter Notebook | UTF-8 | C++ | false | false | 8,632 | cpp | #include "MPC.h"
#include <cppad/cppad.hpp>
#include <cppad/ipopt/solve.hpp>
#include "Eigen-3.3/Eigen/Core"
using CppAD::AD;
size_t N = 15;
double dt = 0.05;
// This value assumes the model presented in the classroom is used.
//
// It was obtained by measuring the radius formed by running the vehicle in the
// simulator around in a circle with a constant steering angle and velocity on a
// flat terrain.
//
// Lf was tuned until the the radius formed by the simulating the model
// presented in the classroom matched the previous radius.
//
// This is the length from front to CoG that has a similar radius.
const double Lf = 2.67;
double ref_v = 60;
size_t x_start = 0;
size_t y_start = x_start + N;
size_t psi_start = y_start + N;
size_t v_start = psi_start + N;
size_t cte_start = v_start + N;
size_t epsi_start = cte_start + N;
size_t delta_start = epsi_start + N;
size_t a_start = delta_start + N - 1;
class FG_eval {
public:
// Fitted polynomial coefficients
Eigen::VectorXd coeffs;
FG_eval(Eigen::VectorXd coeffs) { this->coeffs = coeffs; }
typedef CPPAD_TESTVECTOR(AD<double>) ADvector;
void operator()(ADvector& fg, const ADvector& vars) {
// `fg` a vector of the cost constraints, `vars` is a vector of variable values (state & actuators)
// The cost is stored is the first element of `fg`.
// Any additions to the cost should be added to `fg[0]`.
fg[0] = 0;
// Reference State Cost
// The part of the cost based on the reference state.
for (int t = 0; t < N; t++) {
fg[0] += 0.5 * CppAD::pow(vars[cte_start + t], 2);
fg[0] += 5 * CppAD::pow(vars[epsi_start + t], 2);
fg[0] += CppAD::pow(vars[v_start + t] - ref_v, 2);
}
// Minimize the use of actuators.
for (int t = 0; t < N - 1; t++) {
fg[0] += 5000 * CppAD::pow(vars[delta_start + t], 2);
fg[0] += CppAD::pow(vars[a_start + t], 2);
}
// Minimize the value gap between sequential actuations.
for (int t = 0; t < N - 2; t++) {
fg[0] += 500 * CppAD::pow(vars[delta_start + t + 1] - vars[delta_start + t], 2);
fg[0] += CppAD::pow(vars[a_start + t + 1] - vars[a_start + t], 2);
}
//
// Setup Constraints
//
// Initial constraints
//
// We add 1 to each of the starting indices due to cost being located at
// index 0 of `fg`.
// This bumps up the position of all the other values.
fg[1 + x_start] = vars[x_start];
fg[1 + y_start] = vars[y_start];
fg[1 + psi_start] = vars[psi_start];
fg[1 + v_start] = vars[v_start];
fg[1 + cte_start] = vars[cte_start];
fg[1 + epsi_start] = vars[epsi_start];
// The rest of the constraints
for (int t = 1; t < N; t++) {
// The state at time t+1
AD<double> x1 = vars[x_start + t];
AD<double> y1 = vars[y_start + t];
AD<double> psi1 = vars[psi_start + t];
AD<double> v1 = vars[v_start + t];
AD<double> cte1 = vars[cte_start + t];
AD<double> epsi1 = vars[epsi_start + t];
// The state at time t.
AD<double> x0 = vars[x_start + t - 1];
AD<double> y0 = vars[y_start + t - 1];
AD<double> psi0 = vars[psi_start + t - 1];
AD<double> v0 = vars[v_start + t - 1];
AD<double> cte0 = vars[cte_start + t - 1];
AD<double> epsi0 = vars[epsi_start + t - 1];
// Only consider the actuation at time t.
AD<double> delta0 = vars[delta_start + t - 1];
AD<double> a0 = vars[a_start + t - 1];
AD<double> f0 = coeffs[0] + coeffs[1] * x0 + coeffs[2] * x0 * x0 + coeffs[3] * x0 * x0 * x0;
AD<double> psides0 = CppAD::atan(coeffs[1] + (2 * coeffs[2] * x0) + (3 * coeffs[3] * (x0*x0)));
// The idea here is to constraint this value to be 0.
//
// Recall the equations for the model:
// x_[t+1] = x[t] + v[t] * cos(psi[t]) * dt
// y_[t+1] = y[t] + v[t] * sin(psi[t]) * dt
// psi_[t+1] = psi[t] + v[t] / Lf * delta[t] * dt
// v_[t+1] = v[t] + a[t] * dt
// cte[t+1] = f(x[t]) - y[t] + v[t] * sin(epsi[t]) * dt
// epsi[t+1] = psi[t] - psides[t] + v[t] * delta[t] / Lf * dt
AD<double> psi1c = psi0 + (v0 / Lf * delta0 * dt);
fg[1 + x_start + t] = x1 - (x0 + (v0 * CppAD::cos(psi0) * dt));
fg[1 + y_start + t] = y1 - (y0 + (v0 * CppAD::sin(psi0) * dt));
fg[1 + psi_start + t] = psi1 - psi1c;
fg[1 + v_start + t] = v1 - (v0 + (a0 * dt));
fg[1 + cte_start + t] = cte1 - (f0 - y0 + (v0 * CppAD::sin(epsi0) * dt));
fg[1 + epsi_start + t] = epsi1 - psi1c;
}
}
};
//
// MPC class definition implementation.
//
MPC::MPC() {}
MPC::~MPC() {}
vector<double> MPC::Solve(Eigen::VectorXd state, Eigen::VectorXd coeffs) {
typedef CPPAD_TESTVECTOR(double) Dvector;
double x = state[0];
double y = state[1];
double psi = state[2];
double v = state[3];
double cte = state[4];
double epsi = state[5];
// Set the number of model variables
size_t n_vars = (6 * N) + (2 * (N - 1));
// Set the number of constraints
size_t n_constraints = 6 * N;
// Initial value of the independent variables.
// SHOULD BE 0 besides initial state.
Dvector vars(n_vars);
for (int i = 0; i < n_vars; i++) {
vars[i] = 0;
}
// Set the initial variable values
vars[x_start] = x;
vars[y_start] = y;
vars[psi_start] = psi;
vars[v_start] = v;
vars[cte_start] = cte;
vars[epsi_start] = epsi;
Dvector vars_lowerbound(n_vars);
Dvector vars_upperbound(n_vars);
// Set all non-actuators upper and lowerlimits
// to the max negative and positive values.
for (int i = 0; i < delta_start; i++) {
vars_lowerbound[i] = -1.0e19;
vars_upperbound[i] = 1.0e19;
}
// The upper and lower limits of delta are set to -25 and 25
// degrees (values in radians).
for (int i = delta_start; i < a_start; i++) {
vars_lowerbound[i] = -0.436332;
vars_upperbound[i] = 0.436332;
}
// Acceleration/decceleration upper and lower limits.
for (int i = a_start; i < n_vars; i++) {
vars_lowerbound[i] = -1.0;
vars_upperbound[i] = 1.0;
}
// Lower and upper limits for the constraints
// Should be 0 besides initial state.
Dvector constraints_lowerbound(n_constraints);
Dvector constraints_upperbound(n_constraints);
for (int i = 0; i < n_constraints; i++) {
constraints_lowerbound[i] = 0;
constraints_upperbound[i] = 0;
}
constraints_lowerbound[x_start] = x;
constraints_lowerbound[y_start] = y;
constraints_lowerbound[psi_start] = psi;
constraints_lowerbound[v_start] = v;
constraints_lowerbound[cte_start] = cte;
constraints_lowerbound[epsi_start] = epsi;
constraints_upperbound[x_start] = x;
constraints_upperbound[y_start] = y;
constraints_upperbound[psi_start] = psi;
constraints_upperbound[v_start] = v;
constraints_upperbound[cte_start] = cte;
constraints_upperbound[epsi_start] = epsi;
// object that computes objective and constraints
FG_eval fg_eval(coeffs);
//
// NOTE: You don't have to worry about these options
//
// options for IPOPT solver
std::string options;
// Uncomment this if you'd like more print information
options += "Integer print_level 0\n";
// NOTE: Setting sparse to true allows the solver to take advantage
// of sparse routines, this makes the computation MUCH FASTER. If you
// can uncomment 1 of these and see if it makes a difference or not but
// if you uncomment both the computation time should go up in orders of
// magnitude.
options += "Sparse true forward\n";
options += "Sparse true reverse\n";
// NOTE: Currently the solver has a maximum time limit of 0.5 seconds.
// Change this as you see fit.
options += "Numeric max_cpu_time 0.5\n";
// place to return solution
CppAD::ipopt::solve_result<Dvector> solution;
// solve the problem
CppAD::ipopt::solve<Dvector, FG_eval>(
options, vars, vars_lowerbound, vars_upperbound, constraints_lowerbound,
constraints_upperbound, fg_eval, solution);
// Cost
auto cost = solution.obj_value;
std::cout << "Cost " << cost << std::endl;
// We'll return the following values:
// 0 -> the immediate steering value (in Radians)
// 1 -> the immediate throttle value
// 2 -> amount of coordinate values (N)
// 3 ... 3+N -> X coordinate values
// 3+N+1 ... 3+N+1+N -> Y coordinate values
vector<double> result;
result.push_back(solution.x[delta_start]);
result.push_back(solution.x[a_start]);
result.push_back(N);
for (int i = 0; i < N; ++i)
{
result.push_back(solution.x[x_start + i]);
}
for (int i = 0; i < N; ++i)
{
result.push_back(solution.x[y_start + i]);
}
return result;
}
| [
"daobando@microsoft.com"
] | daobando@microsoft.com |
8a8721d8ea0bc12f82722785c450e2ff8af234cf | 9e71afd5bef444741bef62e5dc62245095c171c6 | /Sources/GameEngine/Engine/EngineContext.h | 2877e3b3b7f498a181174878260aaa9b16d73af5 | [] | no_license | wbach/OpenGL_Engine | f243f5e5c854278660d077593f764f18bb7949c1 | b88cf1da8d57b4737544e6acdf4a5e1bfbbf4613 | refs/heads/master | 2023-02-23T08:40:26.120920 | 2023-02-18T16:48:24 | 2023-02-18T16:48:24 | 91,100,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,896 | h | #pragma once
#include <Types.h>
#include <Utils/MeasurementHandler.h>
#include <Utils/ThreadSync.h>
#include <Utils/Time/TimerService.h>
#include <Mutex.hpp>
#include <list>
#include <memory>
#include <unordered_map>
#include "EngineEvent.h"
#include "GameEngine/Display/DisplayManager.hpp"
#include "GameEngine/Physics/IPhysicsApi.h"
#include "GameEngine/Renderers/RenderersManager.h"
#include "GameEngine/Resources/GpuResourceLoader.h"
#include "MeasurementHandler.h"
namespace GraphicsApi
{
class IGraphicsApi;
} // namespace GraphicsApi
namespace Input
{
class InputManager;
} // namespace Input
namespace Physics
{
class IPhysicsApi;
} // namespace Physics
namespace GameEngine
{
class DisplayManager;
namespace Renderer
{
class RenderersManager;
} // namespace Renderer
class EngineContext
{
public:
EngineContext(std::unique_ptr<GraphicsApi::IGraphicsApi>, std::unique_ptr<Physics::IPhysicsApi>);
~EngineContext();
void AddEngineEvent(EngineEvent);
std::optional<EngineEvent> GetEngineEvent();
inline Utils::MeasurementHandler& GetMeasurmentHandler();
inline DisplayManager& GetDisplayManager();
inline Physics::IPhysicsApi& GetPhysicsApi();
inline Input::InputManager& GetInputManager();
inline IGpuResourceLoader& GetGpuResourceLoader();
inline Utils::Thread::ThreadSync& GetThreadSync();
inline GraphicsApi::IGraphicsApi& GetGraphicsApi();
inline Renderer::RenderersManager& GetRenderersManager();
inline Utils::Time::TimerService& GetTimerService();
private:
Utils::MeasurementHandler measurmentHandler_;
std::unique_ptr<GraphicsApi::IGraphicsApi> graphicsApi_;
std::unique_ptr<Physics::IPhysicsApi> physicsApi_;
DisplayManager displayManager_;
std::unique_ptr<Input::InputManager> inputManager_;
Utils::Thread::ThreadSync threadSync_;
Utils::Time::TimerService timerService_;
GpuResourceLoader gpuResourceLoader_;
Renderer::RenderersManager renderersManager_;
std::mutex engineEventsMutex_;
std::list<EngineEvent> engineEvents_;
};
Utils::MeasurementHandler& EngineContext::GetMeasurmentHandler()
{
return measurmentHandler_;
}
DisplayManager& EngineContext::GetDisplayManager()
{
return displayManager_;
}
Physics::IPhysicsApi& EngineContext::GetPhysicsApi()
{
return *physicsApi_;
}
Input::InputManager& EngineContext::GetInputManager()
{
return *inputManager_;
}
IGpuResourceLoader& EngineContext::GetGpuResourceLoader()
{
return gpuResourceLoader_;
}
Utils::Thread::ThreadSync& EngineContext::GetThreadSync()
{
return threadSync_;
}
GraphicsApi::IGraphicsApi& EngineContext::GetGraphicsApi()
{
return *graphicsApi_;
}
Renderer::RenderersManager& EngineContext::GetRenderersManager()
{
return renderersManager_;
}
Utils::Time::TimerService& EngineContext::GetTimerService()
{
return timerService_;
}
} // namespace GameEngine
| [
"wbach.projects@gmail.com"
] | wbach.projects@gmail.com |
f737ae1cd10d5af11240e20b9ceff97a3229b718 | 04251e142abab46720229970dab4f7060456d361 | /lib/rosetta/source/src/protocols/features/DatabaseJobInputter.cc | e9ea7600961d47b9f51d53728476d8741e1af33a | [] | no_license | sailfish009/binding_affinity_calculator | 216257449a627d196709f9743ca58d8764043f12 | 7af9ce221519e373aa823dadc2005de7a377670d | refs/heads/master | 2022-12-29T11:15:45.164881 | 2020-10-22T09:35:32 | 2020-10-22T09:35:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,903 | cc | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file protocols/features/DatabaseJobInputter.cc
/// @brief
/// @author Matthew O'Meara (mattjomeara@gmail.com)
// Unit Headers
#include <protocols/features/DatabaseJobInputter.hh>
#include <protocols/features/DatabaseJobInputterCreator.hh>
#include <protocols/features/ProteinSilentReport.hh>
#include <protocols/jd2/Job.hh>
#include <protocols/jd2/InnerJob.hh>
// Project Headers
#include <basic/Tracer.hh>
#include <basic/options/option.hh>
#include <basic/options/keys/in.OptionKeys.gen.hh>
#include <basic/options/keys/inout.OptionKeys.gen.hh>
#include <basic/database/sql_utils.hh>
#include <core/conformation/Residue.hh>
#include <core/kinematics/Jump.hh>
#include <core/pose/Pose.hh>
#include <core/pose/util.hh>
#include <core/pose/symmetry/util.hh>
#include <core/scoring/ScoreFunction.hh>
// Utility Headers
#include <utility/vector1.hh>
#include <utility/file/FileName.hh>
#include <utility/string_util.hh>
#include <utility/sql_database/DatabaseSessionManager.hh>
// Boost Headers
#include <boost/lexical_cast.hpp>
// External Headers
#include <cppdb/frontend.h>
// C++ headers
#include <string>
#include <sstream>
static basic::Tracer tr( "protocols.features.DatabaseJobInputter" );
namespace protocols {
namespace features {
using std::string;
using std::stringstream;
using std::map;
using std::endl;
using core::Size;
using core::pose::initialize_disulfide_bonds;
using core::pose::Pose;
using core::pose::symmetry::is_symmetric;
using core::pose::symmetry::make_asymmetric_pose;
using core::scoring::ScoreFunction;
using core::scoring::ScoreFunctionOP;
using utility::vector1;
using utility::sql_database::sessionOP;
using cppdb::result;
DatabaseJobInputter::DatabaseJobInputter() :
scfxn_(utility::pointer::make_shared< ScoreFunction >()),
protein_silent_report_(utility::pointer::make_shared< ProteinSilentReport >())
{
tr.Debug << "Instantiate DatabaseJobInputter" << endl;
load_options_from_option_system();
}
DatabaseJobInputter::~DatabaseJobInputter() = default;
void
DatabaseJobInputter::load_options_from_option_system(){
using namespace basic::options;
using namespace basic::options::OptionKeys;
if ( option.has(inout::dbms::database_name) &&
option[inout::dbms::database_name].user() ) {
set_database_name(option[inout::dbms::database_name]);
}
if ( option.has(inout::dbms::pq_schema) &&
option[inout::dbms::pq_schema].user() ) {
set_database_pq_schema(option[inout::dbms::pq_schema]);
}
// The in::file::tags option was created for the silent file
// system--but using it makes sense here because, it serves the same
// purpose: specify which structures to use from the data source.
if ( option.has(in::dbms::struct_ids) && option[in::dbms::struct_ids].user() ) {
set_struct_ids_from_strings(option[in::dbms::struct_ids]);
}
if ( option[in::dbms::struct_ids].user() && option[in::select_structures_from_database].user() ) {
utility_exit_with_message("you cannot use -in:dbms:struct_ids and -in:select_structures_from_database simultaniously");
}
if ( option[in::select_structures_from_database].user() ) {
set_struct_ids_from_sql(option[in::select_structures_from_database]);
}
//TODO do we want this still?
// input_protocol_id_ = option[in::database_protocol];
}
void
DatabaseJobInputter::register_options(){
using namespace basic::options;
using namespace basic::options::OptionKeys;
option.add_relevant( inout::dbms::database_name );
option.add_relevant( inout::dbms::pq_schema );
option.add_relevant( inout::dbms::host );
option.add_relevant( inout::dbms::user );
option.add_relevant( inout::dbms::password );
option.add_relevant( inout::dbms::port );
option.add_relevant( inout::dbms::readonly );
option.add_relevant( inout::dbms::separate_db_per_mpi_process );
option.add_relevant( in::file::tags );
}
void
DatabaseJobInputter::set_database_name(
string const & database_name
) {
database_name_ = database_name;
}
string
DatabaseJobInputter::get_database_name() const {
if ( database_name_ == "" ) {
utility_exit_with_message(
"To use the DatabaseJobInputter, please specify the database "
"where thinput is data is stored, eg. via the -inout:dbms:database_name "
"<database_name> option system flag.");
}
return database_name_;
}
void
DatabaseJobInputter::set_database_pq_schema(
string const & database_pq_schema
) {
database_pq_schema_ = database_pq_schema;
}
string
DatabaseJobInputter::get_database_pq_schema() const {
return database_pq_schema_;
}
/// @brief Get score function
ScoreFunctionOP
DatabaseJobInputter::get_scorefunction(){
return scfxn_;
}
/// @brief Set score function
void
DatabaseJobInputter::set_scorefunction(ScoreFunctionOP scorefunction ){
scfxn_ = scorefunction;
}
void
DatabaseJobInputter::set_struct_ids_from_strings(
utility::vector1<string> const & struct_id_strings){
for ( core::Size i=1; i<=struct_id_strings.size(); ++i ) {
try{
auto struct_id = boost::lexical_cast<StructureID>(struct_id_strings[i]);
tag_structures_[struct_id_strings[i]] = struct_id;
}
catch(...){
stringstream err_msg;
err_msg
<< "Unable to convert the struct_id '" << struct_id_strings[i]
<< "' to a valid structure id. It should a valid integer value." << endl;
utility_exit_with_message(err_msg.str());
}
}
}
/// @details The specified struct_ids indicate which structures should be
/// used. If no ids are specified, then all will be used. Unless a tag column
/// is specified in the SQL statement, the job name (and
/// consequently, the file output name) will be an integer representation
/// of the struct_id. If a tag column is given, then the file name will
/// be the tag associated with the given row.
void
DatabaseJobInputter::set_struct_ids_from_sql(
utility::vector1<string> const & sql)
{
using namespace cppdb;
using namespace basic::database;
string sql_command(utility::join(sql, " "));
basic::database::check_statement_sanity(sql_command);
sessionOP db_session(
basic::database::get_db_session(database_name_, database_pq_schema_));
statement stmt = safely_prepare_statement( sql_command, db_session );
result res;
res = safely_read_from_database( stmt );
bool res_nums_specified = false;
if ( res.find_column("resnum") != -1 ) { res_nums_specified=true;}
bool tags_specified = false;
if ( res.find_column("tag") != -1 ) { tags_specified=true;}
if ( res.find_column("struct_id") != -1 ) {
while ( res.next() ) {
StructureID struct_id;
res.fetch("struct_id", struct_id);
std::string tag;
if ( tags_specified ) {
res.fetch("tag", tag);
if ( tag_structures_.count(tag) > 0 && tag_structures_[tag] != struct_id ) {
utility_exit_with_message("You have specified non-unque input tags which can cause ambigous output. Please make input tags unique");
}
} else {
tag = std::to_string(struct_id);
}
tag_structures_[tag] = struct_id;
if ( res_nums_specified ) {
core::Size resnum;
res.fetch("resnum", resnum);
tag_residues_[tag].insert(resnum);
}
}
if ( !tag_structures_.size() ) {
utility_exit_with_message("The provided SQL query did not produce any struct_ids");
}
} else {
utility_exit_with_message("Must provide an SQL SELECT command that selects the struct_id column from the structures table");
}
}
/// @details This function will first see if the pose already exists in the Job.
/// If not, it will read it into the pose reference, and hand a COP cloned from
/// that pose to the Job. If the pose pre-exists it just copies the COP's pose
/// into it.
void
DatabaseJobInputter::pose_from_job(
Pose & pose,
protocols::jd2::JobOP job
) {
using namespace basic::options;
using namespace basic::options::OptionKeys;
tr.Debug << "DatabaseJobInputter::pose_from_job" << std::endl;
string tag(job->input_tag());
pose.clear();
if ( !job->inner_job()->get_pose() ) {
tr.Debug << "filling pose from Database (input tag = " << tag << ")" << endl;
sessionOP db_session(
basic::database::get_db_session(database_name_, database_pq_schema_));
StructureID struct_id = tag_structures_[tag];
if ( !tag_residues_.size() ) {
protein_silent_report_->load_pose(db_session, struct_id, pose);
} else {
tr << "Residues list size " << tag_residues_[tag].size() << std::endl;
protein_silent_report_->load_pose(db_session, struct_id, tag_residues_[tag], pose);
}
} else {
tr.Debug << "filling pose from saved copy (input tag = " << tag << ")" << endl;
pose = *(job->inner_job()->get_pose());
}
// TODO: Move to pose.clear()
if ( is_symmetric(pose) ) make_asymmetric_pose( pose );
initialize_disulfide_bonds(pose);
}
/// @details this function determines what jobs exist
void protocols::features::DatabaseJobInputter::fill_jobs( protocols::jd2::JobsContainer & jobs ){
tr.Debug << "DatabaseJobInputter::fill_jobs" << std::endl;
jobs.clear(); //should already be empty anyway
core::Size const nstruct(get_nstruct());
if ( !tag_structures_.size() ) {
tr << "Reading all struct_ids from database ... ";
sessionOP db_session(
basic::database::get_db_session(database_name_, database_pq_schema_));
std::string stmt_string("SELECT struct_id FROM structures;");
cppdb::statement stmt( basic::database::safely_prepare_statement(stmt_string, db_session));
cppdb::result res( basic::database::safely_read_from_database(stmt));
while ( res.next() ) {
StructureID struct_id;
res >> struct_id;
tag_structures_[std::to_string(struct_id)]=struct_id;
}
tr << tag_structures_.size() << " struct_ids found." << endl;
}
vector1< protocols::jd2::InnerJobOP > inner_jobs;
//save list of all inner_jobs first... this allows better sampling
//of jobs in case of unfinished runs:
// input1_0001
// input2_0001
// ...
// inputn_0001
// input1_0002
// input2_0002
// ....
tr.Debug << "reserve memory for InnerJob List " << tag_structures_.size() << endl;
inner_jobs.reserve( tag_structures_.size() );
tr.Debug
<< "fill list with " << tag_structures_.size()
<< " InnerJob Objects" << endl;
for ( std::map<std::string, StructureID>::const_iterator iter=tag_structures_.begin(); iter!=tag_structures_.end(); ++iter ) {
inner_jobs.push_back(utility::pointer::make_shared< protocols::jd2::InnerJob >(iter->first, nstruct));
}
//tr.Debug
// << "reserve list for " << inner_jobs.size() * nstruct
// << " Job Objects" << endl;
//jobs.reserve(inner_jobs.size() * nstruct);
tr.Debug << "fill job list with... " << endl;
for ( core::Size index = 1; index <= nstruct; ++index ) {
for ( protocols::jd2::InnerJobOP ijob : inner_jobs ) {
jobs.push_back(utility::pointer::make_shared< protocols::jd2::Job >(ijob, index));
tr.Trace
<< "pushing " << ijob->input_tag() << " nstruct index " << index << std::endl;
}
}
}
/// @brief Return the type of input source that the
/// DatabaseJobInputter is currently using.
/// @return Always <em>DATABASE</em>.
protocols::jd2::JobInputterInputSource::Enum DatabaseJobInputter::input_source() const {
return protocols::jd2::JobInputterInputSource::DATABASE;
}
//CREATOR SECTION
std::string
DatabaseJobInputterCreator::keyname() const
{
return "DatabaseJobInputter";
}
protocols::jd2::JobInputterOP
DatabaseJobInputterCreator::create_JobInputter() const {
return utility::pointer::make_shared< DatabaseJobInputter >();
}
} // namespace features
} // namespace protocols
| [
"lzhangbk@connect.ust.hk"
] | lzhangbk@connect.ust.hk |
f2b4e7136be0b79b2bfb4b8a3c41716577576adc | 4bde0807beaea9939bc02f02a24c82703f71a4fd | /TBoardControllerRev2/src/Program/BoardController.cpp | 557ae8511d27c8f8c322ca97d035a4282b33c897 | [] | no_license | aelmendorf/ControllerFirmware_Rev2 | 8d58c93e9d8a9ff2f828283dbde7ffa6f8aae571 | b6fccafc5b3fb672c0b79180967377de91eb4bc8 | refs/heads/master | 2023-04-03T08:46:48.641882 | 2021-03-30T18:48:12 | 2021-03-30T18:48:12 | 315,748,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,502 | cpp | /*
* BoardController.cpp
*
* Created: 3/12/2019 12:41:52 PM
* Author: Andrew Elmendorf
* To Be Completely Redone
*/
#include "BoardController.h"
// default constructor
BoardController::BoardController()
{
//all fields explicitly initialized in setup/start
} //BoardController
void BoardController::Setup(){
//disable JTAG
MCUCR|=(1<<JTD);
//_NOP();
MCUCR|=(1<<JTD);
//Set clock 16mhz
CLKPR=0x80;
CLKPR=0;
//Signal LEDS
DDRB|=(1<<LEDR1) | (1<<LEDG1) | (1<<LEDB1);
PORTB|=(1<<LEDR1) | (1<<LEDG1) | (1<<LEDB1);
//Lid Switch setup
PORTF|=(1<<LIDSW);
DDRF&=~(1<<LIDSW);
//Current Driver Ports
DDRC|=(1<<LED_CTRL1);
DDRD|=(1<<LED_CTRL2) | (1<<LED_CTRL3);
//current driver setup
this->currentDriver.init();
//this->currentDriver.led1Current=SET_CURRENT;
}
void BoardController::Start(){
this->Setup();
millis_init();
sei();
this->time_reg.Init();
this->task.state=INIT;
this->task.error=false;
this->switch_latch=false;
}
void BoardController::Run(){
for(int i=0;i<BLINK;i++){
RunRed();
_delay_ms(250);
RunAllOff();
_delay_ms(250);
}
while(1){
switch(task.state){
case INIT:{
this->RunUVOff();
this->time_reg.ResetDay();
this->Transition_Wait(TO);
//this->Transition_AlwaysOn(TO);
break;
}
case WAIT_HR:{
this->Wait_On();
break;
}
case WAIT_DAY:{
this->Wait_Cycle();
break;
}
case WAIT_AUTO: {
this->Wait_Auto();
break;
}
case ALWAYS_ON:{
this->Always_On();
break;
}
}
_delay_ms(5);
}
}
bool BoardController::Check_Lid(){
return (PINF & (1<<LIDSW));
}
void BoardController::Wait_Cycle(){
if(this->Check_Lid()){
if(!this->task.error){
this->RunRed();
}
this->task.error=true;
}else{
if(this->task.error){
this->RunUVOff();
}
this->task.error=false;
}
if(this->time_reg.DayDone()){
this->Transition_Wait(TO);
}
}
void BoardController::Wait_Auto(){
if(this->Check_Lid()){
if(!this->task.error){
this->currentDriver.turn_off(0);
this->RunRed();
}
this->task.error=true;
}else{
if(this->task.error){
this->currentDriver.turn_on(0);
this->RunUVOn();
}
this->task.error=false;
}
if(this->time_reg.AutoDone()){
this->Transition_Auto(FROM);
}
}
void BoardController::Wait_On(){
if(this->Check_Lid()){
if(!this->task.error){
this->RunRed();
}
this->task.error=true;
}else{
if(this->task.error){
this->RunUVOff();
}
this->task.error=false;
}
if(this->time_reg.HrDone()){
this->Transition_Wait(FROM);
}
}
void BoardController::Always_On(void){
if(this->Check_Lid()){
if(!this->task.error){
this->RunRed();
this->currentDriver.turn_off(1);
}
this->task.error=true;
}else{
if(this->task.error){
this->RunUVOn();
this->currentDriver.turn_on(1);
}
this->task.error=false;
}
}
void BoardController::Transition_Auto(Direction direction){
switch(direction){
case TO:{
if(!this->task.error){
this->currentDriver.turn_on(1);
this->RunUVOn();
}
this->task.state=WAIT_AUTO;
this->time_reg.ResetAuto();
break;
}
case FROM:{
this->currentDriver.turn_off(1);
if(!this->task.error){
this->RunUVOff();
}
this->Transition_Cycle(TO);
break;
}
}
}
void BoardController::Transition_Wait(Direction direction){
switch(direction){
case TO:{
this->task.state=WAIT_HR;
if(!this->task.error){
this->RunUVOff();
}
this->time_reg.ResetDay();
break;
}
case FROM:{
this->Transition_Auto(TO);
//this->Transition_AlwaysOn(TO);
break;
}
}
}
void BoardController::Transition_Cycle(Direction direction){
switch(direction){
case TO:{
this->task.state=WAIT_DAY;
break;
}
case FROM:{
this->time_reg.ResetDay();
this->Transition_Wait(TO);
break;
}
}
}
void BoardController::Transition_AlwaysOn(Direction direction){
switch(direction){
case TO:{
this->task.state=ALWAYS_ON;
this->currentDriver.turn_on(1);
this->RunUVOn();
break;
}
case FROM:{
break;
}
}
}
void BoardController::RunUVOff(){
PORTB|=(1<<LEDR1) | (1<<LEDG1) | (1<<LEDB1);
PORTB&=~(1<<LEDG1);
}
void BoardController::RunUVOn(){
PORTB|=(1<<LEDR1) | (1<<LEDG1) | (1<<LEDB1);
PORTB&=~(1<<LEDB1);
}
void BoardController::RunRed(){
PORTB|=(1<<LEDR1) | (1<<LEDG1) | (1<<LEDB1);
PORTB&=~(1<<LEDR1);
}
void BoardController::RunAllOff(){
PORTB|=(1<<LEDR1) | (1<<LEDG1) | (1<<LEDB1);
}
// default destructor
BoardController::~BoardController()
{
//no dynamic memory
} //~BoardController
| [
"aelmendorf234@gmail.com"
] | aelmendorf234@gmail.com |
f0a60bcf05418afe8581bc530ed9f5d96415a446 | 3187dd3c1186cf97781987e455f5d11244f90aec | /examples/tlm/lt_temporal_decouple/src/initiator_top.cpp | 26238ef1a1995c8f6a4dbedf866cd3e09cde932f | [
"Apache-2.0"
] | permissive | Muriukidavid/systemc-2.3.2 | fe5d9d57636025cfdc0dee7eb9c8114ca19628ad | c5d203ac014277b9d2c2af895edc43537a15674e | refs/heads/master | 2020-03-13T13:17:48.813825 | 2018-04-26T09:48:42 | 2018-04-26T09:48:42 | 131,135,420 | 0 | 1 | Apache-2.0 | 2018-06-28T15:17:19 | 2018-04-26T09:51:26 | C++ | UTF-8 | C++ | false | false | 5,297 | cpp | /*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
//=====================================================================
/// @file initiator_top.cpp
//
/// @brief Instantiates initiator and traffic_generator
//
/// @details
/// This module performs:
/// 1. Instantiation of the traffic_generator and the lt_initiator
/// and the interconnecting sc_fifo's
/// 2. Binding of the Interconnect for the components
//
//==============================================================================
//
// Original Authors:
// Jack Donovan, ESLX
// Charles Wilson, ESLX
// Anna Keist, ESLX
//
//==============================================================================
#include "initiator_top.h" // this object's header file
#include "reporting.h" // reporting macro helpers
static const char *filename = "initiator_top.cpp"; ///< filename for reporting
/// Constructor
initiator_top::initiator_top
( sc_core::sc_module_name name
, const unsigned int ID
, sc_dt::uint64 base_address_1
, sc_dt::uint64 base_address_2
)
:sc_module (name) // module instance name
,top_initiator_socket // initialize the tlm socket
("top_initiator_socket")
,m_ID (ID) // initiator ID
,m_initiator // Init initiator
("m_initiator"
,ID // ID for reporting
)
,m_traffic_gen // Init traffic Generator
("m_traffic_gen"
,ID // ID for reporting
,base_address_1 // first base address
,base_address_2 // second base address
,4
)
{
/// Bind ports to m_request_fifo between m_initiator and m_traffic_gen
m_traffic_gen.request_out_port (m_request_fifo);
m_initiator.request_in_port (m_request_fifo);
/// Bind ports to m_response_fifo between m_initiator and m_traffic_gen
m_initiator.response_out_port(m_response_fifo);
m_traffic_gen.response_in_port (m_response_fifo);
/// Bind initiator-socket to initiator-socket hierarchical connection
m_initiator.initiator_socket(top_initiator_socket);
}
//==============================================================================
/// @fn initiator_top::invalidate_direct_mem_ptr
///
/// @brief Mandatory virtual implementation
///
/// @details
/// Unused but required when using hierarchical connectivity with simple_socket
/// Not implemented for this initiator
//
//==============================================================================
void
initiator_top::invalidate_direct_mem_ptr
( sc_dt::uint64 start_range
, sc_dt::uint64 end_range
)
{
std::ostringstream msg; // log message
msg.str ("");
msg << "Initiator: " << m_ID << " Not implemented";
REPORT_ERROR(filename, __FUNCTION__, msg.str());
} // end invalidate_direct_mem_ptr
//==============================================================================
/// @fn initiator_top::nb_transport_bw
//
/// @brief Mandatory virtual implementation
///
/// @details
/// Unused but required when using hierarchical connectivity with simple_socket
/// Not Used or Implemented in this example
///
//==============================================================================
tlm::tlm_sync_enum
initiator_top::nb_transport_bw
( tlm::tlm_generic_payload &payload
, tlm::tlm_phase &phase
, sc_core::sc_time &delta
)
{
std::ostringstream msg; // log message
msg.str ("");
msg << "Initiator: " << m_ID
<< " Not implemented, for hierachical connection of initiator socket";
REPORT_ERROR(filename, __FUNCTION__, msg.str());
return tlm::TLM_COMPLETED;
} // end nb_transport_bw
| [
"karfes@gmail.com"
] | karfes@gmail.com |
2888a2aeca40691260cf87f6c6f87f6a4d6a75cd | 5a161d37069a434b75874333c7b9e987cf89010b | /ogredeps/src/ois/includes/OISEffect.h | 478ca133fb0eec4d22412e0c003c4b14ebf22fbe | [
"Zlib"
] | permissive | jrsnail/u2project_deps | a4bd6835abc80ef35a27445865d8bde47502cb3d | 122b056e81d1d6c4560abd38995dab6f3d48d8a3 | refs/heads/master | 2021-05-04T11:38:50.720775 | 2016-12-02T13:08:39 | 2016-12-02T13:08:49 | 54,451,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,195 | h | /*
The zlib/libpng License
Copyright (c) 2005-2007 Phillip Castaneda (pjcast -- www.wreckedgames.com)
This software is provided 'as-is', without any express or implied warranty. In no event will
the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial
applications, and to alter it and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented; you must not claim that
you wrote the original software. If you use this software in a product,
an acknowledgment in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef OIS_Effect_H
#define OIS_Effect_H
#include "OISPrereqs.h"
namespace OIS
{
//Predeclare some Effect Property structs
class ForceEffect;
class ConstantEffect;
class RampEffect;
class PeriodicEffect;
class ConditionalEffect;
/**
Force Feedback is a relatively complex set of properties to upload to a device.
The best place for information on the different properties, effects, etc is in
the DX Documentation and MSDN - there are even pretty graphs ther =)
As this class is modeled on the the DX interface you can apply that same
knowledge to creating effects via this class on any OS supported by OIS.
In anycase, this is the main class you will be using. There is *absolutely* no
need to instance any of the supporting ForceEffect classes yourself.
*/
class _OISExport Effect
{
/**
hidden so this class cannot be instanced with default constructor
*/
Effect();
public:
//! Type of force
enum EForce
{
UnknownForce = 0,
ConstantForce,
RampForce,
PeriodicForce,
ConditionalForce,
CustomForce,
_ForcesNumber // Always keep in last position.
};
static const char* getForceTypeName(EForce eValue);
//! Type of effect
enum EType
{
//Type ----- Pairs with force:
Unknown = 0, //UnknownForce
Constant, //ConstantForce
Ramp, //RampForce
Square, //PeriodicForce
Triangle, //PeriodicForce
Sine, //PeriodicForce
SawToothUp, //PeriodicForce
SawToothDown,//PeriodicForce
Friction, //ConditionalForce
Damper, //ConditionalForce
Inertia, //ConditionalForce
Spring, //ConditionalForce
Custom, //CustomForce
_TypesNumber // Always keep in last position.
};
static const char* getEffectTypeName(EType eValue);
//! Direction of the Force
enum EDirection
{
NorthWest,
North,
NorthEast,
East,
SouthEast,
South,
SouthWest,
West,
_DirectionsNumber // Always keep in last position.
};
static const char* getDirectionName(EDirection eValue);
/**
This constructor allows you to set the force type and effect.
*/
Effect(EForce ef, EType et);
virtual ~Effect();
const EForce force;
const EType type;
//Infinite Time
static const unsigned int OIS_INFINITE = 0xFFFFFFFF;
//-------------------------------------------------------------------//
//--- Set these variables before uploading or modifying an effect ---//
//Direction to apply to the force - affects two axes+ effects
EDirection direction;
//Number of button triggering an effect (-1 means no trigger)
short trigger_button;
//Time to wait before an effect can be re-triggered (microseconds)
unsigned int trigger_interval;
//Duration of an effect (microseconds)
unsigned int replay_length;
//Time to wait before to start playing an effect (microseconds)
unsigned int replay_delay;
//Get the specific Force Effect. This should be cast depending on the EForce
ForceEffect* getForceEffect() const;
/**
@remarks
Set the number of Axes to use before the initial creation of the effect.
Can only be done prior to creation! Use the FF interface to determine
how many axes can be used (are availiable)
*/
void setNumAxes(short nAxes);
/**
@remarks
Returns the number of axes used in this effect
*/
short getNumAxes() const;
//------------- Library Internal -------------------------------------//
/**
set internally.. do not change or you will not be able to upload/stop
this effect any more. It will become lost. It is mutable so even
with const reference it can/will be changed by this lib
*/
mutable int _handle;
protected:
ForceEffect* effect; //Properties depend on EForce
short axes; //Number of axes to use in effect
};
//-----------------------------------------------------------------------------//
/**
Base class of all effect property classes
*/
class _OISExport ForceEffect
{
public:
virtual ~ForceEffect() {}
};
//-----------------------------------------------------------------------------//
/**
An optional envelope to be applied to the start/end of an effect. If any of
these values are nonzero, then the envelope will be used in setting up the
effect.
*/
class _OISExport Envelope : public ForceEffect
{
public:
Envelope() : attackLength(0), attackLevel(0), fadeLength(0), fadeLevel(0) {}
#if defined(OIS_MSVC_COMPILER)
#pragma warning (push)
#pragma warning (disable : 4800)
#endif
bool isUsed() const { return attackLength | attackLevel | fadeLength | fadeLevel; }
#if defined(OIS_MSVC_COMPILER)
#pragma warning (pop)
#endif
// Duration of the attack (microseconds)
unsigned int attackLength;
// Absolute level at the beginning of the attack (0 to 10K)
// (automatically signed when necessary by FF core according to effect level sign)
unsigned short attackLevel;
// Duration of fade (microseconds)
unsigned int fadeLength;
// Absolute level at the end of fade (0 to 10K)
// (automatically signed when necessary by FF core according to effect level sign)
unsigned short fadeLevel;
};
//-----------------------------------------------------------------------------//
/**
Use this class when dealing with Force type of Constant
*/
class _OISExport ConstantEffect : public ForceEffect
{
public:
ConstantEffect() : level(5000) {}
class Envelope envelope; //Optional envolope
signed short level; //-10K to +10k
};
//-----------------------------------------------------------------------------//
/**
Use this class when dealing with Force type of Ramp
*/
class _OISExport RampEffect : public ForceEffect
{
public:
RampEffect() : startLevel(0), endLevel(0) {}
class Envelope envelope; //Optional envelope
signed short startLevel; //-10K to +10k
signed short endLevel; //-10K to +10k
};
//-----------------------------------------------------------------------------//
/**
Use this class when dealing with Force type of Periodic
*/
class _OISExport PeriodicEffect : public ForceEffect
{
public:
PeriodicEffect() : magnitude(0), offset(0), phase(0), period(0) {}
class Envelope envelope; //Optional Envelope
unsigned short magnitude; //0 to 10,0000
signed short offset;
unsigned short phase; //Position at which playback begins 0 to 35,999
unsigned int period; //Period of effect (microseconds)
};
//-----------------------------------------------------------------------------//
/**
Use this class when dealing with Force type of Condional
*/
class _OISExport ConditionalEffect : public ForceEffect
{
public:
ConditionalEffect() :
rightCoeff(0), leftCoeff(0), rightSaturation(0), leftSaturation(0),
deadband(0), center(0) {}
signed short rightCoeff; //-10k to +10k (Positive Coeff)
signed short leftCoeff; //-10k to +10k (Negative Coeff)
unsigned short rightSaturation; //0 to 10k (Pos Saturation)
unsigned short leftSaturation; //0 to 10k (Neg Saturation)
//Region around center in which the condition is not active, in the range
//from 0 through 10,000
unsigned short deadband;
//(Offset in DX) -10k and 10k
signed short center;
};
}
#endif //OIS_Effect_H
| [
"jr19841227@gmail.com"
] | jr19841227@gmail.com |
94748dbba354bbe2a51dc72f8a30d5b66ff37cf6 | 6997f38c69ace216456c5ba2483f2ae8cbf79da7 | /cctest/run/xor3_main_body.cc | 2707b99781054df56d73d5a5679ac1c3ada2b67c | [] | no_license | hoangt/tdfc | 0b3edfc5c165c70c269bb11b04a4ee2d540575e7 | 409105cce82615f73b4142791de4b4df0d6c1557 | refs/heads/master | 2020-03-22T00:07:57.515493 | 2013-04-17T12:03:58 | 2013-04-17T12:03:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,578 | cc | //////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 1999 The Regents of the University of California
// Permission to use, copy, modify, and distribute this software and
// its documentation for any purpose, without fee, and without a
// written agreement is hereby granted, provided that the above copyright
// notice and this paragraph and the following two paragraphs appear in
// all copies.
//
// IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
// DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
// LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
// EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//
// THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON
// AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
// PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
//////////////////////////////////////////////////////////////////////////////
//
// BRASS source file
//
// SCORE runtime support (test)
// $Revision: 1.1 $
//
//////////////////////////////////////////////////////////////////////////////
#include "ScoreStream.h"
#include <iostream.h>
int main()
{
UNSIGNED_SCORE_STREAM s1, s2, s3, s4, s5;
int len=4;
int res[4];
int expect[4]={0xAA,0xAA,0x00,0xFF};
int in1[4]={0xFF,0xFF,0x00,0x55};
int in2[4]={0x55,0xAA,0xAA,0x5A};
int in3[4]={0x00,0xFF,0xAA,0xF0};
int i;
int errors=0;
s1=NEW_UNSIGNED_SCORE_STREAM(8);
s2=NEW_UNSIGNED_SCORE_STREAM(8);
s3=NEW_UNSIGNED_SCORE_STREAM(8);
// s4 is an intermediate stream inside xor3 in this instance
s5=XOR3_NAME(8,s1,s2,s3);
for (int i=0;i<len;i++)
{
STREAM_WRITE(s1,in1[i]);
// violating abstraction, don't try this at home...
cerr << "stream_data(s1)=" << STREAM_DATA(s1)
<< " stream_data(s2)=" << STREAM_DATA(s2)
<< " stream_data(s3)=" << STREAM_DATA(s3) << endl;
}
for (int i=0;i<len;i++)
{
STREAM_WRITE(s2,in2[i]);
// violating abstraction, don't try this at home...
cerr << "stream_data(s1)=" << STREAM_DATA(s1)
<< " stream_data(s2)=" << STREAM_DATA(s2)
<< " stream_data(s3)=" << STREAM_DATA(s3) << endl;
}
for (int i=0;i<len;i++)
{
STREAM_WRITE(s3,in3[i]);
// violating abstraction, don't try this at home...
cerr << "stream_data(s1)=" << STREAM_DATA(s1)
<< " stream_data(s2)=" << STREAM_DATA(s2)
<< " stream_data(s3)=" << STREAM_DATA(s3) << endl;
}
for (i=0;i<len;i++)
{
res[i]=STREAM_READ(s5);
if (res[i]!=expect[i])
{
cerr << XOR3_NAME << "_main: " << "ERROR" << " got "
<< res[i] << " expected "
<< expect[i] << endl;
errors++;
}
else
{
cout << XOR3_NAME << "_main: "
<< "OK got "
<< res[i]
<< endl;
}
}
STREAM_CLOSE(s1);
cout << "Closed input Stream 1" << endl;
STREAM_CLOSE(s3);
cout << "Closed input Stream 3" << endl;
STREAM_CLOSE(s2);
cout << "Closed input Stream 2" << endl;
while (!STREAM_EOS(s5))
{
int tmp=STREAM_READ(s5);
cerr << "ERROR" << " got " << tmp
<< " expecting eos " << endl;
errors++;
}
cout << "Done. errors=" << errors << endl;
STREAM_FREE(s5);
return(0);
}
| [
"nachiket@gmail.com"
] | nachiket@gmail.com |
4999f078a3cb9b64af013d263d75b3861504678b | 6dd87e89174e3e7fe05d5a56754000d65f06a5e1 | /1151.cpp | 88c2d1ce40d2b409a19c0d3ea5307b95842dbf73 | [] | no_license | danieltex/URI | 4bb4c85c755e6df7c25d0433441776f6192bc5c0 | 9c9fd3f6d1a11237af5917ff43017158f68452f9 | refs/heads/master | 2016-09-03T06:57:40.155154 | 2015-04-29T20:54:17 | 2015-04-29T20:54:17 | 33,696,433 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 266 | cpp | #include <iostream>
using namespace std;
int main() {
unsigned n;
cin >> n;
int i = 0, j = 1, c = 1;
cout << i;
while (c < n) {
c++;
i += j;
swap(i, j);
cout << ' ' << i;
}
cout << endl;
return 0;
} | [
"danieltex@gmail.com"
] | danieltex@gmail.com |
d6b6028273ccb0d858475da21a3defd694ed070f | f22871248319a151f81e1927d0c8b2bd156949cf | /udp_two_way_communicator/global_stuff.h | 3a91c02406e496ecc7bf531eb10caa843d6eeaa8 | [] | no_license | OlehKostiv/udp_experiment | c649230df80df750ce02bc51016c7940dd8555c2 | 244b0905832c9d3268d5f40fd1fdb9be4c09ef6a | refs/heads/master | 2021-01-24T07:55:25.598133 | 2018-02-26T12:14:00 | 2018-02-26T12:14:00 | 122,964,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 183 | h | #pragma once
#include <iostream>
#include <string>
constexpr int port = 8888;
extern void ErrorMessage(const std::string& message, int error = 0, std::ostream& output = std::cerr);
| [
"oleh.kostiv@gmail.com"
] | oleh.kostiv@gmail.com |
da660a40f6f68d6fbc32e719e54d626dda86b560 | 1d9b1b78887bdff6dd5342807c4ee20f504a2a75 | /lib/libcxx/include/__algorithm/ranges_none_of.h | 706ff5cd741dce01142612c8c8aa85ffe7cc30b5 | [
"MIT",
"LicenseRef-scancode-other-permissive",
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | mikdusan/zig | 86831722d86f518d1734ee5a1ca89d3ffe9555e8 | b2ffe113d3fd2835b25ddf2de1cc8dd49f5de722 | refs/heads/master | 2023-08-31T21:29:04.425401 | 2022-11-13T15:43:29 | 2022-11-13T15:43:29 | 173,955,807 | 1 | 0 | MIT | 2021-11-02T03:19:36 | 2019-03-05T13:52:53 | Zig | UTF-8 | C++ | false | false | 2,304 | h | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP___ALGORITHM_RANGES_NONE_OF_H
#define _LIBCPP___ALGORITHM_RANGES_NONE_OF_H
#include <__config>
#include <__functional/identity.h>
#include <__functional/invoke.h>
#include <__iterator/concepts.h>
#include <__iterator/projected.h>
#include <__ranges/access.h>
#include <__ranges/concepts.h>
#include <__utility/move.h>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
# pragma GCC system_header
#endif
#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)
_LIBCPP_BEGIN_NAMESPACE_STD
namespace ranges {
namespace __none_of {
struct __fn {
template <class _Iter, class _Sent, class _Proj, class _Pred>
_LIBCPP_HIDE_FROM_ABI constexpr static
bool __none_of_impl(_Iter __first, _Sent __last, _Pred& __pred, _Proj& __proj) {
for (; __first != __last; ++__first) {
if (std::invoke(__pred, std::invoke(__proj, *__first)))
return false;
}
return true;
}
template <input_iterator _Iter, sentinel_for<_Iter> _Sent, class _Proj = identity,
indirect_unary_predicate<projected<_Iter, _Proj>> _Pred>
_LIBCPP_HIDE_FROM_ABI constexpr
bool operator()(_Iter __first, _Sent __last, _Pred __pred = {}, _Proj __proj = {}) const {
return __none_of_impl(std::move(__first), std::move(__last), __pred, __proj);
}
template <input_range _Range, class _Proj = identity,
indirect_unary_predicate<projected<iterator_t<_Range>, _Proj>> _Pred>
_LIBCPP_HIDE_FROM_ABI constexpr
bool operator()(_Range&& __range, _Pred __pred, _Proj __proj = {}) const {
return __none_of_impl(ranges::begin(__range), ranges::end(__range), __pred, __proj);
}
};
} // namespace __none_of
inline namespace __cpo {
inline constexpr auto none_of = __none_of::__fn{};
} // namespace __cpo
} // namespace ranges
_LIBCPP_END_NAMESPACE_STD
#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)
#endif // _LIBCPP___ALGORITHM_RANGES_NONE_OF_H
| [
"andrew@ziglang.org"
] | andrew@ziglang.org |
c6edc8d33020bab44bea518d7642b1c1db6a6096 | 8563ac804698b11bfe766c93d5666f99335d9d7d | /Program_Class/C/Week2/Week3-4.cpp | ad079d656eb4e729996b19c845c1d79fab832782 | [] | no_license | tom19960222/Program_Class | 7acea70a172296f2c7b5e1a0ab19f0486f225c5b | e25aa0c0104f2e48acc3a052fe3e4296e610e734 | refs/heads/master | 2016-09-06T10:51:47.122837 | 2015-05-25T08:47:10 | 2015-05-25T08:47:10 | 25,857,886 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | cpp | #include <stdio.h>
int main()
{
float discount = 1;
int units;
printf ("Units: ");
scanf ("%d", &units);
if (units >= 10 && units < 20)
discount = 0.8;
else if (units >= 20 && units < 50)
discount = 0.7;
else if (units >= 50 && units < 100)
discount = 0.6;
else if (units > 100)
discount = 0.5;
printf ("Cost: %.0f", units*100*discount);
return 0;
}
| [
"tom19960222@gmail.com"
] | tom19960222@gmail.com |
e86ae06dbfde00f10acc82bd06d8fbff631d82c7 | 2e64cf91ab66a3b9305085e6e5ab338c3da70a63 | /client/src/modules/pump/Pump.hpp | 65b74f64cccd6117bbaa4123851ccb4a11b00f52 | [] | no_license | geNAZt/gardon-ota | 1fea5be70109f88666c5cfa44fb92138fc3f9c26 | e9c49d6ee2893032aeb06bae33c7433f3011edef | refs/heads/main | 2023-08-20T11:42:21.008105 | 2021-10-04T09:25:10 | 2021-10-04T09:25:10 | 412,347,287 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,484 | hpp | #pragma once
#include <NTPClient.h>
#include "../Module.h"
namespace Module {
namespace Pump {
class Pump : public ModuleBase {
public:
explicit Pump(char pin, NTPClient* timeClient) {
this->_pin = pin;
this->_time = timeClient;
pinMode(this->_pin, OUTPUT);
this->off();
}
void loop(unsigned long millis) {
if (this->_onUntil != 0 && millis >= this->_onUntil) {
this->off();
}
}
const char* name() {
return "Pump";
}
String metric() {
return String("pump value=" + String((this->isOn()) ? "1" : "0"));
}
void onFor(unsigned long forMillis) {
digitalWrite(this->_pin, HIGH);
this->_on = true;
this->_onUntil = millis() + forMillis;
}
void off() {
digitalWrite(this->_pin, LOW);
this->_on = false;
}
bool isOn() {
return this->_on;
}
private:
char _pin;
unsigned long _onUntil{};
NTPClient* _time;
bool _on{};
};
}
}
| [
"fabian.fassbender42@googlemail.com"
] | fabian.fassbender42@googlemail.com |
f67b1b68f44aa2ed0aea5f58f48bff13c7c2540b | 24d6d26deecbf7d8449aff93a53dec78405fcbb9 | /gvModel/mCamera.cpp | dc310241b4204675d2e1dc1461edf41591c9b7cf | [] | no_license | serkozzz/GeometryViewer | a1d88b56b2987805b326678ff1ca24d0d139cf96 | 47c45f673bd39d57ae774b330df3f956be18af81 | refs/heads/master | 2020-04-16T02:26:40.814020 | 2016-06-06T17:51:38 | 2016-06-06T17:51:38 | 48,893,252 | 0 | 0 | null | 2016-06-06T17:51:38 | 2016-01-01T23:59:23 | HTML | UTF-8 | C++ | false | false | 1,417 | cpp | #include <glm/gtc/matrix_transform.hpp>
#include "mCamera.h"
using namespace gv::Model;
mCamera::mCamera()
{
_transform = glm::mat4(1.0f);
}
glm::mat4 mCamera::getTransform() const
{
return _transform;
}
void mCamera::setTransform(const glm::mat4& newTransform)
{
_transform = newTransform;
propertyChanged(CameraPropChangedArgs(this, &newTransform, ICamera::transformPropertyName));
}
void mCamera::trySetTransform(const glm::mat4& newTransform) const
{
tryPropertyChanged(CameraPropChangedArgs(this, &newTransform, ICamera::transformPropertyName));
}
glm::vec3 mCamera::getPosition() const
{
return glm::vec3(_transform[3].x, _transform[3].y, _transform[3].z);
}
void mCamera::setPosition(const glm::vec3& newPosition)
{
_transform[3] = glm::vec4(newPosition, 1.0f);
propertyChanged(CameraPropChangedArgs(this, &newPosition, ICamera::positionPropertyName));
}
void mCamera::trySetPosition(const glm::vec3& newPosition) const
{
tryPropertyChanged(CameraPropChangedArgs(this, &newPosition, ICamera::positionPropertyName));
}
std::string mCamera::getName() const
{
return _name;
}
void mCamera::setName(const std::string& newName)
{
_name = newName;
propertyChanged(CameraPropChangedArgs(this, &newName, ICamera::namePropertyName));
}
void mCamera::trySetName(const std::string& newName) const
{
tryPropertyChanged(CameraPropChangedArgs(this, &newName, ICamera::namePropertyName));
}
| [
"s.kozlov@blackmana.com"
] | s.kozlov@blackmana.com |
7806a5952896f4a70fdd117305807821d473685c | 32e43c3cce09f4659035644e70a4e2e88b021c15 | /aoj/dsl/2e.cpp | 89a7f1c48e64a65c3b6e030cc04bf1f1bc393dd1 | [] | no_license | sp4ghet/comp | 22c7453bcd4aff56970f3ee465e0c66ca0ab697f | 222911d45ab513c88d5450919d8c803cb0f7da1c | refs/heads/master | 2020-12-04T15:59:34.368399 | 2020-09-19T15:00:31 | 2020-09-19T15:00:31 | 231,827,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,930 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;
using vint = vector<int>;
using vvint = vector<vint>;
using vll = vector<ll>;
using vvll = vector<vll>;
using vchar = vector<char>;
using vvchar = vector<vchar>;
using vp = vector<P>;
using vpp = vector<pair<P, P>>;
using vvp = vector<vp>;
#define rep(i, n) for (int i = 0; i < n; ++i)
#pragma region Debug
istream &operator>>(istream &is, P &a)
{
return is >> a.first >> a.second;
}
ostream &operator<<(ostream &os, const P &a) { return os << "(" << a.first << "," << a.second << ")"; }
template <typename T>
void view(const std::vector<T> &v)
{
#ifndef ONLINE_JUDGE
for (const auto &e : v)
{
std::cout << e << " ";
}
std::cout << std::endl;
#endif
}
template <typename T>
void view(const std::vector<std::vector<T>> &vv)
{
for (const auto &v : vv)
{
view(v);
}
}
#pragma endregion
int main()
{
int n, q;
cin >> n >> q;
int size = 1 << (int)(log2(n) + 1) + 1;
vint seg(size, 0);
auto get = [&](int i) {
int k = i + n;
int ans = seg[k];
while (k)
{
k /= 2;
ans += seg[k];
}
return ans;
};
auto addRange = [&](int s, int t, int x) {
int l = s + n,
r = t + n;
while (l < r)
{
if (l % 2)
{
seg[l] += x;
l++;
}
l /= 2;
if (r % 2)
{
seg[r - 1] += x;
r--;
}
r /= 2;
}
};
rep(i, q)
{
int com, s, t, x;
cin >> com;
if (com)
{
cin >> t;
int ans = get(t);
cout << ans << "\n";
}
else
{
cin >> s >> t >> x;
addRange(s, t + 1, x);
}
}
return 0;
} | [
"8775460+sp4ghet@users.noreply.github.com"
] | 8775460+sp4ghet@users.noreply.github.com |
697fdf3df9eb2231ef75375c4e4f123fb646dd23 | 6d9104bde8dc3d5d459e1cafae2176a45ae619ba | /Programmers/Hash/Hash_04.cpp | 8978f8d074c44c1c79c6f2e514613adcff445ee0 | [] | no_license | YeJi-Park/Algorithm-Study | ed7c69cb2be277e44d842fc17059016101c094f1 | 2603b036c8c0660493fdcb7f0c6d8d4b8c0361ed | refs/heads/master | 2021-06-08T15:02:23.260710 | 2021-05-16T12:08:58 | 2021-05-16T12:08:58 | 164,603,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | cpp | /*
@Author YJ Park
@Date 19. 01. 10
@Descript Programmers Hash #04
*/
#include <string>
#include <vector>
#include <unordered_map>
#include <map>
#include <iostream>
#include <functional>
using namespace std;
vector<int> solution(vector<string> genres, vector<int> plays) {
vector<int> answer;
unordered_map<string, int> genre_list;
map<int, string, greater<int>> rvs_list;
unordered_map<string, vector<int>> song_list;
int size = genres.size();
for (int i = 0; i < size; i++) {
genre_list[genres[i]] += plays[i];
song_list[genres[i]].push_back(i);
}
for (auto iter = genre_list.begin(); iter != genre_list.end(); ++iter) {
rvs_list[iter->second] = iter->first;
}
for (auto iter = rvs_list.begin(); iter != rvs_list.end(); ++iter) {
string genre = iter->second;
vector<int> songs = song_list[genre];
size = songs.size();
int first = -1, second = -1;
for (int i = size - 1; i >= 0; i--) {
int temp = plays[songs[i]];
if (first == -1) first = songs[i];
else if (second == -1) second = songs[i];
else if (temp >= plays[first]) {
second = first;
first = songs[i];
}
else if (temp >= plays[second])
second = songs[i];
}
answer.push_back(first);
if (size != 1)
answer.push_back(second);
}
return answer;
} | [
"tuilte38@gmail.com"
] | tuilte38@gmail.com |
3bc747638388d2da629b8d40e7a89fd8bd9e4e3c | 5467bbb4c22e130fd510b6fb234770cbc781494c | /Leetcode/Sliding Window Maximum/main.cpp | 04d8a05a3798804ed8260ada580bcce939a9a438 | [] | no_license | mlomb/problems | 064b196214b186450a0b25f1ba4770b56aa311f9 | 9d10710e44ec8dc80874e8560c073792c3a5916b | refs/heads/master | 2021-07-01T18:22:55.034203 | 2019-04-04T17:13:03 | 2019-04-04T17:13:03 | 139,168,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 488 | cpp | class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> result;
deque<int> v;
int i = 0, j = 0;
for(int pos = 0; pos < nums.size(); pos++) {
// advance i
if(pos >= k){
if(v.front() == i)
v.pop_front();
i++;
}
// advance j
while(!v.empty() && nums[j] >= nums[v.back()])
v.pop_back();
v.push_back(j);
j++;
if(pos >= k - 1)
result.push_back(nums[v.front()]);
}
return result;
}
}; | [
"mlomb@users.noreply.github.com"
] | mlomb@users.noreply.github.com |
4ffa7ac2c92718e334dd756ec9bcb734218145b5 | 9de0cec678bc4a3bec2b4adabef9f39ff5b4afac | /PWGLF/NUCLEX/Nuclei/TritonAnalysis/AliAnalysisTaskTritonVsMultiplicity_PbPb.cxx | 25e141e2638f1ef96fd077cb71e238b7e71cb1dc | [] | permissive | alisw/AliPhysics | 91bf1bd01ab2af656a25ff10b25e618a63667d3e | 5df28b2b415e78e81273b0d9bf5c1b99feda3348 | refs/heads/master | 2023-08-31T20:41:44.927176 | 2023-08-31T14:51:12 | 2023-08-31T14:51:12 | 61,661,378 | 129 | 1,150 | BSD-3-Clause | 2023-09-14T18:48:45 | 2016-06-21T19:31:29 | C++ | UTF-8 | C++ | false | false | 22,405 | cxx | #include "AliAnalysisTaskTritonVsMultiplicity_PbPb.h"
#include "AliInputEventHandler.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisTaskSE.h"
#include "AliAnalysisUtils.h"
#include "AliMultSelection.h"
#include "AliMultEstimator.h"
#include "AliAnalysisTask.h"
#include "TLorentzVector.h"
#include "AliPIDResponse.h"
#include "AliCentrality.h"
#include "TDatabasePDG.h"
#include "AliAODVertex.h"
#include "AliEventCuts.h"
#include "AliAODTrack.h"
#include "AliAODEvent.h"
#include "TObjArray.h"
#include "TVector2.h"
#include "TVector3.h"
#include "TRandom.h"
#include "TChain.h"
#include "TMath.h"
#include "TList.h"
#include "TH1F.h"
#include "TH2F.h"
ClassImp(AliAnalysisTaskTritonVsMultiplicity_PbPb)
//_________________________________________________________________________________________________________________________________________________________________________________________________
AliAnalysisTaskTritonVsMultiplicity_PbPb::AliAnalysisTaskTritonVsMultiplicity_PbPb():
AliAnalysisTaskSE(),
fAODevent(NULL),
fPIDResponse(NULL),
fAODeventCuts(),
fUtils(NULL),
fOutputList(NULL),
//fQAList(NULL),
fCentralityMin(0),
fCentralityMax(0),
fVertexZmin(0),
fVertexZmax(0),
fNumberVertexContributorsMin(0),
fCentralityEstimator(NULL),
fPtMin(0),
fPtMax(0),
fEtaMax(0),
fYMax(0),
fNumberClustersITSMin(0),
fNumberClustersTPCMin(0),
fNumberCrossedRowsTPCMin(0),
fCrossedRowsFindableClsMin(0),
fNumberClustersTPCdEdxMin(0),
fChiSquarePerNDFMax(0),
fITSrequirement(NULL),
fDCAzMax(0),
fDCAxyMax(0),
fnSigmaTOFmax(0),
fnSigmaTPCmax(0),
fTRDntracklets(0),
fpar0_mean_TPC(0),
fpar1_mean_TPC(0),
fpar0_sigma_TPC(0),
fpar0_mean_TOF(0),
fpar1_mean_TOF(0),
fpar0_sigma_TOF(0),
fpar1_sigma_TOF(0)
{}
//_________________________________________________________________________________________________________________________________________________________________________________________________
AliAnalysisTaskTritonVsMultiplicity_PbPb::AliAnalysisTaskTritonVsMultiplicity_PbPb(const char *name):
AliAnalysisTaskSE(name),
fAODevent(NULL),
fPIDResponse(NULL),
fAODeventCuts(),
fUtils(NULL),
fOutputList(NULL),
//fQAList(NULL),
fCentralityMin(0),
fCentralityMax(0),
fVertexZmin(0),
fVertexZmax(0),
fNumberVertexContributorsMin(0),
fCentralityEstimator(NULL),
fPtMin(0),
fPtMax(0),
fEtaMax(0),
fYMax(0),
fNumberClustersITSMin(0),
fNumberClustersTPCMin(0),
fNumberCrossedRowsTPCMin(0),
fCrossedRowsFindableClsMin(0),
fNumberClustersTPCdEdxMin(0),
fChiSquarePerNDFMax(0),
fITSrequirement(NULL),
fDCAzMax(0),
fDCAxyMax(0),
fnSigmaTOFmax(0),
fnSigmaTPCmax(0),
fTRDntracklets(0),
fpar0_mean_TPC(0),
fpar1_mean_TPC(0),
fpar0_sigma_TPC(0),
fpar0_mean_TOF(0),
fpar1_mean_TOF(0),
fpar0_sigma_TOF(0),
fpar1_sigma_TOF(0)
{
fUtils = new AliAnalysisUtils();
DefineInput(0, TChain::Class());
DefineOutput(1, TList::Class());
//DefineOutput(2, TList::Class());
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
AliAnalysisTaskTritonVsMultiplicity_PbPb::~AliAnalysisTaskTritonVsMultiplicity_PbPb()
{
fOutputList->Clear();
delete fAODevent;
delete fPIDResponse;
delete fUtils;
delete fOutputList;
//delete fQAList;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
void AliAnalysisTaskTritonVsMultiplicity_PbPb::UserCreateOutputObjects()
{
fOutputList = new TList();
fOutputList -> SetOwner();
//fQAList = new TList();
//fQAList -> SetOwner();
//fAODeventCuts.AddQAplotsToList(fQAList);//Add event selection QA plots
//Number of Events
histoNumberOfEvents = new TH1F("histoNumberOfEvents","Events after selection steps",10,0,10);
fOutputList -> Add (histoNumberOfEvents);
//Signal Extraction
histoNsigmaTPCtriton_vs_pt = new TH2F ("histoNsigmaTPCtriton_vs_pt","",500,0,5,1000,-20,20);
histoNsigmaTOFtriton_vs_pt = new TH2F ("histoNsigmaTOFtriton_vs_pt","",500,0,5,1000,-20,20);
histoNsigmaTPCantitriton_vs_pt = new TH2F ("histoNsigmaTPCantitriton_vs_pt","",500,0,5,1000,-20,20);
histoNsigmaTOFantitriton_vs_pt = new TH2F ("histoNsigmaTOFantitriton_vs_pt","",500,0,5,1000,-20,20);
histoNsigmaTPCtriton_vs_pt_centered = new TH2F ("histoNsigmaTPCtriton_vs_pt_centered","",500,0,5,1000,-20,20);
histoNsigmaTPCantitriton_vs_pt_centered = new TH2F ("histoNsigmaTPCantitriton_vs_pt_centered","",500,0,5,1000,-20,20);
histoNsigmaTOFtriton_vs_pt_centered = new TH2F ("histoNsigmaTOFtriton_vs_pt_centered","",500,0,5,1000,-20,20);
histoNsigmaTOFantitriton_vs_pt_centered = new TH2F ("histoNsigmaTOFantitriton_vs_pt_centered","",500,0,5,1000,-20,20);
histoNsigmaTOFtriton_vs_pt_trd = new TH2F ("histoNsigmaTOFtriton_vs_pt_trd","",500,0,5,1000,-20,20);
histoNsigmaTOFantitriton_vs_pt_trd = new TH2F ("histoNsigmaTOFantitriton_vs_pt_trd","",500,0,5,1000,-20,20);
histoNsigmaTPCtriton_vs_p = new TH2F ("histoNsigmaTPCtriton_vs_p","",500,0,5,1000,-20,20);
histoNsigmaTPCantitriton_vs_p = new TH2F ("histoNsigmaTPCantitriton_vs_p","",500,0,5,1000,-20,20);
histoNsigmaTOFtriton_vs_p = new TH2F ("histoNsigmaTOFtriton_vs_p","",500,0,5,1000,-20,20);
histoNsigmaTOFantitriton_vs_p = new TH2F ("histoNsigmaTOFantitriton_vs_p","",500,0,5,1000,-20,20);
histoNsigmaTPCtriton_vs_p_notof = new TH2F ("histoNsigmaTPCtriton_vs_p_notof","",500,0,5,1000,-20,20);
histoNsigmaTPCantitriton_vs_p_notof = new TH2F ("histoNsigmaTPCantitriton_vs_p_notof","",500,0,5,1000,-20,20);
histoNsigmaTPCtriton_vs_pt -> Sumw2();
histoNsigmaTOFtriton_vs_pt -> Sumw2();
histoNsigmaTPCantitriton_vs_pt -> Sumw2();
histoNsigmaTOFantitriton_vs_pt -> Sumw2();
histoNsigmaTPCtriton_vs_pt_centered -> Sumw2();
histoNsigmaTPCantitriton_vs_pt_centered -> Sumw2();
histoNsigmaTOFtriton_vs_pt_centered -> Sumw2();
histoNsigmaTOFantitriton_vs_pt_centered -> Sumw2();
histoNsigmaTOFtriton_vs_pt_trd -> Sumw2();
histoNsigmaTOFantitriton_vs_pt_trd -> Sumw2();
histoNsigmaTPCtriton_vs_p -> Sumw2();
histoNsigmaTPCantitriton_vs_p -> Sumw2();
histoNsigmaTOFtriton_vs_p -> Sumw2();
histoNsigmaTOFantitriton_vs_p -> Sumw2();
histoNsigmaTPCtriton_vs_p_notof -> Sumw2();
histoNsigmaTPCantitriton_vs_p_notof -> Sumw2();
fOutputList -> Add(histoNsigmaTPCtriton_vs_pt);
fOutputList -> Add(histoNsigmaTOFtriton_vs_pt);
fOutputList -> Add(histoNsigmaTPCantitriton_vs_pt);
fOutputList -> Add(histoNsigmaTOFantitriton_vs_pt);
fOutputList -> Add(histoNsigmaTPCtriton_vs_pt_centered);
fOutputList -> Add(histoNsigmaTPCantitriton_vs_pt_centered);
fOutputList -> Add(histoNsigmaTOFtriton_vs_pt_centered);
fOutputList -> Add(histoNsigmaTOFantitriton_vs_pt_centered);
fOutputList -> Add(histoNsigmaTOFtriton_vs_pt_trd);
fOutputList -> Add(histoNsigmaTOFantitriton_vs_pt_trd);
fOutputList -> Add(histoNsigmaTPCtriton_vs_p);
fOutputList -> Add(histoNsigmaTPCantitriton_vs_p);
fOutputList -> Add(histoNsigmaTOFtriton_vs_p);
fOutputList -> Add(histoNsigmaTOFantitriton_vs_p);
fOutputList -> Add(histoNsigmaTPCtriton_vs_p_notof);
fOutputList -> Add(histoNsigmaTPCantitriton_vs_p_notof);
//DCA Distributions
histoDCAxyTriton_vs_pt = new TH2F ("histoDCAxyTriton_vs_pt","",500,0,5,500,-5,5);
histoDCAxyAntiTriton_vs_pt = new TH2F ("histoDCAxyAntiTriton_vs_pt","",500,0,5,500,-5,5);
histoDCAxyTriton_vs_pt -> Sumw2();
histoDCAxyAntiTriton_vs_pt -> Sumw2();
fOutputList -> Add (histoDCAxyTriton_vs_pt);
fOutputList -> Add (histoDCAxyAntiTriton_vs_pt);
PostData(1, fOutputList);
//PostData(2, fQAList);
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
void AliAnalysisTaskTritonVsMultiplicity_PbPb::UserExec(Option_t *)
{
//Get Input Event
if ( !GetInputEvent ()) return;
//Load PID Response
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler *inputHandler = (AliInputEventHandler*) (mgr->GetInputEventHandler());
fPIDResponse = inputHandler->GetPIDResponse();
//Loop over Reconstructed Tracks
for (Int_t i=0 ; i<fAODevent->GetNumberOfTracks() ; i++) {
//Track Selection
AliAODTrack *track = (AliAODTrack*) fAODevent -> GetTrack(i);
if ( !track ) continue;
if ( PassedTrackQualityCutsNoDCA (track)) {
if (IsCleanTritonCandidate(track)) {
if (track->Charge()>0) histoDCAxyTriton_vs_pt -> Fill (track->Pt(),GetDCAxy(track));
if (track->Charge()<0) histoDCAxyAntiTriton_vs_pt -> Fill (track->Pt(),GetDCAxy(track));
}
}
if ( !PassedTrackQualityCuts (track)) continue;
//Variables
Double_t nsigmaTPC = fPIDResponse -> NumberOfSigmasTPC (track,AliPID::kTriton);
Double_t nsigmaTOF = fPIDResponse -> NumberOfSigmasTOF (track,AliPID::kTriton);
//TPC Signal vs. pT
if (track->Charge()>0) histoNsigmaTPCtriton_vs_p_notof -> Fill (track->P(),nsigmaTPC);
if (track->Charge()<0) histoNsigmaTPCantitriton_vs_p_notof -> Fill (track->P(),nsigmaTPC);
if (PassedTOFSelection(track)) {
if (track->Charge()>0) histoNsigmaTPCtriton_vs_pt -> Fill (track->Pt(),nsigmaTPC);
if (track->Charge()<0) histoNsigmaTPCantitriton_vs_pt -> Fill (track->Pt(),nsigmaTPC);
if (track->Charge()>0) histoNsigmaTPCtriton_vs_p -> Fill (track->P(),nsigmaTPC);
if (track->Charge()<0) histoNsigmaTPCantitriton_vs_p -> Fill (track->P(),nsigmaTPC);
if (track->Charge()>0) histoNsigmaTPCtriton_vs_pt_centered -> Fill (track->Pt(),Centered_nsigmaTPC(track));
if (track->Charge()<0) histoNsigmaTPCantitriton_vs_pt_centered -> Fill (track->Pt(),Centered_nsigmaTPC(track));
}
//TOF Signal vs. pT
if (PassedTPCSelection(track)) {
if (track->Charge()>0) histoNsigmaTOFtriton_vs_pt -> Fill (track->Pt(),nsigmaTOF);
if (track->Charge()<0) histoNsigmaTOFantitriton_vs_pt -> Fill (track->Pt(),nsigmaTOF);
if (track->Charge()>0) histoNsigmaTOFtriton_vs_p -> Fill (track->P(),nsigmaTOF);
if (track->Charge()<0) histoNsigmaTOFantitriton_vs_p -> Fill (track->P(),nsigmaTOF);
if (track->Charge()>0 && track->GetTRDntrackletsPID()>fTRDntracklets) histoNsigmaTOFtriton_vs_pt_trd -> Fill (track->Pt(),nsigmaTOF);
if (track->Charge()<0 && track->GetTRDntrackletsPID()>fTRDntracklets) histoNsigmaTOFantitriton_vs_pt_trd -> Fill (track->Pt(),nsigmaTOF);
if (track->Charge()>0) histoNsigmaTOFtriton_vs_pt_centered -> Fill (track->Pt(),Centered_nsigmaTOF(track));
if (track->Charge()<0) histoNsigmaTOFantitriton_vs_pt_centered -> Fill (track->Pt(),Centered_nsigmaTOF(track));
}
}
PostData(1, fOutputList);
//PostData(2, fQAList);
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
Bool_t AliAnalysisTaskTritonVsMultiplicity_PbPb::GetInputEvent () {
//Get Input Event
fAODevent = dynamic_cast <AliAODEvent*>(InputEvent());
if (!fAODevent) return false;
histoNumberOfEvents -> Fill(0.5);
//Standard Event Cuts
if (!fAODeventCuts.AcceptEvent(fAODevent)) {
//PostData(2, fQAList);
return false;
}
histoNumberOfEvents -> Fill(1.5);
//Centrality
AliMultSelection *multiplicitySelection = (AliMultSelection*) fAODevent->FindListObject("MultSelection");
if( !multiplicitySelection) return false;
histoNumberOfEvents -> Fill(2.5);
Double_t centrality = multiplicitySelection->GetMultiplicityPercentile(fCentralityEstimator);
//Selection of Centrality Range
if (centrality<fCentralityMin || centrality>=fCentralityMax ) return false;
histoNumberOfEvents -> Fill(3.5);
//Primary Vertex
AliAODVertex *vertex = (AliAODVertex*) fAODevent->GetPrimaryVertex();
if ( !vertex ) return false;
histoNumberOfEvents -> Fill(4.5);
//Primary Vertex Selection
if ( vertex->GetZ() < fVertexZmin ) return false;
if ( vertex->GetZ() > fVertexZmax ) return false;
histoNumberOfEvents -> Fill(5.5);
if ( vertex->GetNContributors() < fNumberVertexContributorsMin ) return false;
histoNumberOfEvents -> Fill(6.5);
return true;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
Bool_t AliAnalysisTaskTritonVsMultiplicity_PbPb::PassedTrackQualityCuts (AliAODTrack* track) {
//Filterbit
if(!track->TestFilterMask(AliAODTrack::kTrkGlobalNoDCA)) return false;
//Rapidity Calculation
Double_t m = AliPID::ParticleMass(AliPID::kTriton);
Double_t px = track -> Px();
Double_t py = track -> Py();
Double_t pz = track -> Pz();
Double_t E = TMath::Sqrt(m*m + px*px + py*py + pz*pz);
TLorentzVector P (px,py,pz,E);
Double_t y = P.Rapidity();
//Kinematic Cuts & Acceptance
if ( track->Pt()<fPtMin || track->Pt()>fPtMax ) return false;
if ( TMath::Abs(track->Eta()) > fEtaMax ) return false;
if ( TMath::Abs(y) > fYMax ) return false;
//Track Selection Cuts
if ( track->GetITSNcls() < fNumberClustersITSMin ) return false;
if ( track->GetTPCNcls() < fNumberClustersTPCMin ) return false;
if ( track->GetTPCNCrossedRows() < fNumberCrossedRowsTPCMin ) return false;
if ( static_cast<Double_t>(track->GetTPCNCrossedRows())/static_cast<Double_t>(track->GetTPCNclsF()) < fCrossedRowsFindableClsMin) return false;
if ( track->GetTPCsignalN() < fNumberClustersTPCdEdxMin ) return false;
if ( track->Chi2perNDF() > fChiSquarePerNDFMax) return false;
//ITS Requirement
Bool_t hitInITSLayer0 = track->HasPointOnITSLayer(0);
Bool_t hitInITSLayer1 = track->HasPointOnITSLayer(1);
if (strcmp(fITSrequirement,"kBoth")==0 && !hitInITSLayer0 ) return false;
if (strcmp(fITSrequirement,"kBoth")==0 && !hitInITSLayer1 ) return false;
if (strcmp(fITSrequirement,"kFirst")==0 && !hitInITSLayer0 ) return false;
if (strcmp(fITSrequirement,"kSecond")==0 && !hitInITSLayer1 ) return false;
if (strcmp(fITSrequirement,"kAny")==0 && (!hitInITSLayer0) && (!hitInITSLayer1)) return false;
//DCA Cuts
Double_t dcaxy = GetDCAxy (track);
Double_t dcaz = GetDCAz (track);
if (TMath::Abs(dcaxy) > fDCAxyMax) return false;
if (TMath::Abs(dcaz) > fDCAzMax) return false;
return true;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
Bool_t AliAnalysisTaskTritonVsMultiplicity_PbPb::PassedTrackQualityCutsNoDCA (AliAODTrack* track) {
//Filterbit
if(!track->TestFilterMask(AliAODTrack::kTrkGlobalNoDCA)) return false;
//Rapidity Calculation
Double_t m = AliPID::ParticleMass(AliPID::kTriton);
Double_t px = track -> Px();
Double_t py = track -> Py();
Double_t pz = track -> Pz();
Double_t E = TMath::Sqrt(m*m + px*px + py*py + pz*pz);
TLorentzVector P (px,py,pz,E);
Double_t y = P.Rapidity();
//Kinematic Cuts & Acceptance
if ( track->Pt()<fPtMin || track->Pt()>fPtMax ) return false;
if ( TMath::Abs(track->Eta()) > fEtaMax ) return false;
if ( TMath::Abs(y) > fYMax ) return false;
//Track Selection Cuts
if ( track->GetITSNcls() < fNumberClustersITSMin ) return false;
if ( track->GetTPCNcls() < fNumberClustersTPCMin ) return false;
if ( track->GetTPCNCrossedRows() < fNumberCrossedRowsTPCMin ) return false;
if ( static_cast<Double_t>(track->GetTPCNCrossedRows())/static_cast<Double_t>(track->GetTPCNclsF()) < fCrossedRowsFindableClsMin) return false;
if ( track->GetTPCsignalN() < fNumberClustersTPCdEdxMin ) return false;
if ( track->Chi2perNDF() > fChiSquarePerNDFMax) return false;
//ITS Requirement
Bool_t hitInITSLayer0 = track->HasPointOnITSLayer(0);
Bool_t hitInITSLayer1 = track->HasPointOnITSLayer(1);
if (strcmp(fITSrequirement,"kBoth")==0 && !hitInITSLayer0 ) return false;
if (strcmp(fITSrequirement,"kBoth")==0 && !hitInITSLayer1 ) return false;
if (strcmp(fITSrequirement,"kFirst")==0 && !hitInITSLayer0 ) return false;
if (strcmp(fITSrequirement,"kSecond")==0 && !hitInITSLayer1 ) return false;
if (strcmp(fITSrequirement,"kAny")==0 && (!hitInITSLayer0) && (!hitInITSLayer1)) return false;
return true;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
Bool_t AliAnalysisTaskTritonVsMultiplicity_PbPb::IsCleanTritonCandidate (AliAODTrack *track) {
Double_t nsigmaTOF = fPIDResponse -> NumberOfSigmasTOF (track,AliPID::kTriton);
Double_t nsigmaTPC = fPIDResponse -> NumberOfSigmasTPC (track,AliPID::kTriton);
if (TMath::Abs(nsigmaTOF) > fnSigmaTOFmax) return false;
if (TMath::Abs(nsigmaTPC) > fnSigmaTPCmax) return false;
return true;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
Double_t AliAnalysisTaskTritonVsMultiplicity_PbPb::Centered_nsigmaTPC (AliAODTrack *track) {
Double_t nsigmaTPC = fPIDResponse -> NumberOfSigmasTPC (track,AliPID::kTriton);
Double_t mean_fitted = fpar0_mean_TPC*exp(fpar1_mean_TPC*(track->P()));
Double_t sigma_fitted = fpar0_sigma_TPC*(track->P());
nsigmaTPC = (nsigmaTPC - mean_fitted)/sigma_fitted;
return nsigmaTPC;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
Double_t AliAnalysisTaskTritonVsMultiplicity_PbPb::Centered_nsigmaTOF (AliAODTrack *track) {
Double_t nsigmaTOF = fPIDResponse -> NumberOfSigmasTOF (track,AliPID::kTriton);
Double_t mean_fitted = fpar0_mean_TOF*exp(fpar1_mean_TOF*(track->P()));
Double_t sigma_fitted = fpar0_sigma_TOF*exp(fpar1_sigma_TOF*(track->P()));
nsigmaTOF = (nsigmaTOF - mean_fitted)/sigma_fitted;
return nsigmaTOF;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
Bool_t AliAnalysisTaskTritonVsMultiplicity_PbPb::PassedTOFSelection (AliAODTrack *track) {
Double_t nsigmaTOF = fPIDResponse -> NumberOfSigmasTOF (track,AliPID::kTriton);
if (TMath::Abs(nsigmaTOF) > fnSigmaTOFmax) return false;
return true;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
Bool_t AliAnalysisTaskTritonVsMultiplicity_PbPb::PassedTPCSelection (AliAODTrack *track) {
Double_t nsigmaTPC = fPIDResponse -> NumberOfSigmasTPC (track,AliPID::kTriton);
if (TMath::Abs(nsigmaTPC) > fnSigmaTPCmax || (track->GetStatus()&AliAODTrack::kTOFout)!=0) return false;
//TPC-TOF Matching
// if ((track->GetStatus()&AliAODTrack::kTOFout)==0) hasTOFhit=0;//Track with no TOF hit
// if ((track->GetStatus()&AliAODTrack::kTOFout)!=0) hasTOFhit=1;//Track with TOF hit
return true;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
Double_t AliAnalysisTaskTritonVsMultiplicity_PbPb::GetDCAxy (AliAODTrack *track) {
Double_t impactParameter[2];
Double_t covarianceMatrix[3];
if (!track->PropagateToDCA(fAODevent->GetPrimaryVertex(),fAODevent->GetMagneticField(),10000,impactParameter,covarianceMatrix)) return -999;
Double_t DCAxy = impactParameter[0];
return DCAxy;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
Double_t AliAnalysisTaskTritonVsMultiplicity_PbPb::GetDCAz (AliAODTrack *track) {
Double_t impactParameter[2];
Double_t covarianceMatrix[3];
if (!track->PropagateToDCA(fAODevent->GetPrimaryVertex(),fAODevent->GetMagneticField(),10000,impactParameter,covarianceMatrix)) return -999;
Double_t DCAz = impactParameter[1];
return DCAz;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
void AliAnalysisTaskTritonVsMultiplicity_PbPb::Terminate(Option_t *) {
fOutputList = dynamic_cast<TList*> (GetOutputData(1));
if (!fOutputList) return;
}
//_________________________________________________________________________________________________________________________________________________________________________________________________
| [
"chiara.pinto@cern.ch"
] | chiara.pinto@cern.ch |
8feb4621ff964481319fbf6c69610fc79fad527f | 7fac28de3e586e17d73028eede52174d3bdaae22 | /main.cpp | 90780344ebf264fb61ee11642abe8cda289f51a3 | [] | no_license | wolfmanjm/qtpedometer | 4cc7f81632b9a18e13d014d2bd93dfbaf9b7754b | 8bef2a5d178a92489120d1ba2c2c05c284322cb1 | refs/heads/master | 2020-05-16T22:18:31.250039 | 2010-09-16T23:22:10 | 2010-09-16T23:22:10 | 308,243 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 119 | cpp | #include "qtpedometer.h"
#include <qtopiaapplication.h>
QTOPIA_ADD_APPLICATION(QTOPIA_TARGET,QtPedometer)
QTOPIA_MAIN
| [
"morris@wolfman.com"
] | morris@wolfman.com |
f0595d48e50cfd7d1917d7b73cf1f063524572cd | 492ccb171296e12baf476a9322c9e2d24ab93a99 | /FaceDetection/video.cpp | 6c0fd0037436eef96f8953d084607085aee2b3d3 | [] | no_license | Urmish/HeadPoseTracking | c309272c16348856a8e19e209e87d87a5f695974 | 596843635f72dc1ed2b4b46c97405b414d03845d | refs/heads/master | 2016-09-06T17:15:14.978144 | 2015-05-15T21:20:14 | 2015-05-15T21:20:14 | 33,457,632 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,813 | cpp | /**
* @file objectDetection.cpp
* @author A. Huaman ( based in the classic facedetect.cpp in samples/c )
* @brief A simplified version of facedetect.cpp, show how to load a cascade classifier and how to find objects (Face + eyes) in a video stream
*/
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
/** Function Headers */
void detectAndDisplay( Mat frame );
/** Global variables */
//-- Note, either copy these two files from opencv/data/haarscascades to your current folder, or change these locations
const char *cascade_name[2]={"haar/haarcascade_frontalface_default.xml",
"haar/nose.xml",
};
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
string window_name = "Capture - Face detection";
RNG rng(12345);
/**
* @function main
*/
int main( void )
{
VideoCapture capture;
Mat frame;
//-- 1. Load the cascades
if( !face_cascade.load( cascade_name[0] ) ){ printf("--(!)Error loading\n"); return -1; };
if( !eyes_cascade.load( cascade_name[1] ) ){ printf("--(!)Error loading\n"); return -1; };
//-- 2. Read the video stream
capture.open( -1 );
if( capture.isOpened() )
{
for(;;)
{
capture >> frame;
//-- 3. Apply the classifier to the frame
if( !frame.empty() )
{ detectAndDisplay( frame ); }
else
{ printf(" --(!) No captured frame -- Break!"); break; }
int c = waitKey(10);
if( (char)c == 'c' ) { break; }
}
}
return 0;
}
/**
* @function detectAndDisplay
*/
void detectAndDisplay( Mat frame )
{
std::vector<Rect> faces;
Mat frame_gray;
cvtColor( frame, frame_gray, COLOR_BGR2GRAY );
equalizeHist( frame_gray, frame_gray );
//-- Detect faces
face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t i = 0; i < faces.size(); i++ )
{
Point center( faces[i].x + faces[i].width/2, faces[i].y + faces[i].height/2 );
ellipse( frame, center, Size( faces[i].width/2, faces[i].height/2), 0, 0, 360, Scalar( 255, 0, 255 ), 2, 8, 0 );
Mat faceROI = frame_gray( faces[i] );
std::vector<Rect> eyes;
//-- In each face, detect eyes
eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t j = 0; j < eyes.size(); j++ )
{
Point eye_center( faces[i].x + eyes[j].x + eyes[j].width/2, faces[i].y + eyes[j].y + eyes[j].height/2 );
int radius = cvRound( (eyes[j].width + eyes[j].height)*0.25 );
circle( frame, eye_center, radius, Scalar( 255, 0, 0 ), 3, 8, 0 );
}
}
//-- Show what you got
imshow( window_name, frame );
}
| [
"urmish24@gmail.com"
] | urmish24@gmail.com |
3f419c7f6beed4db6611c69506615aa1d0bfdd0e | 0fdaa8fc6d9d8bd9085f7f45d51c3974a125d135 | /tugas 2/konversi fahrenheit - celcius.cpp | 997904a6bbf1c35954e97583ef343527e24bb56e | [] | no_license | univmajalengka/20.14.1.0055-Andi_gunawan | c291d256697de80a72c2269deabd4a92b69a1d20 | 5e6da65e8d8768b37275d430a818f55468e3bcc0 | refs/heads/main | 2023-04-15T18:19:13.273997 | 2021-04-22T15:21:29 | 2021-04-22T15:21:29 | 350,022,594 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | cpp | //Nama : AndiGunawan
//NPM : 201410055
//Nama program : Tugas3.cpp
#include<iostream>
using namespace std;
int main(){
float f,c;
cout<<"Program Konversi Suhu Fahrenheit - Celsius"<<endl;
cout<<"=========================================="<<endl;
cout<<endl;
cout<<"Masukkan suhu dalam Fahrenheit\t: ";
cin>>f;
cout<<endl;
c =( f - 32)/1.8;
cout<<"Suhu dalam celsius adalah "<<c;
}
| [
"noreply@github.com"
] | noreply@github.com |
5fc00d4db5c2d0cb0faab2f72a524d9ce44fd146 | 8e626e44e13dbcedd327ddb976c0863a54152251 | /cryptopp/include/CXKJ/Cryptopp/misc.h | 41f57e62453baa4797f37a6449d08b4a08f1bad1 | [
"Apache-2.0"
] | permissive | DayBreakZhang/CXKJ_Code | d6048c79845972d8c8a05277cc462e78043a6b1d | c7caab736313f029324f1c95714f5a94b2589076 | refs/heads/master | 2020-08-08T17:54:46.423371 | 2020-05-11T02:32:01 | 2020-05-11T02:32:01 | 213,882,633 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 102,385 | h | // misc.h - originally written and placed in the public domain by Wei Dai
/// \file misc.h
/// \brief Utility functions for the Crypto++ library.
#ifndef CRYPTOPP_MISC_H
#define CRYPTOPP_MISC_H
#include "config.h"
#if !defined(CRYPTOPP_DOXYGEN_PROCESSING)
#if (CRYPTOPP_MSC_VERSION)
# pragma warning(push)
# pragma warning(disable: 4146 4514)
# if (CRYPTOPP_MSC_VERSION >= 1400)
# pragma warning(disable: 6326)
# endif
#endif
// Issue 340
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wsign-conversion"
#endif
#include "cryptlib.h"
#include "stdcpp.h"
#include "smartptr.h"
#ifdef _MSC_VER
#if _MSC_VER >= 1400
// VC2005 workaround: disable declarations that conflict with winnt.h
#define _interlockedbittestandset CRYPTOPP_DISABLED_INTRINSIC_1
#define _interlockedbittestandreset CRYPTOPP_DISABLED_INTRINSIC_2
#define _interlockedbittestandset64 CRYPTOPP_DISABLED_INTRINSIC_3
#define _interlockedbittestandreset64 CRYPTOPP_DISABLED_INTRINSIC_4
#include <intrin.h>
#undef _interlockedbittestandset
#undef _interlockedbittestandreset
#undef _interlockedbittestandset64
#undef _interlockedbittestandreset64
#define CRYPTOPP_FAST_ROTATE(x) 1
#elif _MSC_VER >= 1300
#define CRYPTOPP_FAST_ROTATE(x) ((x) == 32 | (x) == 64)
#else
#define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
#endif
#elif (defined(__MWERKS__) && TARGET_CPU_PPC) || \
(defined(__GNUC__) && (defined(_ARCH_PWR2) || defined(_ARCH_PWR) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || defined(_ARCH_COM)))
#define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
#elif defined(__GNUC__) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86) // depend on GCC's peephole optimization to generate rotate instructions
#define CRYPTOPP_FAST_ROTATE(x) 1
#else
#define CRYPTOPP_FAST_ROTATE(x) 0
#endif
#ifdef __BORLANDC__
#include <mem.h>
#include <stdlib.h>
#endif
#if defined(__GNUC__) && defined(__linux__)
#define CRYPTOPP_BYTESWAP_AVAILABLE
#include <byteswap.h>
#endif
#if defined(__BMI__)
# include <x86intrin.h>
#endif // GCC and BMI
#endif // CRYPTOPP_DOXYGEN_PROCESSING
#if CRYPTOPP_DOXYGEN_PROCESSING
/// \brief The maximum value of a machine word
/// \details SIZE_MAX provides the maximum value of a machine word. The value is
/// 0xffffffff on 32-bit machines, and 0xffffffffffffffff on 64-bit machines.
/// Internally, SIZE_MAX is defined as __SIZE_MAX__ if __SIZE_MAX__ is defined. If not
/// defined, then SIZE_T_MAX is tried. If neither __SIZE_MAX__ nor SIZE_T_MAX is
/// is defined, the library uses std::numeric_limits<size_t>::max(). The library
/// prefers __SIZE_MAX__ because its a constexpr that is optimized well
/// by all compilers. std::numeric_limits<size_t>::max() is not a constexpr,
/// and it is not always optimized well.
# define SIZE_MAX ...
#else
// Its amazing portability problems still plague this simple concept in 2015.
// http://stackoverflow.com/questions/30472731/which-c-standard-header-defines-size-max
// Avoid NOMINMAX macro on Windows. http://support.microsoft.com/en-us/kb/143208
#ifndef SIZE_MAX
# if defined(__SIZE_MAX__) && (__SIZE_MAX__ > 0)
# define SIZE_MAX __SIZE_MAX__
# elif defined(SIZE_T_MAX) && (SIZE_T_MAX > 0)
# define SIZE_MAX SIZE_T_MAX
# elif defined(__SIZE_TYPE__)
# define SIZE_MAX (~(__SIZE_TYPE__)0)
# else
# define SIZE_MAX ((std::numeric_limits<size_t>::max)())
# endif
#endif
#endif // CRYPTOPP_DOXYGEN_PROCESSING
// NumericLimitsMin and NumericLimitsMax added for word128 types,
// see http://github.com/weidai11/cryptopp/issues/364
ANONYMOUS_NAMESPACE_BEGIN
template<class T>
T NumericLimitsMin()
{
CRYPTOPP_ASSERT(std::numeric_limits<T>::is_specialized);
return (std::numeric_limits<T>::min)();
}
template<class T>
T NumericLimitsMax()
{
CRYPTOPP_ASSERT(std::numeric_limits<T>::is_specialized);
return (std::numeric_limits<T>::max)();
}
#if defined(CRYPTOPP_WORD128_AVAILABLE)
template<>
CryptoPP::word128 NumericLimitsMin()
{
return 0;
}
template<>
CryptoPP::word128 NumericLimitsMax()
{
return (((CryptoPP::word128)W64LIT(0xffffffffffffffff)) << 64U) | (CryptoPP::word128)W64LIT(0xffffffffffffffff);
}
#endif
ANONYMOUS_NAMESPACE_END
NAMESPACE_BEGIN(CryptoPP)
// Forward declaration for IntToString specialization
class Integer;
// ************** compile-time assertion ***************
#if CRYPTOPP_DOXYGEN_PROCESSING
/// \brief Compile time assertion
/// \param expr the expression to evaluate
/// \details Asserts the expression expr though a dummy struct.
#define CRYPTOPP_COMPILE_ASSERT(expr) { ... }
#else // CRYPTOPP_DOXYGEN_PROCESSING
template <bool b>
struct CompileAssert
{
static char dummy[2*b-1];
};
#define CRYPTOPP_COMPILE_ASSERT(assertion) CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__)
#if defined(CRYPTOPP_EXPORTS) || defined(CRYPTOPP_IMPORTS)
#define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance)
#else
# if defined(__GNUC__)
# define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
static CompileAssert<(assertion)> \
CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance) __attribute__ ((unused))
# else
# define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
static CompileAssert<(assertion)> \
CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance)
# endif // __GNUC__
#endif
#define CRYPTOPP_ASSERT_JOIN(X, Y) CRYPTOPP_DO_ASSERT_JOIN(X, Y)
#define CRYPTOPP_DO_ASSERT_JOIN(X, Y) X##Y
#endif // CRYPTOPP_DOXYGEN_PROCESSING
// ************** count elements in an array ***************
#if CRYPTOPP_DOXYGEN_PROCESSING
/// \brief Counts elements in an array
/// \param arr an array of elements
/// \details COUNTOF counts elements in an array. On Windows COUNTOF(x) is defined
/// to <tt>_countof(x)</tt> to ensure correct results for pointers.
/// \note COUNTOF does not produce correct results with pointers, and an array must be used.
/// <tt>sizeof(x)/sizeof(x[0])</tt> suffers the same problem. The risk is eliminated by using
/// <tt>_countof(x)</tt> on Windows. Windows will provide the immunity for other platforms.
# define COUNTOF(arr)
#else
// VS2005 added _countof
#ifndef COUNTOF
# if defined(_MSC_VER) && (_MSC_VER >= 1400)
# define COUNTOF(x) _countof(x)
# else
# define COUNTOF(x) (sizeof(x)/sizeof(x[0]))
# endif
#endif // COUNTOF
#endif // CRYPTOPP_DOXYGEN_PROCESSING
// ************** misc classes ***************
/// \brief An Empty class
/// \details The Empty class can be used as a template parameter <tt>BASE</tt> when no base class exists.
class CRYPTOPP_DLL Empty
{
};
#if !defined(CRYPTOPP_DOXYGEN_PROCESSING)
template <class BASE1, class BASE2>
class CRYPTOPP_NO_VTABLE TwoBases : public BASE1, public BASE2
{
};
template <class BASE1, class BASE2, class BASE3>
class CRYPTOPP_NO_VTABLE ThreeBases : public BASE1, public BASE2, public BASE3
{
};
#endif // CRYPTOPP_DOXYGEN_PROCESSING
/// \tparam T class or type
/// \brief Uses encapsulation to hide an object in derived classes
/// \details The object T is declared as protected.
template <class T>
class ObjectHolder
{
protected:
T m_object;
};
/// \brief Ensures an object is not copyable
/// \details NotCopyable ensures an object is not copyable by making the
/// copy constructor and assignment operator private. Deleters are not
/// used under C++11.
/// \sa Clonable class
class NotCopyable
{
public:
NotCopyable() {}
private:
NotCopyable(const NotCopyable &);
void operator=(const NotCopyable &);
};
/// \brief An object factory function
/// \tparam T class or type
/// \details NewObject overloads operator()().
template <class T>
struct NewObject
{
T* operator()() const {return new T;}
};
#if CRYPTOPP_DOXYGEN_PROCESSING
/// \brief A memory barrier
/// \details MEMORY_BARRIER attempts to ensure reads and writes are completed
/// in the absence of a language synchronization point. It is used by the
/// Singleton class if the compiler supports it. The barrier is provided at the
/// customary places in a double-checked initialization.
/// \details Internally, MEMORY_BARRIER uses <tt>std::atomic_thread_fence</tt> if
/// C++11 atomics are available. Otherwise, <tt>intrinsic(_ReadWriteBarrier)</tt>,
/// <tt>_ReadWriteBarrier()</tt> or <tt>__asm__("" ::: "memory")</tt> is used.
#define MEMORY_BARRIER ...
#else
#if defined(CRYPTOPP_CXX11_ATOMICS)
# define MEMORY_BARRIER() std::atomic_thread_fence(std::memory_order_acq_rel)
#elif (_MSC_VER >= 1400)
# pragma intrinsic(_ReadWriteBarrier)
# define MEMORY_BARRIER() _ReadWriteBarrier()
#elif defined(__INTEL_COMPILER)
# define MEMORY_BARRIER() __memory_barrier()
#elif defined(__GNUC__) || defined(__clang__)
# define MEMORY_BARRIER() __asm__ __volatile__ ("" ::: "memory")
#else
# define MEMORY_BARRIER()
#endif
#endif // CRYPTOPP_DOXYGEN_PROCESSING
/// \brief Restricts the instantiation of a class to one static object without locks
/// \tparam T the class or type
/// \tparam F the object factory for T
/// \tparam instance an instance counter for the class object
/// \details This class safely initializes a static object in a multithreaded environment. For C++03
/// and below it will do so without using locks for portability. If two threads call Ref() at the same
/// time, they may get back different references, and one object may end up being memory leaked. This
/// is by design and it avoids a subltle initialization problem ina multithreaded environment with thread
/// local storage on early Windows platforms, like Windows XP and Windows 2003.
/// \details For C++11 and above, a standard double-checked locking pattern with thread fences
/// are used. The locks and fences are standard and do not hinder portability.
/// \details Microsoft's C++11 implementation provides the necessary primitive support on Windows Vista and
/// above when using Visual Studio 2015 (<tt>cl.exe</tt> version 19.00). If C++11 is desired, you should
/// set <tt>WINVER</tt> or <tt>_WIN32_WINNT</tt> to 0x600 (or above), and compile with Visual Studio 2015.
/// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking
/// is Fixed In C++11</A>, <A HREF="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm">Dynamic
/// Initialization and Destruction with Concurrency</A> and
/// <A HREF="http://msdn.microsoft.com/en-us/library/6yh4a9k1.aspx">Thread Local Storage (TLS)</A> on MSDN.
/// \since Crypto++ 5.2
template <class T, class F = NewObject<T>, int instance=0>
class Singleton
{
public:
Singleton(F objectFactory = F()) : m_objectFactory(objectFactory) {}
// prevent this function from being inlined
CRYPTOPP_NOINLINE const T & Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const;
private:
F m_objectFactory;
};
/// \brief Return a reference to the inner Singleton object
/// \tparam T the class or type
/// \tparam F the object factory for T
/// \tparam instance an instance counter for the class object
/// \details Ref() is used to create the object using the object factory. The
/// object is only created once with the limitations discussed in the class documentation.
/// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking is Fixed In C++11</A>
/// \since Crypto++ 5.2
template <class T, class F, int instance>
const T & Singleton<T, F, instance>::Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const
{
#if defined(CRYPTOPP_CXX11_ATOMICS) && defined(CRYPTOPP_CXX11_SYNCHRONIZATION) && defined(CRYPTOPP_CXX11_DYNAMIC_INIT)
static std::mutex s_mutex;
static std::atomic<T*> s_pObject;
T *p = s_pObject.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
if (p)
return *p;
std::lock_guard<std::mutex> lock(s_mutex);
p = s_pObject.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
if (p)
return *p;
T *newObject = m_objectFactory();
s_pObject.store(newObject, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_release);
return *newObject;
#else
static volatile simple_ptr<T> s_pObject;
T *p = s_pObject.m_p;
MEMORY_BARRIER();
if (p)
return *p;
T *newObject = m_objectFactory();
p = s_pObject.m_p;
MEMORY_BARRIER();
if (p)
{
delete newObject;
return *p;
}
s_pObject.m_p = newObject;
MEMORY_BARRIER();
return *newObject;
#endif
}
// ************** misc functions ***************
/// \brief Create a pointer with an offset
/// \tparam PTR a pointer type
/// \tparam OFF a size type
/// \param pointer a pointer
/// \param offset a offset into the pointer
/// \details PtrAdd can be used to squash Clang and GCC
/// UBsan findings for pointer addition and subtraction.
template <typename PTR, typename OFF>
inline PTR PtrAdd(PTR pointer, OFF offset)
{
return pointer+static_cast<ptrdiff_t>(offset);
}
/// \brief Create a pointer with an offset
/// \tparam PTR a pointer type
/// \tparam OFF a size type
/// \param pointer a pointer
/// \param offset a offset into the pointer
/// \details PtrSub can be used to squash Clang and GCC
/// UBsan findings for pointer addition and subtraction.
template <typename PTR, typename OFF>
inline PTR PtrSub(PTR pointer, OFF offset)
{
return pointer-static_cast<ptrdiff_t>(offset);
}
/// \brief Determine pointer difference
/// \tparam PTR a pointer type
/// \param pointer1 the first pointer
/// \param pointer2 the second pointer
/// \details PtrDiff can be used to squash Clang and GCC
/// UBsan findings for pointer addition and subtraction.
/// pointer1 and pointer2 must point to the same object or
/// array (or one past the end), and yields the number of
/// elements (not bytes) difference.
template <typename PTR>
inline ptrdiff_t PtrDiff(const PTR pointer1, const PTR pointer2)
{
return pointer1 - pointer2;
}
/// \brief Determine pointer difference
/// \tparam PTR a pointer type
/// \param pointer1 the first pointer
/// \param pointer2 the second pointer
/// \details PtrByteDiff can be used to squash Clang and GCC
/// UBsan findings for pointer addition and subtraction.
/// pointer1 and pointer2 must point to the same object or
/// array (or one past the end), and yields the number of
/// bytes (not elements) difference.
template <typename PTR>
inline size_t PtrByteDiff(const PTR pointer1, const PTR pointer2)
{
return (size_t)(reinterpret_cast<uintptr_t>(pointer1) - reinterpret_cast<uintptr_t>(pointer2));
}
#if (!__STDC_WANT_SECURE_LIB__ && !defined(_MEMORY_S_DEFINED)) || defined(CRYPTOPP_WANT_SECURE_LIB)
/// \brief Bounds checking replacement for memcpy()
/// \param dest pointer to the desination memory block
/// \param sizeInBytes size of the desination memory block, in bytes
/// \param src pointer to the source memory block
/// \param count the number of bytes to copy
/// \throws InvalidArgument
/// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
/// unsafe functions like memcpy(), strcpy() and memmove(). However,
/// not all standard libraries provides them, like Glibc. The library's
/// memcpy_s() is a near-drop in replacement. Its only a near-replacement
/// because the library's version throws an InvalidArgument on a bounds violation.
/// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
/// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library
/// makes memcpy_s() and memmove_s() available. The library will also optionally
/// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
/// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
/// \details memcpy_s() will assert the pointers src and dest are not NULL
/// in debug builds. Passing NULL for either pointer is undefined behavior.
inline void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
{
// Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
// Pointers must be valid; otherwise undefined behavior
CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR);
// Restricted pointers. We want to check ranges, but it is not clear how to do it.
CRYPTOPP_ASSERT(src != dest);
// Destination buffer must be large enough to satsify request
CRYPTOPP_ASSERT(sizeInBytes >= count);
if (count > sizeInBytes)
throw InvalidArgument("memcpy_s: buffer overflow");
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4996)
# if (CRYPTOPP_MSC_VERSION >= 1400)
# pragma warning(disable: 6386)
# endif
#endif
memcpy(dest, src, count);
#if CRYPTOPP_MSC_VERSION
# pragma warning(pop)
#endif
}
/// \brief Bounds checking replacement for memmove()
/// \param dest pointer to the desination memory block
/// \param sizeInBytes size of the desination memory block, in bytes
/// \param src pointer to the source memory block
/// \param count the number of bytes to copy
/// \throws InvalidArgument
/// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
/// unsafe functions like memcpy(), strcpy() and memmove(). However,
/// not all standard libraries provides them, like Glibc. The library's
/// memmove_s() is a near-drop in replacement. Its only a near-replacement
/// because the library's version throws an InvalidArgument on a bounds violation.
/// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
/// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library
/// makes memcpy_s() and memmove_s() available. The library will also optionally
/// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
/// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
/// \details memmove_s() will assert the pointers src and dest are not NULL
/// in debug builds. Passing NULL for either pointer is undefined behavior.
inline void memmove_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
{
// Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
// Pointers must be valid; otherwise undefined behavior
CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR);
// Destination buffer must be large enough to satsify request
CRYPTOPP_ASSERT(sizeInBytes >= count);
if (count > sizeInBytes)
throw InvalidArgument("memmove_s: buffer overflow");
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4996)
# if (CRYPTOPP_MSC_VERSION >= 1400)
# pragma warning(disable: 6386)
# endif
#endif
memmove(dest, src, count);
#if CRYPTOPP_MSC_VERSION
# pragma warning(pop)
#endif
}
#if __BORLANDC__ >= 0x620
// C++Builder 2010 workaround: can't use std::memcpy_s because it doesn't allow 0 lengths
# define memcpy_s CryptoPP::memcpy_s
# define memmove_s CryptoPP::memmove_s
#endif
#endif // __STDC_WANT_SECURE_LIB__
/// \brief Swaps two variables which are arrays
/// \tparam T class or type
/// \param a the first value
/// \param b the second value
/// \details C++03 does not provide support for <tt>std::swap(__m128i a, __m128i b)</tt>
/// because <tt>__m128i</tt> is an <tt>unsigned long long[2]</tt>. Most compilers
/// support it out of the box, but Sun Studio C++ compilers 12.2 and 12.3 do not.
/// \sa <A HREF="http://stackoverflow.com/q/38417413">How to swap two __m128i variables
/// in C++03 given its an opaque type and an array?</A> on Stack Overflow.
template <class T>
inline void vec_swap(T& a, T& b)
{
// __m128i is an unsigned long long[2], and support for swapping it was
// not added until C++11. SunCC 12.1 - 12.3 fail to consume the swap; while
// SunCC 12.4 consumes it without -std=c++11.
#if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x5120)
T t;
t=a, a=b, b=t;
#else
std::swap(a, b);
#endif
}
/// \brief Memory block initializer and eraser that attempts to survive optimizations
/// \param ptr pointer to the memory block being written
/// \param value the integer value to write for each byte
/// \param num the size of the source memory block, in bytes
/// \details Internally the function calls memset with the value value, and receives the
/// return value from memset as a <tt>volatile</tt> pointer.
inline void * memset_z(void *ptr, int value, size_t num)
{
// avoid extranous warning on GCC 4.3.2 Ubuntu 8.10
#if CRYPTOPP_GCC_VERSION >= 30001
if (__builtin_constant_p(num) && num==0)
return ptr;
#endif
volatile void* x = memset(ptr, value, num);
return const_cast<void*>(x);
}
/// \brief Replacement function for std::min
/// \tparam T class or type
/// \param a the first value
/// \param b the second value
/// \returns the minimum value based on a comparison of <tt>b \< a</tt> using <tt>operator\<</tt>
/// \details STDMIN was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0
template <class T> inline const T& STDMIN(const T& a, const T& b)
{
return b < a ? b : a;
}
/// \brief Replacement function for std::max
/// \tparam T class or type
/// \param a the first value
/// \param b the second value
/// \returns the minimum value based on a comparison of <tt>a \< b</tt> using <tt>operator\<</tt>
/// \details STDMAX was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0
template <class T> inline const T& STDMAX(const T& a, const T& b)
{
return a < b ? b : a;
}
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4389)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wsign-compare"
# pragma GCC diagnostic ignored "-Wstrict-overflow"
# if (CRYPTOPP_LLVM_CLANG_VERSION >= 20800) || (CRYPTOPP_APPLE_CLANG_VERSION >= 30000)
# pragma GCC diagnostic ignored "-Wtautological-compare"
# elif (CRYPTOPP_GCC_VERSION >= 40300)
# pragma GCC diagnostic ignored "-Wtype-limits"
# endif
#endif
/// \brief Safe comparison of values that could be neagtive and incorrectly promoted
/// \tparam T1 class or type
/// \tparam T2 class or type
/// \param a the first value
/// \param b the second value
/// \returns the minimum value based on a comparison a and b using <tt>operator<</tt>.
/// \details The comparison <tt>b \< a</tt> is performed and the value returned is a's type T1.
template <class T1, class T2> inline const T1 UnsignedMin(const T1& a, const T2& b)
{
CRYPTOPP_COMPILE_ASSERT((sizeof(T1)<=sizeof(T2) && T2(-1)>0) || (sizeof(T1)>sizeof(T2) && T1(-1)>0));
if (sizeof(T1)<=sizeof(T2))
return b < (T2)a ? (T1)b : a;
else
return (T1)b < a ? (T1)b : a;
}
/// \brief Tests whether a conversion from -> to is safe to perform
/// \tparam T1 class or type
/// \tparam T2 class or type
/// \param from the first value
/// \param to the second value
/// \returns true if its safe to convert from into to, false otherwise.
template <class T1, class T2>
inline bool SafeConvert(T1 from, T2 &to)
{
to = (T2)from;
if (from != to || (from > 0) != (to > 0))
return false;
return true;
}
/// \brief Converts a value to a string
/// \tparam T class or type
/// \param value the value to convert
/// \param base the base to use during the conversion
/// \returns the string representation of value in base.
template <class T>
std::string IntToString(T value, unsigned int base = 10)
{
// Hack... set the high bit for uppercase.
static const unsigned int HIGH_BIT = (1U << 31);
const char CH = !!(base & HIGH_BIT) ? 'A' : 'a';
base &= ~HIGH_BIT;
CRYPTOPP_ASSERT(base >= 2);
if (value == 0)
return "0";
bool negate = false;
if (value < 0)
{
negate = true;
value = 0-value; // VC .NET does not like -a
}
std::string result;
while (value > 0)
{
T digit = value % base;
result = char((digit < 10 ? '0' : (CH - 10)) + digit) + result;
value /= base;
}
if (negate)
result = "-" + result;
return result;
}
/// \brief Converts an unsigned value to a string
/// \param value the value to convert
/// \param base the base to use during the conversion
/// \returns the string representation of value in base.
/// \details this template function specialization was added to suppress
/// Coverity findings on IntToString() with unsigned types.
template <> CRYPTOPP_DLL
std::string IntToString<word64>(word64 value, unsigned int base);
/// \brief Converts an Integer to a string
/// \param value the Integer to convert
/// \param base the base to use during the conversion
/// \returns the string representation of value in base.
/// \details This is a template specialization of IntToString(). Use it
/// like IntToString():
/// <pre>
/// // Print integer in base 10
/// Integer n...
/// std::string s = IntToString(n, 10);
/// </pre>
/// \details The string is presented with lowercase letters by default. A
/// hack is available to switch to uppercase letters without modifying
/// the function signature.
/// <pre>
/// // Print integer in base 16, uppercase letters
/// Integer n...
/// const unsigned int UPPER = (1 << 31);
/// std::string s = IntToString(n, (UPPER | 16));</pre>
template <> CRYPTOPP_DLL
std::string IntToString<Integer>(Integer value, unsigned int base);
#if CRYPTOPP_MSC_VERSION
# pragma warning(pop)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic pop
#endif
#define RETURN_IF_NONZERO(x) size_t returnedValue = x; if (returnedValue) return returnedValue
// this version of the macro is fastest on Pentium 3 and Pentium 4 with MSVC 6 SP5 w/ Processor Pack
#define GETBYTE(x, y) (unsigned int)byte((x)>>(8*(y)))
// these may be faster on other CPUs/compilers
// #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255)
// #define GETBYTE(x, y) (((byte *)&(x))[y])
#define CRYPTOPP_GET_BYTE_AS_BYTE(x, y) byte((x)>>(8*(y)))
/// \brief Returns the parity of a value
/// \tparam T class or type
/// \param value the value to provide the parity
/// \returns 1 if the number 1-bits in the value is odd, 0 otherwise
template <class T>
unsigned int Parity(T value)
{
for (unsigned int i=8*sizeof(value)/2; i>0; i/=2)
value ^= value >> i;
return (unsigned int)value&1;
}
/// \brief Returns the number of 8-bit bytes or octets required for a value
/// \tparam T class or type
/// \param value the value to test
/// \returns the minimum number of 8-bit bytes or octets required to represent a value
template <class T>
unsigned int BytePrecision(const T &value)
{
if (!value)
return 0;
unsigned int l=0, h=8*sizeof(value);
while (h-l > 8)
{
unsigned int t = (l+h)/2;
if (value >> t)
l = t;
else
h = t;
}
return h/8;
}
/// \brief Returns the number of bits required for a value
/// \tparam T class or type
/// \param value the value to test
/// \returns the maximum number of bits required to represent a value.
template <class T>
unsigned int BitPrecision(const T &value)
{
if (!value)
return 0;
unsigned int l=0, h=8*sizeof(value);
while (h-l > 1)
{
unsigned int t = (l+h)/2;
if (value >> t)
l = t;
else
h = t;
}
return h;
}
/// Determines the number of trailing 0-bits in a value
/// \param v the 32-bit value to test
/// \returns the number of trailing 0-bits in v, starting at the least significant bit position
/// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
/// significant bit position. The return value is undefined if there are no 1-bits set in the value v.
/// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
inline unsigned int TrailingZeros(word32 v)
{
// GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors
// We don't enable for Microsoft because it requires a runtime check.
// http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx
CRYPTOPP_ASSERT(v != 0);
#if defined(__BMI__)
return (unsigned int)_tzcnt_u32(v);
#elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400)
return (unsigned int)__builtin_ctz(v);
#elif defined(_MSC_VER) && (_MSC_VER >= 1400)
unsigned long result;
_BitScanForward(&result, v);
return static_cast<unsigned int>(result);
#else
// from http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
static const int MultiplyDeBruijnBitPosition[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
return MultiplyDeBruijnBitPosition[((word32)((v & -v) * 0x077CB531U)) >> 27];
#endif
}
/// Determines the number of trailing 0-bits in a value
/// \param v the 64-bit value to test
/// \returns the number of trailing 0-bits in v, starting at the least significant bit position
/// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
/// significant bit position. The return value is undefined if there are no 1-bits set in the value v.
/// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
inline unsigned int TrailingZeros(word64 v)
{
// GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors
// We don't enable for Microsoft because it requires a runtime check.
// http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx
CRYPTOPP_ASSERT(v != 0);
#if defined(__BMI__) && defined(__x86_64__)
return (unsigned int)_tzcnt_u64(v);
#elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400)
return (unsigned int)__builtin_ctzll(v);
#elif defined(_MSC_VER) && (_MSC_VER >= 1400) && (defined(_M_X64) || defined(_M_IA64))
unsigned long result;
_BitScanForward64(&result, v);
return static_cast<unsigned int>(result);
#else
return word32(v) ? TrailingZeros(word32(v)) : 32 + TrailingZeros(word32(v>>32));
#endif
}
/// \brief Truncates the value to the specified number of bits.
/// \tparam T class or type
/// \param value the value to truncate or mask
/// \param bits the number of bits to truncate or mask
/// \returns the value truncated to the specified number of bits, starting at the least
/// significant bit position
/// \details This function masks the low-order bits of value and returns the result. The
/// mask is created with <tt>(1 << bits) - 1</tt>.
template <class T>
inline T Crop(T value, size_t bits)
{
if (bits < 8*sizeof(value))
return T(value & ((T(1) << bits) - 1));
else
return value;
}
/// \brief Returns the number of 8-bit bytes or octets required for the specified number of bits
/// \param bitCount the number of bits
/// \returns the minimum number of 8-bit bytes or octets required by bitCount
/// \details BitsToBytes is effectively a ceiling function based on 8-bit bytes.
inline size_t BitsToBytes(size_t bitCount)
{
return ((bitCount+7)/(8));
}
/// \brief Returns the number of words required for the specified number of bytes
/// \param byteCount the number of bytes
/// \returns the minimum number of words required by byteCount
/// \details BytesToWords is effectively a ceiling function based on <tt>WORD_SIZE</tt>.
/// <tt>WORD_SIZE</tt> is defined in config.h
inline size_t BytesToWords(size_t byteCount)
{
return ((byteCount+WORD_SIZE-1)/WORD_SIZE);
}
/// \brief Returns the number of words required for the specified number of bits
/// \param bitCount the number of bits
/// \returns the minimum number of words required by bitCount
/// \details BitsToWords is effectively a ceiling function based on <tt>WORD_BITS</tt>.
/// <tt>WORD_BITS</tt> is defined in config.h
inline size_t BitsToWords(size_t bitCount)
{
return ((bitCount+WORD_BITS-1)/(WORD_BITS));
}
/// \brief Returns the number of double words required for the specified number of bits
/// \param bitCount the number of bits
/// \returns the minimum number of double words required by bitCount
/// \details BitsToDwords is effectively a ceiling function based on <tt>2*WORD_BITS</tt>.
/// <tt>WORD_BITS</tt> is defined in config.h
inline size_t BitsToDwords(size_t bitCount)
{
return ((bitCount+2*WORD_BITS-1)/(2*WORD_BITS));
}
/// Performs an XOR of a buffer with a mask
/// \param buf the buffer to XOR with the mask
/// \param mask the mask to XOR with the buffer
/// \param count the size of the buffers, in bytes
/// \details The function effectively visits each element in the buffers and performs
/// <tt>buf[i] ^= mask[i]</tt>. buf and mask must be of equal size.
CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *buf, const byte *mask, size_t count);
/// Performs an XOR of an input buffer with a mask and stores the result in an output buffer
/// \param output the destination buffer
/// \param input the source buffer to XOR with the mask
/// \param mask the mask buffer to XOR with the input buffer
/// \param count the size of the buffers, in bytes
/// \details The function effectively visits each element in the buffers and performs
/// <tt>output[i] = input[i] ^ mask[i]</tt>. output, input and mask must be of equal size.
CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *output, const byte *input, const byte *mask, size_t count);
/// \brief Performs a near constant-time comparison of two equally sized buffers
/// \param buf1 the first buffer
/// \param buf2 the second buffer
/// \param count the size of the buffers, in bytes
/// \details The function effectively performs an XOR of the elements in two equally sized buffers
/// and retruns a result based on the XOR operation. The function is near constant-time because
/// CPU micro-code timings could affect the "constant-ness". Calling code is responsible for
/// mitigating timing attacks if the buffers are not equally sized.
/// \sa ModPowerOf2
CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count);
/// \brief Tests whether a value is a power of 2
/// \param value the value to test
/// \returns true if value is a power of 2, false otherwise
/// \details The function creates a mask of <tt>value - 1</tt> and returns the result of
/// an AND operation compared to 0. If value is 0 or less than 0, then the function returns false.
template <class T>
inline bool IsPowerOf2(const T &value)
{
return value > 0 && (value & (value-1)) == 0;
}
#if defined(__BMI__)
template <>
inline bool IsPowerOf2<word32>(const word32 &value)
{
return value > 0 && _blsr_u32(value) == 0;
}
# if defined(__x86_64__)
template <>
inline bool IsPowerOf2<word64>(const word64 &value)
{
return value > 0 && _blsr_u64(value) == 0;
}
# endif // __x86_64__
#endif // __BMI__
/// \brief Performs a saturating subtract clamped at 0
/// \tparam T1 class or type
/// \tparam T2 class or type
/// \param a the minuend
/// \param b the subtrahend
/// \returns the difference produced by the saturating subtract
/// \details Saturating arithmetic restricts results to a fixed range. Results that are less than 0 are clamped at 0.
/// \details Use of saturating arithmetic in places can be advantageous because it can
/// avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>).
template <class T1, class T2>
inline T1 SaturatingSubtract(const T1 &a, const T2 &b)
{
// Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html
return T1((a > b) ? (a - b) : 0);
}
/// \brief Performs a saturating subtract clamped at 1
/// \tparam T1 class or type
/// \tparam T2 class or type
/// \param a the minuend
/// \param b the subtrahend
/// \returns the difference produced by the saturating subtract
/// \details Saturating arithmetic restricts results to a fixed range. Results that are less than
/// 1 are clamped at 1.
/// \details Use of saturating arithmetic in places can be advantageous because it can
/// avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>).
template <class T1, class T2>
inline T1 SaturatingSubtract1(const T1 &a, const T2 &b)
{
// Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html
return T1((a > b) ? (a - b) : 1);
}
/// \brief Reduces a value to a power of 2
/// \tparam T1 class or type
/// \tparam T2 class or type
/// \param a the first value
/// \param b the second value
/// \returns ModPowerOf2() returns <tt>a & (b-1)</tt>. <tt>b</tt> must be a power of 2.
/// Use IsPowerOf2() to determine if <tt>b</tt> is a suitable candidate.
/// \sa IsPowerOf2
template <class T1, class T2>
inline T2 ModPowerOf2(const T1 &a, const T2 &b)
{
CRYPTOPP_ASSERT(IsPowerOf2(b));
// Coverity finding CID 170383 Overflowed return value (INTEGER_OVERFLOW)
return T2(a) & SaturatingSubtract(b,1U);
}
/// \brief Rounds a value down to a multiple of a second value
/// \tparam T1 class or type
/// \tparam T2 class or type
/// \param n the value to reduce
/// \param m the value to reduce \n to to a multiple
/// \returns the possibly unmodified value \n
/// \details RoundDownToMultipleOf is effectively a floor function based on m. The function returns
/// the value <tt>n - n\%m</tt>. If n is a multiple of m, then the original value is returned.
/// \note <tt>T1</tt> and <tt>T2</tt> should be usigned arithmetic types. If <tt>T1</tt> or
/// <tt>T2</tt> is signed, then the value should be non-negative. The library asserts in
/// debug builds when practical, but allows you to perform the operation in release builds.
template <class T1, class T2>
inline T1 RoundDownToMultipleOf(const T1 &n, const T2 &m)
{
// http://github.com/weidai11/cryptopp/issues/364
#if !defined(CRYPTOPP_APPLE_CLANG_VERSION) || (CRYPTOPP_APPLE_CLANG_VERSION >= 80000)
CRYPTOPP_ASSERT(std::numeric_limits<T1>::is_integer);
CRYPTOPP_ASSERT(std::numeric_limits<T2>::is_integer);
#endif
CRYPTOPP_ASSERT(!std::numeric_limits<T1>::is_signed || n > 0);
CRYPTOPP_ASSERT(!std::numeric_limits<T2>::is_signed || m > 0);
if (IsPowerOf2(m))
return n - ModPowerOf2(n, m);
else
return n - n%m;
}
/// \brief Rounds a value up to a multiple of a second value
/// \tparam T1 class or type
/// \tparam T2 class or type
/// \param n the value to reduce
/// \param m the value to reduce \n to to a multiple
/// \returns the possibly unmodified value \n
/// \details RoundUpToMultipleOf is effectively a ceiling function based on m. The function
/// returns the value <tt>n + n\%m</tt>. If n is a multiple of m, then the original value is
/// returned. If the value n would overflow, then an InvalidArgument exception is thrown.
/// \note <tt>T1</tt> and <tt>T2</tt> should be usigned arithmetic types. If <tt>T1</tt> or
/// <tt>T2</tt> is signed, then the value should be non-negative. The library asserts in
/// debug builds when practical, but allows you to perform the operation in release builds.
template <class T1, class T2>
inline T1 RoundUpToMultipleOf(const T1 &n, const T2 &m)
{
// http://github.com/weidai11/cryptopp/issues/364
#if !defined(CRYPTOPP_APPLE_CLANG_VERSION) || (CRYPTOPP_APPLE_CLANG_VERSION >= 80000)
CRYPTOPP_ASSERT(std::numeric_limits<T1>::is_integer);
CRYPTOPP_ASSERT(std::numeric_limits<T2>::is_integer);
#endif
CRYPTOPP_ASSERT(!std::numeric_limits<T1>::is_signed || n > 0);
CRYPTOPP_ASSERT(!std::numeric_limits<T2>::is_signed || m > 0);
if (NumericLimitsMax<T1>() - m + 1 < n)
throw InvalidArgument("RoundUpToMultipleOf: integer overflow");
return RoundDownToMultipleOf(T1(n+m-1), m);
}
/// \brief Returns the minimum alignment requirements of a type
/// \tparam T class or type
/// \returns the minimum alignment requirements of <tt>T</tt>, in bytes
/// \details Internally the function calls C++11's <tt>alignof</tt> if available. If not
/// available, then the function uses compiler specific extensions such as
/// <tt>__alignof</tt> and <tt>_alignof_</tt>. If an extension is not available, then
/// the function uses <tt>__BIGGEST_ALIGNMENT__</tt> if <tt>__BIGGEST_ALIGNMENT__</tt>
/// is smaller than <tt>sizeof(T)</tt>. <tt>sizeof(T)</tt> is used if all others are
/// not available.
template <class T>
inline unsigned int GetAlignmentOf()
{
#if defined(CRYPTOPP_CXX11_ALIGNOF)
return alignof(T);
#elif (_MSC_VER >= 1300)
return __alignof(T);
#elif defined(__GNUC__)
return __alignof__(T);
#elif defined(__SUNPRO_CC)
return __alignof__(T);
#elif CRYPTOPP_BOOL_SLOW_WORD64
return UnsignedMin(4U, sizeof(T));
#else
# if __BIGGEST_ALIGNMENT__
if (__BIGGEST_ALIGNMENT__ < sizeof(T))
return __BIGGEST_ALIGNMENT__;
else
# endif
return sizeof(T);
#endif
}
/// \brief Determines whether ptr is aligned to a minimum value
/// \param ptr the pointer being checked for alignment
/// \param alignment the alignment value to test the pointer against
/// \returns true if <tt>ptr</tt> is aligned on at least <tt>alignment</tt> boundary, false otherwise
/// \details Internally the function tests whether alignment is 1. If so, the function returns true.
/// If not, then the function effectively performs a modular reduction and returns true if the residue is 0
inline bool IsAlignedOn(const void *ptr, unsigned int alignment)
{
return alignment==1 || (IsPowerOf2(alignment) ? ModPowerOf2(reinterpret_cast<size_t>(ptr), alignment) == 0 : reinterpret_cast<size_t>(ptr) % alignment == 0);
}
/// \brief Determines whether ptr is minimally aligned
/// \tparam T class or type
/// \param ptr the pointer to check for alignment
/// \returns true if <tt>ptr</tt> is aligned to at least <tt>T</tt> boundary, false otherwise
/// \details Internally the function calls IsAlignedOn with a second parameter of GetAlignmentOf<T>
template <class T>
inline bool IsAligned(const void *ptr)
{
return IsAlignedOn(ptr, GetAlignmentOf<T>());
}
#if defined(CRYPTOPP_LITTLE_ENDIAN)
typedef LittleEndian NativeByteOrder;
#elif defined(CRYPTOPP_BIG_ENDIAN)
typedef BigEndian NativeByteOrder;
#else
# error "Unable to determine endian-ness"
#endif
/// \brief Returns NativeByteOrder as an enumerated ByteOrder value
/// \returns LittleEndian if the native byte order is little-endian, and BigEndian if the
/// native byte order is big-endian
/// \details NativeByteOrder is a typedef depending on the platform. If CRYPTOPP_LITTLE_ENDIAN is
/// set in config.h, then GetNativeByteOrder returns LittleEndian. If
/// CRYPTOPP_BIG_ENDIAN is set, then GetNativeByteOrder returns BigEndian.
/// \note There are other byte orders besides little- and big-endian, and they include bi-endian
/// and PDP-endian. If a system is neither little-endian nor big-endian, then a compile time
/// error occurs.
inline ByteOrder GetNativeByteOrder()
{
return NativeByteOrder::ToEnum();
}
/// \brief Determines whether order follows native byte ordering
/// \param order the ordering being tested against native byte ordering
/// \returns true if order follows native byte ordering, false otherwise
inline bool NativeByteOrderIs(ByteOrder order)
{
return order == GetNativeByteOrder();
}
/// \brief Returns the direction the cipher is being operated
/// \tparam T class or type
/// \param obj the cipher object being queried
/// \returns ENCRYPTION if the cipher obj is being operated in its forward direction,
/// DECRYPTION otherwise
/// \details A cipher can be operated in a "forward" direction (encryption) or a "reverse"
/// direction (decryption). The operations do not have to be symmetric, meaning a second
/// application of the transformation does not necessariy return the original message.
/// That is, <tt>E(D(m))</tt> may not equal <tt>E(E(m))</tt>; and <tt>D(E(m))</tt> may not
/// equal <tt>D(D(m))</tt>.
template <class T>
inline CipherDir GetCipherDir(const T &obj)
{
return obj.IsForwardTransformation() ? ENCRYPTION : DECRYPTION;
}
/// \brief Attempts to reclaim unused memory
/// \throws bad_alloc
/// \details In the normal course of running a program, a request for memory normally succeeds. If a
/// call to AlignedAllocate or UnalignedAllocate fails, then CallNewHandler is called in
/// an effort to recover. Internally, CallNewHandler calls set_new_handler(NULLPTR) in an effort
/// to free memory. There is no guarantee CallNewHandler will be able to procure more memory so
/// an allocation succeeds. If the call to set_new_handler fails, then CallNewHandler throws
/// a bad_alloc exception.
CRYPTOPP_DLL void CRYPTOPP_API CallNewHandler();
/// \brief Performs an addition with carry on a block of bytes
/// \param inout the byte block
/// \param size the size of the block, in bytes
/// \details Performs an addition with carry by adding 1 on a block of bytes starting at the least
/// significant byte. Once carry is 0, the function terminates and returns to the caller.
/// \note The function is not constant time because it stops processing when the carry is 0.
inline void IncrementCounterByOne(byte *inout, unsigned int size)
{
CRYPTOPP_ASSERT(inout != NULLPTR); CRYPTOPP_ASSERT(size < INT_MAX);
for (int i=int(size-1), carry=1; i>=0 && carry; i--)
carry = !++inout[i];
}
/// \brief Performs an addition with carry on a block of bytes
/// \param output the destination block of bytes
/// \param input the source block of bytes
/// \param size the size of the block
/// \details Performs an addition with carry on a block of bytes starting at the least significant
/// byte. Once carry is 0, the remaining bytes from input are copied to output using memcpy.
/// \details The function is close to near-constant time because it operates on all the bytes in the blocks.
inline void IncrementCounterByOne(byte *output, const byte *input, unsigned int size)
{
CRYPTOPP_ASSERT(output != NULLPTR); CRYPTOPP_ASSERT(input != NULLPTR); CRYPTOPP_ASSERT(size < INT_MAX);
int i, carry;
for (i=int(size-1), carry=1; i>=0 && carry; i--)
carry = ((output[i] = input[i]+1) == 0);
memcpy_s(output, size, input, size_t(i)+1);
}
/// \brief Performs a branchless swap of values a and b if condition c is true
/// \tparam T class or type
/// \param c the condition to perform the swap
/// \param a the first value
/// \param b the second value
template <class T>
inline void ConditionalSwap(bool c, T &a, T &b)
{
T t = c * (a ^ b);
a ^= t;
b ^= t;
}
/// \brief Performs a branchless swap of pointers a and b if condition c is true
/// \tparam T class or type
/// \param c the condition to perform the swap
/// \param a the first pointer
/// \param b the second pointer
template <class T>
inline void ConditionalSwapPointers(bool c, T &a, T &b)
{
ptrdiff_t t = size_t(c) * (a - b);
a -= t;
b += t;
}
// see http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/protect-secrets.html
// and http://www.securecoding.cert.org/confluence/display/cplusplus/MSC06-CPP.+Be+aware+of+compiler+optimization+when+dealing+with+sensitive+data
/// \brief Sets each element of an array to 0
/// \tparam T class or type
/// \param buf an array of elements
/// \param n the number of elements in the array
/// \details The operation performs a wipe or zeroization. The function
/// attempts to survive optimizations and dead code removal.
template <class T>
void SecureWipeBuffer(T *buf, size_t n)
{
// GCC 4.3.2 on Cygwin optimizes away the first store if this
// loop is done in the forward direction
volatile T *p = buf+n;
while (n--)
*(--p) = 0;
}
#if !defined(CRYPTOPP_DISABLE_ASM) && \
(_MSC_VER >= 1400 || defined(__GNUC__)) && \
(CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86)
/// \brief Sets each byte of an array to 0
/// \param buf an array of bytes
/// \param n the number of elements in the array
/// \details The operation performs a wipe or zeroization. The function
/// attempts to survive optimizations and dead code removal.
template<> inline void SecureWipeBuffer(byte *buf, size_t n)
{
volatile byte *p = buf;
#ifdef __GNUC__
asm volatile("rep stosb" : "+c"(n), "+D"(p) : "a"(0) : "memory");
#else
__stosb(reinterpret_cast<byte *>(reinterpret_cast<size_t>(p)), 0, n);
#endif
}
/// \brief Sets each 16-bit element of an array to 0
/// \param buf an array of 16-bit words
/// \param n the number of elements in the array
/// \details The operation performs a wipe or zeroization. The function
/// attempts to survive optimizations and dead code removal.
template<> inline void SecureWipeBuffer(word16 *buf, size_t n)
{
volatile word16 *p = buf;
#ifdef __GNUC__
asm volatile("rep stosw" : "+c"(n), "+D"(p) : "a"(0) : "memory");
#else
__stosw(reinterpret_cast<word16 *>(reinterpret_cast<size_t>(p)), 0, n);
#endif
}
/// \brief Sets each 32-bit element of an array to 0
/// \param buf an array of 32-bit words
/// \param n the number of elements in the array
/// \details The operation performs a wipe or zeroization. The function
/// attempts to survive optimizations and dead code removal.
template<> inline void SecureWipeBuffer(word32 *buf, size_t n)
{
volatile word32 *p = buf;
#ifdef __GNUC__
asm volatile("rep stosl" : "+c"(n), "+D"(p) : "a"(0) : "memory");
#else
__stosd(reinterpret_cast<unsigned long *>(reinterpret_cast<size_t>(p)), 0, n);
#endif
}
/// \brief Sets each 64-bit element of an array to 0
/// \param buf an array of 64-bit words
/// \param n the number of elements in the array
/// \details The operation performs a wipe or zeroization. The function
/// attempts to survive optimizations and dead code removal.
template<> inline void SecureWipeBuffer(word64 *buf, size_t n)
{
#if CRYPTOPP_BOOL_X64
volatile word64 *p = buf;
# ifdef __GNUC__
asm volatile("rep stosq" : "+c"(n), "+D"(p) : "a"(0) : "memory");
# else
__stosq(reinterpret_cast<word64 *>(reinterpret_cast<size_t>(p)), 0, n);
# endif
#else
SecureWipeBuffer(reinterpret_cast<word32 *>(buf), 2*n);
#endif
}
#endif // CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86
#if !defined(CRYPTOPP_DISABLE_ASM) && (_MSC_VER >= 1700) && defined(_M_ARM)
template<> inline void SecureWipeBuffer(byte *buf, size_t n)
{
char *p = reinterpret_cast<char*>(buf+n);
while (n--)
__iso_volatile_store8(--p, 0);
}
template<> inline void SecureWipeBuffer(word16 *buf, size_t n)
{
short *p = reinterpret_cast<short*>(buf+n);
while (n--)
__iso_volatile_store16(--p, 0);
}
template<> inline void SecureWipeBuffer(word32 *buf, size_t n)
{
int *p = reinterpret_cast<int*>(buf+n);
while (n--)
__iso_volatile_store32(--p, 0);
}
template<> inline void SecureWipeBuffer(word64 *buf, size_t n)
{
__int64 *p = reinterpret_cast<__int64*>(buf+n);
while (n--)
__iso_volatile_store64(--p, 0);
}
#endif
/// \brief Sets each element of an array to 0
/// \tparam T class or type
/// \param buf an array of elements
/// \param n the number of elements in the array
/// \details The operation performs a wipe or zeroization. The function
/// attempts to survive optimizations and dead code removal.
template <class T>
inline void SecureWipeArray(T *buf, size_t n)
{
if (sizeof(T) % 8 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word64>() == 0)
SecureWipeBuffer(reinterpret_cast<word64 *>(static_cast<void *>(buf)), n * (sizeof(T)/8));
else if (sizeof(T) % 4 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word32>() == 0)
SecureWipeBuffer(reinterpret_cast<word32 *>(static_cast<void *>(buf)), n * (sizeof(T)/4));
else if (sizeof(T) % 2 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word16>() == 0)
SecureWipeBuffer(reinterpret_cast<word16 *>(static_cast<void *>(buf)), n * (sizeof(T)/2));
else
SecureWipeBuffer(reinterpret_cast<byte *>(static_cast<void *>(buf)), n * sizeof(T));
}
/// \brief Converts a wide character C-string to a multibyte string
/// \param str C-string consisting of wide characters
/// \param throwOnError flag indicating the function should throw on error
/// \returns str converted to a multibyte string or an empty string.
/// \details StringNarrow() converts a wide string to a narrow string using C++ std::wcstombs() under
/// the executing thread's locale. A locale must be set before using this function, and it can be
/// set with std::setlocale() if needed. Upon success, the converted string is returned.
/// \details Upon failure with throwOnError as false, the function returns an empty string. If
/// throwOnError as true, the function throws an InvalidArgument() exception.
/// \note If you try to convert, say, the Chinese character for "bone" from UTF-16 (0x9AA8) to UTF-8
/// (0xE9 0xAA 0xA8), then you must ensure the locale is available. If the locale is not available,
/// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.
std::string StringNarrow(const wchar_t *str, bool throwOnError = true);
/// \brief Converts a multibyte C-string to a wide character string
/// \param str C-string consisting of wide characters
/// \param throwOnError flag indicating the function should throw on error
/// \returns str converted to a multibyte string or an empty string.
/// \details StringWiden() converts a narrow string to a wide string using C++ std::mbstowcs() under
/// the executing thread's locale. A locale must be set before using this function, and it can be
/// set with std::setlocale() if needed. Upon success, the converted string is returned.
/// \details Upon failure with throwOnError as false, the function returns an empty string. If
/// throwOnError as true, the function throws an InvalidArgument() exception.
/// \note If you try to convert, say, the Chinese character for "bone" from UTF-8 (0xE9 0xAA 0xA8)
/// to UTF-16 (0x9AA8), then you must ensure the locale is available. If the locale is not available,
/// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.
std::wstring StringWiden(const char *str, bool throwOnError = true);
#ifdef CRYPTOPP_DOXYGEN_PROCESSING
/// \brief Allocates a buffer on 16-byte boundary
/// \param size the size of the buffer
/// \details AlignedAllocate is primarily used when the data will be proccessed by MMX, SSE2 and NEON
/// instructions. The assembly language routines rely on the alignment. If the alignment is not
/// respected, then a SIGBUS could be generated on Unix and Linux, and an
/// EXCEPTION_DATATYPE_MISALIGNMENT could be generated on Windows.
/// \note AlignedAllocate and AlignedDeallocate are available when CRYPTOPP_BOOL_ALIGN16 is
/// defined. CRYPTOPP_BOOL_ALIGN16 is defined in config.h
CRYPTOPP_DLL void* CRYPTOPP_API AlignedAllocate(size_t size);
/// \brief Frees a buffer allocated with AlignedAllocate
/// \param ptr the buffer to free
/// \note AlignedAllocate and AlignedDeallocate are available when CRYPTOPP_BOOL_ALIGN16 is
/// defined. CRYPTOPP_BOOL_ALIGN16 is defined in config.h
CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr);
#endif // CRYPTOPP_DOXYGEN_PROCESSING
#if CRYPTOPP_BOOL_ALIGN16
CRYPTOPP_DLL void* CRYPTOPP_API AlignedAllocate(size_t size);
CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr);
#endif // CRYPTOPP_BOOL_ALIGN16
/// \brief Allocates a buffer
/// \param size the size of the buffer
CRYPTOPP_DLL void * CRYPTOPP_API UnalignedAllocate(size_t size);
/// \brief Frees a buffer allocated with UnalignedAllocate
/// \param ptr the buffer to free
CRYPTOPP_DLL void CRYPTOPP_API UnalignedDeallocate(void *ptr);
// ************** rotate functions ***************
/// \brief Performs a left rotate
/// \tparam R the number of bit positions to rotate the value
/// \tparam T the word type
/// \param x the value to rotate
/// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
/// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// Use rotlMod if the rotate amount R is outside the range.
/// \details Use rotlConstant when the rotate amount is constant. The template function was added
/// because Clang did not propagate the constant when passed as a function parameter. Clang's
/// need for a constexpr meant rotlFixed failed to compile on occassion.
/// \note rotlConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
/// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
/// counterparts.
/// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
/// \since Crypto++ 6.0
template <unsigned int R, class T> inline T rotlConstant(T x)
{
// Portable rotate that reduces to single instruction...
// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
// http://software.intel.com/en-us/forums/topic/580884
// and http://llvm.org/bugs/show_bug.cgi?id=24226
static const unsigned int THIS_SIZE = sizeof(T)*8;
static const unsigned int MASK = THIS_SIZE-1;
CRYPTOPP_ASSERT(R < THIS_SIZE);
return T((x<<R)|(x>>(-R&MASK)));
}
/// \brief Performs a right rotate
/// \tparam R the number of bit positions to rotate the value
/// \tparam T the word type
/// \param x the value to rotate
/// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
/// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// Use rotrMod if the rotate amount R is outside the range.
/// \details Use rotrConstant when the rotate amount is constant. The template function was added
/// because Clang did not propagate the constant when passed as a function parameter. Clang's
/// need for a constexpr meant rotrFixed failed to compile on occassion.
/// \note rotrConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
/// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
/// counterparts.
/// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
template <unsigned int R, class T> inline T rotrConstant(T x)
{
// Portable rotate that reduces to single instruction...
// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
// http://software.intel.com/en-us/forums/topic/580884
// and http://llvm.org/bugs/show_bug.cgi?id=24226
static const unsigned int THIS_SIZE = sizeof(T)*8;
static const unsigned int MASK = THIS_SIZE-1;
CRYPTOPP_ASSERT(R < THIS_SIZE);
return T((x >> R)|(x<<(-R&MASK)));
}
/// \brief Performs a left rotate
/// \tparam T the word type
/// \param x the value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
/// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// Use rotlMod if the rotate amount y is outside the range.
/// \note rotlFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
/// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
/// counterparts. New code should use <tt>rotlConstant</tt>, which accepts the rotate amount as a
/// template parameter.
/// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
/// \since Crypto++ 6.0
template <class T> inline T rotlFixed(T x, unsigned int y)
{
// Portable rotate that reduces to single instruction...
// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
// http://software.intel.com/en-us/forums/topic/580884
// and http://llvm.org/bugs/show_bug.cgi?id=24226
static const unsigned int THIS_SIZE = sizeof(T)*8;
static const unsigned int MASK = THIS_SIZE-1;
CRYPTOPP_ASSERT(y < THIS_SIZE);
return T((x<<y)|(x>>(-y&MASK)));
}
/// \brief Performs a right rotate
/// \tparam T the word type
/// \param x the value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
/// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// Use rotrMod if the rotate amount y is outside the range.
/// \note rotrFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
/// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
/// counterparts. New code should use <tt>rotrConstant</tt>, which accepts the rotate amount as a
/// template parameter.
/// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
/// \since Crypto++ 3.0
template <class T> inline T rotrFixed(T x, unsigned int y)
{
// Portable rotate that reduces to single instruction...
// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
// http://software.intel.com/en-us/forums/topic/580884
// and http://llvm.org/bugs/show_bug.cgi?id=24226
static const unsigned int THIS_SIZE = sizeof(T)*8;
static const unsigned int MASK = THIS_SIZE-1;
CRYPTOPP_ASSERT(y < THIS_SIZE);
return T((x >> y)|(x<<(-y&MASK)));
}
/// \brief Performs a left rotate
/// \tparam T the word type
/// \param x the value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
/// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// Use rotlMod if the rotate amount y is outside the range.
/// \note rotlVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
/// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
/// counterparts.
/// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
/// \since Crypto++ 3.0
template <class T> inline T rotlVariable(T x, unsigned int y)
{
static const unsigned int THIS_SIZE = sizeof(T)*8;
static const unsigned int MASK = THIS_SIZE-1;
CRYPTOPP_ASSERT(y < THIS_SIZE);
return T((x<<y)|(x>>(-y&MASK)));
}
/// \brief Performs a right rotate
/// \tparam T the word type
/// \param x the value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
/// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// Use rotrMod if the rotate amount y is outside the range.
/// \note rotrVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
/// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
/// counterparts.
/// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
/// \since Crypto++ 3.0
template <class T> inline T rotrVariable(T x, unsigned int y)
{
static const unsigned int THIS_SIZE = sizeof(T)*8;
static const unsigned int MASK = THIS_SIZE-1;
CRYPTOPP_ASSERT(y < THIS_SIZE);
return T((x>>y)|(x<<(-y&MASK)));
}
/// \brief Performs a left rotate
/// \tparam T the word type
/// \param x the value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
/// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
/// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
/// \since Crypto++ 3.0
template <class T> inline T rotlMod(T x, unsigned int y)
{
static const unsigned int THIS_SIZE = sizeof(T)*8;
static const unsigned int MASK = THIS_SIZE-1;
return T((x<<(y&MASK))|(x>>(-y&MASK)));
}
/// \brief Performs a right rotate
/// \tparam T the word type
/// \param x the value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
/// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
/// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
/// \since Crypto++ 3.0
template <class T> inline T rotrMod(T x, unsigned int y)
{
static const unsigned int THIS_SIZE = sizeof(T)*8;
static const unsigned int MASK = THIS_SIZE-1;
return T((x>>(y&MASK))|(x<<(-y&MASK)));
}
#ifdef _MSC_VER
/// \brief Performs a left rotate
/// \tparam T the word type
/// \param x the 32-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
/// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \note rotlFixed will assert in Debug builds if is outside the allowed range.
/// \since Crypto++ 3.0
template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
{
// Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
CRYPTOPP_ASSERT(y < 8*sizeof(x));
return y ? _lrotl(x, static_cast<byte>(y)) : x;
}
/// \brief Performs a right rotate
/// \tparam T the word type
/// \param x the 32-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
/// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \note rotrFixed will assert in Debug builds if is outside the allowed range.
/// \since Crypto++ 3.0
template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
{
// Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
CRYPTOPP_ASSERT(y < 8*sizeof(x));
return y ? _lrotr(x, static_cast<byte>(y)) : x;
}
/// \brief Performs a left rotate
/// \tparam T the word type
/// \param x the 32-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
/// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \note rotlVariable will assert in Debug builds if is outside the allowed range.
/// \since Crypto++ 3.0
template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
{
CRYPTOPP_ASSERT(y < 8*sizeof(x));
return _lrotl(x, static_cast<byte>(y));
}
/// \brief Performs a right rotate
/// \tparam T the word type
/// \param x the 32-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
/// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \note rotrVariable will assert in Debug builds if is outside the allowed range.
/// \since Crypto++ 3.0
template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
{
CRYPTOPP_ASSERT(y < 8*sizeof(x));
return _lrotr(x, static_cast<byte>(y));
}
/// \brief Performs a left rotate
/// \tparam T the word type
/// \param x the 32-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
/// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \since Crypto++ 3.0
template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
{
y %= 8*sizeof(x);
return _lrotl(x, static_cast<byte>(y));
}
/// \brief Performs a right rotate
/// \tparam T the word type
/// \param x the 32-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
/// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \since Crypto++ 3.0
template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
{
y %= 8*sizeof(x);
return _lrotr(x, static_cast<byte>(y));
}
#endif // #ifdef _MSC_VER
#if (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
// Intel C++ Compiler 10.0 calls a function instead of using the rotate instruction when using these instructions
/// \brief Performs a left rotate
/// \tparam T the word type
/// \param x the 64-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
/// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \note rotrFixed will assert in Debug builds if is outside the allowed range.
/// \since Crypto++ 3.0
template<> inline word64 rotlFixed<word64>(word64 x, unsigned int y)
{
// Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
CRYPTOPP_ASSERT(y < 8*sizeof(x));
return y ? _rotl64(x, static_cast<byte>(y)) : x;
}
/// \brief Performs a right rotate
/// \tparam T the word type
/// \param x the 64-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
/// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \note rotrFixed will assert in Debug builds if is outside the allowed range.
/// \since Crypto++ 3.0
template<> inline word64 rotrFixed<word64>(word64 x, unsigned int y)
{
// Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
CRYPTOPP_ASSERT(y < 8*sizeof(x));
return y ? _rotr64(x, static_cast<byte>(y)) : x;
}
/// \brief Performs a left rotate
/// \tparam T the word type
/// \param x the 64-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
/// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \note rotlVariable will assert in Debug builds if is outside the allowed range.
/// \since Crypto++ 3.0
template<> inline word64 rotlVariable<word64>(word64 x, unsigned int y)
{
CRYPTOPP_ASSERT(y < 8*sizeof(x));
return _rotl64(x, static_cast<byte>(y));
}
/// \brief Performs a right rotate
/// \tparam T the word type
/// \param x the 64-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
/// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \note rotrVariable will assert in Debug builds if is outside the allowed range.
/// \since Crypto++ 3.0
template<> inline word64 rotrVariable<word64>(word64 x, unsigned int y)
{
CRYPTOPP_ASSERT(y < 8*sizeof(x));
return y ? _rotr64(x, static_cast<byte>(y)) : x;
}
/// \brief Performs a left rotate
/// \tparam T the word type
/// \param x the 64-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
/// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \since Crypto++ 3.0
template<> inline word64 rotlMod<word64>(word64 x, unsigned int y)
{
CRYPTOPP_ASSERT(y < 8*sizeof(x));
return y ? _rotl64(x, static_cast<byte>(y)) : x;
}
/// \brief Performs a right rotate
/// \tparam T the word type
/// \param x the 64-bit value to rotate
/// \param y the number of bit positions to rotate the value
/// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
/// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
/// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
/// \since Crypto++ 3.0
template<> inline word64 rotrMod<word64>(word64 x, unsigned int y)
{
CRYPTOPP_ASSERT(y < 8*sizeof(x));
return y ? _rotr64(x, static_cast<byte>(y)) : x;
}
#endif // #if _MSC_VER >= 1310
#if _MSC_VER >= 1400 && !defined(__INTEL_COMPILER)
// Intel C++ Compiler 10.0 gives undefined externals with these
template<> inline word16 rotlFixed<word16>(word16 x, unsigned int y)
{
// Intrinsic, not bound to C/C++ language rules.
return _rotl16(x, static_cast<byte>(y));
}
template<> inline word16 rotrFixed<word16>(word16 x, unsigned int y)
{
// Intrinsic, not bound to C/C++ language rules.
return _rotr16(x, static_cast<byte>(y));
}
template<> inline word16 rotlVariable<word16>(word16 x, unsigned int y)
{
return _rotl16(x, static_cast<byte>(y));
}
template<> inline word16 rotrVariable<word16>(word16 x, unsigned int y)
{
return _rotr16(x, static_cast<byte>(y));
}
template<> inline word16 rotlMod<word16>(word16 x, unsigned int y)
{
return _rotl16(x, static_cast<byte>(y));
}
template<> inline word16 rotrMod<word16>(word16 x, unsigned int y)
{
return _rotr16(x, static_cast<byte>(y));
}
template<> inline byte rotlFixed<byte>(byte x, unsigned int y)
{
// Intrinsic, not bound to C/C++ language rules.
return _rotl8(x, static_cast<byte>(y));
}
template<> inline byte rotrFixed<byte>(byte x, unsigned int y)
{
// Intrinsic, not bound to C/C++ language rules.
return _rotr8(x, static_cast<byte>(y));
}
template<> inline byte rotlVariable<byte>(byte x, unsigned int y)
{
return _rotl8(x, static_cast<byte>(y));
}
template<> inline byte rotrVariable<byte>(byte x, unsigned int y)
{
return _rotr8(x, static_cast<byte>(y));
}
template<> inline byte rotlMod<byte>(byte x, unsigned int y)
{
return _rotl8(x, static_cast<byte>(y));
}
template<> inline byte rotrMod<byte>(byte x, unsigned int y)
{
return _rotr8(x, static_cast<byte>(y));
}
#endif // #if _MSC_VER >= 1400
#if (defined(__MWERKS__) && TARGET_CPU_PPC)
template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
{
CRYPTOPP_ASSERT(y < 32);
return y ? __rlwinm(x,y,0,31) : x;
}
template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
{
CRYPTOPP_ASSERT(y < 32);
return y ? __rlwinm(x,32-y,0,31) : x;
}
template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
{
CRYPTOPP_ASSERT(y < 32);
return (__rlwnm(x,y,0,31));
}
template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
{
CRYPTOPP_ASSERT(y < 32);
return (__rlwnm(x,32-y,0,31));
}
template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
{
return (__rlwnm(x,y,0,31));
}
template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
{
return (__rlwnm(x,32-y,0,31));
}
#endif // __MWERKS__ && TARGET_CPU_PPC
// ************** endian reversal ***************
/// \brief Gets a byte from a value
/// \param order the ByteOrder of the value
/// \param value the value to retrieve the byte
/// \param index the location of the byte to retrieve
template <class T>
inline unsigned int GetByte(ByteOrder order, T value, unsigned int index)
{
if (order == LITTLE_ENDIAN_ORDER)
return GETBYTE(value, index);
else
return GETBYTE(value, sizeof(T)-index-1);
}
/// \brief Reverses bytes in a 8-bit value
/// \param value the 8-bit value to reverse
/// \note ByteReverse returns the value passed to it since there is nothing to reverse
inline byte ByteReverse(byte value)
{
return value;
}
/// \brief Reverses bytes in a 16-bit value
/// \param value the 16-bit value to reverse
/// \details ByteReverse calls bswap if available. Otherwise the function performs a 8-bit rotate on the word16
inline word16 ByteReverse(word16 value)
{
#if defined(CRYPTOPP_BYTESWAP_AVAILABLE)
return bswap_16(value);
#elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
return _byteswap_ushort(value);
#else
return rotlFixed(value, 8U);
#endif
}
/// \brief Reverses bytes in a 32-bit value
/// \param value the 32-bit value to reverse
/// \details ByteReverse calls bswap if available. Otherwise the function uses a combination of rotates on the word32
inline word32 ByteReverse(word32 value)
{
#if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
__asm__ ("bswap %0" : "=r" (value) : "0" (value));
return value;
#elif defined(CRYPTOPP_BYTESWAP_AVAILABLE)
return bswap_32(value);
#elif defined(__MWERKS__) && TARGET_CPU_PPC
return (word32)__lwbrx(&value,0);
#elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
return _byteswap_ulong(value);
#elif CRYPTOPP_FAST_ROTATE(32) && !defined(__xlC__)
// 5 instructions with rotate instruction, 9 without
return (rotrFixed(value, 8U) & 0xff00ff00) | (rotlFixed(value, 8U) & 0x00ff00ff);
#else
// 6 instructions with rotate instruction, 8 without
value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
return rotlFixed(value, 16U);
#endif
}
/// \brief Reverses bytes in a 64-bit value
/// \param value the 64-bit value to reverse
/// \details ByteReverse calls bswap if available. Otherwise the function uses a combination of rotates on the word64
inline word64 ByteReverse(word64 value)
{
#if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE) && defined(__x86_64__)
__asm__ ("bswap %0" : "=r" (value) : "0" (value));
return value;
#elif defined(CRYPTOPP_BYTESWAP_AVAILABLE)
return bswap_64(value);
#elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
return _byteswap_uint64(value);
#elif CRYPTOPP_BOOL_SLOW_WORD64
return (word64(ByteReverse(word32(value))) << 32) | ByteReverse(word32(value>>32));
#else
value = ((value & W64LIT(0xFF00FF00FF00FF00)) >> 8) | ((value & W64LIT(0x00FF00FF00FF00FF)) << 8);
value = ((value & W64LIT(0xFFFF0000FFFF0000)) >> 16) | ((value & W64LIT(0x0000FFFF0000FFFF)) << 16);
return rotlFixed(value, 32U);
#endif
}
/// \brief Reverses bits in a 8-bit value
/// \param value the 8-bit value to reverse
/// \details BitReverse performs a combination of shifts on the byte
inline byte BitReverse(byte value)
{
value = byte((value & 0xAA) >> 1) | byte((value & 0x55) << 1);
value = byte((value & 0xCC) >> 2) | byte((value & 0x33) << 2);
return rotlFixed(value, 4U);
}
/// \brief Reverses bits in a 16-bit value
/// \param value the 16-bit value to reverse
/// \details BitReverse performs a combination of shifts on the word16
inline word16 BitReverse(word16 value)
{
value = word16((value & 0xAAAA) >> 1) | word16((value & 0x5555) << 1);
value = word16((value & 0xCCCC) >> 2) | word16((value & 0x3333) << 2);
value = word16((value & 0xF0F0) >> 4) | word16((value & 0x0F0F) << 4);
return ByteReverse(value);
}
/// \brief Reverses bits in a 32-bit value
/// \param value the 32-bit value to reverse
/// \details BitReverse performs a combination of shifts on the word32
inline word32 BitReverse(word32 value)
{
value = word32((value & 0xAAAAAAAA) >> 1) | word32((value & 0x55555555) << 1);
value = word32((value & 0xCCCCCCCC) >> 2) | word32((value & 0x33333333) << 2);
value = word32((value & 0xF0F0F0F0) >> 4) | word32((value & 0x0F0F0F0F) << 4);
return ByteReverse(value);
}
/// \brief Reverses bits in a 64-bit value
/// \param value the 64-bit value to reverse
/// \details BitReverse performs a combination of shifts on the word64
inline word64 BitReverse(word64 value)
{
#if CRYPTOPP_BOOL_SLOW_WORD64
return (word64(BitReverse(word32(value))) << 32) | BitReverse(word32(value>>32));
#else
value = word64((value & W64LIT(0xAAAAAAAAAAAAAAAA)) >> 1) | word64((value & W64LIT(0x5555555555555555)) << 1);
value = word64((value & W64LIT(0xCCCCCCCCCCCCCCCC)) >> 2) | word64((value & W64LIT(0x3333333333333333)) << 2);
value = word64((value & W64LIT(0xF0F0F0F0F0F0F0F0)) >> 4) | word64((value & W64LIT(0x0F0F0F0F0F0F0F0F)) << 4);
return ByteReverse(value);
#endif
}
/// \brief Reverses bits in a value
/// \param value the value to reverse
/// \details The template overload of BitReverse operates on signed and unsigned values.
/// Internally the size of T is checked, and then value is cast to a byte,
/// word16, word32 or word64. After the cast, the appropriate BitReverse
/// overload is called.
template <class T>
inline T BitReverse(T value)
{
if (sizeof(T) == 1)
return (T)BitReverse((byte)value);
else if (sizeof(T) == 2)
return (T)BitReverse((word16)value);
else if (sizeof(T) == 4)
return (T)BitReverse((word32)value);
else
{
CRYPTOPP_ASSERT(sizeof(T) == 8);
return (T)BitReverse((word64)value);
}
}
/// \brief Reverses bytes in a value depending upon endianness
/// \tparam T the class or type
/// \param order the ByteOrder of the data
/// \param value the value to conditionally reverse
/// \details Internally, the ConditionalByteReverse calls NativeByteOrderIs.
/// If order matches native byte order, then the original value is returned.
/// If not, then ByteReverse is called on the value before returning to the caller.
template <class T>
inline T ConditionalByteReverse(ByteOrder order, T value)
{
return NativeByteOrderIs(order) ? value : ByteReverse(value);
}
/// \brief Reverses bytes in an element from an array of elements
/// \tparam T the class or type
/// \param out the output array of elements
/// \param in the input array of elements
/// \param byteCount the total number of bytes in the array
/// \details Internally, ByteReverse visits each element in the in array
/// calls ByteReverse on it, and writes the result to out.
/// \details ByteReverse does not process tail byes, or bytes that are
/// not part of a full element. If T is int (and int is 4 bytes), then
/// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are
/// reversed.
/// \details The following program should help illustrate the behavior.
/// <pre>vector<word32> v1, v2;
///
/// v1.push_back(1);
/// v1.push_back(2);
/// v1.push_back(3);
/// v1.push_back(4);
///
/// v2.resize(v1.size());
/// ByteReverse<word32>(&v2[0], &v1[0], 16);
///
/// cout << "V1: ";
/// for(unsigned int i = 0; i < v1.size(); i++)
/// cout << std::hex << v1[i] << " ";
/// cout << endl;
///
/// cout << "V2: ";
/// for(unsigned int i = 0; i < v2.size(); i++)
/// cout << std::hex << v2[i] << " ";
/// cout << endl;</pre>
/// The program above results in the following output.
/// <pre>V1: 00000001 00000002 00000003 00000004
/// V2: 01000000 02000000 03000000 04000000</pre>
/// \sa ConditionalByteReverse
template <class T>
void ByteReverse(T *out, const T *in, size_t byteCount)
{
// Alignment check due to Issues 690
CRYPTOPP_ASSERT(byteCount % sizeof(T) == 0);
CRYPTOPP_ASSERT(IsAligned<T>(in));
CRYPTOPP_ASSERT(IsAligned<T>(out));
size_t count = byteCount/sizeof(T);
for (size_t i=0; i<count; i++)
out[i] = ByteReverse(in[i]);
}
/// \brief Conditionally reverses bytes in an element from an array of elements
/// \tparam T the class or type
/// \param order the ByteOrder of the data
/// \param out the output array of elements
/// \param in the input array of elements
/// \param byteCount the byte count of the arrays
/// \details Internally, ByteReverse visits each element in the in array
/// calls ByteReverse on it depending on the desired endianness, and writes the result to out.
/// \details ByteReverse does not process tail byes, or bytes that are
/// not part of a full element. If T is int (and int is 4 bytes), then
/// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are
/// reversed.
/// \sa ByteReverse
template <class T>
inline void ConditionalByteReverse(ByteOrder order, T *out, const T *in, size_t byteCount)
{
if (!NativeByteOrderIs(order))
ByteReverse(out, in, byteCount);
else if (in != out)
memcpy_s(out, byteCount, in, byteCount);
}
template <class T>
inline void GetUserKey(ByteOrder order, T *out, size_t outlen, const byte *in, size_t inlen)
{
const size_t U = sizeof(T);
CRYPTOPP_ASSERT(inlen <= outlen*U);
memcpy_s(out, outlen*U, in, inlen);
memset_z((byte *)out+inlen, 0, outlen*U-inlen);
ConditionalByteReverse(order, out, out, RoundUpToMultipleOf(inlen, U));
}
inline byte UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const byte *)
{
CRYPTOPP_UNUSED(order);
return block[0];
}
inline word16 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word16 *)
{
return (order == BIG_ENDIAN_ORDER)
? block[1] | (block[0] << 8)
: block[0] | (block[1] << 8);
}
inline word32 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word32 *)
{
return (order == BIG_ENDIAN_ORDER)
? word32(block[3]) | (word32(block[2]) << 8) | (word32(block[1]) << 16) | (word32(block[0]) << 24)
: word32(block[0]) | (word32(block[1]) << 8) | (word32(block[2]) << 16) | (word32(block[3]) << 24);
}
inline word64 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word64 *)
{
return (order == BIG_ENDIAN_ORDER)
?
(word64(block[7]) |
(word64(block[6]) << 8) |
(word64(block[5]) << 16) |
(word64(block[4]) << 24) |
(word64(block[3]) << 32) |
(word64(block[2]) << 40) |
(word64(block[1]) << 48) |
(word64(block[0]) << 56))
:
(word64(block[0]) |
(word64(block[1]) << 8) |
(word64(block[2]) << 16) |
(word64(block[3]) << 24) |
(word64(block[4]) << 32) |
(word64(block[5]) << 40) |
(word64(block[6]) << 48) |
(word64(block[7]) << 56));
}
inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, byte value, const byte *xorBlock)
{
CRYPTOPP_UNUSED(order);
block[0] = static_cast<byte>(xorBlock ? (value ^ xorBlock[0]) : value);
}
inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word16 value, const byte *xorBlock)
{
if (order == BIG_ENDIAN_ORDER)
{
if (xorBlock)
{
block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
}
else
{
block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
}
}
else
{
if (xorBlock)
{
block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
}
else
{
block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
}
}
}
inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word32 value, const byte *xorBlock)
{
if (order == BIG_ENDIAN_ORDER)
{
if (xorBlock)
{
block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
}
else
{
block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
}
}
else
{
if (xorBlock)
{
block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
}
else
{
block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
}
}
}
inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word64 value, const byte *xorBlock)
{
if (order == BIG_ENDIAN_ORDER)
{
if (xorBlock)
{
block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
}
else
{
block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
}
}
else
{
if (xorBlock)
{
block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
}
else
{
block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
}
}
}
/// \brief Access a block of memory
/// \tparam T class or type
/// \param assumeAligned flag indicating alignment
/// \param order the ByteOrder of the data
/// \param block the byte buffer to be processed
/// \returns the word in the specified byte order
/// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates
/// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
/// LITTLE_ENDIAN_ORDER.
/// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt>
/// will be <tt>0x03020100</tt>.
/// <pre>
/// word32 w;
/// byte buffer[4] = {0,1,2,3};
/// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);
/// </pre>
template <class T>
inline T GetWord(bool assumeAligned, ByteOrder order, const byte *block)
{
CRYPTOPP_UNUSED(assumeAligned);
T temp;
memcpy(&temp, block, sizeof(T));
return ConditionalByteReverse(order, temp);
}
/// \brief Access a block of memory
/// \tparam T class or type
/// \param assumeAligned flag indicating alignment
/// \param order the ByteOrder of the data
/// \param result the word in the specified byte order
/// \param block the byte buffer to be processed
/// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates
/// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
/// LITTLE_ENDIAN_ORDER.
/// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt>
/// will be <tt>0x03020100</tt>.
/// <pre>
/// word32 w;
/// byte buffer[4] = {0,1,2,3};
/// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);
/// </pre>
template <class T>
inline void GetWord(bool assumeAligned, ByteOrder order, T &result, const byte *block)
{
result = GetWord<T>(assumeAligned, order, block);
}
/// \brief Access a block of memory
/// \tparam T class or type
/// \param assumeAligned flag indicating alignment
/// \param order the ByteOrder of the data
/// \param block the destination byte buffer
/// \param value the word in the specified byte order
/// \param xorBlock an optional byte buffer to xor
/// \details PutWord() provides alternate write access to a block of memory. The flag assumeAligned indicates
/// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
/// LITTLE_ENDIAN_ORDER.
template <class T>
inline void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock = NULLPTR)
{
CRYPTOPP_UNUSED(assumeAligned);
T t1, t2;
t1 = ConditionalByteReverse(order, value);
if (xorBlock) {memcpy(&t2, xorBlock, sizeof(T)); t1 ^= t2;}
memcpy(block, &t1, sizeof(T));
}
/// \brief Access a block of memory
/// \tparam T class or type
/// \tparam B enumeration indicating endianness
/// \tparam A flag indicating alignment
/// \details GetBlock() provides alternate read access to a block of memory. The enumeration B is
/// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
/// Repeatedly applying operator() results in advancing in the block of memory.
/// \details An example of reading two word32 values from a block of memory is shown below. <tt>w1</tt>
/// will be <tt>0x03020100</tt> and <tt>w1</tt> will be <tt>0x07060504</tt>.
/// <pre>
/// word32 w1, w2;
/// byte buffer[8] = {0,1,2,3,4,5,6,7};
/// GetBlock<word32, LittleEndian> block(buffer);
/// block(w1)(w2);
/// </pre>
template <class T, class B, bool A=false>
class GetBlock
{
public:
/// \brief Construct a GetBlock
/// \param block the memory block
GetBlock(const void *block)
: m_block((const byte *)block) {}
/// \brief Access a block of memory
/// \tparam U class or type
/// \param x the value to read
/// \returns pointer to the remainder of the block after reading x
template <class U>
inline GetBlock<T, B, A> & operator()(U &x)
{
CRYPTOPP_COMPILE_ASSERT(sizeof(U) >= sizeof(T));
x = GetWord<T>(A, B::ToEnum(), m_block);
m_block += sizeof(T);
return *this;
}
private:
const byte *m_block;
};
/// \brief Access a block of memory
/// \tparam T class or type
/// \tparam B enumeration indicating endianness
/// \tparam A flag indicating alignment
/// \details PutBlock() provides alternate write access to a block of memory. The enumeration B is
/// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
/// Repeatedly applying operator() results in advancing in the block of memory.
/// \details An example of writing two word32 values from a block of memory is shown below. After the code
/// executes, the byte buffer will be <tt>{0,1,2,3,4,5,6,7}</tt>.
/// <pre>
/// word32 w1=0x03020100, w2=0x07060504;
/// byte buffer[8];
/// PutBlock<word32, LittleEndian> block(NULLPTR, buffer);
/// block(w1)(w2);
/// </pre>
template <class T, class B, bool A=false>
class PutBlock
{
public:
/// \brief Construct a PutBlock
/// \param block the memory block
/// \param xorBlock optional mask
PutBlock(const void *xorBlock, void *block)
: m_xorBlock((const byte *)xorBlock), m_block((byte *)block) {}
/// \brief Access a block of memory
/// \tparam U class or type
/// \param x the value to write
/// \returns pointer to the remainder of the block after writing x
template <class U>
inline PutBlock<T, B, A> & operator()(U x)
{
PutWord(A, B::ToEnum(), m_block, (T)x, m_xorBlock);
m_block += sizeof(T);
if (m_xorBlock)
m_xorBlock += sizeof(T);
return *this;
}
private:
const byte *m_xorBlock;
byte *m_block;
};
/// \brief Access a block of memory
/// \tparam T class or type
/// \tparam B enumeration indicating endianness
/// \tparam GA flag indicating alignment for the Get operation
/// \tparam PA flag indicating alignment for the Put operation
/// \details GetBlock() provides alternate write access to a block of memory. The enumeration B is
/// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
/// \sa GetBlock() and PutBlock().
template <class T, class B, bool GA=false, bool PA=false>
struct BlockGetAndPut
{
// function needed because of C++ grammatical ambiguity between expression-statements and declarations
static inline GetBlock<T, B, GA> Get(const void *block) {return GetBlock<T, B, GA>(block);}
typedef PutBlock<T, B, PA> Put;
};
/// \brief Convert a word to a string
/// \tparam T class or type
/// \param value the word to convert
/// \param order byte order
/// \returns a string representing the value of the word
template <class T>
std::string WordToString(T value, ByteOrder order = BIG_ENDIAN_ORDER)
{
if (!NativeByteOrderIs(order))
value = ByteReverse(value);
return std::string((char *)&value, sizeof(value));
}
/// \brief Convert a string to a word
/// \tparam T class or type
/// \param str the string to convert
/// \param order byte order
/// \returns a word representing the value of the string
template <class T>
T StringToWord(const std::string &str, ByteOrder order = BIG_ENDIAN_ORDER)
{
T value = 0;
memcpy_s(&value, sizeof(value), str.data(), UnsignedMin(str.size(), sizeof(value)));
return NativeByteOrderIs(order) ? value : ByteReverse(value);
}
// ************** help remove warning on g++ ***************
/// \brief Safely shift values when undefined behavior could occur
/// \tparam overflow boolean flag indicating if overflow is present
/// \details SafeShifter safely shifts values when undefined behavior could occur under C/C++ rules.
/// The class behaves much like a saturating arithmetic class, clamping values rather than allowing
/// the compiler to remove undefined behavior.
/// \sa SafeShifter<true>, SafeShifter<false>
template <bool overflow> struct SafeShifter;
/// \brief Shifts a value in the presence of overflow
/// \details the true template parameter indicates overflow would occur.
/// In this case, SafeShifter clamps the value and returns 0.
template<> struct SafeShifter<true>
{
/// \brief Right shifts a value that overflows
/// \tparam T class or type
/// \return 0
/// \details Since <tt>overflow == true</tt>, the value 0 is always returned.
/// \sa SafeLeftShift
template <class T>
static inline T RightShift(T value, unsigned int bits)
{
CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
return 0;
}
/// \brief Left shifts a value that overflows
/// \tparam T class or type
/// \return 0
/// \details Since <tt>overflow == true</tt>, the value 0 is always returned.
/// \sa SafeRightShift
template <class T>
static inline T LeftShift(T value, unsigned int bits)
{
CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
return 0;
}
};
/// \brief Shifts a value in the absence of overflow
/// \details the false template parameter indicates overflow would not occur.
/// In this case, SafeShifter returns the shfted value.
template<> struct SafeShifter<false>
{
/// \brief Right shifts a value that does not overflow
/// \tparam T class or type
/// \return the shifted value
/// \details Since <tt>overflow == false</tt>, the shifted value is returned.
/// \sa SafeLeftShift
template <class T>
static inline T RightShift(T value, unsigned int bits)
{
return value >> bits;
}
/// \brief Left shifts a value that does not overflow
/// \tparam T class or type
/// \return the shifted value
/// \details Since <tt>overflow == false</tt>, the shifted value is returned.
/// \sa SafeRightShift
template <class T>
static inline T LeftShift(T value, unsigned int bits)
{
return value << bits;
}
};
/// \brief Safely right shift values when undefined behavior could occur
/// \tparam bits the number of bit positions to shift the value
/// \tparam T class or type
/// \param value the value to right shift
/// \result the shifted value or 0
/// \details SafeRightShift safely shifts the value to the right when undefined behavior
/// could occur under C/C++ rules. SafeRightShift will return the shifted value or 0
/// if undefined behavior would occur.
template <unsigned int bits, class T>
inline T SafeRightShift(T value)
{
return SafeShifter<(bits>=(8*sizeof(T)))>::RightShift(value, bits);
}
/// \brief Safely left shift values when undefined behavior could occur
/// \tparam bits the number of bit positions to shift the value
/// \tparam T class or type
/// \param value the value to left shift
/// \result the shifted value or 0
/// \details SafeLeftShift safely shifts the value to the left when undefined behavior
/// could occur under C/C++ rules. SafeLeftShift will return the shifted value or 0
/// if undefined behavior would occur.
template <unsigned int bits, class T>
inline T SafeLeftShift(T value)
{
return SafeShifter<(bits>=(8*sizeof(T)))>::LeftShift(value, bits);
}
/// \brief Finds first element not in a range
/// \tparam InputIt Input iterator type
/// \tparam T class or type
/// \param first iterator to first element
/// \param last iterator to last element
/// \param value the value used as a predicate
/// \returns iterator to the first element in the range that is not value
template<typename InputIt, typename T>
inline InputIt FindIfNot(InputIt first, InputIt last, const T &value) {
#ifdef CRYPTOPP_CXX11_LAMBDA
return std::find_if(first, last, [&value](const T &o) {
return value!=o;
});
#else
return std::find_if(first, last, std::bind2nd(std::not_equal_to<T>(), value));
#endif
}
// ************** use one buffer for multiple data members ***************
#define CRYPTOPP_BLOCK_1(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+0);} size_t SS1() {return sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
#define CRYPTOPP_BLOCK_2(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS1());} size_t SS2() {return SS1()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
#define CRYPTOPP_BLOCK_3(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS2());} size_t SS3() {return SS2()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
#define CRYPTOPP_BLOCK_4(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS3());} size_t SS4() {return SS3()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
#define CRYPTOPP_BLOCK_5(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS4());} size_t SS5() {return SS4()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
#define CRYPTOPP_BLOCK_6(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS5());} size_t SS6() {return SS5()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
#define CRYPTOPP_BLOCK_7(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS6());} size_t SS7() {return SS6()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
#define CRYPTOPP_BLOCK_8(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS7());} size_t SS8() {return SS7()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
#define CRYPTOPP_BLOCKS_END(i) size_t SST() {return SS##i();} void AllocateBlocks() {m_aggregate.New(SST());} AlignedSecByteBlock m_aggregate;
NAMESPACE_END
#if (CRYPTOPP_MSC_VERSION)
# pragma warning(pop)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic pop
#endif
#endif
| [
"daybreak7788@gmail.com"
] | daybreak7788@gmail.com |
4a379e4065af4c838d4e3505fbbe75b77dec7dae | 31da102cbdd447e8507aca9ece320452c4df8875 | /Cosmonaught.ino | 3133437515d1a30f6517d71f8fd179c5cebf9773 | [] | no_license | cutlasses/Cosmonaught | a4a57536c327aac65b3e1ef97dee87b78fca9bb1 | a6fccf2d40f6185561623fc61b2ff333a2d4519b | refs/heads/master | 2021-09-10T10:43:25.325044 | 2018-03-24T18:10:09 | 2018-03-24T18:10:09 | 125,648,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,842 | ino | #include <OctoWS2811.h>
#include "TapBPM.h"
const int LEDS_IN_STRIP = 18;
const int NUM_COLOURS = 5;
const int g_colours[NUM_COLOURS] = { 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFFFFFF };
DMAMEM int g_display_memory[ LEDS_IN_STRIP * 6 ];
int g_drawing_memory[ LEDS_IN_STRIP * 6 ];
const int LED_CONFIG = WS2811_GRB | WS2811_800kHz;
OctoWS2811 g_led_strip( LEDS_IN_STRIP, g_display_memory, g_drawing_memory, LED_CONFIG );
TAP_BPM g_tap_bpm( 23 ); // pin 23
void setup()
{
Serial.begin(9600);
#ifdef DEBUG_OUTPUT
serial_port_initialised = true;
#endif // DEBUG_OUTPUT
g_led_strip.begin();
g_led_strip.show();
g_tap_bpm.setup();
DEBUG_TEXT("SETUP\n");
}
void light_pixel( int pixel_index, int colour )
{
for( int i = 0; i < LEDS_IN_STRIP; ++i )
{
if( i == pixel_index )
{
g_led_strip.setPixel( i, colour );
}
else
{
g_led_strip.setPixel( i, 0 );
}
}
}
void clear_pixels()
{
for( int i = 0; i < LEDS_IN_STRIP; ++i )
{
g_led_strip.setPixel( i, 0 );
}
}
void loop()
{
static int pixel = 0;
static int colour = 0;
static int inc = 1;
static bool reset = true;
g_tap_bpm.update( millis() );
if( g_tap_bpm.valid_bpm() )
{
const int beat_duration_us = g_tap_bpm.beat_duration_ms() * 1000;
const int light_duration_us = beat_duration_us / LEDS_IN_STRIP;
reset = false;
pixel += inc;
if( pixel == 0 || pixel == LEDS_IN_STRIP - 1 )
{
inc *= -1; // invert direction
colour = (colour + 1) % NUM_COLOURS;
}
light_pixel( pixel, g_colours[colour] );
g_led_strip.show();
delayMicroseconds( light_duration_us );
}
else if( !reset )
{
// don't bother to clear pixels until the first beat (might conserve power this way)
reset = true;
clear_pixels();
g_led_strip.show();
}
}
| [
"spitkethly@gmail.com"
] | spitkethly@gmail.com |
c5c81eaba2b857d3ddb75c8d2c4611af66053f78 | 07ebeee5b2cdf13aac3fed34a2498d21156dba2c | /src/services/render/close-to-gl/raster/filter/NoTexture.cpp | 5002e44252d884d18bb57c7fef491e0c0d850242 | [] | no_license | marcelogm/close-to-gl | e91000b9291d478672a40a7d5f976598f3fd7b91 | ac54807c7a7942cf73a282b76798ab2ceb1bf766 | refs/heads/master | 2023-08-30T18:28:22.210482 | 2023-08-23T04:28:46 | 2023-08-23T04:28:46 | 395,832,964 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | cpp | #include "filter.h"
using namespace filter;
NoTexture::NoTexture() {
config = Config::getInstance();
}
bool NoTexture::matches() {
return *config->getTextureUse() == 0;
}
vec3 NoTexture::apply(data::Texture* texture, float x, float y, vec3 color, float deltaX, float deltaY) {
return vec3(
color.r * 255.0f,
color.g * 255.0f,
color.b * 255.0f
);
} | [
"marcelo-martins@defensoria.rs.def.br"
] | marcelo-martins@defensoria.rs.def.br |
bd31df395513c0b5729672713b6ad96c176ee907 | 34874bd874c9e3016c9f4af332294e4f605b0e35 | /lab_2/at-home/Kingdom.cpp | 3e5c260d7ae16f434446614b5c55ac3d52a9dab0 | [] | no_license | JelaniThompson/OOP244-1 | a8917156f1101663cb4b1258ab152e02090b345e | b4ac98db1038ec76daf67e2df381d96980588ec9 | refs/heads/master | 2020-03-09T14:49:52.857761 | 2018-04-06T17:17:56 | 2018-04-06T17:17:56 | 128,844,409 | 1 | 0 | null | 2018-04-09T23:11:51 | 2018-04-09T23:11:51 | null | UTF-8 | C++ | false | false | 1,391 | cpp | /***********************************************************
// OOP244 Workshop 2: Dynamic Memory
// File Kingdom.cpp
// Version 1.0
// Date 1/30/2018
// Author Lean Junio
// Description
// Kingdom Implementation File
//
//
// Revision History
///////////////////////////////////////////////////////////
// Name Date Reason
//
///////////////////////////////////////////////////////////
***********************************************************/
// TODO: include the necessary headers
#include <iostream>
#include "Kingdom.h"
using namespace std;
// TODO: the sict namespace
namespace sict
{
// TODO:definition for display(...)
void display(Kingdom &k)
{
cout << k.m_name << ", population " << k.m_population << endl;
}
void display(const Kingdom kArr[], int size)
{
int totalPopulation = 0;
for (int i = 0; i < size; i++)
{
totalPopulation += kArr[i].m_population;
}
cout << "------------------------------" << endl;
cout << "Kingdoms are" << endl;
cout << "------------------------------" << endl;
for (int i = 0; i < size; i++)
{
cout << i + 1 << ". " << kArr[i].m_name << ", population " << kArr[i].m_population << endl;
}
cout << "------------------------------" << endl;
cout << "Total population of all Kingdoms: " << totalPopulation << endl;
cout << "------------------------------" << endl;
}
}
| [
"ljjunio@matrix.senecac.on.ca"
] | ljjunio@matrix.senecac.on.ca |
3fab502fcac9ae96e9f39a0df6dd4cd3608c21e0 | cea4642a6f6182da6c3d46a0fdbd1c4f56854192 | /src/qt/clientmodel.h | 523dcb781d462890a9566e85ae5c74dd67372d79 | [
"MIT"
] | permissive | ticoincc/ticoin | 7dbef45af35cabd990094aa1f691b1bd5c448e36 | f3703e97d8dc88371a9e7931882d3e025624c840 | refs/heads/master | 2020-11-26T08:53:16.578939 | 2019-12-19T10:11:59 | 2019-12-19T10:11:59 | 229,021,095 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,065 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_CLIENTMODEL_H
#define BITCOIN_QT_CLIENTMODEL_H
#include <QObject>
class AddressTableModel;
class OptionsModel;
class PeerTableModel;
class TransactionTableModel;
class CWallet;
QT_BEGIN_NAMESPACE
class QDateTime;
class QTimer;
QT_END_NAMESPACE
enum BlockSource {
BLOCK_SOURCE_NONE,
BLOCK_SOURCE_REINDEX,
BLOCK_SOURCE_DISK,
BLOCK_SOURCE_NETWORK
};
enum NumConnections {
CONNECTIONS_NONE = 0,
CONNECTIONS_IN = (1U << 0),
CONNECTIONS_OUT = (1U << 1),
CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
};
/** Model for TICO network client. */
class ClientModel : public QObject
{
Q_OBJECT
public:
explicit ClientModel(OptionsModel* optionsModel, QObject* parent = 0);
~ClientModel();
OptionsModel* getOptionsModel();
PeerTableModel* getPeerTableModel();
//! Return number of connections, default is in- and outbound (total)
int getNumConnections(unsigned int flags = CONNECTIONS_ALL) const;
QString getMasternodeCountString() const;
int getNumBlocks() const;
int getNumBlocksAtStartup();
quint64 getTotalBytesRecv() const;
quint64 getTotalBytesSent() const;
double getVerificationProgress() const;
QDateTime getLastBlockDate() const;
//! Return true if core is doing initial block download
bool inInitialBlockDownload() const;
//! Return true if core is importing blocks
enum BlockSource getBlockSource() const;
//! Return warnings to be displayed in status bar
QString getStatusBarWarnings() const;
QString formatFullVersion() const;
QString formatBuildDate() const;
bool isReleaseVersion() const;
QString clientName() const;
QString formatClientStartupTime() const;
private:
OptionsModel* optionsModel;
PeerTableModel* peerTableModel;
int cachedNumBlocks;
QString cachedMasternodeCountString;
bool cachedReindexing;
bool cachedImporting;
int numBlocksAtStartup;
QTimer* pollTimer;
QTimer* pollMnTimer;
void subscribeToCoreSignals();
void unsubscribeFromCoreSignals();
signals:
void numConnectionsChanged(int count);
void numBlocksChanged(int count);
void strMasternodesChanged(const QString& strMasternodes);
void alertsChanged(const QString& warnings);
void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut);
//! Fired when a message should be reported to the user
void message(const QString& title, const QString& message, unsigned int style);
// Show progress dialog e.g. for verifychain
void showProgress(const QString& title, int nProgress);
public slots:
void updateTimer();
void updateMnTimer();
void updateNumConnections(int numConnections);
void updateAlert(const QString& hash, int status);
};
#endif // BITCOIN_QT_CLIENTMODEL_H
| [
"admin@ticoin.cc"
] | admin@ticoin.cc |
096b35423dbc53ce1f0d3f4516002b6f4de33758 | 0575637a79f4720aa8f6a3a7024735d8194dc447 | /include/CommonHeaders.h | 57c9dcd7fdf5bbb1358f2a46889686175f42f2b9 | [] | no_license | shashankmca80/WrterReaderThreads | 6b87fdaa7c52c00f805fe4212ad9ba5385484034 | 3d4d4d8e6e6d0326e0bfa3f774179fe123d84361 | refs/heads/master | 2020-03-14T16:28:02.155399 | 2018-05-01T11:03:42 | 2018-05-01T11:03:42 | 131,698,650 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 543 | h | #ifndef _COMMON_DEFS_H
#define _COMMON_DEFS_H
#include "iostream"
#include "string"
#include "vector"
#include "list"
#include "fstream"
#include "algorithm"
#include "queue"
#include "atomic"
#include "thread"
#include "mutex"
#include "shared_mutex"
#include "unordered_map"
#include "sstream"
#include "sys/stat.h"
#include "memory"
#define DISKSIZE 1000000
typedef std::unordered_map<std::string, std::string> MemCache;
typedef std::list<std::string> CachedItemsList;
typedef unsigned int C_UINT;
typedef long int C_LINT;
#endif
| [
"shashank.garg29@gmail.com"
] | shashank.garg29@gmail.com |
4b3e136bebd4b52cdafcd2743e1147dafe856d95 | 92e67b30497ffd29d3400e88aa553bbd12518fe9 | /assignment2/part6/Re=110/89.2/phi | c05ee69a88d6753d387c20cb3a5729442e2ba3f1 | [] | no_license | henryrossiter/OpenFOAM | 8b89de8feb4d4c7f9ad4894b2ef550508792ce5c | c54b80dbf0548b34760b4fdc0dc4fb2facfdf657 | refs/heads/master | 2022-11-18T10:05:15.963117 | 2020-06-28T15:24:54 | 2020-06-28T15:24:54 | 241,991,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,285 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "89.2";
object phi;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 3 -1 0 0 0 0];
internalField nonuniform List<scalar>
3880
(
-1.8206e-05
-0.000483779
0.000501985
-1.74951e-05
-0.00116863
0.00116792
1.28461e-05
-0.00157415
0.00154381
7.80411e-05
-0.00174086
0.00167567
0.00018314
-0.00169616
0.00159106
0.000334256
-0.00145878
0.00130767
0.00053813
-0.00104211
0.000838234
0.000800358
-0.000457098
0.00019487
0.00112302
0.000285301
-0.000607964
0.00117296
0.00150198
-0.00155192
-6.8698e-06
-0.000476909
1.67518e-05
-0.00119225
7.63701e-05
-0.00163377
0.000173825
-0.00183832
0.000311735
-0.00183407
0.000494796
-0.00164184
0.000729223
-0.00127654
0.00102105
-0.000748925
0.00137375
-6.73987e-05
0.000761368
0.00178535
8.6131e-06
-0.000485522
6.23588e-05
-0.001246
0.00016073
-0.00173214
0.000301299
-0.00197889
0.000483699
-0.00201647
0.000710537
-0.00186868
0.000986863
-0.00155286
0.0013186
-0.00108066
0.00171038
-0.000459173
0.000309287
0.00216246
2.74092e-05
-0.000512932
0.000117705
-0.00133629
0.00026287
-0.0018773
0.000455907
-0.00217192
0.000693184
-0.00225375
0.000974904
-0.0021504
0.00130455
-0.0018825
0.00168745
-0.00146357
0.00212884
-0.000900558
-0.000193012
0.00263114
4.90118e-05
-0.000561943
0.000180304
-0.00146758
0.000377832
-0.00207483
0.000629786
-0.00242388
0.000929264
-0.00255323
0.00127409
-0.00249523
0.00166612
-0.00227454
0.00210989
-0.00190734
0.00261069
-0.00140136
-0.000754766
0.00317244
7.23143e-05
-0.000634258
0.000246754
-0.00164202
0.000498806
-0.00232688
0.000811831
-0.0027369
0.00117586
-0.00291726
0.00158664
-0.00290601
0.00204472
-0.00273261
0.00255397
-0.00241659
0.0031196
-0.00196698
-0.00138107
0.0037459
9.60297e-05
-0.000730287
0.000312934
-0.00185893
0.000617491
-0.00263144
0.000988322
-0.00310773
0.00141269
-0.00334162
0.00188469
-0.00337801
0.00240404
-0.00325196
0.00297464
-0.0029872
0.00360206
-0.0025944
-0.00206893
0.00428992
0.00011873
-0.000849017
0.000374272
-0.00211447
0.000724695
-0.00298186
0.00114407
-0.00352711
0.00161719
-0.00381474
0.00213685
-0.00389768
0.00270242
-0.00381753
0.0033186
-0.00360337
0.00399297
-0.00326878
-0.00280466
0.0047287
0.000138923
-0.000987939
0.000426055
-0.0024016
0.000811087
-0.0033669
0.0012639
-0.00397992
0.00176716
-0.004318
0.00231259
-0.0044431
0.00289914
-0.00440408
0.00353248
-0.00423672
0.00422441
-0.0039607
-0.00356519
0.00498494
0.000155132
-0.00114307
0.000463747
-0.00271022
0.000867976
-0.00377112
0.00133422
-0.00444616
0.00184361
-0.0048274
0.00238708
-0.00498657
0.0029628
-0.00497979
0.00357572
-0.00484964
0.00424107
-0.00462605
0.00500144
-0.00432557
0.00267435
0.0125698
-0.0137422
0.00401279
0.0312145
-0.032553
0.00463304
0.0514191
-0.0520394
0.00457803
0.0702077
-0.0701527
0.00409092
0.0885398
-0.0880527
0.00331838
0.107812
-0.10704
0.00236266
0.129837
-0.128882
0.00125745
0.160083
-0.158978
0.000353461
0.206016
-0.205112
0.260887
-0.260534
0.00298435
0.0113708
0.00455753
0.0296414
0.00546038
0.0505163
0.0055975
0.0700706
0.00520353
0.0889338
0.00444036
0.108576
0.00342299
0.130855
0.00218859
0.161318
0.000940129
0.207265
0.261828
0.00332309
0.0102102
0.00507321
0.0278912
0.00626124
0.0493282
0.00660637
0.0697255
0.00631623
0.089224
0.00556645
0.109325
0.00448671
0.131935
0.00311505
0.162689
0.00153381
0.208846
0.263361
0.0036959
0.00914543
0.00554752
0.0260396
0.00701225
0.0478635
0.00758125
0.0691565
0.00740914
0.0893961
0.0066794
0.110055
0.00554077
0.133073
0.00403209
0.164198
0.00212088
0.210757
0.265482
0.00410441
0.00821346
0.0059742
0.0241698
0.00769241
0.0461453
0.00849947
0.0683494
0.00846241
0.0894331
0.00776355
0.110754
0.00657243
0.134264
0.00492994
0.16584
0.00269589
0.212991
0.268178
0.00453924
0.00742012
0.00635154
0.0223575
0.00828465
0.0442122
0.00933985
0.0672942
0.00945696
0.089316
0.00880271
0.111408
0.00756825
0.135499
0.00579786
0.167611
0.00325161
0.215537
0.27143
0.00497342
0.00673663
0.0066773
0.0206536
0.00877684
0.0421126
0.0100837
0.0659874
0.0103759
0.0890238
0.00978387
0.112
0.00851897
0.136764
0.00663007
0.1695
0.00378744
0.21838
0.275217
0.00535508
0.00611025
0.00694025
0.0190685
0.0091595
0.0398934
0.010715
0.0644319
0.0112001
0.0885387
0.0106866
0.112514
0.00940486
0.138045
0.00741047
0.171494
0.00429091
0.221499
0.279508
0.00560646
0.00548873
0.0071112
0.0175637
0.00941808
0.0375865
0.0112236
0.0626263
0.0119328
0.0878295
0.0115233
0.112923
0.0102422
0.139326
0.00815159
0.173585
0.00477187
0.224879
0.28428
0.00569438
0.00479579
0.00722634
0.0160318
0.00957807
0.0352348
0.01158
0.0606244
0.0125066
0.0869029
0.0122215
0.113208
0.010984
0.140564
0.00880096
0.175768
0.00523341
0.228447
0.289513
0.0182427
0.00889443
-0.0223414
0.0140609
0.0202136
0.0118971
0.0373986
0.0107975
0.0617241
0.00945666
0.0882437
0.00759225
0.115073
0.0051235
0.143033
0.00219623
0.178695
-6.09541e-05
0.230704
0.289452
0.0190659
0.0117346
-0.021906
0.0149976
0.0242819
0.0120301
0.040366
0.0104779
0.0632763
0.00907927
0.0896423
0.0072385
0.116914
0.00480475
0.145466
0.00200505
0.181495
-0.000120654
0.23283
0.289332
0.0186357
0.01317
-0.0200711
0.0154832
0.0274343
0.0123391
0.0435101
0.0102944
0.065321
0.00866432
0.0912724
0.00681967
0.118758
0.00448169
0.147804
0.00181438
0.184162
-0.000159118
0.234803
0.289173
0.0173175
0.0136843
-0.0178318
0.0151148
0.029637
0.0123588
0.0462661
0.0101672
0.0675126
0.00836437
0.0930752
0.00648613
0.120636
0.00422177
0.150069
0.0017169
0.186667
-0.000122102
0.236642
0.289051
0.015637
0.0135444
-0.015497
0.0142178
0.0310562
0.0119789
0.048505
0.00990739
0.0695841
0.00808926
0.0948934
0.00620503
0.122521
0.00399026
0.152284
0.00158627
0.189071
-0.000147061
0.238375
0.288904
0.0137674
0.0128508
-0.0130738
0.0130133
0.0318102
0.0112762
0.0502422
0.00945204
0.0714082
0.00775647
0.0965889
0.00595772
0.124319
0.00383539
0.154406
0.0015575
0.191349
-8.57882e-05
0.240019
0.288818
0.0118515
0.011647
-0.0106478
0.0117363
0.0319255
0.0105163
0.0514622
0.00894993
0.0729746
0.00738243
0.0981564
0.00567915
0.126023
0.00365275
0.156432
0.00145968
0.193542
-0.000105907
0.241584
0.288712
0.00990137
0.00996913
-0.00822348
0.0103135
0.0315134
0.00959513
0.0521806
0.00838936
0.0741803
0.00702478
0.099521
0.00545606
0.127591
0.00353858
0.15835
0.00147594
0.195605
-1.43042e-05
0.243075
0.288698
0.00836806
0.00764221
-0.00604114
0.00936605
0.0305154
0.00902591
0.0525207
0.00800547
0.0752008
0.006734
0.100792
0.00524476
0.129081
0.00340004
0.160194
0.00140195
0.197603
-3.1915e-05
0.244508
0.288666
0.00601459
-0.00337924
0.00786011
0.00830457
0.00771338
0.00663236
0.00519062
0.00343009
0.00147046
9.42548e-05
0.00485157
-0.0225157
-0.00467725
0.0044134
-0.0214678
0.00368537
-0.0193431
0.00288182
-0.0170282
0.00205683
-0.0146721
0.00122929
-0.0122462
0.000404363
-0.00982286
-0.000390605
-0.00742852
-0.00126701
-0.00516474
-0.00266874
0.00397427
-0.022348
-0.00414195
0.00330743
-0.020801
0.00246514
-0.0185008
0.00159327
-0.0161564
0.0007203
-0.0137991
-0.000140812
-0.0113851
-0.000988569
-0.0089751
-0.0018037
-0.00661338
-0.00264469
-0.00432375
-0.0020221
0.0029582
-0.0218955
-0.00341069
0.00209979
-0.0199426
0.00116847
-0.0175695
0.000241181
-0.0152291
-0.000661681
-0.0128962
-0.00153756
-0.0105092
-0.00238292
-0.00812975
-0.00318278
-0.00581352
-0.00395248
-0.00355405
-0.00146572
0.00180147
-0.0212127
-0.00248429
0.000805255
-0.0189463
-0.000185631
-0.0165786
-0.00114231
-0.0142724
-0.00205872
-0.0119798
-0.0029277
-0.00964024
-0.0037459
-0.00731155
-0.0044995
-0.00505991
-0.00517403
-0.00287953
-0.00101373
0.000520228
-0.0203434
-0.00138954
-0.000561129
-0.017865
-0.00157737
-0.0155624
-0.00254196
-0.0133078
-0.00344488
-0.0110769
-0.00428267
-0.00880245
-0.00504997
-0.00654425
-0.00573186
-0.00437803
-0.00629663
-0.00231476
-0.000668774
-0.000842194
-0.0193389
-0.000162294
-0.00196776
-0.0167394
-0.00298185
-0.0145483
-0.00392565
-0.012364
-0.00479138
-0.0102112
-0.00557586
-0.00801797
-0.00627221
-0.0058479
-0.0068643
-0.00378594
-0.00731436
-0.0018647
-0.000425877
-0.00224449
-0.0182178
0.00112335
-0.00337294
-0.015611
-0.00435952
-0.0135617
-0.00526032
-0.0114632
-0.00606921
-0.00940227
-0.00678302
-0.00730416
-0.00739459
-0.00523632
-0.00788754
-0.00329299
-0.00822631
-0.00152592
-0.000274719
-0.00363208
-0.0170285
0.00244285
-0.00473413
-0.0145089
-0.00567423
-0.0126216
-0.0065148
-0.0106227
-0.0072529
-0.00866416
-0.00788493
-0.00667213
-0.00840513
-0.00471612
-0.00879811
-0.00290002
-0.00903557
-0.00128846
-0.000201637
-0.00495893
-0.0158096
0.00373994
-0.00601326
-0.0134546
-0.00689411
-0.0117408
-0.00766306
-0.00985371
-0.00832283
-0.00800439
-0.00886872
-0.00612625
-0.00929807
-0.00428677
-0.00959748
-0.00260061
-0.00974812
-0.00113782
-0.000191277
-0.00618616
-0.0145939
0.00497048
-0.00717918
-0.0124615
-0.00799407
-0.0109259
-0.00868598
-0.0091618
-0.00926619
-0.00742418
-0.00972799
-0.00566445
-0.0100732
-0.00394154
-0.0102909
-0.00238292
-0.0103718
-0.0010569
-0.000227754
-0.0072843
-0.0134077
0.00609809
-0.00820884
-0.011537
-0.00895691
-0.0101778
-0.00957185
-0.00854686
-0.0100769
-0.00691908
-0.0104622
-0.0052792
-0.0107348
-0.00366892
-0.0108862
-0.00223151
-0.0109156
-0.00102757
-0.000295361
-0.00823832
-0.0122698
0.00710046
-0.0090902
-0.0106851
-0.00977479
-0.00949323
-0.0103172
-0.00800442
-0.0107558
-0.00648055
-0.0110759
-0.00495901
-0.0112905
-0.00345438
-0.0113929
-0.00212913
-0.0113886
-0.00103177
-0.000378941
-0.00903874
-0.0111926
0.0079615
-0.00981725
-0.00990661
-0.0104453
-0.00886516
-0.0109237
-0.00752608
-0.0113072
-0.00609696
-0.0115767
-0.00468953
-0.0117495
-0.00328164
-0.0118207
-0.00205791
-0.0118003
-0.00105218
-0.00046404
-0.00968496
-0.0101811
0.00867354
-0.0103917
-0.00919991
-0.0109723
-0.00828448
-0.0113978
-0.00710062
-0.0117397
-0.00575504
-0.0119744
-0.00445483
-0.0121222
-0.00313384
-0.0121799
-0.00200023
-0.0121596
-0.0010725
-0.00053693
-0.0101825
-0.00923278
0.00923409
-0.0108206
-0.00856178
-0.0113637
-0.0077414
-0.0117496
-0.00671468
-0.0120636
-0.00544103
-0.01228
-0.00423846
-0.0124194
-0.00299445
-0.0124803
-0.00193928
-0.0124752
-0.00107756
-0.000584543
-0.0105405
-0.00833568
0.00964336
-0.0111155
-0.00798669
-0.0116298
-0.00722718
-0.0119909
-0.00635359
-0.0122903
-0.00514158
-0.0125046
-0.00402421
-0.0126513
-0.00284771
-0.0127313
-0.00185928
-0.0127556
-0.00105324
-0.000594362
-0.0107692
-0.00746839
0.0099019
-0.0112908
-0.0074651
-0.0117822
-0.00673571
-0.0121339
-0.00600195
-0.0124314
-0.00484411
-0.012659
-0.0037966
-0.0128279
-0.00267879
-0.0129417
-0.00174548
-0.0130087
-0.000986247
-0.000554298
-0.0108718
-0.00660681
0.0100102
-0.0113573
-0.00697953
-0.0118304
-0.00626261
-0.012189
-0.00564341
-0.0124969
-0.00453616
-0.0127528
-0.00354078
-0.012958
-0.00247359
-0.0131195
-0.00158392
-0.0132419
-0.000863843
-0.000452534
-0.0108449
-0.00573787
0.00997595
-0.0113259
-0.00649855
-0.0117846
-0.00580389
-0.0121661
-0.00526185
-0.012497
-0.00420535
-0.0127949
-0.00324281
-0.0130498
-0.00221873
-0.0132723
-0.00136137
-0.0134625
-0.000673675
-0.000277322
-0.0107326
-0.00484488
0.00983957
-0.0112393
-0.00599178
-0.011672
-0.00537122
-0.0120788
-0.00485511
-0.0124417
-0.00384245
-0.012792
-0.00289242
-0.0131099
-0.00190091
-0.0134065
-0.00106472
-0.0136781
-0.00040207
-1.74997e-05
-0.0480628
-0.00470353
0.0479214
-0.0492097
-0.00484486
-0.0504554
-0.00412554
-0.0516954
-0.00361508
-0.0527306
-0.00280724
-0.0535358
-0.00208725
-0.0540824
-0.00135432
-0.0543901
-0.000757023
-0.0545054
-0.000286712
-2.14663e-05
-0.0570246
-0.00472395
0.057045
-0.0577356
-0.00413382
-0.0584334
-0.00342777
-0.0592092
-0.00283929
-0.0598507
-0.00216566
-0.0603525
-0.00158548
-0.0606844
-0.00102248
-0.0608599
-0.000581463
-0.0609176
-0.000229032
-2.63599e-05
-0.0681375
-0.00484491
0.0682585
-0.0684698
-0.00380155
-0.0688216
-0.00307598
-0.0692774
-0.0023835
-0.0696396
-0.00180342
-0.0699462
-0.00127888
-0.0701322
-0.000836467
-0.070232
-0.000481629
-0.0702533
-0.000207764
-2.91407e-05
-0.0818525
-0.00491723
0.0819248
-0.0820485
-0.0036055
-0.0822338
-0.00289065
-0.0825178
-0.00209954
-0.0827225
-0.00159866
-0.0829195
-0.00108196
-0.0830245
-0.000731468
-0.0830918
-0.000414317
-0.0830999
-0.000199653
-2.70894e-05
-0.0981273
-0.00477076
0.0979808
-0.0983564
-0.00337637
-0.0985385
-0.00270852
-0.0987721
-0.00186597
-0.0989296
-0.00144111
-0.0990908
-0.000920821
-0.0991753
-0.000646914
-0.0992473
-0.000342309
-0.0992675
-0.000179472
-1.40546e-05
-0.115892
-0.00431807
0.115439
-0.116266
-0.00300207
-0.116563
-0.00241159
-0.116829
-0.00159971
-0.117021
-0.00124949
-0.117191
-0.000750758
-0.117297
-0.000540612
-0.117394
-0.00024596
-0.117439
-0.000134037
6.84793e-06
-0.133184
-0.00354295
0.132409
-0.133747
-0.00243931
-0.134201
-0.00195708
-0.134535
-0.00126595
-0.134792
-0.000991869
-0.134983
-0.000560406
-0.135122
-0.000401576
-0.135228
-0.000139564
-0.135289
-7.31471e-05
2.62786e-05
-0.147788
-0.00250469
0.14675
-0.148517
-0.00171048
-0.149105
-0.00136867
-0.1495
-0.000871161
-0.149811
-0.000680944
-0.150008
-0.000363477
-0.150157
-0.000252545
-0.150242
-5.50001e-05
-0.150292
-2.27575e-05
3.20136e-05
-0.158081
-0.00129453
0.156871
-0.158916
-0.000875767
-0.159584
-0.000700277
-0.160015
-0.000440954
-0.160351
-0.000344568
-0.160538
-0.000176382
-0.160672
-0.000118717
-0.160715
-1.15604e-05
-0.160737
-1.5043e-06
2.15373e-05
-0.163336
0.162041
-0.164211
-0.164912
-0.165353
-0.165697
-0.165874
-0.165992
-0.166004
-0.166005
-0.0110228
0.0489237
0.0100205
-0.0117618
0.057784
-0.0123615
0.0688582
-0.0126812
0.0822444
-0.0125024
0.097802
-0.0115776
0.114514
-0.0097553
0.130586
-0.00706636
0.144061
-0.00371438
0.153519
0.158327
-0.0104658
0.0496911
0.00969848
-0.0111541
0.0584722
-0.0116833
0.0693874
-0.0119177
0.0824788
-0.0116673
0.0975515
-0.0107237
0.113571
-0.00897382
0.128836
-0.00646481
0.141552
-0.00338574
0.15044
0.154941
-0.00993167
0.0504011
0.00922161
-0.010554
0.0590946
-0.0110044
0.0698378
-0.0111632
0.0826377
-0.0108632
0.0972515
-0.00992793
0.112636
-0.00826887
0.127177
-0.00593671
0.13922
-0.00310274
0.147606
0.151838
-0.00930557
0.0510856
0.00862113
-0.00986617
0.0596552
-0.0102352
0.0702068
-0.0103212
0.0827237
-0.009981
0.0969113
-0.00906844
0.111723
-0.00751683
0.125626
-0.005378
0.137081
-0.00280472
0.145033
0.149034
-0.00857267
0.0517357
0.00792258
-0.00907378
0.0601563
-0.0093695
0.0705026
-0.00939464
0.0827488
-0.00903012
0.0965468
-0.00815778
0.110851
-0.00672969
0.124198
-0.00479752
0.135149
-0.00249617
0.142732
0.146537
-0.00775156
0.0523416
0.00714563
-0.00818692
0.0605917
-0.00841309
0.0707287
-0.00838822
0.0827239
-0.00801512
0.0961737
-0.00720088
0.110036
-0.00591263
0.122909
-0.0041999
0.133436
-0.00217985
0.140712
0.144358
-0.00685958
0.052895
0.0063062
-0.00722483
0.0609569
-0.00738321
0.0708871
-0.00731636
0.0826571
-0.00694738
0.0958047
-0.00620615
0.109295
-0.00507163
0.121775
-0.00358917
0.131954
-0.00185791
0.13898
0.1425
-0.00591107
0.0533857
0.00542034
-0.00620544
0.0612513
-0.00629885
0.0709805
-0.00619716
0.0825554
-0.00584251
0.0954501
-0.00518573
0.108638
-0.00421511
0.120804
-0.00297047
0.130709
-0.00153279
0.137543
0.140967
-0.00492208
0.0538026
0.00450517
-0.0051468
0.061476
-0.00517848
0.0710122
-0.00504863
0.0824255
-0.00471653
0.095118
-0.0041526
0.108075
-0.0033525
0.120004
-0.00234971
0.129706
-0.00120735
0.1364
0.139759
-0.00390998
0.0541339
0.00357869
-0.00406849
0.0616345
-0.00404065
0.0709844
-0.00388837
0.0822733
-0.00358476
0.0948144
-0.00311925
0.107609
-0.00249306
0.119378
-0.00173293
0.128946
-0.000884599
0.135552
0.138875
-0.00290215
0.0543727
0.00266337
-0.0029947
0.0617271
-0.00290843
0.0708981
-0.00273748
0.0821023
-0.00246516
0.094542
-0.00210033
0.107244
-0.00164785
0.118926
-0.00112736
0.128426
-0.000568165
0.134993
0.138307
-0.00191794
0.0545212
0.00176941
-0.00193966
0.0617488
-0.00180076
0.0707592
-0.00161153
0.0819131
-0.00137139
0.0943019
-0.00110534
0.106978
-0.000823123
0.118643
-0.000538015
0.12814
-0.000260394
0.134715
0.138046
-0.000987991
0.054594
0.000915211
-0.000928654
0.0616894
-0.000748536
0.0705791
-0.000540692
0.0817052
-0.000335246
0.0940965
-0.000165569
0.106808
-4.90136e-05
0.118527
1.12663e-05
0.12808
2.70698e-05
0.134699
0.138073
-0.000148758
0.0546392
0.000103499
-3.65391e-06
0.0615443
0.000230893
0.0703445
0.000475147
0.081461
0.000661869
0.0939097
0.000749789
0.106721
0.00071641
0.11856
0.000562561
0.128234
0.00031257
0.134949
0.138386
0.000689911
0.0545944
-0.000645104
0.00091762
0.0613166
0.00118639
0.0700758
0.00144288
0.0812045
0.00160304
0.0937496
0.0016077
0.106716
0.00142829
0.11874
0.00107121
0.128591
0.000577085
0.135443
0.138963
0.00144724
0.0544874
-0.00134018
0.00173954
0.0610243
0.00204796
0.0697673
0.00232443
0.080928
0.0024651
0.0936089
0.00239729
0.106784
0.00208534
0.119052
0.00154104
0.129135
0.000820667
0.136164
0.139784
0.00212048
0.0543473
-0.00198038
0.00247686
0.060668
0.00282014
0.069424
0.0031171
0.0806311
0.00324451
0.0934815
0.00311538
0.106913
0.00268541
0.119482
0.00197077
0.12985
0.00104271
0.137092
0.140826
0.00271811
0.0542039
-0.00257476
0.00312795
0.0602581
0.00349941
0.0690526
0.00381275
0.0803177
0.00392946
0.0933648
0.00374815
0.107094
0.00321514
0.120015
0.00234993
0.130715
0.0012374
0.138204
0.142064
0.00325404
0.0540885
-0.00313864
0.00370066
0.0598115
0.00409953
0.0686537
0.00443
0.0799873
0.00454289
0.0932519
0.0043197
0.107317
0.00369566
0.120639
0.00269343
0.131717
0.00141244
0.139485
0.143476
0.00365499
0.0540983
-0.00366476
0.00409783
0.0593687
0.00452185
0.0682297
0.00486069
0.0796484
0.00497012
0.0931425
0.0047201
0.107567
0.00403468
0.121324
0.00293591
0.132816
0.00153295
0.140888
0.145009
-0.0354863
0.0499118
0.0396727
-0.0322604
0.0561428
-0.0301176
0.0660869
-0.0278385
0.0773693
-0.0250795
0.0903835
-0.0215359
0.104024
-0.0170994
0.116888
-0.0118702
0.127587
-0.00607448
0.135093
0.138935
-0.0435451
0.0462463
0.0472106
-0.0405637
0.0531614
-0.0378482
0.0633714
-0.0347292
0.0742504
-0.0310755
0.0867297
-0.0265036
0.0994519
-0.0209363
0.11132
-0.0144951
0.121146
-0.00743606
0.128034
0.131499
-0.0526158
0.0427689
0.0560932
-0.0495619
0.0501076
-0.0462076
0.0600171
-0.0422368
0.0702795
-0.0375171
0.08201
-0.0316873
0.0936221
-0.0248081
0.104441
-0.0170369
0.113375
-0.00863529
0.119632
0.122863
-0.0635086
0.0394417
0.0668358
-0.0599733
0.0465722
-0.0558115
0.0558553
-0.0508714
0.0653394
-0.0449234
0.076062
-0.0376657
0.0863644
-0.0293031
0.0960786
-0.0200431
0.104115
-0.0102105
0.109799
0.112653
-0.0756869
0.0355696
0.079559
-0.0713345
0.0422198
-0.0661087
0.0506295
-0.059819
0.0590497
-0.0522291
0.0684721
-0.0432253
0.0773606
-0.0331731
0.0860264
-0.0223138
0.0932552
-0.0110732
0.0985588
0.10158
-0.0896277
0.0316856
0.0935117
-0.08417
0.0367621
-0.0776904
0.0441499
-0.069849
0.0512083
-0.0605411
0.0591642
-0.0498398
0.0666593
-0.0380634
0.07425
-0.0255174
0.0807092
-0.0129012
0.0859426
0.0886785
-0.102898
0.0259496
0.108634
-0.0962523
0.0301162
-0.0882441
0.0361417
-0.0783895
0.0413537
-0.0670058
0.0477805
-0.054118
0.0537715
-0.0400873
0.0602193
-0.0254252
0.0660471
-0.0113445
0.0718619
0.077334
-0.116944
0.0203475
0.122546
-0.109192
0.0223646
-0.0998585
0.0268081
-0.0887099
0.030205
-0.0761069
0.0351774
-0.0618804
0.0395451
-0.0465433
0.0448822
-0.0306252
0.0501289
-0.0161598
0.0573965
0.0611742
-0.131279
0.00990654
0.14172
-0.12019
0.0112761
-0.107079
0.0136963
-0.0923875
0.0155139
-0.0755705
0.0183605
-0.0569587
0.0209333
-0.0364947
0.0244182
-0.0151146
0.0287488
0.00464079
0.0376411
0.065815
-0.236403
0.24631
-0.225127
-0.211431
-0.195917
-0.177556
-0.156623
-0.132205
-0.103456
-0.065815
0.00198623
0.0410692
-0.00338269
0.000733081
0.0484637
-0.000241283
0.0570675
-0.0008866
0.0674811
-0.00128028
0.0799527
-0.00142508
0.0936565
-0.00120134
0.10841
-0.000896499
0.122241
-0.00165689
0.14248
0.244653
0.00232036
0.0424204
-0.0036716
0.00109563
0.0496885
0.000118067
0.0580451
-0.000565793
0.068165
-0.000998096
0.080385
-0.00117467
0.0938331
-0.00102604
0.108262
-0.00077452
0.121989
-0.00145917
0.143165
0.243194
0.00272226
0.0436708
-0.00397265
0.00153703
0.0508737
0.000594464
0.0589877
-0.000134956
0.0688944
-0.000573304
0.0808234
-0.000791482
0.0940513
-0.000704276
0.108175
-0.000560689
0.121846
-0.00125948
0.143864
0.241934
0.00312713
0.044821
-0.00427731
0.00198825
0.0520126
0.00107769
0.0598982
0.000365285
0.0696068
-9.76783e-05
0.0812863
-0.000355894
0.0943095
-0.000307882
0.108127
-0.00029699
0.121835
-0.00100338
0.14457
0.240931
0.00352634
0.0458672
-0.00457252
0.00245207
0.0530869
0.00158289
0.0607674
0.000903904
0.0702858
0.00044296
0.0817473
0.000129407
0.0946231
0.000136889
0.108119
-7.18008e-06
0.121979
-0.00070195
0.145265
0.240229
0.00393251
0.0467828
-0.00484811
0.00294449
0.0540749
0.00212493
0.061587
0.00148137
0.0709293
0.00102906
0.0821996
0.000717768
0.0949344
0.000615851
0.108221
0.000426819
0.122168
-0.000359504
0.146051
0.239869
0.00434489
0.0475351
-0.00509719
0.00346367
0.0549561
0.00270333
0.0623473
0.0021007
0.071532
0.00165897
0.0826413
0.00133351
0.0952598
0.00114978
0.108405
0.000867991
0.12245
2.64816e-05
0.146893
0.239896
0.00475847
0.0480903
-0.00531372
0.00400055
0.055714
0.00330945
0.0630384
0.00275416
0.0720873
0.00232712
0.0830683
0.00198609
0.0956009
0.00172472
0.108666
0.00134081
0.122834
0.000397566
0.147836
0.240293
0.00516441
0.0484168
-0.00549087
0.00454473
0.0563337
0.003933
0.0636501
0.00343146
0.0725888
0.00302514
0.0834746
0.00266916
0.0959568
0.00233228
0.109003
0.00184416
0.123322
0.000808883
0.148871
0.241102
0.00555061
0.0484873
-0.00562112
0.00508452
0.0567998
0.00456309
0.0641715
0.00412161
0.0730303
0.00374307
0.0838532
0.00337295
0.0963269
0.00296421
0.109412
0.00237205
0.123914
0.00124102
0.150002
0.242343
0.00589982
0.0482821
-0.00569461
0.00560315
0.0570965
0.00518467
0.06459
0.00480877
0.0734062
0.00446414
0.0841978
0.00408362
0.0967075
0.00360851
0.109887
0.0029148
0.124608
0.00168481
0.151232
0.244028
0.00620445
0.0477916
-0.00571398
0.00609354
0.0572074
0.00578968
0.0648939
0.00548558
0.0737103
0.0051807
0.0845027
0.00479536
0.0970928
0.00425975
0.110422
0.00346826
0.125399
0.00213716
0.152563
0.246165
0.00644773
0.0470205
-0.00567665
0.00653798
0.0571171
0.00635871
0.0650732
0.00613328
0.0739357
0.00587455
0.0847614
0.00549234
0.097475
0.00490418
0.111011
0.00402189
0.126282
0.00259091
0.153994
0.248756
0.00661899
0.0459892
-0.00558768
0.00692213
0.056814
0.00687655
0.0651187
0.0067366
0.0740757
0.00653096
0.0849671
0.00616123
0.0978448
0.00553041
0.111641
0.00456705
0.127245
0.00303969
0.155522
0.251796
0.0067112
0.0447351
-0.00545712
0.00723373
0.0562915
0.00732927
0.0650232
0.00728102
0.0741239
0.00713593
0.0851122
0.00678887
0.0981918
0.00612744
0.112303
0.00509531
0.128277
0.00347745
0.15714
0.255273
0.00672307
0.0433122
-0.00530016
0.00746354
0.055551
0.00770477
0.064782
0.00775336
0.0740753
0.00767652
0.085189
0.00736227
0.0985061
0.00668408
0.112981
0.00559807
0.129363
0.00389608
0.158842
0.259169
0.0066619
0.0417851
-0.00513477
0.00760637
0.0546065
0.00799341
0.0643949
0.00814301
0.0739257
0.00814136
0.0851907
0.00787127
0.0987762
0.00719224
0.11366
0.00606963
0.130486
0.004291
0.16062
0.26346
0.00654239
0.0402156
-0.00497285
0.00766082
0.0534881
0.00818964
0.0638661
0.00844036
0.073675
0.00851707
0.0851139
0.00830042
0.0989928
0.00763616
0.114324
0.00649807
0.131624
0.0046493
0.162469
0.26811
0.00636205
0.0386433
-0.00478978
0.00762209
0.052228
0.00829687
0.0631913
0.00865294
0.0733189
0.00881408
0.0849528
0.00866235
0.0991445
0.00802708
0.11496
0.00689247
0.132758
0.0049764
0.164385
0.273086
0.00609458
0.0370117
-0.00446295
0.00742163
0.050901
0.00823592
0.062377
0.00869263
0.0728622
0.0089432
0.0847022
0.00886646
0.0992213
0.00829302
0.115533
0.00718341
0.133868
0.00526815
0.1663
0.278354
-0.0163197
0.0370873
0.0162441
-0.0146193
0.0492006
-0.0121401
0.0598978
-0.0092649
0.0699871
-0.00627012
0.0817075
-0.00305737
0.0960085
0.000246059
0.11223
0.0026661
0.131448
0.00193851
0.167028
0.280293
-0.0290915
0.0358343
0.0303446
-0.0265092
0.0466183
-0.0227888
0.0561774
-0.0185249
0.0657232
-0.0140108
0.0771933
-0.00910448
0.0911022
-0.00406497
0.10719
-0.000116652
0.1275
0.000664619
0.166247
0.280957
-0.0430712
0.0337198
0.0451857
-0.0393519
0.042899
-0.0342508
0.0510762
-0.0286097
0.0600822
-0.0225548
0.0711384
-0.015825
0.0843724
-0.00879829
0.100163
-0.0028904
0.121592
-0.000561783
0.163918
0.280395
-0.0582519
0.0307024
0.0612693
-0.0531207
0.0377677
-0.0468312
0.0447867
-0.0399334
0.0531844
-0.032214
0.0634191
-0.0234776
0.075636
-0.0143449
0.0910306
-0.00640872
0.113656
-0.00216929
0.159679
0.278226
-0.0748255
0.0262929
0.079235
-0.0684697
0.031412
-0.0613581
0.0376751
-0.0531174
0.0449437
-0.043577
0.0538786
-0.0328014
0.0648604
-0.0215317
0.0797609
-0.0113304
0.103454
-0.00452201
0.15287
0.273704
-0.0934265
0.0212844
0.098435
-0.0862161
0.0242015
-0.0781674
0.0296264
-0.0683896
0.0351659
-0.0571538
0.0426428
-0.0445175
0.0522241
-0.0313508
0.0665943
-0.0188417
0.0909452
-0.00883108
0.14286
0.264873
-0.11499
0.014641
0.121633
-0.107328
0.0165401
-0.0985409
0.0208392
-0.0878995
0.0245246
-0.0759133
0.0306566
-0.0622297
0.0385405
-0.0476553
0.0520199
-0.0327092
0.0759991
-0.017799
0.127949
0.247074
-0.145729
0.00777287
0.152597
-0.137654
0.00846538
-0.128199
0.0113837
-0.117242
0.013568
-0.104817
0.0182313
-0.0907485
0.0244721
-0.0752675
0.0365389
-0.0581238
0.0588553
-0.0359592
0.105785
0.211115
-0.203221
0.00190643
0.209087
-0.197111
0.00235587
-0.189362
0.0036339
-0.180806
0.00501251
-0.170338
0.00776299
-0.157894
0.012028
-0.141501
0.0201465
-0.117583
0.0349368
-0.0762967
0.0644986
0.134818
-0.285193
0.2871
-0.282838
-0.279204
-0.274191
-0.266428
-0.2544
-0.234254
-0.199317
-0.134818
0.00208581
0.0170399
-0.00288165
0.000597684
0.0318327
-0.000955828
0.0467392
-0.0023541
0.0626675
-0.00349026
0.0803711
-0.00443798
0.0993827
-0.00507375
0.122269
-0.00556764
0.153091
-0.00473046
0.20825
0.282369
0.00182102
0.0175102
-0.00229128
0.000625829
0.0330279
-0.000783751
0.0481488
-0.00212446
0.0640082
-0.0032503
0.081497
-0.00418513
0.100318
-0.00483112
0.122915
-0.00534253
0.153602
-0.00428881
0.207197
0.278081
0.0016513
0.0177289
-0.00187002
0.000737724
0.0339414
-0.000495657
0.0493822
-0.00172399
0.0652366
-0.00279548
0.0825685
-0.00370044
0.101222
-0.00437052
0.123585
-0.00484968
0.154082
-0.00392341
0.20627
0.274157
0.0015634
0.0177351
-0.00156961
0.000917544
0.0345873
-0.000140654
0.0504404
-0.00123646
0.0663324
-0.00223308
0.0835651
-0.0031126
0.102102
-0.00379724
0.124269
-0.00428564
0.15457
-0.00350552
0.20549
0.270652
0.00155147
0.0175409
-0.00135729
0.00117457
0.0349642
0.000326552
0.0512884
-0.000665122
0.0673241
-0.00158491
0.0844849
-0.00243767
0.102955
-0.00314023
0.124972
-0.00365729
0.155087
-0.00304162
0.204874
0.26761
0.00161077
0.0171479
-0.00121777
0.00151123
0.0350637
0.000884148
0.0519155
-2.28109e-05
0.068231
-0.000839198
0.0853013
-0.00167263
0.103788
-0.00239804
0.125697
-0.00296386
0.155653
-0.00253903
0.20445
0.265071
0.00173421
0.0165576
-0.00114384
0.00192087
0.0348771
0.00152268
0.0523137
0.000801195
0.0689525
2.45151e-06
0.0861
-0.000822943
0.104614
-0.00156671
0.126441
-0.00220927
0.156295
-0.00200421
0.204245
0.263067
0.00191234
0.0157779
-0.00113265
0.00239251
0.0343969
0.00223215
0.052474
0.00166788
0.0695168
0.000939732
0.0868281
8.78432e-05
0.105465
-0.000645338
0.127174
-0.00140525
0.157055
-0.00144184
0.204281
0.261625
0.00213472
0.0148282
-0.001185
0.00291125
0.0336204
0.00299832
0.052387
0.0025958
0.0699193
0.00194348
0.0874805
0.00114945
0.10626
0.000336553
0.127987
-0.00057115
0.157963
-0.000854062
0.204564
0.260771
0.00239151
-0.00130553
0.00345892
0.00380651
0.00357311
0.00300083
0.0022205
0.00132605
0.000311087
-0.000236902
0.000166579
-0.00130965
0.000483784
-0.00302743
0.000887827
-0.00417517
0.00134307
-0.00490141
0.00183041
-0.00531473
0.0023411
-0.00549726
0.00287319
-0.00551188
0.00343013
-0.00540657
0.00402257
-0.00521849
-0.00498025
0.000169084
-0.00147873
0.000479076
-0.00333742
0.000862208
-0.0045583
0.00128212
-0.00532132
0.00172069
-0.00575331
0.00217095
-0.00594753
0.00263269
-0.00597362
0.00311004
-0.00588392
0.00361024
-0.00571868
-0.00551196
0.000163603
-0.00164234
0.000449966
-0.00362378
0.000790304
-0.00489864
0.00114961
-0.00568062
0.00151237
-0.00611607
0.00187462
-0.00630978
0.00223906
-0.00633806
0.0026119
-0.00625676
0.00300045
-0.00610723
-0.0059222
0.000149382
-0.00179172
0.00039529
-0.00386969
0.000671538
-0.00517488
0.000946809
-0.00595589
0.00120965
-0.00637891
0.00146001
-0.00656014
0.00170389
-0.00658194
0.00194999
-0.00650285
0.0022074
-0.00636465
-0.00619909
0.000126123
-0.00191784
0.000315346
-0.00405891
0.000508202
-0.00536774
0.000679456
-0.00612715
0.000822993
-0.00652245
0.000943097
-0.00668024
0.00104903
-0.00668787
0.00115163
-0.00660545
0.00126125
-0.00647427
-0.00632738
9.4037e-05
-0.00201188
0.000211919
-0.00417679
0.000305263
-0.00546108
0.000357158
-0.00617904
0.000367723
-0.00653301
0.000345633
-0.00665815
0.000302932
-0.00664517
0.000252129
-0.00655465
0.000204065
-0.00642621
-0.00628561
5.38749e-05
-0.00206575
8.81569e-05
-0.00421108
6.99262e-05
-0.00544285
-7.62353e-06
-0.00610149
-0.000137624
-0.00640301
-0.00030738
-0.0064884
-0.000502784
-0.00644977
-0.000710947
-0.00634649
-0.000921356
-0.0062158
-0.00608361
6.63071e-06
-0.00207239
-5.15587e-05
-0.00415289
-0.000188956
-0.00530546
-0.000400605
-0.00588984
-0.000673021
-0.0061306
-0.000990127
-0.00617129
-0.00133674
-0.00610316
-0.0017003
-0.00598292
-0.0020712
-0.00584491
-0.00571196
-4.5717e-05
-0.00202667
-0.000202186
-0.00399642
-0.000461627
-0.00504602
-0.000806965
-0.0055445
-0.00121845
-0.00571911
-0.00167753
-0.00571221
-0.00216881
-0.00561187
-0.00268082
-0.00547092
-0.00320578
-0.00531995
-0.00517779
-0.000101377
-0.00192529
-0.000358016
-0.00373978
-0.000738044
-0.00466599
-0.00121215
-0.0050704
-0.00175506
-0.0051762
-0.00234661
-0.00512066
-0.00297189
-0.0049866
-0.00362085
-0.00482196
-0.00428761
-0.00465318
-0.00449492
-0.000149296
-0.00177599
-0.000500751
-0.00338832
-0.000995373
-0.00417137
-0.00159049
-0.00447528
-0.00225545
-0.00451124
-0.00296879
-0.00440732
-0.00371627
-0.00423911
-0.00448926
-0.00404897
-0.00528335
-0.00385909
-0.00368018
-0.000203276
-0.00157272
-0.000647822
-0.00294378
-0.00124922
-0.00356996
-0.00195343
-0.00377107
-0.00272588
-0.00373879
-0.00354483
-0.00358837
-0.00439714
-0.0033868
-0.00527552
-0.0031706
-0.00617664
-0.00295797
-0.00275636
-0.000254155
-0.00131856
-0.000784326
-0.00241361
-0.00148149
-0.0028728
-0.00228131
-0.00297125
-0.00314625
-0.00287385
-0.0040548
-0.00267982
-0.00499508
-0.00244653
-0.00596096
-0.00220472
-0.00694978
-0.00196914
-0.00174465
-0.000300185
-0.00101838
-0.000906141
-0.00180765
-0.00168605
-0.00209289
-0.00256658
-0.00209072
-0.00350802
-0.00193241
-0.00448953
-0.00169832
-0.00550058
-0.00143548
-0.00653612
-0.00116917
-0.00759391
-0.000911356
-0.000665021
-0.000339872
-0.000678507
-0.00100996
-0.00113757
-0.00185824
-0.0012446
-0.00280374
-0.00114522
-0.00380524
-0.000930905
-0.00484286
-0.000660698
-0.00590756
-0.000370783
-0.00699545
-8.12805e-05
-0.00810463
0.000197826
0.000464437
-0.000372066
-0.00030644
-0.00109336
-0.000416273
-0.0019949
-0.000343062
-0.00298935
-0.000150772
-0.00403445
0.00011419
-0.00511138
0.000416235
-0.00621276
0.000730595
-0.00733612
0.00104209
-0.00848026
0.00134196
0.00162754
-0.000395987
8.95471e-05
-0.00115486
0.000342599
-0.00209435
0.000596425
-0.00312201
0.000876896
-0.00419467
0.00118685
-0.00529442
0.00151599
-0.00641551
0.00185168
-0.00755735
0.00218392
-0.00872024
0.00250485
0.0028092
-0.000411228
0.000500775
-0.00119383
0.0011252
-0.00215633
0.00155893
-0.00320238
0.00192294
-0.0042877
0.00227217
-0.00539471
0.002623
-0.00651871
0.00297568
-0.00766104
0.00332625
-0.00882496
0.00366876
0.00399444
-0.00041771
0.000918485
-0.00121041
0.0019179
-0.00218184
0.00253036
-0.00323305
0.00297416
-0.0043185
0.00335761
-0.00541994
0.00372443
-0.00653229
0.00408803
-0.00765721
0.00445118
-0.00880101
0.00481256
0.00516937
-0.000415618
0.0013341
-0.00120524
0.00270752
-0.00217264
0.00349777
-0.00321805
0.00401956
-0.00429523
0.0044348
-0.00538539
0.00481459
-0.00648251
0.00518516
-0.0075859
0.00555457
-0.00870008
0.00592674
0.00630886
-0.000406257
0.00174036
-0.00118036
0.00348162
-0.00213122
0.00444863
-0.00316078
0.00504912
-0.00422419
0.00549821
-0.00530577
0.00589617
-0.00640605
0.00628544
-0.00753713
0.00668564
-0.00872552
0.00711514
0.00760382
-0.000386074
0.00212643
-0.00113102
0.00422657
-0.0020532
0.00537081
-0.00305739
0.00605331
-0.00409984
0.00654066
-0.00516594
0.00696227
-0.00625637
0.00737586
-0.00737791
0.00780718
-0.00853306
0.00827029
0.00876923
-0.000357896
0.00248433
-0.00106138
0.00493005
-0.00194229
0.00625173
-0.00290902
0.00702003
-0.00391747
0.00754911
-0.00495074
0.00799554
-0.00600465
0.00842978
-0.007077
0.00887953
-0.00815788
0.00935117
0.00983297
-0.000322423
0.00280675
-0.000972688
0.00558032
-0.00179964
0.00707868
-0.00271584
0.00793623
-0.00367574
0.00850901
-0.00465841
0.00897821
-0.00565407
0.00942544
-0.00665471
0.00988016
-0.00764851
0.010345
0.0108056
-0.000280573
0.00308733
-0.000866765
0.00616651
-0.00162751
0.00783942
-0.00248039
0.00878912
-0.00337811
0.00940673
-0.00429544
0.00989554
-0.00521824
0.0103482
-0.00613606
0.010798
-0.00703937
0.0112483
0.0116888
-0.000233469
0.0033208
-0.00074603
0.00667907
-0.00142936
0.00852275
-0.00220725
0.00956701
-0.00303107
0.0102305
-0.00387188
0.0107364
-0.00471243
0.0111888
-0.00554168
0.0116272
-0.00635296
0.0120596
0.0124815
-0.0001824
0.0035032
-0.000613428
0.0071101
-0.00120964
0.00911896
-0.00190251
0.0102599
-0.00264296
0.010971
-0.00339915
0.0114925
-0.00415158
0.0119412
-0.00488904
0.0123647
-0.00560674
0.0127773
0.0131809
-0.000128755
0.00363195
-0.000472296
0.00745364
-0.000973534
0.0096202
-0.0015732
0.0108595
-0.00222303
0.0116208
-0.00288906
0.0121586
-0.00354992
0.0126021
-0.00419394
0.0130087
-0.00481686
0.0134002
0.0137844
-7.39189e-05
0.00370587
-0.000326152
0.00770587
-0.000726652
0.0100207
-0.00122691
0.0113598
-0.00178085
0.0121748
-0.00235323
0.012731
-0.00292094
0.0131698
-0.00347122
0.013559
-0.00399917
0.0139281
0.0142904
-1.92055e-05
0.00372508
-0.000178382
0.00786505
-0.00047465
0.010317
-0.000871315
0.0117565
-0.00132595
0.0126294
-0.00180288
0.0132079
-0.00227737
0.0136443
-0.00273506
0.0140167
-0.00316948
0.0143625
0.0146996
1.58921e-05
0.00370918
-5.96529e-05
0.00794059
-0.000252796
0.0105101
-0.000542552
0.0120462
-0.000893378
0.0129802
-0.00127084
0.0135854
-0.00164923
0.0140227
-0.00201243
0.0143799
-0.00235203
0.0147021
0.015011
6.12553e-05
0.00364793
7.2736e-05
0.00792911
-1.54189e-05
0.0105983
-0.000198964
0.0122298
-0.000447566
0.0132288
-0.000728803
0.0138666
-0.00101627
0.0143101
-0.00129193
0.0146556
-0.00154524
0.0149554
0.0152351
0.000102119
0.00354581
0.000196255
0.00783498
0.00020938
0.0105851
0.00013198
0.0123072
-1.49565e-05
0.0133758
-0.00020169
0.0140533
-0.000401426
0.0145099
-0.000594498
0.0148486
-0.000767625
0.0151286
0.0153827
0.000137849
0.00340796
0.000308505
0.00766432
0.000418854
0.0104748
0.000444302
0.0122817
0.000396931
0.0134231
0.000302539
0.0141477
0.000187088
0.0146253
7.09549e-05
0.0149648
-3.18239e-05
0.0152314
0.0154544
0.000167859
0.0032401
0.000407353
0.00742483
0.000608655
0.0102735
0.00073277
0.0121576
0.000781991
0.0133739
0.000777009
0.0141527
0.000742328
0.01466
0.000699207
0.0150079
0.000663609
0.0152669
0.0154729
0.000191867
0.00304823
0.000491397
0.0071253
0.000775801
0.00998908
0.000992798
0.0119406
0.00113449
0.0132322
0.00121559
0.0140716
0.00125821
0.0146174
0.00128332
0.0149828
0.00130674
0.0152435
0.0154394
0.000209853
0.00283838
0.000559854
0.00677529
0.000918157
0.00963078
0.00122078
0.011638
0.00144968
0.0130033
0.00161294
0.0139083
0.00172964
0.0145007
0.00182029
0.0148921
0.00190063
0.0151632
0.0153597
0.000222023
0.00261636
0.000612541
0.00638478
0.00103449
0.00920884
0.00141411
0.0112584
0.00172366
0.0126938
0.00196426
0.0136677
0.00215169
0.0143132
0.00230663
0.0147372
0.0024461
0.0150237
0.015231
0.000228773
0.00238758
0.000649848
0.0059637
0.00112449
0.0087342
0.0015713
0.0108116
0.00195344
0.0123116
0.00226494
0.0133562
0.00251814
0.01406
0.00273553
0.0145198
0.0029424
0.0148169
0.0150348
0.000230651
0.00215693
0.000672696
0.00552166
0.00118883
0.00821806
0.00169211
0.0103083
0.0021372
0.0118665
0.00251042
0.012983
0.00281965
0.0137508
0.00308838
0.0142511
0.00335924
0.014546
0.0147293
0.000227909
0.00192902
0.00068315
0.00506642
0.00123186
0.00766935
0.0017831
0.00975703
0.00228287
0.0113668
0.00270632
0.0125596
0.00304703
0.0134101
0.003301
0.0139971
0.00343921
0.0144078
0.0147858
0.00022481
0.00170421
0.000686051
0.00460518
0.00125619
0.00709921
0.00184305
0.00917016
0.00238591
0.0108239
0.00285
0.0120955
0.00321812
0.013042
0.00347963
0.0137356
0.00362372
0.0142637
0.0147379
0.000218384
0.00148583
0.000678645
0.00414491
0.00126137
0.00651649
0.00187555
0.00855599
0.00245623
0.0102432
0.00296189
0.0115898
0.00336936
0.0126345
0.00366798
0.013437
0.00385874
0.0140729
0.014624
0.000209496
0.00127633
0.000663003
0.00369141
0.00125064
0.00592885
0.00188478
0.00792185
0.00249878
0.00962924
0.00304665
0.0110419
0.00350096
0.0121802
0.00385006
0.0130879
0.00409884
0.0138242
0.0144455
0.000198897
0.00107744
0.000640988
0.00324932
0.00122688
0.00534296
0.00187412
0.0072746
0.0025165
0.00898686
0.00310536
0.0104531
0.00360978
0.0116758
0.00401606
0.0126816
0.00432866
0.0135116
0.0142017
0.000187208
0.00089023
0.000614216
0.00282231
0.00119258
0.00476459
0.0018464
0.00662079
0.00251168
0.00832158
0.00313867
0.00982608
0.0036937
0.0111208
0.00416009
0.0122152
0.00453887
0.0131328
0.0138924
0.000174934
0.000715296
0.000584067
0.00241317
0.00114994
0.00419872
0.0018041
0.00596663
0.00248624
0.00763943
0.00314695
0.00916537
0.00375052
0.0105172
0.00427685
0.0116889
0.00472209
0.0126875
0.0135173
0.000162472
0.000552824
0.000551706
0.00202394
0.00110089
0.00364954
0.00174947
0.00531805
0.00244196
0.00694695
0.0031305
0.00847682
0.00377824
0.00986945
0.0043618
0.0111053
0.0048722
0.0121771
0.0130758
0.00015012
0.000402704
0.000518107
0.00165595
0.00104714
0.00312051
0.00168465
0.00468054
0.00238066
0.00625094
0.00308996
0.00776752
0.00377551
0.0091839
0.00441128
0.0104695
0.00498362
0.0116048
0.0125686
0.000138073
0.000264631
0.000484072
0.00130995
0.000990282
0.0026143
0.0016118
0.00405902
0.00230451
0.00555823
0.00302669
0.00704534
0.00374207
0.00846852
0.00442287
0.00978875
0.00505147
0.0109762
0.0119989
0.000123953
0.000140679
0.000444404
0.000989503
0.000922754
0.00213595
0.0015217
0.00346007
0.00220332
0.00487662
0.00292999
0.00631867
0.00366709
0.00773141
0.00438592
0.00906993
0.00506565
0.0102965
0.01137
0.00011322
2.74585e-05
0.000411422
0.000691301
0.000863264
0.0016841
0.00143806
0.00288527
0.00210367
0.00421101
0.00282681
0.00559553
0.00357516
0.00698306
0.00431998
0.00832511
0.00503819
0.00957825
0.0106942
0.000103388
-7.59293e-05
0.00037995
0.000414739
0.000804602
0.00125945
0.00135257
0.00233731
0.0019971
0.00356648
0.00270931
0.00488332
0.00345956
0.0062328
0.00421973
0.00756494
0.0049652
0.00883278
0.00998273
9.43856e-05
-0.000170315
0.00035005
0.000159075
0.000747298
0.000862204
0.00126656
0.00181805
0.00188606
0.00294698
0.00258115
0.00418823
0.00332511
0.00548884
0.0040908
0.00679925
0.0048525
0.00807108
0.00924755
8.60759e-05
-0.000256391
0.000321545
-7.63945e-05
0.000691415
0.000492333
0.00118074
0.00132872
0.00177231
0.00235541
0.00244562
0.00351493
0.00317694
0.00475752
0.00394037
0.00603582
0.00470911
0.00730233
0.00849955
7.82358e-05
-0.000334626
0.000293977
-0.000292135
0.000636424
0.000149886
0.00109482
0.000870319
0.00165626
0.00179397
0.00230442
0.00286676
0.00301898
0.00404296
0.00377561
0.00527919
0.00454628
0.00653167
0.00774566
7.05568e-05
-0.000405183
0.000266604
-0.000488182
0.000581147
-0.000164657
0.00100726
0.00044421
0.00153621
0.00126502
0.00215622
0.00224675
0.00285132
0.00334787
0.00360015
0.00453035
0.00437401
0.00575781
0.0069849
6.26796e-05
-0.000467863
0.000238499
-0.000664002
0.000523888
-0.000450046
0.000915283
5.28147e-05
0.00140788
0.000772429
0.00199485
0.00165978
0.00266626
0.00267646
0.00340718
0.00378943
0.00419237
0.00497262
0.00620442
5.42636e-05
-0.000522127
0.000208758
-0.000818497
0.000462848
-0.000704136
0.000815487
-0.000299824
0.00126477
0.000323146
0.00180822
0.00111633
0.00244299
0.00204168
0.00316574
0.00306668
0.00396725
0.00417111
0.00538188
4.50822e-05
-0.000567209
0.000176823
-0.000950238
0.000396903
-0.000924215
0.000705414
-0.000608335
0.00110085
-7.22851e-05
0.00158097
0.000636207
0.00214436
0.00147829
0.0027944
0.00241664
0.00355248
0.00341304
0.00447142
3.53022e-05
-0.000602511
0.000142929
-0.00105786
0.000326618
-0.0011079
0.000586453
-0.000868171
0.000918454
-0.000404286
0.00131382
0.00024084
0.00175674
0.00103537
0.00221715
0.00195623
0.00263074
0.00299945
0.0042205
2.40985e-05
-0.000626609
0.000106781
-0.00114055
0.000253442
-0.00125456
0.000463859
-0.00107859
0.000731985
-0.000672412
0.00104515
-7.23263e-05
0.00138283
0.000697689
0.0017157
0.00162337
0.00201252
0.00270262
0.00394175
1.26267e-05
-0.000639236
7.06029e-05
-0.00119852
0.000181398
-0.00136536
0.000345392
-0.00124258
0.000556687
-0.000883706
0.000803498
-0.000319138
0.00106925
0.000431939
0.0013362
0.00135642
0.00159576
0.00244306
0.00366749
1.5432e-06
-0.000640779
3.60478e-05
-0.00123303
0.000113933
-0.00144324
0.000236991
-0.00136564
0.000401223
-0.00104794
0.000598195
-0.00051611
0.000817247
0.000212887
0.00104971
0.00112396
0.00129575
0.00219701
0.00339364
-9.14002e-06
-0.000631639
4.88197e-06
-0.00124705
5.42559e-05
-0.00149262
0.000143244
-0.00145463
0.000270638
-0.00117533
0.000432057
-0.000677529
0.000622158
2.27868e-05
0.000837696
0.000908421
0.00108069
0.00195402
0.00311703
-1.80546e-05
-0.000613585
-2.12357e-05
-0.00124387
5.32506e-06
-0.00151918
6.78671e-05
-0.00151717
0.000168233
-0.0012757
0.000305857
-0.000815153
0.000479528
-0.000150884
0.000688882
0.000699067
0.000935047
0.00170786
0.00283432
-2.49232e-05
-0.000588661
-4.05458e-05
-0.00122825
-3.02258e-05
-0.0015295
1.40969e-05
-0.00156149
9.66899e-05
-0.00135829
0.000220167
-0.00093863
0.000386344
-0.000317061
0.000596468
0.000488942
0.000850434
0.00145389
0.0025409
-2.91179e-05
-0.000559544
-5.14774e-05
-0.00120589
-4.97547e-05
-0.00153122
-1.49676e-05
-0.00159628
5.8842e-05
-0.0014321
0.000176567
-0.00105635
0.000342206
-0.0004827
0.000558179
0.00027297
0.000823797
0.00118827
0.00223205
-3.00989e-05
-0.000529445
-5.26288e-05
-0.00118336
-5.09724e-05
-0.00153288
-1.63186e-05
-0.00163093
5.79531e-05
-0.00150637
0.000178053
-0.00117645
0.000349494
-0.000654141
0.000575792
4.6672e-05
0.000856547
0.000907519
0.0019036
-2.74592e-05
-4.28987e-05
-3.19703e-05
1.27644e-05
9.7455e-05
0.000228667
0.000412759
0.000654301
0.000953856
)
;
boundaryField
{
inlet
{
type calculated;
value uniform 0;
}
outlet
{
type calculated;
value nonuniform List<scalar>
40
(
0.00500686
0.0286699
0.0520763
0.075792
0.101873
0.130522
0.161955
0.199562
0.245885
0.28876
-0.0019775
-0.00329133
-0.00450885
-0.00562602
-0.00664158
-0.00755725
-0.00837747
-0.00910865
-0.00975848
-0.0103353
-0.010848
-0.0113051
-0.0117152
-0.0120867
-0.0124276
-0.0127458
-0.0130487
-0.0133437
-0.0136377
-0.0139379
-0.0545015
-0.0609127
-0.0702505
-0.0831019
-0.0992806
-0.11746
-0.135309
-0.150298
-0.160726
-0.165984
)
;
}
cylinder
{
type calculated;
value uniform 0;
}
top
{
type symmetryPlane;
value uniform 0;
}
bottom
{
type symmetryPlane;
value uniform 0;
}
defaultFaces
{
type empty;
value nonuniform 0();
}
}
// ************************************************************************* //
| [
"henry.rossiter@utexas.edu"
] | henry.rossiter@utexas.edu | |
c483b71697304bd3350b8b316cb398898c677ea9 | c29e9d984244dc7d1addaaa8c1fe061c743e3dbd | /cpp code/Problem/PAT A1113.cpp | 76ae27c11e569bcf941be8ef7ec25131ac5bfe34 | [] | no_license | KaihongGo/PAT | b596519a74ff9e5ce508b95fe05070a551896fa1 | 3b9d80681694aedf33e7f355cb684576156811c4 | refs/heads/master | 2023-01-09T07:56:18.829829 | 2020-11-02T13:05:39 | 2020-11-02T13:05:39 | 304,880,027 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 586 | cpp | //PAT A1113.cpp 1113 Integer Set Partition (25 ·Ö)
//s1 = accumulate(vi.begin(), vi.end(), 0);º¯Êý
#include <cstdio>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;
const int maxn = 100010;
int main()
{
int n;
scanf("%d", &n);
vector<int> vi;
for (int i = 0; i < n; i++)
{
int a;
scanf("%d", &a);
vi.push_back(a);
}
sort(vi.begin(), vi.end());
int n1, n2, s1, s2;
n1 = n / 2;
n2 = n - n1;
s1 = accumulate(vi.begin(), vi.begin() + n1, 0);
s2 = accumulate(vi.begin() + n1, vi.end(), 0);
printf("%d %d", abs(n1 - n2), s2 - s1);
} | [
"34575284+KaihongGo@users.noreply.github.com"
] | 34575284+KaihongGo@users.noreply.github.com |
7f072ed1418c938ee3d5da72298ee45ec5afa37a | 479b80d38ee858e29b3ea48999260934aff02f8c | /src/main.cpp | 54b88f9ba74f00610dea8a80cf7cf3dda2c6b018 | [
"MIT"
] | permissive | crypt0n1nja/xbrc-core | cff83e9a825c51ce50f7223f4cdac892430dde84 | b6060e8d3b344d6ec6c4020ec51d78a24a5c4718 | refs/heads/master | 2020-04-03T05:08:44.084790 | 2018-10-28T04:53:50 | 2018-10-28T04:53:50 | 155,019,677 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 163,253 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "addrman.h"
#include "alert.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "db.h"
#include "init.h"
#include "kernel.h"
#include "net.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "instantx.h"
#include "darksend.h"
#include "masternodeman.h"
#include "masternode-payments.h"
#include "spork.h"
#include "smessage.h"
#include "util.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
//
// Global state
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
map<uint256, CBlockIndex*> mapBlockIndex;
set<pair<COutPoint, unsigned int> > setStakeSeen;
CBigNum bnProofOfStakeLimit(~uint256(0) >> 20);
unsigned int nStakeMinAge = 60 * 60;
unsigned int nModifierInterval = 8 * 60;
int nCoinbaseMaturity = 20;
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
uint256 nBestChainTrust = 0;
uint256 nBestInvalidTrust = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64_t nTimeBestReceived = 0;
bool fImporting = false;
bool fReindex = false;
bool fAddrIndex = false;
bool fHaveGUI = false;
struct COrphanBlock {
uint256 hashBlock;
uint256 hashPrev;
std::pair<COutPoint, unsigned int> stake;
vector<unsigned char> vchBlock;
};
map<uint256, COrphanBlock*> mapOrphanBlocks;
multimap<uint256, COrphanBlock*> mapOrphanBlocksByPrev;
set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
map<uint256, CTransaction> mapOrphanTransactions;
map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "Bitrewards Signed Message:\n";
std::set<uint256> setValidatedTx;
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
namespace {
struct CMainSignals {
// Notifies listeners of updated transaction data (passing hash, transaction, and optionally the block it is found in.
boost::signals2::signal<void (const CTransaction &, const CBlock *, bool)> SyncTransaction;
// Notifies listeners of an erased transaction (currently disabled, requires transaction replacement).
boost::signals2::signal<void (const uint256 &)> EraseTransaction;
// Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible).
boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
// Notifies listeners of a new active block chain.
boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
// Notifies listeners about an inventory item being seen on the network.
boost::signals2::signal<void (const uint256 &)> Inventory;
// Tells listeners to broadcast their data.
boost::signals2::signal<void (bool)> Broadcast;
} g_signals;
}
void RegisterWallet(CWalletInterface* pwalletIn) {
g_signals.SyncTransaction.connect(boost::bind(&CWalletInterface::SyncTransaction, pwalletIn, _1, _2, _3));
g_signals.EraseTransaction.connect(boost::bind(&CWalletInterface::EraseFromWallet, pwalletIn, _1));
g_signals.UpdatedTransaction.connect(boost::bind(&CWalletInterface::UpdatedTransaction, pwalletIn, _1));
g_signals.SetBestChain.connect(boost::bind(&CWalletInterface::SetBestChain, pwalletIn, _1));
g_signals.Inventory.connect(boost::bind(&CWalletInterface::Inventory, pwalletIn, _1));
g_signals.Broadcast.connect(boost::bind(&CWalletInterface::ResendWalletTransactions, pwalletIn, _1));
}
void UnregisterWallet(CWalletInterface* pwalletIn) {
g_signals.Broadcast.disconnect(boost::bind(&CWalletInterface::ResendWalletTransactions, pwalletIn, _1));
g_signals.Inventory.disconnect(boost::bind(&CWalletInterface::Inventory, pwalletIn, _1));
g_signals.SetBestChain.disconnect(boost::bind(&CWalletInterface::SetBestChain, pwalletIn, _1));
g_signals.UpdatedTransaction.disconnect(boost::bind(&CWalletInterface::UpdatedTransaction, pwalletIn, _1));
g_signals.EraseTransaction.disconnect(boost::bind(&CWalletInterface::EraseFromWallet, pwalletIn, _1));
g_signals.SyncTransaction.disconnect(boost::bind(&CWalletInterface::SyncTransaction, pwalletIn, _1, _2, _3));
}
void UnregisterAllWallets() {
g_signals.Broadcast.disconnect_all_slots();
g_signals.Inventory.disconnect_all_slots();
g_signals.SetBestChain.disconnect_all_slots();
g_signals.UpdatedTransaction.disconnect_all_slots();
g_signals.EraseTransaction.disconnect_all_slots();
g_signals.SyncTransaction.disconnect_all_slots();
}
void SyncWithWallets(const CTransaction &tx, const CBlock *pblock, bool fConnect) {
g_signals.SyncTransaction(tx, pblock, fConnect);
}
void ResendWalletTransactions(bool fBitrewards) {
g_signals.Broadcast(fBitrewards);
}
//////////////////////////////////////////////////////////////////////////////
//
// Registration of network node signals.
//
namespace {
// Maintain validation-specific state about nodes, protected by cs_main, instead
// by CNode's own locks. This simplifies asynchronous operation, where
// processing of incoming data is done after the ProcessMessage call returns,
// and we're no longer holding the node's locks.
struct CNodeState {
// Accumulated misbehaviour Bitrewards for this peer.
int nMisbehavior;
// Whether this peer should be disconnected and banned.
bool fShouldBan;
std::string name;
CNodeState() {
nMisbehavior = 0;
fShouldBan = false;
}
};
map<NodeId, CNodeState> mapNodeState;
// Requires cs_main.
CNodeState *State(NodeId pnode) {
map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
if (it == mapNodeState.end())
return NULL;
return &it->second;
}
int GetHeight()
{
while(true){
TRY_LOCK(cs_main, lockMain);
if(!lockMain) { MilliSleep(50); continue; }
return pindexBest->nHeight;
}
}
void InitializeNode(NodeId nodeid, const CNode *pnode) {
LOCK(cs_main);
CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
state.name = pnode->addrName;
}
void FinalizeNode(NodeId nodeid) {
LOCK(cs_main);
mapNodeState.erase(nodeid);
}
}
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
LOCK(cs_main);
CNodeState *state = State(nodeid);
if (state == NULL)
return false;
stats.nMisbehavior = state->nMisbehavior;
return true;
}
void RegisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.GetHeight.connect(&GetHeight);
nodeSignals.ProcessMessages.connect(&ProcessMessages);
nodeSignals.SendMessages.connect(&SendMessages);
nodeSignals.InitializeNode.connect(&InitializeNode);
nodeSignals.FinalizeNode.connect(&FinalizeNode);
}
void UnregisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.GetHeight.disconnect(&GetHeight);
nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
nodeSignals.SendMessages.disconnect(&SendMessages);
nodeSignals.InitializeNode.disconnect(&InitializeNode);
nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
}
bool AbortNode(const std::string &strMessage, const std::string &userMessage) {
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(
userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CTransaction& tx)
{
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (nSize > 5000)
{
LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", nSize, hash.ToString());
return false;
}
mapOrphanTransactions[hash] = tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
LogPrint("mempool", "stored orphan tx %s (mapsz %u)\n", hash.ToString(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
map<uint256, CTransaction>::iterator it = mapOrphanTransactions.find(hash);
if (it == mapOrphanTransactions.end())
return;
BOOST_FOREACH(const CTxIn& txin, it->second.vin)
{
map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
if (itPrev == mapOrphanTransactionsByPrev.end())
continue;
itPrev->second.erase(hash);
if (itPrev->second.empty())
mapOrphanTransactionsByPrev.erase(itPrev);
}
mapOrphanTransactions.erase(it);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction and CTxIndex
//
bool CTransaction::ReadFromDisk(CTxDB& txdb, const uint256& hash, CTxIndex& txindexRet)
{
SetNull();
if (!txdb.ReadTxIndex(hash, txindexRet))
return false;
if (!ReadFromDisk(txindexRet.pos))
return false;
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
{
if (!ReadFromDisk(txdb, prevout.hash, txindexRet))
return false;
if (prevout.n >= vout.size())
{
SetNull();
return false;
}
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
{
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::ReadFromDisk(COutPoint prevout)
{
CTxDB txdb("r");
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool IsStandardTx(const CTransaction& tx, string& reason)
{
if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
reason = "version";
return false;
}
// Treat non-final transactions as non-standard to prevent a specific type
// of double-spend attack, as well as DoS attacks. (if the transaction
// can't be mined, the attacker isn't expending resources broadcasting it)
// Basically we don't want to propagate transactions that can't be included in
// the next block.
//
// However, IsFinalTx() is confusing... Without arguments, it uses
// chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height()
// is set to the value of nHeight in the block. However, when IsFinalTx()
// is called within CBlock::AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a transaction can
// be part of the *next* block, we need to call IsFinalTx() with one more
// than chainActive.Height().
//
// Timestamps on the other hand don't get any special treatment, because we
// can't know what timestamp the next block will have, and there aren't
// timestamp applications where it matters.
if (!IsFinalTx(tx, nBestHeight + 1)) {
reason = "non-final";
return false;
}
// nTime has different purpose from nLockTime but can be used in similar attacks
if (tx.nTime > FutureDrift(GetAdjustedTime())) {
reason = "time-too-new";
return false;
}
// Extremely large transactions with lots of inputs can cost the network
// almost as much to process as they cost the sender in fees, because
// computing signature hashes is O(ninputs*txsize). Limiting transactions
// to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (sz >= MAX_STANDARD_TX_SIZE) {
reason = "tx-size";
return false;
}
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
// keys. (remember the 520 byte limit on redeemScript size) That works
// out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
// bytes of scriptSig, which we round off to 1650 bytes for some minor
// future-proofing. That's also enough to spend a 20-of-20
// CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
// considered standard)
if (txin.scriptSig.size() > 1650) {
reason = "scriptsig-size";
return false;
}
if (!txin.scriptSig.IsPushOnly()) {
reason = "scriptsig-not-pushonly";
return false;
}
if (!txin.scriptSig.HasCanonicalPushes()) {
reason = "scriptsig-non-canonical-push";
return false;
}
}
unsigned int nDataOut = 0;
txnouttype whichType;
BOOST_FOREACH(const CTxOut& txout, tx.vout) {
if (!::IsStandard(txout.scriptPubKey, whichType))
{
reason = "scriptpubkey";
return false;
}
if (whichType == TX_NULL_DATA)
{
nDataOut++;
} else if (txout.nValue == 0) {
reason = "dust";
return false;
}
if (!txout.scriptPubKey.HasCanonicalPushes()) {
reason = "scriptpubkey-non-canonical-push";
return false;
}
}
// not more than one data txout per non-data txout is permitted
// only one data txout is permitted too
if (nDataOut > 1 && nDataOut > tx.vout.size()/2) {
reason = "multi-op-return";
return false;
}
return true;
}
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
{
AssertLockHeld(cs_main);
// Time based nLockTime implemented in 0.1.6
if (tx.nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = nBestHeight;
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
if (!txin.IsFinal())
return false;
return true;
}
//
// Check transaction inputs to mitigate two
// potential denial-of-service attacks:
//
// 1. scriptSigs with extra data stuffed into them,
// not consumed by scriptPubKey (or P2SH script)
// 2. P2SH scripts with a crazy number of expensive
// CHECKSIG/CHECKMULTISIG operations
//
bool AreInputsStandard(const CTransaction& tx, const MapPrevTx& mapInputs)
{
if (tx.IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
const CTxOut& prev = tx.GetOutputFor(tx.vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig
// IsStandard() will have already returned false
// and this method isn't called.
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, tx.vin[i].scriptSig, tx, i, SCRIPT_VERIFY_NONE, 0))
return false;
if (whichType == TX_SCRIPTHASH)
{
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (Solver(subscript, whichType2, vSolutions2))
{
int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (whichType2 == TX_SCRIPTHASH)
return false;
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
else
{
// Any other Script with less than 15 sigops OK:
unsigned int sigops = subscript.GetSigOpCount(true);
// ... extra data left on the stack after execution is OK, too:
return (sigops <= MAX_P2SH_SIGOPS);
}
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int GetLegacySigOpCount(const CTransaction& tx)
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
unsigned int GetP2SHSigOpCount(const CTransaction& tx, const MapPrevTx& inputs)
{
if (tx.IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
const CTxOut& prevout = tx.GetOutputFor(tx.vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
AssertLockHeld(cs_main);
CBlock blockTmp;
if (pblock == NULL) {
// Load the block this tx is in
CTxIndex txindex;
if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
return 0;
if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) {
return 0;
pblock = &blockTmp;
}
}
if (pblock) {
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const
{
// In order to avoid disincentivizing cleaning up the UTXO set we don't count
// the constant overhead for each txin and up to 110 bytes of scriptSig (which
// is enough to cover a compressed pubkey p2sh redemption) for priority.
// Providing any more cleanup incentive than making additional inputs free would
// risk encouraging people to create junk outputs to redeem later.
if (nTxSize == 0)
nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
BOOST_FOREACH(const CTxIn& txin, vin)
{
unsigned int offset = 41U + std::min(110U, (unsigned int)txin.scriptSig.size());
if (nTxSize > offset)
nTxSize -= offset;
}
if (nTxSize == 0) return 0.0;
return dPriorityInputs / nTxSize;
}
bool CTransaction::CheckTransaction() const
{
// Basic checks that don't depend on any context
if (vin.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64_t nValueOut = 0;
for (unsigned int i = 0; i < vout.size(); i++)
{
const CTxOut& txout = vout[i];
if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
if (txout.nValue < 0)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
if (txout.nValue > MAX_MONEY)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return false;
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
int64_t GetMinFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree, enum GetMinFee_mode mode)
{
// Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
int64_t nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
/*if (fAllowFree)
{
// There is a free transaction area in blocks created by most miners,
// * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
// to be considered to fall into this category. We don't want to encourage sending
// multiple transactions instead of one big transaction to avoid fees.
// * If we are creating a transaction we allow transactions up to 1,000 bytes
// to be considered safe and assume they can likely make it into this section.
if (nBytes < (mode == GMF_SEND ? 1000 : (DEFAULT_BLOCK_PRIORITY_SIZE - 1000)))
nMinFee = 0;
}*/
// This code can be removed after enough miners have upgraded to version 0.9.
// Until then, be safe when sending and require a fee if any output
// is less than CENT:
if (nMinFee < nBaseFee && mode == GMF_SEND)
{
BOOST_FOREACH(const CTxOut& txout, tx.vout)
if (txout.nValue < CENT)
nMinFee = nBaseFee;
}
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}
bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx, bool fLimitFree,
bool* pfMissingInputs, bool fRejectInsaneFee, bool ignoreFees)
{
AssertLockHeld(cs_main);
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("AcceptToMemoryPool : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("AcceptToMemoryPool : coinbase as individual tx"));
// ppcoin: coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return tx.DoS(100, error("AcceptToMemoryPool : coinstake as individual tx"));
// Rather not work on nonstandard transactions (unless -testnet)
string reason;
if (!TestNet() && !IsStandardTx(tx, reason))
return error("AcceptToMemoryPool : nonstandard transaction: %s",
reason);
// is it already in the memory pool?
uint256 hash = tx.GetHash();
if (pool.exists(hash))
return false;
// ----------- instantX transaction scanning -----------
BOOST_FOREACH(const CTxIn& in, tx.vin){
if(mapLockedInputs.count(in.prevout)){
if(mapLockedInputs[in.prevout] != tx.GetHash()){
return tx.DoS(0, error("AcceptToMemoryPool : conflicts with existing transaction lock: %s", reason));
}
}
}
// Check for conflicts with in-memory transactions
{
LOCK(pool.cs); // protect pool.mapNextTx
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (pool.mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
}
}
}
{
CTxDB txdb("r");
// do we already have it?
if (txdb.ContainsTx(hash))
return false;
// do all inputs exist?
// Note that this does not check for the presence of actual outputs (see the next check for that),
// only helps filling in pfMissingInputs (to determine missing vs spent).
BOOST_FOREACH(const CTxIn txin, tx.vin) {
if (!txdb.ContainsTx(txin.prevout.hash)) {
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
}
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("AcceptToMemoryPool : FetchInputs found invalid tx %s", hash.ToString());
return false;
}
// Check for non-standard pay-to-script-hash in inputs
if (!TestNet() && !AreInputsStandard(tx, mapInputs))
return error("AcceptToMemoryPool : nonstandard transaction input");
// Check that the transaction doesn't have an excessive number of
// sigops, making it impossible to mine. Since the coinbase transaction
// itself can contain sigops MAX_TX_SIGOPS is less than
// MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
// merely non-standard transaction.
unsigned int nSigOps = GetLegacySigOpCount(tx);
nSigOps += GetP2SHSigOpCount(tx, mapInputs);
if (nSigOps > MAX_TX_SIGOPS)
return tx.DoS(0,
error("AcceptToMemoryPool : too many sigops %s, %d > %d",
hash.ToString(), nSigOps, MAX_TX_SIGOPS));
int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
// but prioritise dstx and don't check fees for it
if(mapDarksendBroadcastTxes.count(hash)) {
// Normally we would PrioritiseTransaction But currently it is unimplemented
// mempool.PrioritiseTransaction(hash, hash.ToString(), 1000, 0.1*COIN);
} else if(!ignoreFees){
int64_t txMinFee = GetMinFee(tx, nSize, true, GMF_RELAY);
if (fLimitFree && nFees < txMinFee)
return error("AcceptToMemoryPool : not enough fees %s, %d < %d",
hash.ToString(),
nFees, txMinFee);
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (fLimitFree && nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection csFreeLimiter;
static double dFreeCount;
static int64_t nLastTime;
int64_t nNow = GetTime();
LOCK(csFreeLimiter);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000)
return error("AcceptableInputs : free transaction rejected by rate limiter");
LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
}
if (fRejectInsaneFee && nFees > MIN_RELAY_TX_FEE * 10000)
return error("AcceptableInputs: : insane fees %s, %d > %d",
hash.ToString(),
nFees, MIN_RELAY_TX_FEE * 10000);
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, STANDARD_SCRIPT_VERIFY_FLAGS))
{
return error("AcceptToMemoryPool : ConnectInputs failed %s", hash.ToString());
}
// Check again against just the consensus-critical mandatory script
// verification flags, in case of bugs in the standard flags that cause
// transactions to pass as valid when they're actually invalid. For
// instance the STRICTENC flag was incorrectly allowing certain
// CHECKSIG NOT scripts to pass, even though they were invalid.
//
// There is a similar check in CreateNewBlock() to prevent creating
// invalid blocks, however allowing such transactions into the mempool
// can be exploited as a DoS attack.
if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, MANDATORY_SCRIPT_VERIFY_FLAGS))
{
return error("AcceptToMemoryPool: : BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
}
}
// Store transaction in memory
pool.addUnchecked(hash, tx);
setValidatedTx.insert(hash);
SyncWithWallets(tx, NULL);
LogPrint("mempool", "AcceptToMemoryPool : accepted %s (poolsz %u)\n",
hash.ToString(),
pool.mapTx.size());
return true;
}
bool AcceptableInputs(CTxMemPool& pool, const CTransaction &txo, bool fLimitFree,
bool* pfMissingInputs, bool fRejectInsaneFee, bool isDSTX)
{
AssertLockHeld(cs_main);
if (pfMissingInputs)
*pfMissingInputs = false;
CTransaction tx(txo);
string reason;
if (!tx.CheckTransaction())
return error("AcceptableInputs : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("AcceptableInputs : coinbase as individual tx"));
// ppcoin: coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return tx.DoS(100, error("AcceptableInputs : coinstake as individual tx"));
// is it already in the memory pool?
uint256 hash = tx.GetHash();
if (pool.exists(hash))
return false;
// ----------- instantX transaction scanning -----------
BOOST_FOREACH(const CTxIn& in, tx.vin){
if(mapLockedInputs.count(in.prevout)){
if(mapLockedInputs[in.prevout] != tx.GetHash()){
return tx.DoS(0, error("AcceptableInputs : conflicts with existing transaction lock: %s", reason));
}
}
}
// Check for conflicts with in-memory transactions
{
LOCK(pool.cs); // protect pool.mapNextTx
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (pool.mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
}
}
}
{
CTxDB txdb("r");
// do we already have it?
if (txdb.ContainsTx(hash))
return false;
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("AcceptableInputs : FetchInputs found invalid tx %s", hash.ToString());
return false;
}
// Check for non-standard pay-to-script-hash in inputs
//if (!TestNet() && !AreInputsStandard(tx, mapInputs))
// return error("AcceptToMemoryPool : nonstandard transaction input");
// Check that the transaction doesn't have an excessive number of
// sigops, making it impossible to mine. Since the coinbase transaction
// itself can contain sigops MAX_TX_SIGOPS is less than
// MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
// merely non-standard transaction.
unsigned int nSigOps = GetLegacySigOpCount(tx);
nSigOps += GetP2SHSigOpCount(tx, mapInputs);
if (nSigOps > MAX_TX_SIGOPS)
return tx.DoS(0,
error("AcceptableInputs : too many sigops %s, %d > %d",
hash.ToString(), nSigOps, MAX_TX_SIGOPS));
int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
int64_t txMinFee = GetMinFee(tx, nSize, true, GMF_RELAY);
// Don't accept it if it can't get into a block
if(isDSTX) {
// Normally we would PrioritiseTransaction But currently it is unimplemented
// mempool.PrioritiseTransaction(hash, hash.ToString(), 1000, 0.1*COIN);
} else { // same as !ignoreFees for AcceptToMemoryPool
if (fLimitFree && nFees < txMinFee)
return error("AcceptableInputs : not enough fees %s, %d < %d",
hash.ToString(),
nFees, txMinFee);
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (fLimitFree && nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection csFreeLimiter;
static double dFreeCount;
static int64_t nLastTime;
int64_t nNow = GetTime();
LOCK(csFreeLimiter);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000)
return error("AcceptableInputs : free transaction rejected by rate limiter");
LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
}
if (fRejectInsaneFee && nFees > txMinFee * 10000)
return error("AcceptableInputs: : insane fees %s, %d > %d",
hash.ToString(),
nFees, MIN_RELAY_TX_FEE * 10000);
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, true, false, STANDARD_SCRIPT_VERIFY_FLAGS, false))
{
return error("AcceptableInputs : ConnectInputs failed %s", hash.ToString());
}
}
/*LogPrint("mempool", "AcceptableInputs : accepted %s (poolsz %u)\n",
hash.ToString(),
pool.mapTx.size());
*/
return true;
}
int CMerkleTx::GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
AssertLockHeld(cs_main);
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetTransactionLockSignatures() const
{
if(!IsSporkActive(SPORK_2_INSTANTX)) return -3;
if(!fEnableInstantX) return -1;
//compile consessus vote
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash());
if (i != mapTxLocks.end()){
return (*i).second.CountSignatures();
}
return -1;
}
bool CMerkleTx::IsTransactionLockTimedOut() const
{
if(!fEnableInstantX) return -1;
//compile consessus vote
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash());
if (i != mapTxLocks.end()){
return GetTime() > (*i).second.nTimeout;
}
return false;
}
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet, bool enableIX) const
{
AssertLockHeld(cs_main);
int nResult = GetDepthInMainChainINTERNAL(pindexRet);
if (nResult == 0 && !mempool.exists(GetHash()))
return -1; // Not in chain, not in mempool
if(enableIX){
if (nResult < 10){
int signatures = GetTransactionLockSignatures();
if(signatures >= INSTANTX_SIGNATURES_REQUIRED){
return nInstantXDepth+nResult;
}
}
}
return nResult;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
return max(0, nCoinbaseMaturity - GetDepthInMainChain() + 1);
}
bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee, bool ignoreFees)
{
return ::AcceptToMemoryPool(mempool, *this, fLimitFree, NULL, fRejectInsaneFee, ignoreFees);
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb)
{
{
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
tx.AcceptToMemoryPool(false);
}
}
return AcceptToMemoryPool(false);
}
return false;
}
bool CWalletTx::AcceptWalletTransaction()
{
CTxDB txdb("r");
return AcceptWalletTransaction(txdb);
}
int GetInputAge(CTxIn& vin)
{
const uint256& prevHash = vin.prevout.hash;
CTransaction tx;
uint256 hashBlock;
bool fFound = GetTransaction(prevHash, tx, hashBlock);
if(fFound)
{
if(mapBlockIndex.find(hashBlock) != mapBlockIndex.end())
{
return pindexBest->nHeight - mapBlockIndex[hashBlock]->nHeight;
}
else
return 0;
}
else
return 0;
}
int GetInputAgeIX(uint256 nTXHash, CTxIn& vin)
{
int sigs = 0;
int nResult = GetInputAge(vin);
if(nResult < 0) nResult = 0;
if (nResult < 6){
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(nTXHash);
if (i != mapTxLocks.end()){
sigs = (*i).second.CountSignatures();
}
if(sigs >= INSTANTX_SIGNATURES_REQUIRED){
return nInstantXDepth+nResult;
}
}
return -1;
}
int GetIXConfirmations(uint256 nTXHash)
{
int sigs = 0;
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(nTXHash);
if (i != mapTxLocks.end()){
sigs = (*i).second.CountSignatures();
}
if(sigs >= INSTANTX_SIGNATURES_REQUIRED){
return nInstantXDepth;
}
return 0;
}
int CTxIndex::GetDepthInMainChain() const
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return 1 + nBestHeight - pindex->nHeight;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
{
{
LOCK(cs_main);
{
if (mempool.lookup(hash, tx))
{
return true;
}
}
CTxDB txdb("r");
CTxIndex txindex;
if (tx.ReadFromDisk(txdb, hash, txindex))
{
CBlock block;
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
hashBlock = block.GetHash();
return true;
}
// look for transaction in disconnected blocks to find orphaned CoinBase and CoinStake transactions
BOOST_FOREACH(PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
{
CBlockIndex* pindex = item.second;
if (pindex == pindexBest || pindex->pnext != 0)
continue;
CBlock block;
if (!block.ReadFromDisk(pindex))
continue;
BOOST_FOREACH(const CTransaction& txOrphan, block.vtx)
{
if (txOrphan.GetHash() == hash)
{
tx = txOrphan;
return true;
}
}
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
static CBlockIndex* pblockindexFBBHLast;
CBlockIndex* FindBlockByHeight(int nHeight)
{
CBlockIndex *pblockindex;
if (nHeight < nBestHeight / 2)
pblockindex = pindexGenesisBlock;
else
pblockindex = pindexBest;
if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
pblockindex = pblockindexFBBHLast;
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
while (pblockindex->nHeight < nHeight)
pblockindex = pblockindex->pnext;
pblockindexFBBHLast = pblockindex;
return pblockindex;
}
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
{
if (!fReadTransactions)
{
*this = pindex->GetBlockHeader();
return true;
}
if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
string getDevAddress(int nHeight) {
int addrId = nHeight % 2;
if (addrId == 0) {
return "VPrtySS2dnvRAzjbYUgiSSE6bfwYLYRMTn";
} else {
return "VPXxDyfPBoV7XoKmS7FjaHV4BmVHksStzc";
}
}
uint256 static GetOrphanRoot(const uint256& hash)
{
map<uint256, COrphanBlock*>::iterator it = mapOrphanBlocks.find(hash);
if (it == mapOrphanBlocks.end())
return hash;
// Work back to the first block in the orphan chain
do {
map<uint256, COrphanBlock*>::iterator it2 = mapOrphanBlocks.find(it->second->hashPrev);
if (it2 == mapOrphanBlocks.end())
return it->first;
it = it2;
} while(true);
}
// ppcoin: find block wanted by given orphan block
uint256 WantedByOrphan(const COrphanBlock* pblockOrphan)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblockOrphan->hashPrev))
pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrev];
return pblockOrphan->hashPrev;
}
// Remove a random orphan block (which does not have any dependent orphans).
void static PruneOrphanBlocks()
{
if (mapOrphanBlocksByPrev.size() <= (size_t)std::max((int64_t)0, GetArg("-maxorphanblocks", DEFAULT_MAX_ORPHAN_BLOCKS)))
return;
// Pick a random orphan block.
int pos = insecure_rand() % mapOrphanBlocksByPrev.size();
std::multimap<uint256, COrphanBlock*>::iterator it = mapOrphanBlocksByPrev.begin();
while (pos--) it++;
// As long as this block has other orphans depending on it, move to one of those successors.
do {
std::multimap<uint256, COrphanBlock*>::iterator it2 = mapOrphanBlocksByPrev.find(it->second->hashBlock);
if (it2 == mapOrphanBlocksByPrev.end())
break;
it = it2;
} while(1);
setStakeSeenOrphan.erase(it->second->stake);
uint256 hash = it->second->hashBlock;
delete it->second;
mapOrphanBlocksByPrev.erase(it);
mapOrphanBlocks.erase(hash);
}
static CBigNum GetProofOfStakeLimit(int nHeight)
{
return bnProofOfStakeLimit;
}
// miner's coin base reward
//will only last up to 300 blocks to help with the network stability
int64_t GetProofOfWorkReward(int nHeight, int64_t nFees)
{
int64_t nSubsidy = 0 * COIN;
if (nHeight == 1) {
nSubsidy = 50000000 * COIN;
}
else if (nHeight == 2) {
nSubsidy = 50000000 * COIN;
}
else if (nHeight == 3) {
nSubsidy = 50000000 * COIN;
}
else if (nHeight == 4) {
nSubsidy = 50000000 * COIN;
}
else if (nHeight == 5) {
nSubsidy = 50000000 * COIN;
}
else if (nHeight == 6) {
nSubsidy = 50000000 * COIN;
}
else if (nHeight == 7) {
nSubsidy = 50000000 * COIN;
}
else if (nHeight == 8) {
nSubsidy = 50000000 * COIN;
}
else if (nHeight > 8) {
nSubsidy = 1 * COIN;
}
return nSubsidy + nFees;
}
// miner's coin stake reward
int64_t GetProofOfStakeReward(const CBlockIndex* pindexPrev, int64_t nCoinAge, int64_t nFees)
{
int64_t nSubsidy = 0;
if (pindexBest->nHeight+1 > 2 && pindexBest->nHeight+1 <= 45000) {
nSubsidy = 20 * COIN;
}
else if (pindexBest->nHeight+1 > 45000 && pindexBest->nHeight+1 <= 90000) {
nSubsidy = 40 * COIN;
}
else if (pindexBest->nHeight+1 > 90000 && pindexBest->nHeight+1 <= 180002) {
nSubsidy = 80 * COIN;
}
else if (pindexBest->nHeight+1 > 180002 && pindexBest->nHeight+1 <= 3336706) {
nSubsidy = 160 * COIN;
}
else if (pindexBest->nHeight+1 > 3336706 && pindexBest->nHeight+1 <= 4915058) {
nSubsidy = 120 * COIN;
}
else if (pindexBest->nHeight+1 > 4915058 && pindexBest->nHeight+1 <= 6493410) {
nSubsidy = 100 * COIN;
}
else if (pindexBest->nHeight+1 > 6493410 && pindexBest->nHeight+1 <= 8071762) {
nSubsidy = 80 * COIN;
}
else if (pindexBest->nHeight+1 > 8071762 && pindexBest->nHeight+1 <= 9650114) {
nSubsidy = 70 * COIN;
}
else if (pindexBest->nHeight+1 > 9650114 && pindexBest->nHeight+1 <= 11228466) {
nSubsidy = 60 * COIN;
}
else if (pindexBest->nHeight+1 > 11228466 && pindexBest->nHeight+1 <= 12806818) {
nSubsidy = 40 * COIN;
}
else if (pindexBest->nHeight+1 > 12806818 && pindexBest->nHeight+1 <= 14385170) {
nSubsidy = 30 * COIN;
}
else if (pindexBest->nHeight+1 > 14385170 && pindexBest->nHeight+1 <= 14385171) {
nSubsidy = 20 * COIN;
}
else if (pindexBest->nHeight+1 > 14385171) {
nSubsidy = 10 * COIN;
}
return nSubsidy + nFees;
}
static int64_t nTargetTimespan = 10 * 60; // 10 mins
// ppcoin: find last block index up to pindex
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
{
while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
pindex = pindex->pprev;
return pindex;
}
unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
{
CBigNum bnTargetLimit = fProofOfStake ? GetProofOfStakeLimit(pindexLast->nHeight) : Params().ProofOfWorkLimit();
if (pindexLast == NULL)
return bnTargetLimit.GetCompact(); // genesis block
const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
if (pindexPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // first block
const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
if (pindexPrevPrev->pprev == NULL)
return bnTargetLimit.GetCompact(); // second block
int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
if (nActualSpacing < 0){
nActualSpacing = GetTargetSpacing(pindexLast->nHeight, fProofOfStake);
}
// ppcoin: target change every block
// ppcoin: retarget with exponential moving toward target spacing
CBigNum bnNew;
bnNew.SetCompact(pindexPrev->nBits);
int64_t nInterval = nTargetTimespan / GetTargetSpacing(pindexLast->nHeight, fProofOfStake);
bnNew *= ((nInterval - 1) * GetTargetSpacing(pindexLast->nHeight, fProofOfStake) + nActualSpacing + nActualSpacing);
bnNew /= ((nInterval + 1) * GetTargetSpacing(pindexLast->nHeight, fProofOfStake));
if (bnNew <= 0 || bnNew > bnTargetLimit)
bnNew = bnTargetLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > Params().ProofOfWorkLimit())
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
bool IsInitialBlockDownload()
{
LOCK(cs_main);
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64_t nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 15 &&
pindexBest->GetBlockTime() < GetTime() - 8 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->nChainTrust > nBestInvalidTrust)
{
nBestInvalidTrust = pindexNew->nChainTrust;
CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
}
uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
LogPrintf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%d date=%s\n",
pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
CBigNum(pindexNew->nChainTrust).ToString(), nBestInvalidBlockTrust.Get64(),
DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()));
LogPrintf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%d date=%s\n",
hashBestChain.ToString(), nBestHeight,
CBigNum(pindexBest->nChainTrust).ToString(),
nBestBlockTrust.Get64(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()));
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(GetBlockTime(), GetAdjustedTime());
}
bool IsConfirmedInNPrevBlocks(const CTxIndex& txindex, const CBlockIndex* pindexFrom, int nMaxDepth, int& nActualDepth)
{
for (const CBlockIndex* pindex = pindexFrom; pindex && pindexFrom->nHeight - pindex->nHeight < nMaxDepth; pindex = pindex->pprev)
{
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
{
nActualDepth = pindexFrom->nHeight - pindex->nHeight;
return true;
}
}
return false;
}
bool CTransaction::DisconnectInputs(CTxDB& txdb)
{
// Relinquish previous transactions' spent pointers
if (!IsCoinBase())
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
COutPoint prevout = txin.prevout;
// Get prev txindex from disk
CTxIndex txindex;
if (!txdb.ReadTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : ReadTxIndex failed");
if (prevout.n >= txindex.vSpent.size())
return error("DisconnectInputs() : prevout.n out of range");
// Mark outpoint as not spent
txindex.vSpent[prevout.n].SetNull();
// Write back
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : UpdateTxIndex failed");
}
}
// Remove transaction from index
// This can fail if a duplicate of this transaction was in a chain that got
// reorganized away. This is only possible if this transaction was completely
// spent, so erasing it would be a no-op anyway.
txdb.EraseTxIndex(*this);
return true;
}
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
{
// FetchInputs can return false either because we just haven't seen some inputs
// (in which case the transaction should be stored as an orphan)
// or because the transaction is malformed (in which case the transaction should
// be dropped). If tx is definitely invalid, fInvalid will be set to true.
fInvalid = false;
if (IsCoinBase())
return true; // Coinbase transactions have no inputs to fetch.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
if (inputsRet.count(prevout.hash))
continue; // Got it already
// Read txindex
CTxIndex& txindex = inputsRet[prevout.hash].first;
bool fFound = true;
if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
{
// Get txindex from current proposed changes
txindex = mapTestPool.find(prevout.hash)->second;
}
else
{
// Read txindex from txdb
fFound = txdb.ReadTxIndex(prevout.hash, txindex);
}
if (!fFound && (fBlock || fMiner))
return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString(), prevout.hash.ToString());
// Read txPrev
CTransaction& txPrev = inputsRet[prevout.hash].second;
if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
{
// Get prev tx from single transactions in memory
if (!mempool.lookup(prevout.hash, txPrev))
return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString(), prevout.hash.ToString());
if (!fFound)
txindex.vSpent.resize(txPrev.vout.size());
}
else
{
// Get prev tx from disk
if (!txPrev.ReadFromDisk(txindex.pos))
return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString(), prevout.hash.ToString());
}
}
// Make sure all prevout.n indexes are valid:
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint prevout = vin[i].prevout;
assert(inputsRet.count(prevout.hash) != 0);
const CTxIndex& txindex = inputsRet[prevout.hash].first;
const CTransaction& txPrev = inputsRet[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
{
// Revisit this if/when transaction replacement is implemented and allows
// adding inputs:
fInvalid = true;
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %u %u prev tx %s\n%s", GetHash().ToString(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString(), txPrev.ToString()));
}
}
return true;
}
const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
{
MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
if (mi == inputs.end())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
const CTransaction& txPrev = (mi->second).second;
if (input.prevout.n >= txPrev.vout.size())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
return txPrev.vout[input.prevout.n];
}
int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
int64_t nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
nResult += GetOutputFor(vin[i], inputs).nValue;
}
return nResult;
}
bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, unsigned int flags, bool fValidateSig)
{
// Take over previous transactions' spent pointers
// fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
// fMiner is true when called from the internal bitcoin miner
// ... both are false when called from CTransaction::AcceptToMemoryPool
if (!IsCoinBase())
{
int64_t nValueIn = 0;
int64_t nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %u %u prev tx %s\n%s", GetHash().ToString(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString(), txPrev.ToString()));
// If prev is coinbase or coinstake, check that it's matured
if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
{
int nSpendDepth;
if (IsConfirmedInNPrevBlocks(txindex, pindexBlock, nCoinbaseMaturity, nSpendDepth)){
return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", nSpendDepth);
}
}
// ppcoin: check transaction timestamp
if (txPrev.nTime > nTime)
return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
// Check for negative or overflow input values
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return DoS(100, error("ConnectInputs() : txin values out of range"));
}
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
// Check for conflicts (double-spend)
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!txindex.vSpent[prevout.n].IsNull())
return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString(), txindex.vSpent[prevout.n].ToString());
if(fValidateSig)
{
// Skip ECDSA signature verification when connecting blocks (fBlock=true)
// before the last blockchain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (!(fBlock && !IsInitialBlockDownload()))
{
// Verify signature
if (!VerifySignature(txPrev, *this, i, flags, 0))
{
if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
// Check whether the failure was caused by a
// non-mandatory script verification check, such as
// non-null dummy arguments;
// if so, don't trigger DoS protection to
// avoid splitting the network between upgraded and
// non-upgraded nodes.
if (VerifySignature(txPrev, *this, i, flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, 0))
return error("ConnectInputs() : %s non-mandatory VerifySignature failed", GetHash().ToString());
}
// Failures of other flags indicate a transaction that is
// invalid in new blocks, e.g. a invalid P2SH. We DoS ban
// such nodes as they are not following the protocol. That
// said during an upgrade careful thought should be taken
// as to the correct behavior - we may want to continue
// peering with non-upgraded nodes even after a soft-fork
// super-majority vote has passed.
return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString()));
}
}
}
// Mark outpoints as spent
txindex.vSpent[prevout.n] = posThisTx;
// Write back
if (fBlock || fMiner)
{
mapTestPool[prevout.hash] = txindex;
}
}
if (!IsCoinStake())
{
if (nValueIn < GetValueOut())
return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString()));
// Tally transaction fees
int64_t nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString()));
nFees += nTxFee;
if (!MoneyRange(nFees))
return DoS(100, error("ConnectInputs() : nFees out of range"));
}
}
return true;
}
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Disconnect in reverse order
for (int i = vtx.size()-1; i >= 0; i--)
if (!vtx[i].DisconnectInputs(txdb))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = 0;
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("DisconnectBlock() : WriteBlockIndex failed");
}
// ppcoin: clean up wallet after disconnecting coinstake
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, false);
return true;
}
bool static BuildAddrIndex(const CScript &script, std::vector<uint160>& addrIds)
{
CScript::const_iterator pc = script.begin();
CScript::const_iterator pend = script.end();
std::vector<unsigned char> data;
opcodetype opcode;
bool fHaveData = false;
while (pc < pend) {
script.GetOp(pc, opcode, data);
if (0 <= opcode && opcode <= OP_PUSHDATA4 && data.size() >= 8) { // data element
uint160 addrid = 0;
if (data.size() <= 20) {
memcpy(&addrid, &data[0], data.size());
} else {
addrid = Hash160(data);
}
addrIds.push_back(addrid);
fHaveData = true;
}
}
if (!fHaveData) {
uint160 addrid = Hash160(script);
addrIds.push_back(addrid);
return true;
}
else
{
if(addrIds.size() > 0)
return true;
else
return false;
}
}
bool FindTransactionsByDestination(const CTxDestination &dest, std::vector<uint256> &vtxhash) {
uint160 addrid = 0;
const CKeyID *pkeyid = boost::get<CKeyID>(&dest);
if (pkeyid)
addrid = static_cast<uint160>(*pkeyid);
if (!addrid) {
const CScriptID *pscriptid = boost::get<CScriptID>(&dest);
if (pscriptid)
addrid = static_cast<uint160>(*pscriptid);
}
if (!addrid)
{
LogPrintf("FindTransactionsByDestination(): Couldn't parse dest into addrid\n");
return false;
}
LOCK(cs_main);
CTxDB txdb("r");
if(!txdb.ReadAddrIndex(addrid, vtxhash))
{
LogPrintf("FindTransactionsByDestination(): txdb.ReadAddrIndex failed\n");
return false;
}
return true;
}
void CBlock::RebuildAddressIndex(CTxDB& txdb)
{
BOOST_FOREACH(CTransaction& tx, vtx)
{
uint256 hashTx = tx.GetHash();
// inputs
if(!tx.IsCoinBase())
{
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapQueuedChangesT;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChangesT, true, false, mapInputs, fInvalid))
return;
MapPrevTx::const_iterator mi;
for(MapPrevTx::const_iterator mi = mapInputs.begin(); mi != mapInputs.end(); ++mi)
{
BOOST_FOREACH(const CTxOut &atxout, (*mi).second.second.vout)
{
std::vector<uint160> addrIds;
if(BuildAddrIndex(atxout.scriptPubKey, addrIds))
{
BOOST_FOREACH(uint160 addrId, addrIds)
{
if(!txdb.WriteAddrIndex(addrId, hashTx))
LogPrintf("RebuildAddressIndex(): txins WriteAddrIndex failed addrId: %s txhash: %s\n", addrId.ToString().c_str(), hashTx.ToString().c_str());
}
}
}
}
}
// outputs
BOOST_FOREACH(const CTxOut &atxout, tx.vout) {
std::vector<uint160> addrIds;
if(BuildAddrIndex(atxout.scriptPubKey, addrIds))
{
BOOST_FOREACH(uint160 addrId, addrIds)
{
if(!txdb.WriteAddrIndex(addrId, hashTx))
LogPrintf("RebuildAddressIndex(): txouts WriteAddrIndex failed addrId: %s txhash: %s\n", addrId.ToString().c_str(), hashTx.ToString().c_str());
}
}
}
}
}
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
{
// Check it again in case a previous version let a bad block in, but skip BlockSig checking
if (!CheckBlock(!fJustCheck, !fJustCheck, false))
return false;
unsigned int flags = SCRIPT_VERIFY_NOCACHE;
//// issue here: it doesn't know the version
unsigned int nTxPos;
if (fJustCheck)
// FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
// Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from
nTxPos = 1;
else
nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
int64_t nFees = 0;
int64_t nValueIn = 0;
int64_t nValueOut = 0;
int64_t nStakeReward = 0;
unsigned int nSigOps = 0;
int nInputs = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
{
uint256 hashTx = tx.GetHash();
nInputs += tx.vin.size();
nSigOps += GetLegacySigOpCount(tx);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
if (!fJustCheck)
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
MapPrevTx mapInputs;
if (tx.IsCoinBase())
nValueOut += tx.GetValueOut();
else
{
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
return false;
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += GetP2SHSigOpCount(tx, mapInputs);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
int64_t nTxValueIn = tx.GetValueIn(mapInputs);
int64_t nTxValueOut = tx.GetValueOut();
nValueIn += nTxValueIn;
nValueOut += nTxValueOut;
if (!tx.IsCoinStake())
nFees += nTxValueIn - nTxValueOut;
if (tx.IsCoinStake())
nStakeReward = nTxValueOut - nTxValueIn;
if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, flags))
return false;
}
mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
}
if (IsProofOfWork())
{
int64_t nReward = GetProofOfWorkReward(pindex->nHeight, nFees);
// Check coinbase reward
if (vtx[0].GetValueOut() > nReward)
return DoS(50, error("ConnectBlock() : coinbase reward exceeded (actual=%d vs calculated=%d)",
vtx[0].GetValueOut(),
nReward));
}
if (IsProofOfStake())
{
// ppcoin: coin stake tx earns reward instead of paying fee
uint64_t nCoinAge;
if (!vtx[1].GetCoinAge(txdb, pindex->pprev, nCoinAge))
return error("ConnectBlock() : %s unable to get coin age for coinstake", vtx[1].GetHash().ToString());
int64_t nCalculatedStakeReward = GetProofOfStakeReward(pindex->pprev, nCoinAge, nFees);
if (nStakeReward > nCalculatedStakeReward)
return DoS(100, error("ConnectBlock() : coinstake pays too much(actual=%d vs calculated=%d)", nStakeReward, nCalculatedStakeReward));
}
// ppcoin: track money supply and mint amount info
#ifndef LOWMEM
pindex->nMint = nValueOut - nValueIn + nFees;
pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
#endif
if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
return error("Connect() : WriteBlockIndex for pindex failed");
if (fJustCheck)
return true;
// Write queued txindex changes
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
{
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
return error("ConnectBlock() : UpdateTxIndex failed");
}
if(GetBoolArg("-addrindex", false))
{
// Write Address Index
BOOST_FOREACH(CTransaction& tx, vtx)
{
uint256 hashTx = tx.GetHash();
// inputs
if(!tx.IsCoinBase())
{
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapQueuedChangesT;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChangesT, true, false, mapInputs, fInvalid))
return false;
MapPrevTx::const_iterator mi;
for(MapPrevTx::const_iterator mi = mapInputs.begin(); mi != mapInputs.end(); ++mi)
{
BOOST_FOREACH(const CTxOut &atxout, (*mi).second.second.vout)
{
std::vector<uint160> addrIds;
if(BuildAddrIndex(atxout.scriptPubKey, addrIds))
{
BOOST_FOREACH(uint160 addrId, addrIds)
{
if(!txdb.WriteAddrIndex(addrId, hashTx))
LogPrintf("ConnectBlock(): txins WriteAddrIndex failed addrId: %s txhash: %s\n", addrId.ToString().c_str(), hashTx.ToString().c_str());
}
}
}
}
}
// outputs
BOOST_FOREACH(const CTxOut &atxout, tx.vout)
{
std::vector<uint160> addrIds;
if(BuildAddrIndex(atxout.scriptPubKey, addrIds))
{
BOOST_FOREACH(uint160 addrId, addrIds)
{
if(!txdb.WriteAddrIndex(addrId, hashTx))
LogPrintf("ConnectBlock(): txouts WriteAddrIndex failed addrId: %s txhash: %s\n", addrId.ToString().c_str(), hashTx.ToString().c_str());
}
}
}
}
}
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = pindex->GetBlockHash();
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("ConnectBlock() : WriteBlockIndex failed");
}
// Watch for transactions paying to me
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this);
return true;
}
bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
{
LogPrintf("REORGANIZE\n");
// Find the fork
CBlockIndex* pfork = pindexBest;
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return error("Reorganize() : plonger->pprev is null");
if (pfork == plonger)
break;
if (!(pfork = pfork->pprev))
return error("Reorganize() : pfork->pprev is null");
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
LogPrintf("REORGANIZE: Disconnect %u blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString(), pindexBest->GetBlockHash().ToString());
LogPrintf("REORGANIZE: Connect %u blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString(), pindexNew->GetBlockHash().ToString());
// Disconnect shorter branch
list<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for disconnect failed");
if (!block.DisconnectBlock(txdb, pindex))
return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString());
// Queue memory transactions to resurrect.
// We only do this for blocks after the last checkpoint (reorganisation before that
// point should only happen with -reindex/-loadblock, or a misbehaving peer.
BOOST_REVERSE_FOREACH(const CTransaction& tx, block.vtx)
if (!(tx.IsCoinBase() || tx.IsCoinStake()) && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
vResurrect.push_front(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
for (unsigned int i = 0; i < vConnect.size(); i++)
{
CBlockIndex* pindex = vConnect[i];
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for connect failed");
if (!block.ConnectBlock(txdb, pindex))
{
// Invalid block
return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString());
}
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
return error("Reorganize() : WriteHashBestChain failed");
// Make sure it's successfully written to disk before changing memory structure
if (!txdb.TxnCommit())
return error("Reorganize() : TxnCommit failed");
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect)
AcceptToMemoryPool(mempool, tx, false, NULL);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete) {
mempool.remove(tx);
mempool.removeConflicts(tx);
}
LogPrintf("REORGANIZE: done\n");
return true;
}
// Called from inside SetBestChain: attaches a block to the new best chain being built
bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
{
uint256 hash = GetHash();
// Adding to current best branch
if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return false;
}
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
// Add to current best branch
pindexNew->pprev->pnext = pindexNew;
// Delete redundant memory transactions
BOOST_FOREACH(CTransaction& tx, vtx)
mempool.remove(tx);
return true;
}
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
{
uint256 hash = GetHash();
if (!txdb.TxnBegin())
return error("SetBestChain() : TxnBegin failed");
if (pindexGenesisBlock == NULL && hash == Params().HashGenesisBlock())
{
txdb.WriteHashBestChain(hash);
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
pindexGenesisBlock = pindexNew;
}
else if (hashPrevBlock == hashBestChain)
{
if (!SetBestChainInner(txdb, pindexNew))
return error("SetBestChain() : SetBestChainInner failed");
}
else
{
// the first block in the new chain that will cause it to become the new best chain
CBlockIndex *pindexIntermediate = pindexNew;
// list of blocks that need to be connected afterwards
std::vector<CBlockIndex*> vpindexSecondary;
// Reorganize is costly in terms of db load, as it works in a single db transaction.
// Try to limit how much needs to be done inside
while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
{
vpindexSecondary.push_back(pindexIntermediate);
pindexIntermediate = pindexIntermediate->pprev;
}
if (!vpindexSecondary.empty())
LogPrintf("Postponing %u reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return error("SetBestChain() : Reorganize failed");
}
// Connect further blocks
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
{
LogPrintf("SetBestChain() : ReadFromDisk failed\n");
break;
}
if (!txdb.TxnBegin()) {
LogPrintf("SetBestChain() : TxnBegin 2 failed\n");
break;
}
// errors now are not fatal, we still did a reorganisation to a new chain in a valid way
if (!block.SetBestChainInner(txdb, pindex))
break;
}
}
// Update best block in wallet (so we can detect restored wallets)
bool fIsInitialDownload = IsInitialBlockDownload();
if ((pindexNew->nHeight % 20160) == 0 || (!fIsInitialDownload && (pindexNew->nHeight % 144) == 0))
{
const CBlockLocator locator(pindexNew);
g_signals.SetBestChain(locator);
}
// New best block
hashBestChain = hash;
pindexBest = pindexNew;
pblockindexFBBHLast = NULL;
nBestHeight = pindexBest->nHeight;
nBestChainTrust = pindexNew->nChainTrust;
nTimeBestReceived = GetTime();
mempool.AddTransactionsUpdated(1);
uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
LogPrintf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%d date=%s\n",
hashBestChain.ToString(), nBestHeight,
CBigNum(nBestChainTrust).ToString(),
nBestBlockTrust.Get64(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()));
// Check the version of the last 100 blocks to see if we need to upgrade:
if (!fIsInitialDownload)
{
int nUpgraded = 0;
const CBlockIndex* pindex = pindexBest;
for (int i = 0; i < 100 && pindex != NULL; i++)
{
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
if (nUpgraded > 100/2)
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
}
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
// ppcoin: total coin age spent in transaction, in the unit of coin-days.
// Only those coins meeting minimum age requirement counts. As those
// transactions not in main chain are not currently indexed so we
// might not find out about their coin age. Older transactions are
// guaranteed to be in main chain by sync-checkpoint. This rule is
// introduced to help nodes establish a consistent view of the coin
// age (trust Bitrewards) of competing branches.
bool CTransaction::GetCoinAge(CTxDB& txdb, const CBlockIndex* pindexPrev, uint64_t& nCoinAge) const
{
CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
nCoinAge = 0;
if (IsCoinBase())
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// First try finding the previous transaction in database
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
continue; // previous transaction not in main chain
if (nTime < txPrev.nTime)
return false; // Transaction timestamp violation
// Read block header
CBlock block;
if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
return false; // unable to read block of previous transaction
if (block.GetBlockTime() + nStakeMinAge > nTime)
continue; // only count coins meeting min age requirement
int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
LogPrint("coinage", "coin age nValueIn=%d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString());
}
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
LogPrint("coinage", "coin age bnCoinDay=%s\n", bnCoinDay.ToString());
nCoinAge = bnCoinDay.getuint64();
return true;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, const uint256& hashProof)
{
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AddToBlockIndex() : %s already exists", hash.ToString());
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
pindexNew->phashBlock = &hash;
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
// ppcoin: compute chain trust Bitrewards
pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
// ppcoin: compute stake entropy bit for stake modifier
if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit()))
return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
// Record proof hash value
pindexNew->hashProof = hashProof;
// ppcoin: compute stake modifier
uint64_t nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
// Add to mapBlockIndex
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
// Write to disk block index
CTxDB txdb;
if (!txdb.TxnBegin())
return false;
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
if (!txdb.TxnCommit())
return false;
// New best
if (pindexNew->nChainTrust > nBestChainTrust)
if (!SetBestChain(txdb, pindexNew))
return false;
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
g_signals.UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = vtx[0].GetHash();
}
return true;
}
bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CheckBlock() : size limits failed"));
// Check proof of work matches claimed amount
if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetPoWHash(), nBits))
return DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
return error("CheckBlock() : block timestamp too far in the future");
// First transaction must be coinbase, the rest must not be
if (vtx.empty() || !vtx[0].IsCoinBase())
return DoS(100, error("CheckBlock() : first tx is not coinbase"));
for (unsigned int i = 1; i < vtx.size(); i++)
if (vtx[i].IsCoinBase())
return DoS(100, error("CheckBlock() : more than one coinbase"));
if (IsProofOfStake())
{
// Coinbase output should be empty if proof-of-stake block
if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
// Second transaction must be coinstake, the rest must not be
if (vtx.empty() || !vtx[1].IsCoinStake())
return DoS(100, error("CheckBlock() : second tx is not coinstake"));
for (unsigned int i = 2; i < vtx.size(); i++)
if (vtx[i].IsCoinStake())
return DoS(100, error("CheckBlock() : more than one coinstake"));
}
// Check proof-of-stake block signature
if (fCheckSig && !CheckBlockSignature())
return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
// ----------- instantX transaction scanning -----------
if(IsSporkActive(SPORK_3_INSTANTX_BLOCK_FILTERING)){
BOOST_FOREACH(const CTransaction& tx, vtx){
if (!tx.IsCoinBase()){
//only reject blocks when it's based on complete consensus
BOOST_FOREACH(const CTxIn& in, tx.vin){
if(mapLockedInputs.count(in.prevout)){
if(mapLockedInputs[in.prevout] != tx.GetHash()){
if(fDebug) { LogPrintf("CheckBlock() : found conflicting transaction with transaction lock %s %s\n", mapLockedInputs[in.prevout].ToString().c_str(), tx.GetHash().ToString().c_str()); }
return DoS(0, error("CheckBlock() : found conflicting transaction with transaction lock"));
}
}
}
}
}
} else{
if(fDebug) { LogPrintf("CheckBlock() : skipping transaction locking checks\n"); }
}
// ----------- masternode payments -----------
bool MasternodePayments = false;
bool fIsInitialDownload = IsInitialBlockDownload();
if(nTime > START_MASTERNODE_PAYMENTS) MasternodePayments = true;
if (!fIsInitialDownload)
{
if(MasternodePayments)
{
LOCK2(cs_main, mempool.cs);
CBlockIndex *pindex = pindexBest;
if(IsProofOfStake() && pindex != NULL){
if(pindex->GetBlockHash() == hashPrevBlock){
// If we don't already have its previous block, skip masternode payment step
CAmount masternodePaymentAmount;
for (int i = vtx[1].vout.size(); i--> 0; ) {
masternodePaymentAmount = vtx[1].vout[i].nValue;
break;
}
bool foundPaymentAmount = false;
bool foundPayee = false;
bool foundPaymentAndPayee = false;
bool foundDevFee = true;
CScript payee;
CTxIn vin;
if(!masternodePayments.GetBlockPayee(pindexBest->nHeight+1, payee, vin) || payee == CScript()){
foundPayee = true; //doesn't require a specific payee
foundPaymentAmount = true;
foundPaymentAndPayee = true;
if(fDebug) { LogPrintf("CheckBlock() : Using non-specific masternode payments %d\n", pindexBest->nHeight+1); }
}
for (unsigned int i = 0; i < vtx[1].vout.size(); i++) {
if(vtx[1].vout[i].nValue == masternodePaymentAmount )
foundPaymentAmount = true;
if(vtx[1].vout[i].scriptPubKey == payee )
foundPayee = true;
if(vtx[1].vout[i].nValue == masternodePaymentAmount && vtx[1].vout[i].scriptPubKey == payee)
foundPaymentAndPayee = true;
}
CTxDestination address1;
ExtractDestination(payee, address1);
CBitrewardscoinAddress address2(address1);
if (!foundDevFee) {
if(fDebug) { LogPrintf("CheckBlock() : Couldn't find devfee payment(%d|%d) or payee(%d|%s) nHeight %d. \n", foundPaymentAmount, masternodePaymentAmount, foundPayee, address2.ToString().c_str(), pindexBest->nHeight+1); }
return DoS(100, error("CheckBlock() : Couldn't find devfee payment or payee"));
} else if(!foundPaymentAndPayee) {
if(fDebug) { LogPrintf("CheckBlock() : Couldn't find masternode payment(%d|%d) or payee(%d|%s) nHeight %d. \n", foundPaymentAmount, masternodePaymentAmount, foundPayee, address2.ToString().c_str(), pindexBest->nHeight+1); }
return DoS(100, error("CheckBlock() : Couldn't find masternode payment or payee"));
} else {
LogPrintf("CheckBlock() : Found payment(%d|%d) or payee(%d|%s) nHeight %d. \n", foundPaymentAmount, masternodePaymentAmount, foundPayee, address2.ToString().c_str(), pindexBest->nHeight+1);
}
} else {
if(fDebug) { LogPrintf("CheckBlock() : Skipping masternode payment check - nHeight %d Hash %s\n", pindexBest->nHeight+1, GetHash().ToString().c_str()); }
}
} else {
if(fDebug) { LogPrintf("CheckBlock() : pindex is null, skipping masternode payment check\n"); }
}
} else {
if(fDebug) { LogPrintf("CheckBlock() : skipping masternode payment checks\n"); }
}
} else {
if(fDebug) { LogPrintf("CheckBlock() : Is initial download, skipping masternode payment check %d\n", pindexBest->nHeight+1); }
}
// Check transactions
BOOST_FOREACH(const CTransaction& tx, vtx)
{
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
// ppcoin: check transaction timestamp
if (GetBlockTime() < (int64_t)tx.nTime)
return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
}
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
set<uint256> uniqueTx;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uniqueTx.insert(tx.GetHash());
}
if (uniqueTx.size() != vtx.size())
return DoS(100, error("CheckBlock() : duplicate transaction"));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
nSigOps += GetLegacySigOpCount(tx);
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkle root
if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
return true;
}
bool CBlock::AcceptBlock()
{
AssertLockHeld(cs_main);
// Remove for BIP-0034 FORK
if (nVersion > CURRENT_VERSION)
return DoS(100, error("AcceptBlock() : reject unknown block version %d", nVersion));
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
int nHeight = pindexPrev->nHeight+1;
uint256 hashProof;
if (IsProofOfWork() && nHeight > Params().LastPOWBlock()){
return DoS(100, error("AcceptBlock() : reject proof-of-work at height %d", nHeight));
} else {
// PoW is checked in CheckBlock()
if (IsProofOfWork())
{
hashProof = GetPoWHash();
}
}
if (IsProofOfStake() && nHeight < Params().POSStartBlock())
return DoS(100, error("AcceptBlock() : reject proof-of-stake at height <= %d", nHeight));
// Check coinbase timestamp
if (GetBlockTime() > FutureDrift((int64_t)vtx[0].nTime) && IsProofOfStake())
return DoS(50, error("AcceptBlock() : coinbase timestamp is too early"));
// Check coinstake timestamp
if (IsProofOfStake() && !CheckCoinStakeTimestamp(nHeight, GetBlockTime(), (int64_t)vtx[1].nTime))
return DoS(50, error("AcceptBlock() : coinstake timestamp violation nTimeBlock=%d nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
// Check proof-of-work or proof-of-stake
if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetPastTimeLimit() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!IsFinalTx(tx, nHeight, GetBlockTime()))
return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckHardened(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
// Verify hash target and signature of coinstake tx
if (IsProofOfStake())
{
uint256 targetProofOfStake;
if (!CheckProofOfStake(pindexPrev, vtx[1], nBits, hashProof, targetProofOfStake))
{
return error("AcceptBlock() : check proof-of-stake failed for block %s", hash.ToString());
}
}
// Check that the block satisfies synchronized checkpoint
if (!Checkpoints::CheckSync(nHeight))
return error("AcceptBlock() : rejected by synchronized checkpoint");
// EnBitrewards rule that the coinbase starts with serialized block height
CScript expect = CScript() << nHeight;
if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
// Write block to history file
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
return error("AcceptBlock() : out of disk space");
unsigned int nFile = -1;
unsigned int nBlockPos = 0;
if (!WriteToDisk(nFile, nBlockPos))
return error("AcceptBlock() : WriteToDisk failed");
if (!AddToBlockIndex(nFile, nBlockPos, hashProof))
return error("AcceptBlock() : AddToBlockIndex failed");
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
return true;
}
uint256 CBlockIndex::GetBlockTrust() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
return ((CBigNum(1)<<256) / (bnTarget+1)).getuint256();
}
void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pnode->pindexLastGetBlocksBegin && hashEnd == pnode->hashLastGetBlocksEnd)
return;
pnode->pindexLastGetBlocksBegin = pindexBegin;
pnode->hashLastGetBlocksEnd = hashEnd;
pnode->PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
bool static IsCanonicalBlockSignature(CBlock* pblock)
{
if (pblock->IsProofOfWork()) {
return pblock->vchBlockSig.empty();
}
return IsDERSignature(pblock->vchBlockSig, false);
}
void Misbehaving(NodeId pnode, int howmuch)
{
if (howmuch == 0)
return;
CNodeState *state = State(pnode);
if (state == NULL)
return;
state->nMisbehavior += howmuch;
if (state->nMisbehavior >= GetArg("-banBitrewards", 100))
{
LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name.c_str(), state->nMisbehavior-howmuch, state->nMisbehavior);
state->fShouldBan = true;
} else
LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name.c_str(), state->nMisbehavior-howmuch, state->nMisbehavior);
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString());
if (mapOrphanBlocks.count(hash))
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString());
// ppcoin: check proof-of-stake
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (!fReindex && !fImporting && pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString(), pblock->GetProofOfStake().second, hash.ToString());
if (pblock->hashPrevBlock != hashBestChain)
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
const CBlockIndex* pcheckpoint = Checkpoints::AutoSelectSyncCheckpoint();
int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
if (deltaTime < 0)
{
if (pfrom)
Misbehaving(pfrom->GetId(), 1);
return error("ProcessBlock() : block with timestamp before last checkpoint");
}
}
// Block signature can be malleated in such a way that it increases block size up to maximum allowed by protocol
// For now we just strip garbage from newly received blocks
if (!IsCanonicalBlockSignature(pblock)) {
return error("ProcessBlock(): bad block signature encoding");
}
// Preliminary checks
if (!pblock->CheckBlock())
return error("ProcessBlock() : CheckBlock FAILED");
// If we don't already have its previous block, shunt it off to holding area until we get it
if (!mapBlockIndex.count(pblock->hashPrevBlock))
{
LogPrintf("ProcessBlock: ORPHAN BLOCK %lu, prev=%s\n", (unsigned long)mapOrphanBlocks.size(), pblock->hashPrevBlock.ToString());
// Accept orphans as long as there is a node to request its parents from
if (pfrom) {
// ppcoin: check proof-of-stake
if (pblock->IsProofOfStake())
{
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock->GetProofOfStake().first.ToString(), pblock->GetProofOfStake().second, hash.ToString());
}
PruneOrphanBlocks();
COrphanBlock* pblock2 = new COrphanBlock();
{
CDataStream ss(SER_DISK, CLIENT_VERSION);
ss << *pblock;
pblock2->vchBlock = std::vector<unsigned char>(ss.begin(), ss.end());
}
pblock2->hashBlock = hash;
pblock2->hashPrev = pblock->hashPrevBlock;
pblock2->stake = pblock->GetProofOfStake();
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrev, pblock2));
if (pblock->IsProofOfStake())
setStakeSeenOrphan.insert(pblock->GetProofOfStake());
// Ask this guy to fill in what we're missing
PushGetBlocks(pfrom, pindexBest, GetOrphanRoot(hash));
// ppcoin: getblocks may not obtain the ancestor block rejected
// earlier by duplicate-stake check so we ask for it again directly
if (!IsInitialBlockDownload())
pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
}
return true;
}
// Store to disk
if (!pblock->AcceptBlock())
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, COrphanBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
CBlock block;
{
CDataStream ss(mi->second->vchBlock, SER_DISK, CLIENT_VERSION);
ss >> block;
}
block.BuildMerkleTree();
if (block.AcceptBlock())
vWorkQueue.push_back(mi->second->hashBlock);
mapOrphanBlocks.erase(mi->second->hashBlock);
setStakeSeenOrphan.erase(block.GetProofOfStake());
delete mi->second;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
if(!IsInitialBlockDownload()){
CScript payee;
CTxIn vin;
// If we're in LiteMode disable darksend features without disabling masternodes
if (!fLiteMode && !fImporting && !fReindex && pindexBest->nHeight > Checkpoints::GetTotalBlocksEstimate()){
if(masternodePayments.GetBlockPayee(pindexBest->nHeight, payee, vin)){
//UPDATE MASTERNODE LAST PAID TIME
CMasternode* pmn = mnodeman.Find(vin);
if(pmn != NULL) {
pmn->nLastPaid = GetAdjustedTime();
}
LogPrintf("ProcessBlock() : Update Masternode Last Paid Time - %d\n", pindexBest->nHeight);
}
darkSendPool.CheckTimeout();
darkSendPool.NewBlock();
masternodePayments.ProcessBlock(GetHeight()+10);
} else if (fLiteMode && !fImporting && !fReindex && pindexBest->nHeight > Checkpoints::GetTotalBlocksEstimate())
{
if(masternodePayments.GetBlockPayee(pindexBest->nHeight, payee, vin)){
//UPDATE MASTERNODE LAST PAID TIME
CMasternode* pmn = mnodeman.Find(vin);
if(pmn != NULL) {
pmn->nLastPaid = GetAdjustedTime();
}
LogPrintf("ProcessBlock() : Update Masternode Last Paid Time - %d\n", pindexBest->nHeight);
}
masternodePayments.ProcessBlock(GetHeight()+10);
}
}
LogPrintf("ProcessBlock: ACCEPTED\n");
return true;
}
#ifdef ENABLE_WALLET
// novacoin: attempt to generate suitable proof-of-stake
bool CBlock::SignBlock(CWallet& wallet, int64_t nFees)
{
// if we are trying to sign
// something except proof-of-stake block template
if (!vtx[0].vout[0].IsEmpty())
return false;
// if we are trying to sign
// a complete proof-of-stake block
if (IsProofOfStake())
return true;
static int64_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
CKey key;
CTransaction txCoinStake;
txCoinStake.nTime &= ~STAKE_TIMESTAMP_MASK;
int64_t nSearchTime = txCoinStake.nTime; // search to current time
if (nSearchTime > nLastCoinStakeSearchTime)
{
int64_t nSearchInterval = 1;
if (wallet.CreateCoinStake(wallet, nBits, nSearchInterval, nFees, txCoinStake, key))
{
if (txCoinStake.nTime >= pindexBest->GetPastTimeLimit()+1)
{
// make sure coinstake would meet timestamp protocol
// as it would be the same as the block timestamp
vtx[0].nTime = nTime = txCoinStake.nTime;
// we have to make sure that we have no future timestamps in
// our transactions set
for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
vtx.insert(vtx.begin() + 1, txCoinStake);
hashMerkleRoot = BuildMerkleTree();
// append a signature to our block
return key.Sign(GetHash(), vchBlockSig);
}
}
nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
nLastCoinStakeSearchTime = nSearchTime;
}
return false;
}
#endif
bool CBlock::CheckBlockSignature() const
{
if (IsProofOfWork())
return vchBlockSig.empty();
if (vchBlockSig.empty())
return false;
vector<valtype> vSolutions;
txnouttype whichType;
const CTxOut& txout = vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
valtype& vchPubKey = vSolutions[0];
return CPubKey(vchPubKey).Verify(GetHash(), vchBlockSig);
}
return false;
}
bool CheckDiskSpace(uint64_t nAdditionalBytes)
{
uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
{
string strMessage = _("Error: Disk space is low!");
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return false;
}
return true;
}
static filesystem::path BlockFilePath(unsigned int nFile)
{
string strBlockFn = strprintf("blk%04u.dat", nFile);
return GetDataDir() / strBlockFn;
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if ((nFile < 1) || (nFile == (unsigned int) -1))
return NULL;
FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
if (!file)
return NULL;
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
{
if (fseek(file, nBlockPos, SEEK_SET) != 0)
{
fclose(file);
return NULL;
}
}
return file;
}
static unsigned int nCurrentBlockFile = 1;
FILE* AppendBlockFile(unsigned int& nFileRet)
{
nFileRet = 0;
while (true)
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
bool LoadBlockIndex(bool fAllowNew)
{
LOCK(cs_main);
if (TestNet())
{
nCoinbaseMaturity = 10; // test maturity is 10 blocks
}
//
// Load block index
//
CTxDB txdb("cr+");
if (!txdb.LoadBlockIndex())
return false;
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
// Start new block file
unsigned int nFile;
unsigned int nBlockPos;
if (!block.WriteToDisk(nFile, nBlockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(nFile, nBlockPos, Params().HashGenesisBlock()))
return error("LoadBlockIndex() : genesis block not accepted");
}
return true;
}
void PrintBlockTree()
{
AssertLockHeld(cs_main);
// pre-compute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
LogPrintf("| ");
LogPrintf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
LogPrintf("| ");
LogPrintf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
LogPrintf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
#ifndef LOWMEM
LogPrintf("%d (%u,%u) %s %08x %s mint %7s tx %u",
#else
LogPrintf("%d (%u,%u) %s %08x %s tx %u",
#endif
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
block.GetHash().ToString(),
block.nBits,
DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()),
#ifndef LOWMEM
FormatMoney(pindex->nMint),
#endif
block.vtx.size());
// put the main time-chain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
bool LoadExternalBlockFile(FILE* fileIn)
{
int64_t nStart = GetTimeMillis();
int nLoaded = 0;
{
try {
CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
unsigned int nPos = 0;
while (nPos != (unsigned int)-1 && blkdat.good())
{
boost::this_thread::interruption_point();
unsigned char pchData[65536];
do {
fseek(blkdat.Get(), nPos, SEEK_SET);
int nRead = fread(pchData, 1, sizeof(pchData), blkdat.Get());
if (nRead <= 8)
{
nPos = (unsigned int)-1;
break;
}
void* nFind = memchr(pchData, Params().MessageStart()[0], nRead+1-MESSAGE_START_SIZE);
if (nFind)
{
if (memcmp(nFind, Params().MessageStart(), MESSAGE_START_SIZE)==0)
{
nPos += ((unsigned char*)nFind - pchData) + MESSAGE_START_SIZE;
break;
}
nPos += ((unsigned char*)nFind - pchData) + 1;
}
else
nPos += sizeof(pchData) - MESSAGE_START_SIZE + 1;
boost::this_thread::interruption_point();
} while(true);
if (nPos == (unsigned int)-1)
break;
fseek(blkdat.Get(), nPos, SEEK_SET);
unsigned int nSize;
blkdat >> nSize;
if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
{
CBlock block;
blkdat >> block;
LOCK(cs_main);
if (ProcessBlock(NULL,&block))
{
nLoaded++;
nPos += 4 + nSize;
}
}
}
}
catch (std::exception &e) {
LogPrintf("%s() : Deserialize or I/O error caught during load\n",
__PRETTY_FUNCTION__);
}
}
LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
RenameThread("Bitrewards-loadblk");
CImportingNow imp;
// -loadblock=
BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
FILE *file = fopen(path.string().c_str(), "rb");
if (file)
LoadExternalBlockFile(file);
}
// hardcoded $DATADIR/bootstrap.dat
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
extern map<uint256, CAlert> mapAlerts;
extern CCriticalSection cs_mapAlerts;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode", false))
strRPC = "test";
if (!CLIENT_VERSION_IS_RELEASE)
strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
if (nPriority > 1000)
strRPC = strStatusBar;
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
{
switch (inv.type)
{
case MSG_DSTX:
return mapDarksendBroadcastTxes.count(inv.hash);
case MSG_TX:
{
bool txInMap = false;
txInMap = mempool.exists(inv.hash);
return txInMap ||
mapOrphanTransactions.count(inv.hash) ||
txdb.ContainsTx(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
case MSG_TXLOCK_REQUEST:
return mapTxLockReq.count(inv.hash) ||
mapTxLockReqRejected.count(inv.hash);
case MSG_TXLOCK_VOTE:
return mapTxLockVote.count(inv.hash);
case MSG_SPORK:
return mapSporks.count(inv.hash);
case MSG_MASTERNODE_WINNER:
return mapSeenMasternodeVotes.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
void static ProcessGetData(CNode* pfrom)
{
std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
vector<CInv> vNotFound;
LOCK(cs_main);
while (it != pfrom->vRecvGetData.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
const CInv &inv = *it;
{
boost::this_thread::interruption_point();
it++;
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
pfrom->PushMessage("block", block);
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
if(fDebug) LogPrintf("ProcessGetData -- Starting \n");
// Send stream from relay memory
bool pushed = false;
/*{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end()) {
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
if(fDebug) LogPrintf("ProcessGetData -- pushed = true Rest will fail\n");
pushed = true;
}
}*/
if (!pushed && inv.type == MSG_TX) {
CTransaction tx;
if (mempool.lookup(inv.hash, tx)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << tx;
pfrom->PushMessage("tx", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TXLOCK_VOTE) {
if(mapTxLockVote.count(inv.hash)){
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapTxLockVote[inv.hash];
pfrom->PushMessage("txlvote", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TXLOCK_REQUEST) {
if(mapTxLockReq.count(inv.hash)){
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapTxLockReq[inv.hash];
pfrom->PushMessage("txlreq", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_SPORK) {
if(mapSporks.count(inv.hash)){
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapSporks[inv.hash];
pfrom->PushMessage("spork", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_MASTERNODE_WINNER) {
if(mapSeenMasternodeVotes.count(inv.hash)){
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapSeenMasternodeVotes[inv.hash];
pfrom->PushMessage("mnw", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_DSTX) {
if(mapDarksendBroadcastTxes.count(inv.hash)){
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss <<
mapDarksendBroadcastTxes[inv.hash].tx <<
mapDarksendBroadcastTxes[inv.hash].vin <<
mapDarksendBroadcastTxes[inv.hash].vchSig <<
mapDarksendBroadcastTxes[inv.hash].sigTime;
pfrom->PushMessage("dstx", ss);
pushed = true;
}
}
if (!pushed) {
vNotFound.push_back(inv);
}
}
// Track requests for our stuff.
g_signals.Inventory(inv.hash);
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
break;
}
}
pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
if (!vNotFound.empty()) {
// Let the peer know that we didn't find what it asked for, so it doesn't
// have to wait around forever. Currently only SPV clients actually care
// about this message: it's needed when they are recursively walking the
// dependencies of relevant unconfirmed transactions. SPV clients want to
// do that because they want to know about (and store and rebroadcast and
// risk analyze) the dependencies of transactions relevant to them, without
// having to download the entire memory pool.
pfrom->PushMessage("notfound", vNotFound);
}
}
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
RandAddSeedPerfmon();
LogPrint("net", "received: %s (%u bytes)\n", strCommand, vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
Misbehaving(pfrom->GetId(), 1);
return false;
}
int64_t nTime;
CAddress addrMe;
CAddress addrFrom;
uint64_t nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
{
// disconnect from peers older than this proto version
LogPrintf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty()) {
vRecv >> pfrom->strSubVer;
pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
}
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (!vRecv.empty())
pfrom->fRelayTxes = true;
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
pfrom->fDisconnect = true;
return true;
}
if (pfrom->fInbound && addrMe.IsRoutable())
{
pfrom->addrLocal = addrMe;
SeenLocal(addrMe);
}
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
// Change version
pfrom->PushMessage("verack");
pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
{
pfrom->PushAddress(addr);
} else if (IsPeerAddrLocalGood(pfrom)) {
addr.SetIP(pfrom->addrLocal);
pfrom->PushAddress(addr);
}
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
{
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
LogPrintf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString(), addrFrom.ToString(), pfrom->addr.ToString());
if (GetBoolArg("-synctime", true)){
AddTimeData(pfrom->addr, nTime);
}
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
Misbehaving(pfrom->GetId(), 1);
return false;
}
else if (strCommand == "verack")
{
pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000)
{
Misbehaving(pfrom->GetId(), 20);
return error("message addr size() = %u", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
boost::this_thread::interruption_point();
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64_t hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
Misbehaving(pfrom->GetId(), 20);
return error("message inv size() = %u", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
LOCK(cs_main);
CTxDB txdb("r");
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
boost::this_thread::interruption_point();
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(txdb, inv);
LogPrint("net", " got inventory: %s %s\n", inv.ToString(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave) {
if (!fImporting)
pfrom->AskFor(inv);
} else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
PushGetBlocks(pfrom, pindexBest, GetOrphanRoot(inv.hash));
} else if (nInv == nLastBlock) {
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
PushGetBlocks(pfrom, mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
LogPrintf("Bitrewards request: %s\n", inv.ToString());
}
// Track requests for our stuff
g_signals.Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
Misbehaving(pfrom->GetId(), 20);
return error("message getdata size() = %u", vInv.size());
}
if (fDebug || (vInv.size() != 1))
LogPrint("net", "received getdata (%u invsz)\n", vInv.size());
if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
LogPrint("net", "received getdata for: %s\n", vInv[0].ToString());
pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
ProcessGetData(pfrom);
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 500;
LogPrint("net", "getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
if (IsInitialBlockDownload())
return true;
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
int nLimit = 2000;
LogPrint("net", "getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx"|| strCommand == "dstx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CTransaction tx;
//masternode signed transaction
bool ignoreFees = false;
CTxIn vin;
CInv inv;
vector<unsigned char> vchSig;
int64_t sigTime;
CTxDB txdb("r");
if(strCommand == "tx") {
vRecv >> tx;
inv = CInv(MSG_TX, tx.GetHash());
// Check for recently rejected (and do other quick existence checks)
if (AlreadyHave(txdb, inv))
return true;
}
else if (strCommand == "dstx") {
vRecv >> tx >> vin >> vchSig >> sigTime;
inv = CInv(MSG_DSTX, tx.GetHash());
// Check for recently rejected (and do other quick existence checks)
if (AlreadyHave(txdb, inv))
return true;
//these allow masternodes to publish a limited amount of free transactions
CMasternode* pmn = mnodeman.Find(vin);
if(pmn != NULL)
{
if(!pmn->allowFreeTx){
//multiple peers can send us a valid masternode transaction
if(fDebug) LogPrintf("dstx: Masternode sending too many transactions %s\n", tx.GetHash().ToString().c_str());
return true;
}
std::string strMessage = tx.GetHash().ToString() + boost::lexical_cast<std::string>(sigTime);
std::string errorMessage = "";
if(!darkSendSigner.VerifyMessage(pmn->pubkey2, vchSig, strMessage, errorMessage)){
LogPrintf("dstx: Got bad masternode address signature %s \n", vin.ToString().c_str());
//Misbehaving(pfrom->GetId(), 20);
return false;
}
LogPrintf("dstx: Got Masternode transaction %s\n", tx.GetHash().ToString().c_str());
ignoreFees = true;
pmn->allowFreeTx = false;
if(!mapDarksendBroadcastTxes.count(tx.GetHash())){
CDarksendBroadcastTx dstx;
dstx.tx = tx;
dstx.vin = vin;
dstx.vchSig = vchSig;
dstx.sigTime = sigTime;
mapDarksendBroadcastTxes.insert(make_pair(tx.GetHash(), dstx));
}
}
}
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
bool fMissingInputs = false;
pfrom->setAskFor.erase(inv.hash);
mapAlreadyAskedFor.erase(inv);
if (AcceptToMemoryPool(mempool, tx, true, &fMissingInputs, false, ignoreFees))
{
RelayTransaction(tx, inv.hash);
vWorkQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
if (itByPrev == mapOrphanTransactionsByPrev.end())
continue;
for (set<uint256>::iterator mi = itByPrev->second.begin();
mi != itByPrev->second.end();
++mi)
{
const uint256& orphanTxHash = *mi;
CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
bool fMissingInputs2 = false;
if (AcceptToMemoryPool(mempool, orphanTx, true, &fMissingInputs2))
{
LogPrint("mempool", " accepted orphan tx %s\n", orphanTxHash.ToString());
RelayTransaction(orphanTx, orphanTxHash);
vWorkQueue.push_back(orphanTxHash);
vEraseQueue.push_back(orphanTxHash);
}
else if (!fMissingInputs2)
{
// Has inputs but not accepted to mempool
// Probably non-standard or insufficient fee/priority
vEraseQueue.push_back(orphanTxHash);
LogPrint("mempool", " removed orphan tx %s\n", orphanTxHash.ToString());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(tx);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
if (nEvicted > 0)
LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
}
if(strCommand == "dstx"){
inv = CInv(MSG_DSTX, tx.GetHash());
RelayInventory(inv);
}
if (tx.nDoS) Misbehaving(pfrom->GetId(), tx.nDoS);
}
else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
{
CBlock block;
vRecv >> block;
uint256 hashBlock = block.GetHash();
LogPrint("net", "received block %s\n", hashBlock.ToString());
CInv inv(MSG_BLOCK, hashBlock);
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
if (ProcessBlock(pfrom, &block))
mapAlreadyAskedFor.erase(inv);
if (block.nDoS) Misbehaving(pfrom->GetId(), block.nDoS);
if (fSecMsgEnabled)
SecureMsgScanBlock(block);
}
// This asymmetric behavior for inbound and outbound connections was introduced
// to prevent a fingerprinting attack: an attacker can send specific fake addresses
// to users' AddrMan and later request them by sending getaddr messages.
// Making users (which are behind NAT and can only make outgoing connections) ignore
// getaddr message mitigates the attack.
else if ((strCommand == "getaddr") && (pfrom->fInbound))
{
// Don't return addresses older than nCutOff timestamp
int64_t nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
if(addr.nTime > nCutOff)
pfrom->PushAddress(addr);
}
else if (strCommand == "mempool")
{
LOCK(cs_main);
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
vector<CInv> vInv;
CInv inv;
for (unsigned int i = 0; i < vtxid.size(); i++) {
inv = CInv(MSG_TX, vtxid[i]);
vInv.push_back(inv);
if (i == (MAX_INV_SZ - 1))
break;
}
if (vInv.size() > 0)
pfrom->PushMessage("inv", vInv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64_t nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "pong")
{
int64_t pingUsecEnd = GetTimeMicros();
uint64_t nonce = 0;
size_t nAvail = vRecv.in_avail();
bool bPingFinished = false;
std::string sProblem;
if (nAvail >= sizeof(nonce)) {
vRecv >> nonce;
// Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
if (pfrom->nPingNonceSent != 0) {
if (nonce == pfrom->nPingNonceSent) {
// Matching pong received, this ping is no longer outstanding
bPingFinished = true;
int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
if (pingUsecTime > 0) {
// Successful ping time measurement, replace previous
pfrom->nPingUsecTime = pingUsecTime;
} else {
// This should never happen
sProblem = "Timing mishap";
}
} else {
// Nonce mismatches are normal when pings are overlapping
sProblem = "Nonce mismatch";
if (nonce == 0) {
// This is most likely a bug in another implementation somewhere, cancel this ping
bPingFinished = true;
sProblem = "Nonce zero";
}
}
} else {
sProblem = "Unsolicited pong without ping";
}
} else {
// This is most likely a bug in another implementation somewhere, cancel this ping
bPingFinished = true;
sProblem = "Short payload";
}
if (!(sProblem.empty())) {
LogPrint("net", "pong %s %s: %s, %x expected, %x received, %zu bytes\n"
, pfrom->addr.ToString()
, pfrom->strSubVer
, sProblem
, pfrom->nPingNonceSent
, nonce
, nAvail);
}
if (bPingFinished) {
pfrom->nPingNonceSent = 0;
}
}
else if (strCommand == "alert")
{
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0)
{
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
Misbehaving(pfrom->GetId(), 10);
}
}
}
else
{
if (fSecMsgEnabled)
SecureMsgReceiveData(pfrom, strCommand, vRecv);
darkSendPool.ProcessMessageDarksend(pfrom, strCommand, vRecv);
mnodeman.ProcessMessage(pfrom, strCommand, vRecv);
ProcessMessageMasternodePayments(pfrom, strCommand, vRecv);
ProcessMessageInstantX(pfrom, strCommand, vRecv);
ProcessSpork(pfrom, strCommand, vRecv);
// Ignore unknown commands for extensibility
}
// Update the last seen time for this node's address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
// requires LOCK(cs_vRecvMsg)
bool ProcessMessages(CNode* pfrom)
{
//if (fDebug)
// LogPrintf("ProcessMessages(%zu messages)\n", pfrom->vRecvMsg.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
bool fOk = true;
if (!pfrom->vRecvGetData.empty())
ProcessGetData(pfrom);
// this maintains the order of responses
if (!pfrom->vRecvGetData.empty()) return fOk;
std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
// get next message
CNetMessage& msg = *it;
//if (fDebug)
// LogPrintf("ProcessMessages(message %u msgsz, %zu bytes, complete:%s)\n",
// msg.hdr.nMessageSize, msg.vRecv.size(),
// msg.complete() ? "Y" : "N");
// end, if an incomplete message is found
if (!msg.complete())
break;
// at this point, any failure means we can delete the current message
it++;
// Scan for message start
if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
LogPrintf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
fOk = false;
break;
}
// Read header
CMessageHeader& hdr = msg.hdr;
if (!hdr.IsValid())
{
LogPrintf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
// Checksum
CDataStream& vRecv = msg.vRecv;
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
LogPrintf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
strCommand, nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Process message
bool fRet = false;
try
{
fRet = ProcessMessage(pfrom, strCommand, vRecv);
boost::this_thread::interruption_point();
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand, nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand, nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
LogPrintf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand, nMessageSize);
break;
}
// In case the connection got shut down, its receive buffer was wiped
if (!pfrom->fDisconnect)
pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
return fOk;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
//
// Message: ping
//
bool pingSend = false;
if (pto->fPingQueued) {
// RPC ping request by user
pingSend = true;
}
if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
// Ping automatically sent as a latency probe & keepalive.
pingSend = true;
}
if (pingSend) {
uint64_t nonce = 0;
while (nonce == 0) {
GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
}
pto->fPingQueued = false;
pto->nPingUsecStart = GetTimeMicros();
if (pto->nVersion > BIP0031_VERSION) {
pto->nPingNonceSent = nonce;
pto->PushMessage("ping", nonce);
} else {
// Peer is too old to support ping command with nonce, pong will never arrive.
pto->nPingNonceSent = 0;
pto->PushMessage("ping");
}
}
TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
if (!lockMain)
return true;
// Start block sync
if (pto->fStartSync && !fImporting && !fReindex) {
pto->fStartSync = false;
PushGetBlocks(pto, pindexBest, uint256(0));
}
// Resend wallet transactions that haven't gotten in a block yet
// Except during reindex, importing and IBD, when old wallet
// transactions become unconfirmed and spams other nodes.
if (!fReindex && !fImporting && !IsInitialBlockDownload())
{
ResendWalletTransactions();
}
// Address refresh broadcast
static int64_t nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
if (!fNoListen)
{
CAddress addr = GetLocalAddress(&pnode->addr);
if (addr.IsRoutable())
pnode->PushAddress(addr);
}
}
}
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second)
{
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
if (State(pto->GetId())->fShouldBan) {
if (pto->addr.IsLocal())
LogPrintf("Warning: not banning local node %s!\n", pto->addr.ToString().c_str());
else {
pto->fDisconnect = true;
CNode::Ban(pto->addr, BanReasonNodeMisbehaving);
}
State(pto->GetId())->fShouldBan = false;
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle)
{
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
if (fTrickleWait)
{
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second)
{
vInv.push_back(inv);
if (vInv.size() >= 1000)
{
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
//
// Message: getdata
//
vector<CInv> vGetData;
int64_t nNow = GetTime() * 1000000;
CTxDB txdb("r");
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(txdb, inv))
{
if (fDebug)
LogPrint("net", "sending getdata: %s\n", inv.ToString());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
} else {
//If we're not going to ask, don't expect a response.
pto->setAskFor.erase(inv.hash);
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
if (fSecMsgEnabled)
SecureMsgSendData(pto, fSendTrickle); // should be in cs_main?
}
return true;
}
| [
"36816492+crypt0n1nja@users.noreply.github.com"
] | 36816492+crypt0n1nja@users.noreply.github.com |
c9bf168bac9bba7c7d83ee7dd3206b7d2423ccd1 | 6f663a6cc620bc301d5eede361cdddabf8ead11c | /ejercitacion_dos/src/Diccionario.cpp | 11845e578013455586b0ff9dc288493ca7e73dd4 | [] | no_license | CiroCarvallo/practicar_cplusplus | b0f4b87a6ebcf80174bb32fd9483138341fd25c9 | f5e9dce48637c686e4f5393877a59a525240cbd9 | refs/heads/master | 2020-03-28T04:45:41.382215 | 2018-10-06T03:01:35 | 2018-10-06T03:01:35 | 147,735,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,404 | cpp | /* Completar */
#include "Diccionario.h"
#include <vector>
Diccionario::Diccionario(){
_diccionario;
}
void Diccionario::definir(Clave k, Valor v){
for (int i=0; i<_diccionario.size();i++){
if (_diccionario[i].clave==k){
_diccionario[i].valor=v;
return;
}
}
Asociacion a;
a.clave=k;
a.valor=v;
_diccionario.push_back(a);
}
bool Diccionario::def(Clave k) const{
for (int i=0; i<_diccionario.size();i++){
if(_diccionario[i].clave==k){
return true;
}
}
return false;
}
// asumo que clave esta en diccionario
Valor Diccionario::obtener(Clave k) const {
for (int i=0; i<_diccionario.size();i++){
if(_diccionario[i].clave==k){
return _diccionario[i].valor;
}
}
}
void Diccionario::borrar(Clave k){
for (int i=0; i<_diccionario.size();i++){
if(_diccionario[i].clave==k){
_diccionario.erase(_diccionario.begin()+i);
return;
}
}
}
std::vector <Clave> Diccionario::claves() const {
std::vector <Clave> claves;
for (int i=0; i<_diccionario.size();i++){
claves.push_back(_diccionario[i].clave);
}
return claves;
}
bool Diccionario::operator==(Diccionario o) const {
std::vector<Clave> v1;
for (int i=0; i<_diccionario.size(); i++){
v1.push_back(_diccionario[i].clave);
}
if(not esPermutacion(v1,o.claves())){return false;}
for (int i=0; i<_diccionario.size();i++){
if (_diccionario[i].valor!=o.obtener(_diccionario[i].clave)){
return false;
}
}
return true;
}
Diccionario Diccionario::operator||(Diccionario o) const {
//Diccionario d=this;
Diccionario d;
for (int i=0;i<_diccionario.size();i++){
d.definir(_diccionario[i].clave,_diccionario[i].valor);
}
std::vector<Clave> o_claves;
o_claves=o.claves();
for (int j=0;j<o_claves.size();j++){
if(not d.def(o_claves[j])){
d.definir(o_claves[j],o.obtener(o_claves[j]));
}
}
return d;
}
Diccionario Diccionario::operator&&(Diccionario o) const{
Diccionario d;
for (int i=0;i<_diccionario.size();i++){
if(o.def(_diccionario[i].clave)){
d.definir(_diccionario[i].clave,_diccionario[i].valor);
}
}
return d;
}
int cantidad(Clave k, std::vector<Clave> v1){
int cnt=0;
for (int i=0; i<v1.size();i++){
if(v1[i]==k) cnt++;
}
return cnt;
}
bool esPermutacion(std::vector<Clave> v1,std::vector <Clave> v2){
if (v1.size()!=v2.size()){return false;}
for (int i=0; i<v1.size();i++){
if(cantidad(v1[i],v1)!=cantidad(v1[i],v2)){return false;}
}
return true;
}
| [
"cirocarvallo@gmail.com"
] | cirocarvallo@gmail.com |
30f3c749f8d6ba9550bbf595e7a3b3a9ec7f64ab | e74f70cec1bf3ec49a85681ee72b9b00b1c72893 | /Checkers/CheckerEngineX/CBInterface.cpp | c4dd3102827097edcbb8704cc3a4f3db5dcc9e32 | [
"MIT"
] | permissive | CheckersGuy/DarkHorse | 9c647bee6e5ad594bd8540658ac02779c0c88639 | 16a79242d46be9663df8fbc2037768027215c6a2 | refs/heads/master | 2023-08-17T04:41:28.944045 | 2020-02-01T22:16:40 | 2020-02-01T22:16:40 | 155,374,636 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,267 | cpp | //
// Created by Robin on 02.02.2018.
//
#include "CBInterface.h"
Board playBoard;
int convIndex[32] = {0, 2, 4, 6, 9, 11, 13, 15, 16, 18, 20, 22, 25, 27, 29, 31, 32, 34, 36, 38, 41, 43, 45, 47, 48, 50,
52, 54, 57, 59, 61, 63};
char *output = nullptr;
bool initialized=false;
int getmove(int board[8][8], int color, double maxtime, char str[1024], int *playnow, int info, int unused,
struct CBmove *move) {
output = str;
Position *pos = &playBoard.pStack[playBoard.pCounter];
pos->BP=0;
pos->WP=0;
pos->K=0;
if (isBitSet(info, 0)) {
sprintf(str, "interupt");
//Natural course of the game has been interrupted;
playBoard.pCounter = 0;
}
if (color == CBWHITE) {
playBoard.pStack[playBoard.pCounter].color = WHITE;
} else {
playBoard.pStack[playBoard.pCounter].color = BLACK;
}
sprintf(str, "Some testing");
if (*playnow) {
playBoard.pCounter=0;
}
pos->BP=0;
pos->WP=0;
pos->K=0;
if (!initialized) {
sprintf(str, "initializing the engine");
initialized=true;
initialize();
}
//Trying to setup the startingPosition
int counter = 0;
std::string testString;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if ((j + i) % 2 == 0) {
uint32_t mask = 1 << S[counter];
if (board[j][i] == CBMAN + CBWHITE) {
pos->WP |= mask;
} else if (board[j][i] == CBMAN + CBBLACK) {
pos->BP |= mask;
} else if (board[j][i] == CBKING + CBBLACK) {
pos->BP |= mask;
pos->K |= mask;
} else if (board[j][i] == CBKING + CBWHITE) {
pos->WP |= mask;
pos->K |= mask;
}
counter++;
}
}
}
MoveListe liste;
getMoves(*playBoard.getPosition(), liste);
Move bestMove;
Value value = searchValue(playBoard, bestMove, 128, static_cast<uint32_t>(maxtime * 1000), false);
int from = bestMove.getFrom();
from = convIndex[S[from]];
int to = bestMove.getTo();
to = convIndex[S[to]];
board[from % 8][from / 8] = CBFREE;
if (color == CBBLACK) {
if (bestMove.isPromotion() || bestMove.getPieceType() == 1) {
board[to % 8][to / 8] = CBBLACK + CBKING;
} else {
board[to % 8][to / 8] = CBBLACK + CBMAN;
}
} else {
if (bestMove.isPromotion() || bestMove.getPieceType() == 1) {
board[to % 8][to / 8] = CBWHITE + CBKING;
} else {
board[to % 8][to / 8] = CBWHITE + CBMAN;
}
}
if (bestMove.isCapture()) {
uint32_t captures = bestMove.captures;
while (captures) {
uint32_t index = convIndex[S[__tzcnt_u32(captures)]];
captures &= captures - 1;
board[index % 8][index / 8] = CBFREE;
}
}
testString += std::to_string(to % 8) + "|" + std::to_string(from / 8);
sprintf(str, ((std::to_string(bestMove.getFrom() + 1) + "|" + std::to_string(bestMove.getTo() + 1) + "TEST: " +
std::to_string(from % 8) + "|" + std::to_string(from / 8) + " To: " + std::to_string(to % 8) + "|" +
std::to_string(to / 8)).c_str()));
playBoard.pCounter++;
return 3;
};
int enginecommand(char str[256], char reply[1024]) {
const uint32_t mbSize =10000000;
if(strcmp(str,"about")==0){
sprintf(reply,"This is a test version");
return 1;
}
if(strcmp(str,"get hashsize")==0){
//calculate the size of the hashtable in MB
uint32_t hashSize =(TT.getCapacity())*2*sizeof(Entry);
hashSize=hashSize/mbSize;
int power =0;
while((hashSize/2)){
hashSize=hashSize/2;
power++;
}
sprintf(reply,std::to_string(1<<power).c_str());
return 1;
}
if(strcmp(str,"name")==0){
sprintf(reply,"CheckerEngineX");
return 1;
}
if(strcmp(str,"set hashsize 2048")==0) {
TT.resize(((1 << 9) * mbSize) / (sizeof(Entry) * 2));
return 1;
}
return 0;
} | [
"checkersprogramming@gmail.com"
] | checkersprogramming@gmail.com |
cc62ebb771a61db00131e2b0a1eb9193385a04ce | 15c1f1bc535d4ac9ca79c0fcb9e230d71677d9b3 | /external/include/Eigen/src/Core/DenseBase.h | 68b21eea4c61edf835b93b779c97a19e9cc5bd71 | [
"MIT"
] | permissive | brookejbarton/animation-toolkit | 5bfc280bc5a1ff33e79665be8341db27091db98b | 0b14f689a5ca564d1abf7c1e735973b0a6935d04 | refs/heads/main | 2023-08-13T04:52:01.046801 | 2021-10-07T01:00:57 | 2021-10-07T01:00:57 | 402,525,604 | 0 | 0 | MIT | 2021-09-02T18:35:02 | 2021-09-02T18:35:02 | null | UTF-8 | C++ | false | false | 28,163 | h | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2007-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DENSEBASE_H
#define EIGEN_DENSEBASE_H
namespace Eigen {
namespace internal {
// The index type defined by EIGEN_DEFAULT_DENSE_INDEX_TYPE must be a signed type.
// This dummy function simply aims at checking that at compile time.
static inline void check_DenseIndex_is_signed() {
EIGEN_STATIC_ASSERT(NumTraits<DenseIndex>::IsSigned,THE_INDEX_TYPE_MUST_BE_A_SIGNED_TYPE);
}
} // end namespace internal
/** \class DenseBase
* \ingroup Core_Module
*
* \brief Base class for all dense matrices, vectors, and arrays
*
* This class is the base that is inherited by all dense objects (matrix, vector, arrays,
* and related expression types). The common Eigen API for dense objects is contained in this class.
*
* \tparam Derived is the derived type, e.g., a matrix type or an expression.
*
* This class can be extended with the help of the plugin mechanism described on the page
* \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_DENSEBASE_PLUGIN.
*
* \sa \blank \ref TopicClassHierarchy
*/
template<typename Derived> class DenseBase
#ifndef EIGEN_PARSED_BY_DOXYGEN
: public DenseCoeffsBase<Derived, internal::accessors_level<Derived>::value>
#else
: public DenseCoeffsBase<Derived,DirectWriteAccessors>
#endif // not EIGEN_PARSED_BY_DOXYGEN
{
public:
/** Inner iterator type to iterate over the coefficients of a row or column.
* \sa class InnerIterator
*/
typedef Eigen::InnerIterator<Derived> InnerIterator;
typedef typename internal::traits<Derived>::StorageKind StorageKind;
/**
* \brief The type used to store indices
* \details This typedef is relevant for types that store multiple indices such as
* PermutationMatrix or Transpositions, otherwise it defaults to Eigen::Index
* \sa \blank \ref TopicPreprocessorDirectives, Eigen::Index, SparseMatrixBase.
*/
typedef typename internal::traits<Derived>::StorageIndex StorageIndex;
/** The numeric type of the expression' coefficients, e.g. float, double, int or std::complex<float>, etc. */
typedef typename internal::traits<Derived>::Scalar Scalar;
/** The numeric type of the expression' coefficients, e.g. float, double, int or std::complex<float>, etc.
*
* It is an alias for the Scalar type */
typedef Scalar value_type;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef DenseCoeffsBase<Derived, internal::accessors_level<Derived>::value> Base;
using Base::derived;
using Base::const_cast_derived;
using Base::rows;
using Base::cols;
using Base::size;
using Base::rowIndexByOuterInner;
using Base::colIndexByOuterInner;
using Base::coeff;
using Base::coeffByOuterInner;
using Base::operator();
using Base::operator[];
using Base::x;
using Base::y;
using Base::z;
using Base::w;
using Base::stride;
using Base::innerStride;
using Base::outerStride;
using Base::rowStride;
using Base::colStride;
typedef typename Base::CoeffReturnType CoeffReturnType;
enum {
RowsAtCompileTime = internal::traits<Derived>::RowsAtCompileTime,
/**< The number of rows at compile-time. This is just a copy of the value provided
* by the \a Derived type. If a value is not known at compile-time,
* it is set to the \a Dynamic constant.
* \sa MatrixBase::rows(), MatrixBase::cols(), ColsAtCompileTime, SizeAtCompileTime */
ColsAtCompileTime = internal::traits<Derived>::ColsAtCompileTime,
/**< The number of columns at compile-time. This is just a copy of the value provided
* by the \a Derived type. If a value is not known at compile-time,
* it is set to the \a Dynamic constant.
* \sa MatrixBase::rows(), MatrixBase::cols(), RowsAtCompileTime, SizeAtCompileTime */
SizeAtCompileTime = (internal::size_at_compile_time<internal::traits<Derived>::RowsAtCompileTime,
internal::traits<Derived>::ColsAtCompileTime>::ret),
/**< This is equal to the number of coefficients, i.e. the number of
* rows times the number of columns, or to \a Dynamic if this is not
* known at compile-time. \sa RowsAtCompileTime, ColsAtCompileTime */
MaxRowsAtCompileTime = internal::traits<Derived>::MaxRowsAtCompileTime,
/**< This value is equal to the maximum possible number of rows that this expression
* might have. If this expression might have an arbitrarily high number of rows,
* this value is set to \a Dynamic.
*
* This value is useful to know when evaluating an expression, in order to determine
* whether it is possible to avoid doing a dynamic memory allocation.
*
* \sa RowsAtCompileTime, MaxColsAtCompileTime, MaxSizeAtCompileTime
*/
MaxColsAtCompileTime = internal::traits<Derived>::MaxColsAtCompileTime,
/**< This value is equal to the maximum possible number of columns that this expression
* might have. If this expression might have an arbitrarily high number of columns,
* this value is set to \a Dynamic.
*
* This value is useful to know when evaluating an expression, in order to determine
* whether it is possible to avoid doing a dynamic memory allocation.
*
* \sa ColsAtCompileTime, MaxRowsAtCompileTime, MaxSizeAtCompileTime
*/
MaxSizeAtCompileTime = (internal::size_at_compile_time<internal::traits<Derived>::MaxRowsAtCompileTime,
internal::traits<Derived>::MaxColsAtCompileTime>::ret),
/**< This value is equal to the maximum possible number of coefficients that this expression
* might have. If this expression might have an arbitrarily high number of coefficients,
* this value is set to \a Dynamic.
*
* This value is useful to know when evaluating an expression, in order to determine
* whether it is possible to avoid doing a dynamic memory allocation.
*
* \sa SizeAtCompileTime, MaxRowsAtCompileTime, MaxColsAtCompileTime
*/
IsVectorAtCompileTime = internal::traits<Derived>::MaxRowsAtCompileTime == 1
|| internal::traits<Derived>::MaxColsAtCompileTime == 1,
/**< This is set to true if either the number of rows or the number of
* columns is known at compile-time to be equal to 1. Indeed, in that case,
* we are dealing with a column-vector (if there is only one column) or with
* a row-vector (if there is only one row). */
Flags = internal::traits<Derived>::Flags,
/**< This stores expression \ref flags flags which may or may not be inherited by new expressions
* constructed from this one. See the \ref flags "list of flags".
*/
IsRowMajor = int(Flags) & RowMajorBit, /**< True if this expression has row-major storage order. */
InnerSizeAtCompileTime = int(IsVectorAtCompileTime) ? int(SizeAtCompileTime)
: int(IsRowMajor) ? int(ColsAtCompileTime) : int(RowsAtCompileTime),
InnerStrideAtCompileTime = internal::inner_stride_at_compile_time<Derived>::ret,
OuterStrideAtCompileTime = internal::outer_stride_at_compile_time<Derived>::ret
};
typedef typename internal::find_best_packet<Scalar,SizeAtCompileTime>::type PacketScalar;
enum { IsPlainObjectBase = 0 };
/** The plain matrix type corresponding to this expression.
* \sa PlainObject */
typedef Matrix<typename internal::traits<Derived>::Scalar,
internal::traits<Derived>::RowsAtCompileTime,
internal::traits<Derived>::ColsAtCompileTime,
AutoAlign | (internal::traits<Derived>::Flags&RowMajorBit ? RowMajor : ColMajor),
internal::traits<Derived>::MaxRowsAtCompileTime,
internal::traits<Derived>::MaxColsAtCompileTime
> PlainMatrix;
/** The plain array type corresponding to this expression.
* \sa PlainObject */
typedef Array<typename internal::traits<Derived>::Scalar,
internal::traits<Derived>::RowsAtCompileTime,
internal::traits<Derived>::ColsAtCompileTime,
AutoAlign | (internal::traits<Derived>::Flags&RowMajorBit ? RowMajor : ColMajor),
internal::traits<Derived>::MaxRowsAtCompileTime,
internal::traits<Derived>::MaxColsAtCompileTime
> PlainArray;
/** \brief The plain matrix or array type corresponding to this expression.
*
* This is not necessarily exactly the return type of eval(). In the case of plain matrices,
* the return type of eval() is a const reference to a matrix, not a matrix! It is however guaranteed
* that the return type of eval() is either PlainObject or const PlainObject&.
*/
typedef typename internal::conditional<internal::is_same<typename internal::traits<Derived>::XprKind,MatrixXpr >::value,
PlainMatrix, PlainArray>::type PlainObject;
/** \returns the number of nonzero coefficients which is in practice the number
* of stored coefficients. */
EIGEN_DEVICE_FUNC
inline Index nonZeros() const { return size(); }
/** \returns the outer size.
*
* \note For a vector, this returns just 1. For a matrix (non-vector), this is the major dimension
* with respect to the \ref TopicStorageOrders "storage order", i.e., the number of columns for a
* column-major matrix, and the number of rows for a row-major matrix. */
EIGEN_DEVICE_FUNC
Index outerSize() const
{
return IsVectorAtCompileTime ? 1
: int(IsRowMajor) ? this->rows() : this->cols();
}
/** \returns the inner size.
*
* \note For a vector, this is just the size. For a matrix (non-vector), this is the minor dimension
* with respect to the \ref TopicStorageOrders "storage order", i.e., the number of rows for a
* column-major matrix, and the number of columns for a row-major matrix. */
EIGEN_DEVICE_FUNC
Index innerSize() const
{
return IsVectorAtCompileTime ? this->size()
: int(IsRowMajor) ? this->cols() : this->rows();
}
/** Only plain matrices/arrays, not expressions, may be resized; therefore the only useful resize methods are
* Matrix::resize() and Array::resize(). The present method only asserts that the new size equals the old size, and does
* nothing else.
*/
EIGEN_DEVICE_FUNC
void resize(Index newSize)
{
EIGEN_ONLY_USED_FOR_DEBUG(newSize);
eigen_assert(newSize == this->size()
&& "DenseBase::resize() does not actually allow to resize.");
}
/** Only plain matrices/arrays, not expressions, may be resized; therefore the only useful resize methods are
* Matrix::resize() and Array::resize(). The present method only asserts that the new size equals the old size, and does
* nothing else.
*/
EIGEN_DEVICE_FUNC
void resize(Index rows, Index cols)
{
EIGEN_ONLY_USED_FOR_DEBUG(rows);
EIGEN_ONLY_USED_FOR_DEBUG(cols);
eigen_assert(rows == this->rows() && cols == this->cols()
&& "DenseBase::resize() does not actually allow to resize.");
}
#ifndef EIGEN_PARSED_BY_DOXYGEN
/** \internal Represents a matrix with all coefficients equal to one another*/
typedef CwiseNullaryOp<internal::scalar_constant_op<Scalar>,PlainObject> ConstantReturnType;
/** \internal \deprecated Represents a vector with linearly spaced coefficients that allows sequential access only. */
typedef CwiseNullaryOp<internal::linspaced_op<Scalar,PacketScalar>,PlainObject> SequentialLinSpacedReturnType;
/** \internal Represents a vector with linearly spaced coefficients that allows random access. */
typedef CwiseNullaryOp<internal::linspaced_op<Scalar,PacketScalar>,PlainObject> RandomAccessLinSpacedReturnType;
/** \internal the return type of MatrixBase::eigenvalues() */
typedef Matrix<typename NumTraits<typename internal::traits<Derived>::Scalar>::Real, internal::traits<Derived>::ColsAtCompileTime, 1> EigenvaluesReturnType;
#endif // not EIGEN_PARSED_BY_DOXYGEN
/** Copies \a other into *this. \returns a reference to *this. */
template<typename OtherDerived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator=(const DenseBase<OtherDerived>& other);
/** Special case of the template operator=, in order to prevent the compiler
* from generating a default operator= (issue hit with g++ 4.1)
*/
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator=(const DenseBase& other);
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
Derived& operator=(const EigenBase<OtherDerived> &other);
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
Derived& operator+=(const EigenBase<OtherDerived> &other);
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
Derived& operator-=(const EigenBase<OtherDerived> &other);
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
Derived& operator=(const ReturnByValue<OtherDerived>& func);
/** \internal
* Copies \a other into *this without evaluating other. \returns a reference to *this.
* \deprecated */
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
Derived& lazyAssign(const DenseBase<OtherDerived>& other);
EIGEN_DEVICE_FUNC
CommaInitializer<Derived> operator<< (const Scalar& s);
/** \deprecated it now returns \c *this */
template<unsigned int Added,unsigned int Removed>
EIGEN_DEPRECATED
const Derived& flagged() const
{ return derived(); }
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
CommaInitializer<Derived> operator<< (const DenseBase<OtherDerived>& other);
typedef Transpose<Derived> TransposeReturnType;
EIGEN_DEVICE_FUNC
TransposeReturnType transpose();
typedef typename internal::add_const<Transpose<const Derived> >::type ConstTransposeReturnType;
EIGEN_DEVICE_FUNC
ConstTransposeReturnType transpose() const;
EIGEN_DEVICE_FUNC
void transposeInPlace();
EIGEN_DEVICE_FUNC static const ConstantReturnType
Constant(Index rows, Index cols, const Scalar& value);
EIGEN_DEVICE_FUNC static const ConstantReturnType
Constant(Index size, const Scalar& value);
EIGEN_DEVICE_FUNC static const ConstantReturnType
Constant(const Scalar& value);
EIGEN_DEVICE_FUNC static const SequentialLinSpacedReturnType
LinSpaced(Sequential_t, Index size, const Scalar& low, const Scalar& high);
EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType
LinSpaced(Index size, const Scalar& low, const Scalar& high);
EIGEN_DEVICE_FUNC static const SequentialLinSpacedReturnType
LinSpaced(Sequential_t, const Scalar& low, const Scalar& high);
EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType
LinSpaced(const Scalar& low, const Scalar& high);
template<typename CustomNullaryOp> EIGEN_DEVICE_FUNC
static const CwiseNullaryOp<CustomNullaryOp, PlainObject>
NullaryExpr(Index rows, Index cols, const CustomNullaryOp& func);
template<typename CustomNullaryOp> EIGEN_DEVICE_FUNC
static const CwiseNullaryOp<CustomNullaryOp, PlainObject>
NullaryExpr(Index size, const CustomNullaryOp& func);
template<typename CustomNullaryOp> EIGEN_DEVICE_FUNC
static const CwiseNullaryOp<CustomNullaryOp, PlainObject>
NullaryExpr(const CustomNullaryOp& func);
EIGEN_DEVICE_FUNC static const ConstantReturnType Zero(Index rows, Index cols);
EIGEN_DEVICE_FUNC static const ConstantReturnType Zero(Index size);
EIGEN_DEVICE_FUNC static const ConstantReturnType Zero();
EIGEN_DEVICE_FUNC static const ConstantReturnType Ones(Index rows, Index cols);
EIGEN_DEVICE_FUNC static const ConstantReturnType Ones(Index size);
EIGEN_DEVICE_FUNC static const ConstantReturnType Ones();
EIGEN_DEVICE_FUNC void fill(const Scalar& value);
EIGEN_DEVICE_FUNC Derived& setConstant(const Scalar& value);
EIGEN_DEVICE_FUNC Derived& setLinSpaced(Index size, const Scalar& low, const Scalar& high);
EIGEN_DEVICE_FUNC Derived& setLinSpaced(const Scalar& low, const Scalar& high);
EIGEN_DEVICE_FUNC Derived& setZero();
EIGEN_DEVICE_FUNC Derived& setOnes();
EIGEN_DEVICE_FUNC Derived& setRandom();
template<typename OtherDerived> EIGEN_DEVICE_FUNC
bool isApprox(const DenseBase<OtherDerived>& other,
const RealScalar& prec = NumTraits<Scalar>::dummy_precision()) const;
EIGEN_DEVICE_FUNC
bool isMuchSmallerThan(const RealScalar& other,
const RealScalar& prec = NumTraits<Scalar>::dummy_precision()) const;
template<typename OtherDerived> EIGEN_DEVICE_FUNC
bool isMuchSmallerThan(const DenseBase<OtherDerived>& other,
const RealScalar& prec = NumTraits<Scalar>::dummy_precision()) const;
EIGEN_DEVICE_FUNC bool isApproxToConstant(const Scalar& value, const RealScalar& prec = NumTraits<Scalar>::dummy_precision()) const;
EIGEN_DEVICE_FUNC bool isConstant(const Scalar& value, const RealScalar& prec = NumTraits<Scalar>::dummy_precision()) const;
EIGEN_DEVICE_FUNC bool isZero(const RealScalar& prec = NumTraits<Scalar>::dummy_precision()) const;
EIGEN_DEVICE_FUNC bool isOnes(const RealScalar& prec = NumTraits<Scalar>::dummy_precision()) const;
inline bool hasNaN() const;
inline bool allFinite() const;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator*=(const Scalar& other);
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator/=(const Scalar& other);
typedef typename internal::add_const_on_value_type<typename internal::eval<Derived>::type>::type EvalReturnType;
/** \returns the matrix or vector obtained by evaluating this expression.
*
* Notice that in the case of a plain matrix or vector (not an expression) this function just returns
* a const reference, in order to avoid a useless copy.
*
* \warning Be carefull with eval() and the auto C++ keyword, as detailed in this \link TopicPitfalls_auto_keyword page \endlink.
*/
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE EvalReturnType eval() const
{
// Even though MSVC does not honor strong inlining when the return type
// is a dynamic matrix, we desperately need strong inlining for fixed
// size types on MSVC.
return typename internal::eval<Derived>::type(derived());
}
/** swaps *this with the expression \a other.
*
*/
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
void swap(const DenseBase<OtherDerived>& other)
{
EIGEN_STATIC_ASSERT(!OtherDerived::IsPlainObjectBase,THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY);
eigen_assert(rows()==other.rows() && cols()==other.cols());
call_assignment(derived(), other.const_cast_derived(), internal::swap_assign_op<Scalar>());
}
/** swaps *this with the matrix or array \a other.
*
*/
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
void swap(PlainObjectBase<OtherDerived>& other)
{
eigen_assert(rows()==other.rows() && cols()==other.cols());
call_assignment(derived(), other.derived(), internal::swap_assign_op<Scalar>());
}
EIGEN_DEVICE_FUNC inline const NestByValue<Derived> nestByValue() const;
EIGEN_DEVICE_FUNC inline const ForceAlignedAccess<Derived> forceAlignedAccess() const;
EIGEN_DEVICE_FUNC inline ForceAlignedAccess<Derived> forceAlignedAccess();
template<bool Enable> EIGEN_DEVICE_FUNC
inline const typename internal::conditional<Enable,ForceAlignedAccess<Derived>,Derived&>::type forceAlignedAccessIf() const;
template<bool Enable> EIGEN_DEVICE_FUNC
inline typename internal::conditional<Enable,ForceAlignedAccess<Derived>,Derived&>::type forceAlignedAccessIf();
EIGEN_DEVICE_FUNC Scalar sum() const;
EIGEN_DEVICE_FUNC Scalar mean() const;
EIGEN_DEVICE_FUNC Scalar trace() const;
EIGEN_DEVICE_FUNC Scalar prod() const;
EIGEN_DEVICE_FUNC typename internal::traits<Derived>::Scalar minCoeff() const;
EIGEN_DEVICE_FUNC typename internal::traits<Derived>::Scalar maxCoeff() const;
template<typename IndexType> EIGEN_DEVICE_FUNC
typename internal::traits<Derived>::Scalar minCoeff(IndexType* row, IndexType* col) const;
template<typename IndexType> EIGEN_DEVICE_FUNC
typename internal::traits<Derived>::Scalar maxCoeff(IndexType* row, IndexType* col) const;
template<typename IndexType> EIGEN_DEVICE_FUNC
typename internal::traits<Derived>::Scalar minCoeff(IndexType* index) const;
template<typename IndexType> EIGEN_DEVICE_FUNC
typename internal::traits<Derived>::Scalar maxCoeff(IndexType* index) const;
template<typename BinaryOp>
EIGEN_DEVICE_FUNC
Scalar redux(const BinaryOp& func) const;
template<typename Visitor>
EIGEN_DEVICE_FUNC
void visit(Visitor& func) const;
/** \returns a WithFormat proxy object allowing to print a matrix the with given
* format \a fmt.
*
* See class IOFormat for some examples.
*
* \sa class IOFormat, class WithFormat
*/
inline const WithFormat<Derived> format(const IOFormat& fmt) const
{
return WithFormat<Derived>(derived(), fmt);
}
/** \returns the unique coefficient of a 1x1 expression */
EIGEN_DEVICE_FUNC
CoeffReturnType value() const
{
EIGEN_STATIC_ASSERT_SIZE_1x1(Derived)
eigen_assert(this->rows() == 1 && this->cols() == 1);
return derived().coeff(0,0);
}
EIGEN_DEVICE_FUNC bool all() const;
EIGEN_DEVICE_FUNC bool any() const;
EIGEN_DEVICE_FUNC Index count() const;
typedef VectorwiseOp<Derived, Horizontal> RowwiseReturnType;
typedef const VectorwiseOp<const Derived, Horizontal> ConstRowwiseReturnType;
typedef VectorwiseOp<Derived, Vertical> ColwiseReturnType;
typedef const VectorwiseOp<const Derived, Vertical> ConstColwiseReturnType;
/** \returns a VectorwiseOp wrapper of *this providing additional partial reduction operations
*
* Example: \include MatrixBase_rowwise.cpp
* Output: \verbinclude MatrixBase_rowwise.out
*
* \sa colwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting
*/
//Code moved here due to a CUDA compiler bug
EIGEN_DEVICE_FUNC inline ConstRowwiseReturnType rowwise() const {
return ConstRowwiseReturnType(derived());
}
EIGEN_DEVICE_FUNC RowwiseReturnType rowwise();
/** \returns a VectorwiseOp wrapper of *this providing additional partial reduction operations
*
* Example: \include MatrixBase_colwise.cpp
* Output: \verbinclude MatrixBase_colwise.out
*
* \sa rowwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting
*/
EIGEN_DEVICE_FUNC inline ConstColwiseReturnType colwise() const {
return ConstColwiseReturnType(derived());
}
EIGEN_DEVICE_FUNC ColwiseReturnType colwise();
typedef CwiseNullaryOp<internal::scalar_random_op<Scalar>,PlainObject> RandomReturnType;
static const RandomReturnType Random(Index rows, Index cols);
static const RandomReturnType Random(Index size);
static const RandomReturnType Random();
template<typename ThenDerived,typename ElseDerived>
const Select<Derived,ThenDerived,ElseDerived>
select(const DenseBase<ThenDerived>& thenMatrix,
const DenseBase<ElseDerived>& elseMatrix) const;
template<typename ThenDerived>
inline const Select<Derived,ThenDerived, typename ThenDerived::ConstantReturnType>
select(const DenseBase<ThenDerived>& thenMatrix, const typename ThenDerived::Scalar& elseScalar) const;
template<typename ElseDerived>
inline const Select<Derived, typename ElseDerived::ConstantReturnType, ElseDerived >
select(const typename ElseDerived::Scalar& thenScalar, const DenseBase<ElseDerived>& elseMatrix) const;
template<int p> RealScalar lpNorm() const;
template<int RowFactor, int ColFactor>
EIGEN_DEVICE_FUNC
const Replicate<Derived,RowFactor,ColFactor> replicate() const;
/**
* \return an expression of the replication of \c *this
*
* Example: \include MatrixBase_replicate_int_int.cpp
* Output: \verbinclude MatrixBase_replicate_int_int.out
*
* \sa VectorwiseOp::replicate(), DenseBase::replicate<int,int>(), class Replicate
*/
//Code moved here due to a CUDA compiler bug
EIGEN_DEVICE_FUNC
const Replicate<Derived, Dynamic, Dynamic> replicate(Index rowFactor, Index colFactor) const
{
return Replicate<Derived, Dynamic, Dynamic>(derived(), rowFactor, colFactor);
}
typedef Reverse<Derived, BothDirections> ReverseReturnType;
typedef const Reverse<const Derived, BothDirections> ConstReverseReturnType;
EIGEN_DEVICE_FUNC ReverseReturnType reverse();
/** This is the const version of reverse(). */
//Code moved here due to a CUDA compiler bug
EIGEN_DEVICE_FUNC ConstReverseReturnType reverse() const
{
return ConstReverseReturnType(derived());
}
EIGEN_DEVICE_FUNC void reverseInPlace();
#define EIGEN_CURRENT_STORAGE_BASE_CLASS Eigen::DenseBase
#define EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL
#define EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(COND)
# include "../plugins/BlockMethods.h"
# ifdef EIGEN_DENSEBASE_PLUGIN
# include EIGEN_DENSEBASE_PLUGIN
# endif
#undef EIGEN_CURRENT_STORAGE_BASE_CLASS
#undef EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL
#undef EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF
// disable the use of evalTo for dense objects with a nice compilation error
template<typename Dest>
EIGEN_DEVICE_FUNC
inline void evalTo(Dest& ) const
{
EIGEN_STATIC_ASSERT((internal::is_same<Dest,void>::value),THE_EVAL_EVALTO_FUNCTION_SHOULD_NEVER_BE_CALLED_FOR_DENSE_OBJECTS);
}
protected:
EIGEN_DEFAULT_COPY_CONSTRUCTOR(DenseBase)
/** Default constructor. Do nothing. */
EIGEN_DEVICE_FUNC DenseBase()
{
/* Just checks for self-consistency of the flags.
* Only do it when debugging Eigen, as this borders on paranoia and could slow compilation down
*/
#ifdef EIGEN_INTERNAL_DEBUGGING
EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, int(IsRowMajor))
&& EIGEN_IMPLIES(MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1, int(!IsRowMajor))),
INVALID_STORAGE_ORDER_FOR_THIS_VECTOR_EXPRESSION)
#endif
}
private:
EIGEN_DEVICE_FUNC explicit DenseBase(int);
EIGEN_DEVICE_FUNC DenseBase(int,int);
template<typename OtherDerived> EIGEN_DEVICE_FUNC explicit DenseBase(const DenseBase<OtherDerived>&);
};
} // end namespace Eigen
#endif // EIGEN_DENSEBASE_H
| [
"alinen@savvysine.com"
] | alinen@savvysine.com |
fdd51f8129e2cd8e2e50fce75dccb601d2500751 | 90f46593da6c69c31c80bb8b0f01befebbc6bc55 | /include/gtStackTrace.h | 52722d55d14b390ad2d21b93e7a59eca60f6a4c9 | [
"MIT"
] | permissive | MrOnlineCoder/GoST | 0a0762ace6666288d1c32023ba29e52ff1aadd78 | c88da91f2826b633a8e241ebeb15a33507873f95 | refs/heads/master | 2021-09-01T12:25:09.184075 | 2017-12-27T01:05:53 | 2017-12-27T01:05:53 | 115,792,900 | 0 | 1 | null | 2017-12-30T11:36:31 | 2017-12-30T11:36:31 | null | UTF-8 | C++ | false | false | 3,738 | h | // GOST
#pragma once
#ifndef __GT_STACK_TRACE_H__
#define __GT_STACK_TRACE_H__
#if defined( GT_USE_STACK_TRACE )
#if defined( GT_PLATFORM_WIN32 )
#include <Windows.h>
#include <dbghelp.h>
#pragma comment(lib,"Dbghelp.lib")
#else
#error Класс gtStackTrace поддерживается только для Win32
#endif
#endif
namespace gost{
constexpr u32 gtMaxStackFrames = 1024u;
/// Выводит цепочку вызовов функций от текущей до самого начала
/// По логике должен работать только в Debug версии
class gtStackTrace{
/// для вывода текста
gtPtr<gtLoger> m_log;
/// нельзя создать объект с таким конструктором
gtStackTrace( void ){}
/// инициализация при первом вызове printStackTrace
void initialize( void ); bool m_is_initialized;
/// производит зависимое от ОС операции по освобождению ранее взятой памяти
void shutdown( void );
public:
// конструирует объект и инициализирует логер
gtStackTrace( gtMainSystem* s ) : m_is_initialized( false ){
m_log = gtPtrNew<gtLoger>( s->getLoger() );
m_log->setOutputWindow( s->getOutputWindow() );
m_log->addRef();
}
// dtor
virtual ~gtStackTrace( void ){
}
// skip_begin - пропуск с начала
// skip_end - пропуск с конца
// если skip_begin = 0 то будет показан gtStackTrace::printStackTrace()
// что очевидно, по этому по умолчанию стоит 1
// skip_end = 7 значит не напечатает последние 7
void printStackTrace( u32 skip_begin = 1u, u32 skip_end = 7u );
// движок имеет свой объект gtStackTrace
// данной функцией можно вызывать printStackTrace()
// всего лишь 1м предложением gtStackTrace::dumpStackTrace()
// создан специально чтобы не плодить объекты gtStackTrace в разных модулях (.exe, .dll)
GT_API static void dumpStackTrace( void );
};
}
#if defined( GT_USE_STACK_TRACE )
#if defined( GT_PLATFORM_WIN32 )
#include <gtStackTraceWin32.inl>
#else
#error Класс gtStackTrace поддерживается только для Win32
#endif
#else
void gtStackTrace::printStackTrace( u32 skip_begin, u32 skip_end ){}
#endif
#endif
/*
Copyright (c) 2017 532235
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ | [
"noreply@github.com"
] | noreply@github.com |
5325f01527b73b4d3837bfb1baee998185fbb237 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-workspaces-web/source/model/DeleteBrowserSettingsRequest.cpp | e5d85155e6a183f9acdf90390e1214adb0d5bff1 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 563 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/workspaces-web/model/DeleteBrowserSettingsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::WorkSpacesWeb::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DeleteBrowserSettingsRequest::DeleteBrowserSettingsRequest() :
m_browserSettingsArnHasBeenSet(false)
{
}
Aws::String DeleteBrowserSettingsRequest::SerializePayload() const
{
return {};
}
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
bf6314c1c528d60a6813a572dbb5dfcc62ba6be8 | a4ed008ccae67854ee9f5d7f4b6744042faec82e | /chapter_07_STL_Algorithms/main.cpp | 74793bf123564bb55054d21d2b894c9a9254cb63 | [] | no_license | qqzeng/cs106l | 64b790334c9dfdc1412fdaf62ba1dfcaad0cd58b | faecfcb90aa277941d6dad197e982ac0253847fb | refs/heads/master | 2022-07-04T05:19:49.787198 | 2020-05-08T12:01:05 | 2020-05-08T12:01:05 | 255,878,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,675 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
#include <sstream>
#include <iterator>
#include <fstream>
#include <numeric>
#include <direct.h>
#include <cmath>
#include <map>
#include <set>
#include <time.h>
using namespace std;
/* Program solutions in chapter 7, i.e., STL Algorithms */
/* judge whether a string is palindrome. */
bool IsNotAlpha(char ch) {
return !isalpha(ch);
}
bool IsPalindrome(string &input) {
input.erase(remove_if(input.begin(), input.end(), IsNotAlpha), input.end());
transform(input.begin(), input.end(), input.begin(), ::toupper);
return equal(input.begin(), input.begin()+input.size()/2, input.rbegin());
}
void TestIsPalindrome() {
vector<string> vs = {"Go hang a salami! I'm a lasagna hog", "Mr. Owl ate my metal worm", "Part y traP", "you are you!"};
for (size_t i = 0; i < vs.size(); ++i) cout << boolalpha << IsPalindrome(vs[i]) << endl;
}
/* judge whether a string is word-palindrome. */
bool IsNotAlphaAndSpace(char ch) {
return !isalpha(ch) && ch != ' ';
}
bool IsWordPalindrome(string &input) {
input.erase(remove_if(input.begin(), input.end(), IsNotAlphaAndSpace), input.end());
transform(input.begin(), input.end(), input.begin(), ::toupper);
stringstream text(input);
vector<string> words;
// words.insert(words.begin(), istream_iterator<string>(text), istream_iterator<string>());
copy(istream_iterator<string>(text), istream_iterator<string>(), back_inserter(words));
return equal(words.begin(), words.begin()+words.size()/2, words.rbegin());
}
void TestIsWordPalindrome() {
vector<string> vs = {"Hello? Hello!? HELLO?", "Go hang a salami! I'm a lasagna hog", "Did mom pop? Mom did!",
"Mr. Owl ate my metal worm", "Part y traP", "you are you!"};
for (size_t i = 0; i < vs.size(); ++i) cout << boolalpha << IsWordPalindrome(vs[i]) << endl;
}
/************************************************ Exercise solutions. ************************************************/
/* Exercise 6. */
bool NotInRange(int num) {
return num >= 75 || num <= 25;
}
void GetAvgOfRangeOfValuesFromFile(string file_name) {
fstream input(file_name);
if (!input.is_open()) {
cerr << "Open file " << file_name << "fail, abort successive computing...";
return;
}
vector<int> values;
values.insert(values.begin(), istream_iterator<int>(input), istream_iterator<int>());
values.erase(remove_if(values.begin(), values.end(), NotInRange), values.end());
cout << accumulate(values.cbegin(), values.cend(), 0) / values.size() << endl;
cout << accumulate(values.cbegin(), values.cend(), 0) / distance(values.cbegin(), values.cend()) << endl;
}
void TestGetAvgOfRangeOfValuesFromFile() {
char *cur_dir;
if((cur_dir = getcwd(NULL, 0)) == NULL) {
perror("getcwd error");
}
string dir(cur_dir);
dir = dir.substr(0, dir.find_last_of('\\')+1);
GetAvgOfRangeOfValuesFromFile(dir + string("exe06_nums.txt"));
}
/* Exercise 7. */
bool isLEThan(string &s) {
return s.size() <= 3;
}
void RemoveShortWords(vector<string> &strs) {
strs.erase(remove_if(strs.begin(), strs.end(), isLEThan), strs.end());
copy(strs.begin(), strs.end(), ostream_iterator<string>(cout, " "));
}
void TestRemoveShortWords() {
vector<string> strs = {"Today", "is", "a", "nice", "day", "and",
"I", "wanna", "to", "play", "with", "my", "good", "friends"};
RemoveShortWords(strs);
}
/* Exercise 8. */
double DistanceToOrigin(vector<double> &points) {
return sqrt(inner_product(points.begin(), points.end(), points.begin(), 0.));
}
void TestDistanceToOrigin() {
vector<double> dv = {2.1, 3, 4};
cout << DistanceToOrigin(dv) << endl;
}
/* Exercise 9. */
bool StrCompare(string &s1, string &s2) {
if (strcmp(s1.c_str(), "Me First,") == 0) {
return true;
} else if (strcmp(s2.c_str(), "Me First,") == 0) {
return false;
} else {
return s1.compare(s2) < 0; // case-sensitive
}
}
void BiasedSort(vector<string> &strs) {
sort(strs.begin(), strs.end(), StrCompare);
copy(strs.begin(), strs.end(), ostream_iterator<string>(cout, " "));
}
void TestBiasedSort() {
vector<string> strs = {"Today", "is", "a", "nice", "day", "and", "Me First,",
"I", "wanna", "to", "play", "with", "my", "good", "friends", "Me First,"};
BiasedSort(strs);
}
/* Exercise 10. */
multimap<double, string> InvertMap(map<string, double> &m) {
multimap<double, string> invert_m;
for (map<string, double>::iterator itr = m.begin(); itr != m.end(); ++itr) {
invert_m.insert(make_pair(itr->second, itr->first));
}
return invert_m;
}
set<string> TopNSongs(map<string, double> &song_ratings, size_t n) {
multimap<double, string> invert_m = InvertMap(song_ratings);
set<string> topn_songs;
size_t i = 0;
for (multimap<double, string>::reverse_iterator itr = invert_m.rbegin();
itr != invert_m.rend() && i++ < n; ++itr) {
topn_songs.insert(itr->second);
}
return topn_songs;
}
void TestTopNSongs() {
map<string, double> song_ratings;
song_ratings.insert(make_pair("ac", 8.8));
song_ratings.insert(make_pair("b", 8.2));
song_ratings.insert(make_pair("cd", 7.1));
song_ratings.insert(make_pair("dad", 8.9));
song_ratings.insert(make_pair("ee", 9.9));
song_ratings.insert(make_pair("faaa", 9.0));
song_ratings.insert(make_pair("gbb", 6.0));
set<string> songs = TopNSongs(song_ratings, 3);
copy(songs.begin(), songs.end(), ostream_iterator<string>(cout, " "));
}
/* Exercise 11. */
int count(vector<int>::iterator start, vector<int>::iterator stop, int element) {
size_t total = 0;
while (start != stop) {
if (*start == element) total++;
++start;
}
return total;
}
void TestCount() {
vector<int> vc = {8, 3, 7, 5, 6, 9, 6, 10, 1, 6, 5, 2};
cout << count(vc.begin(), vc.end(), 100) << endl;
}
/* Exercise 12. */
double AvgRandomNumber(size_t n) {
vector<int> values(n);
srand(static_cast<unsigned int>(time(nullptr)));
generate_n(values.begin(), n, rand);
return accumulate(values.begin(), values.end(), 0.0) / values.size();
}
void TestAvgAvgRandomNumber() {
cout << AvgRandomNumber(3) << endl;
}
/* Exercise 13. */
double MedianEleOfVector(vector<double> &values) {
nth_element(values.begin(), values.begin() + values.size() / 2, values.end());
if (values.size() % 2 == 1) {
return values[values.size() / 2];
} else {
return (values[values.size() / 2] + values[values.size() / 2 -1]) / 2;
}
}
void TestMedianEleOfVector() {
vector<double > vc = {8, 3, 7, 5, 6.5, 9, 7, 1, 6, 5, 2};
cout << MedianEleOfVector(vc) << endl;
sort(vc.begin(), vc.end());
copy(vc.begin(), vc.end(), ostream_iterator<double>(cout, " "));
}
/* Exercise 14. */
void PrintFileContent(string file_name) {
fstream file(file_name);
if (!file.is_open()) {
cerr << "Error open file " << file_name << endl;
return;
}
copy(istream_iterator<string>(file), istream_iterator<string>(), ostream_iterator<string>(cout, " "));
}
void TestPrintFileContent() {
char *cur_dir;
if((cur_dir = getcwd(NULL, 0)) == NULL) {
perror("getcwd error");
}
string dir(cur_dir);
dir = dir.substr(0, dir.find_last_of('\\')+1);
PrintFileContent(dir + string("exe06_nums.txt"));
}
/* Exercise 15. */
void OutputToFile(vector<string> &values) {
ofstream file("test.txt");
if (!file.is_open()) {
cerr << "Error open file test.txt" << endl;
return;
}
copy(values.begin(), values.end(), ostream_iterator<string>(file, "\n"));
}
void TestOutputToFile() {
vector<string> strs = {"Today", "is", "a", "nice", "day", "and", "Me First,",
"I", "wanna", "to", "play", "with", "my", "good", "friends", "Me First,"};
OutputToFile(strs);
}
/* Exercise 16. */
vector<int> IntersectionOfVector(vector<int> &v1, vector<int> &v2) {
vector<int> result;
// set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_insert_iterator<vector<int>>(result));
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(result));
return result;
}
void TestIntersectionOfVector() {
vector<int> vc1 = {8, 3, 7, 5, 6, 9, 7, 1, 6, 55, 2};
vector<int> vc2 = {88, 6, 73, 53, 6, 9, 2, 1, 6, 1, 55};
sort(vc1.begin(), vc1.end());
sort(vc2.begin(), vc2.end());
vector<int> result = IntersectionOfVector(vc1, vc2);
copy(result.begin(), result.end(), ostream_iterator<int>(cout, " "));
}
/* Exercise 17. */
char Encrypt(char c) {
}
string MonoalphabeticSubstitutionEncrypt(string &plain_text) {
string alphbet = "abcdefghiklmnopqrstuvwxyz";
string cipher_text = plain_text;
random_shuffle(alphbet.begin(), alphbet.end());
for (string::iterator itr = cipher_text.begin(); itr != cipher_text.end(); ++itr) *itr = alphbet[*itr-'a'];
return cipher_text;
}
void TestMonoalphabeticSubstitutionEncrypt() {
string plain_text = "todayisaniceday";
cout << MonoalphabeticSubstitutionEncrypt(plain_text) << endl;
}
int main() {
TestMonoalphabeticSubstitutionEncrypt();
// TestIntersectionOfVector();
// TestOutputToFile();
// TestPrintFileContent();
// TestMedianEleOfVector();
// TestAvgAvgRandomNumber();
// TestCount();
// TestTopNSongs();
// TestBiasedSort();
// TestDistanceToOrigin();
// TestRemoveShortWords();
// TestGetAvgOfRangeOfValuesFromFile();
// TestIsWordPalindrome();
// TestIsPalindrome();
return 0;
} | [
"qtozeng@qq.com"
] | qtozeng@qq.com |
076118bd9bd9ee1bc57692573c9927133b850a55 | a08d69383be2bfb210c4275e78b40c4f8ec496be | /math/원형에서구간(시계수).cpp | 242c7699291f807ee15ab52f671c206597a3555b | [] | no_license | auddl0756/My-Algorithm | ee23bb764133bfb00a886dd695386ac59317a725 | 8b8ca742a16f9571c8bcf718b5c6574ace546ea4 | refs/heads/master | 2023-03-20T03:24:37.709975 | 2021-03-09T13:52:33 | 2021-03-09T13:52:33 | 279,713,797 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,958 | cpp | #include <bits/stdc++.h>
#define pii pair<int,int>
#define pdi pair<double,int>
#define ppi pair<pair<int,int>,int>
#define pipi pair<pair<int,int>,pair<int,int> >
#define fs first
#define sc second
#define sorta(a) sort(a.begin(),a.end());
#define rsorta(a) sort(a.rbegin(),a.rend());
#define sorta2(a,n) sort(a,a+n);
#define debug(a) for(int i=0;i<a.size();i++)cout<<a[i]<<" ";cout<<"\n";
#define debug2(a,n) for(int i=0;i<n;i++)cout<<a[i]<<" ";cout<<"\n";
#define all(v) (v).begin(), (v).end()
#define lbd(arr,num) lower_bound(all(arr),num)
#define maxi(a,b,c) max(a,max(b,c))
#define mini(a,b,c) min(a,min(b,c))
#define msi map<string,int>
typedef long long ll;
using namespace std;
//typedef vector<vector<ll> > matrix;
#define pll pair<ll,ll>
#define ppl pair<pll,ll>
//https://www.acmicpc.net/problem/10165
bool comp(ppi a,ppi b){ //시작위치가 빠른순으로 정렬, 같다면 도착위치가 더 먼 것이 앞에 오도록 정렬.
if(a.fs.fs<b.fs.fs) return true;
else if(a.fs.fs==b.fs.fs){
if(a.fs.sc>b.fs.sc) return true;
else return false;
}
else return false;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
int n,m; cin>>n>>m;
vector<ppi> a; //pair<pair<ll,ll>,ll> :: 시작위치,도착위치,노선번호
vector<ppi> R,I;
for(int i=0;i<m;i++){
//입력받으면서 원형 구간을 일직선으로 변환.
int x,y,z; cin>>x>>y; z=i+1;
if(x>y){
a.push_back({{x-n,y},z}); //모듈러 합동.
a.push_back({{x,y+n},z});
}else{
a.push_back({{x,y},z});
}
}
sort(all(a),comp);
// for(int i=0;i<a.size();i++){
// cout<<a[i].fs.fs<<" "<<a[i].fs.sc<<" "<<a[i].sc<<"\n";
// }
//case 1: R in R
//case 2: R in I
//case 3: I in I
set<int> ans;
int nowend=-n;
for(int i=0;i<a.size();i++){
if(nowend<a[i].fs.sc){
ans.insert(a[i].sc);
nowend=a[i].fs.sc;
}
}
vector<int> res(all(ans));
debug(res);
}
//참고: https://blog.naver.com/pasdfq/221251549101
| [
"cjddl789123@naver.com"
] | cjddl789123@naver.com |
2f75be0502357f64c6ca98caa626733343706610 | c70ffe04668c4e81622f30a6ff6db27df9c518e3 | /app/tests/util_test.cc | c0fc858942f9310d126a15d72ab013745903755f | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | permissive | firebase/firebase-cpp-sdk | 469a8514beb1425afdcc923e0f5f9fb64092cdc1 | f55c43c2485e91c67a52ce60e1191fa3b0c4df61 | refs/heads/main | 2023-09-01T11:50:35.258358 | 2023-08-31T00:35:26 | 2023-08-31T00:35:26 | 175,263,313 | 270 | 112 | Apache-2.0 | 2023-09-14T19:41:20 | 2019-03-12T17:23:01 | C++ | UTF-8 | C++ | false | false | 2,012 | cc | /*
* Copyright 2020 Google LLC
*
* 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 "app/src/util.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace firebase {
namespace {
using ::testing::ElementsAre;
using ::testing::IsEmpty;
TEST(UtilTest, SplitStringRegularCase) {
EXPECT_THAT(SplitString("a/b/c", '/'), ElementsAre("a", "b", "c"));
}
TEST(UtilTest, SplitStringNoDelimeters) {
EXPECT_THAT(SplitString("a", '/'), ElementsAre("a"));
}
TEST(UtilTest, SplitStringTrailingDelimeter) {
EXPECT_THAT(SplitString("a/b/c/", '/'), ElementsAre("a", "b", "c"));
}
TEST(UtilTest, SplitStringLeadingDelimeter) {
EXPECT_THAT(SplitString("/a/b/c", '/'), ElementsAre("a", "b", "c"));
}
TEST(UtilTest, SplitStringConsecutiveDelimeters) {
EXPECT_THAT(SplitString("a///b/c", '/'), ElementsAre("a", "b", "c"));
EXPECT_THAT(SplitString("///a///b///c///", '/'), ElementsAre("a", "b", "c"));
}
TEST(UtilTest, SplitStringEmptyString) {
EXPECT_THAT(SplitString("", '/'), IsEmpty());
}
TEST(UtilTest, SplitStringDelimetersOnly) {
EXPECT_THAT(SplitString("///", '/'), IsEmpty());
}
TEST(UtilTest, CreateApiIdentifierUnique) {
int v1, v2;
EXPECT_STRNE(CreateApiIdentifier("Test", &v1).c_str(),
CreateApiIdentifier("Test", &v2).c_str());
}
TEST(UtilTest, CreateApiIdentifierReallyUnique) {
int v1;
EXPECT_STRNE(CreateApiIdentifier("Test", &v1).c_str(),
CreateApiIdentifier("Test", &v1).c_str());
}
} // namespace
} // namespace firebase
| [
"noreply@github.com"
] | noreply@github.com |
8361cd4cf1039f977d57ba13881019a3fd0d5950 | 7fd8e1f8150e44f610ab2b915fbd7d0fe42db1df | /PckDll/PckClass/PckClassHeadTailWriter.cpp | 70e79871f4540b33e30bf1a44dedd20c678c11d1 | [] | no_license | kaito373/WinPCK | 26396940a09de6e4f1db94b447ae8a3db6a19ad3 | d9ec682d584ce959aea43243f677d3606ac448c9 | refs/heads/master | 2020-06-02T06:07:56.612188 | 2019-06-12T12:44:17 | 2019-06-12T12:44:17 | 191,063,634 | 0 | 0 | null | 2019-06-09T22:57:54 | 2019-06-09T22:57:54 | null | GB18030 | C++ | false | false | 1,267 | cpp |
#include "PckClassHeadTailWriter.h"
CPckClassHeadTailWriter::CPckClassHeadTailWriter()
{}
CPckClassHeadTailWriter::~CPckClassHeadTailWriter()
{}
BOOL CPckClassHeadTailWriter::AfterProcess(CMapViewFileMultiPckWrite *lpWrite, PCK_ALL_INFOS &PckAllInfo, QWORD &dwAddress, BOOL isRenewAddtional)
{
assert(NULL != dwAddress);
assert(0 != (PckAllInfo.dwFileCount + PckAllInfo.dwFileCountToAdd));
if(isRenewAddtional)
strcpy(PckAllInfo.szAdditionalInfo, PCK_ADDITIONAL_INFO);
//写pckTail
if (!lpWrite->Write2(dwAddress, m_PckAllInfo.lpSaveAsPckVerFunc->FillTailData(&PckAllInfo), m_PckAllInfo.lpSaveAsPckVerFunc->dwTailSize)) {
m_PckLog.PrintLogEL(TEXT_VIEWMAP_FAIL, __FILE__, __FUNCTION__, __LINE__);
return FALSE;
}
dwAddress += m_PckAllInfo.lpSaveAsPckVerFunc->dwTailSize;
//写pckHead
PckAllInfo.qwPckSize = dwAddress;
assert(0 != PckAllInfo.qwPckSize);
if (!lpWrite->Write2(0, m_PckAllInfo.lpSaveAsPckVerFunc->FillHeadData(&PckAllInfo), m_PckAllInfo.lpSaveAsPckVerFunc->dwHeadSize)) {
m_PckLog.PrintLogEL(TEXT_VIEWMAP_FAIL, __FILE__, __FUNCTION__, __LINE__);
return FALSE;
}
lpWrite->UnMaping();
//这里将文件大小重新设置一下
lpWrite->SetFilePointer(dwAddress, FILE_BEGIN);
lpWrite->SetEndOfFile();
return TRUE;
} | [
"stsm85@126.com"
] | stsm85@126.com |
99fbb6afb5b481f976020bc9d84562184c441bd0 | 51faca0ffd1c452a427e551cd8c528a4ac80fc75 | /vg/tg/LCT/div1/B.cpp | cca11b8fc41a282d702070097f1096273b2c5d82 | [] | no_license | xLLLxLLLx/xLLLx | 37f4127a34374b27f14fe856d854c9a13a9b2e28 | 7ec2ddf39d903c0cdfd52268edd44b2ccbe7e73b | refs/heads/master | 2020-04-18T16:19:24.099657 | 2019-11-03T05:11:41 | 2019-11-03T05:11:41 | 167,631,326 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,285 | cpp | #include<bits/stdc++.h>
#define fr(i,x,y) for(int i=x;i<=y;++i)
#define rf(i,x,y) for(int i=x;i>=y;--i)
#define LL long long
using namespace std;
const int N=5e5+10;
struct data{
int nt,to;
}a[N<<1];
LL ans=0;
int cnt=0;
int head[N];
template <class T>
void read(T &x){
char ch=getchar();x=0;
for(;ch<'0'||ch>'9';ch=getchar()) ;
for(;ch>='0'&&ch<='9';ch=getchar()) x=(x<<1)+(x<<3)+(ch^48);
}
void add(int x,int y){
a[++cnt].to=y,a[cnt].nt=head[x],head[x]=cnt;
a[++cnt].to=x,a[cnt].nt=head[y],head[y]=cnt;
}
#define ls ch[x][0]
#define rs ch[x][1]
int ch[N][2],f[N],zs[N];
LL tag[N],sum[N],v[N],A[N];
bool isroot(int x){
return (ch[f[x]][0]!=x)&&(ch[f[x]][1]!=x);
}
void down(int x){
if(x&&tag[x]){
if(ls) tag[ls]+=tag[x];
if(rs) tag[rs]+=tag[x];
sum[x]+=tag[x];
tag[x]=0;
}
}
void pushdown(int x){
if(!isroot(x)) pushdown(f[x]);
down(x);
}
bool pd(int x){ return ch[f[x]][1]==x; }
void rotate(int x){
int y=f[x],z=f[y];
int k=pd(y),d=pd(x);
if(!isroot(y)) ch[z][k]=x;
f[x]=z;
ch[y][d]=ch[x][d^1],f[ch[x][d^1]]=y;
ch[x][d^1]=y,f[y]=x;
}
void splay(int x){
pushdown(x);
//printf("wx=%d\n",x);
for(;!isroot(x);rotate(x)){
//printf("x=%d\n",x);
if(!isroot(f[x])) pd(f[x])^pd(x) ? rotate(x) : rotate(f[x]);
}
}
void cal(int x){
ans-=A[x];
//printf("x=%d sum=%d %d %d %d\n",x,sum[x],zs[x],sum[zs[x]],v[x]);
A[x]=(zs[x]) ? (2*(sum[x]-sum[zs[x]])) : (sum[x]-1);
if(v[x]*2>sum[x]+1) A[x]=2*(sum[x]-v[x]);
ans+=A[x];
}
int Getroot(int x){
for(;ls;) down(x),x=ls;
down(x);
return x;
}
void access(int x,int y){
v[x]+=y;
for(int i=0;x;i=x,x=f[x]){
splay(x);
sum[x]+=y,tag[ls]+=y,down(ls);
if(zs[x]){
pushdown(zs[x]);
if(sum[zs[x]]*2<=sum[x]+1) zs[x]=rs=0;
}
int zz=Getroot(i);
if(sum[zz]*2>sum[x]+1) zs[x]=zz,rs=i;
cal(x);
}
}
void dfs(int x,int fa){
f[x]=fa,sum[x]=v[x];
for(int i=head[x];i;i=a[i].nt){
if(a[i].to==fa) continue;
dfs(a[i].to,x);
sum[x]+=sum[a[i].to];
if(sum[a[i].to]>sum[zs[x]]) zs[x]=a[i].to;
}
if(sum[zs[x]]*2<=sum[x]+1) zs[x]=0;
rs=zs[x],cal(x);
}
int main(){
int n,m;read(n),read(m);
fr(i,1,n) read(v[i]);
for(int i=1,x,y;i<n;++i) read(x),read(y),add(x,y);
dfs(1,0);
printf("%lld\n",ans);
for(int i=1,x,y;i<=m;++i) read(x),read(y),access(x,y),printf("%lld\n",ans);
return 0;
} | [
"pysxlqp@163.com"
] | pysxlqp@163.com |
21988b26734ae982b17ad09e5f1aadad53ca2657 | 9bbfeafc43c6b9bd081ea39ada440390a04d9c94 | /libraries/breakout_trackball/breakout_trackball.hpp | 46f10197c15b588f151251cf41090d3c4ab35e85 | [
"MIT"
] | permissive | cho7627/pimoroni-pico | e7b519fa2cf904c964449472f93664fd7fd3b9fd | 15b85d1ee2eecbcc670ef1e48fbbd538b0efc1d0 | refs/heads/main | 2023-05-02T02:19:57.221282 | 2021-05-12T15:16:25 | 2021-05-12T15:16:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 135 | hpp | #pragma once
#include "../../drivers/trackball/trackball.hpp"
namespace pimoroni {
typedef Trackball BreakoutTrackball;
}
| [
"noreply@github.com"
] | noreply@github.com |
650658f97cb65670f2d487c227ea316af5ea0af1 | ad273708d98b1f73b3855cc4317bca2e56456d15 | /aws-cpp-sdk-datasync/source/model/PrivateLinkConfig.cpp | 999b609e2fe7fc0c81d8b80216d83701fe24d0e9 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | novaquark/aws-sdk-cpp | b390f2e29f86f629f9efcf41c4990169b91f4f47 | a0969508545bec9ae2864c9e1e2bb9aff109f90c | refs/heads/master | 2022-08-28T18:28:12.742810 | 2020-05-27T15:46:18 | 2020-05-27T15:46:18 | 267,351,721 | 1 | 0 | Apache-2.0 | 2020-05-27T15:08:16 | 2020-05-27T15:08:15 | null | UTF-8 | C++ | false | false | 3,667 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/datasync/model/PrivateLinkConfig.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace DataSync
{
namespace Model
{
PrivateLinkConfig::PrivateLinkConfig() :
m_vpcEndpointIdHasBeenSet(false),
m_privateLinkEndpointHasBeenSet(false),
m_subnetArnsHasBeenSet(false),
m_securityGroupArnsHasBeenSet(false)
{
}
PrivateLinkConfig::PrivateLinkConfig(JsonView jsonValue) :
m_vpcEndpointIdHasBeenSet(false),
m_privateLinkEndpointHasBeenSet(false),
m_subnetArnsHasBeenSet(false),
m_securityGroupArnsHasBeenSet(false)
{
*this = jsonValue;
}
PrivateLinkConfig& PrivateLinkConfig::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("VpcEndpointId"))
{
m_vpcEndpointId = jsonValue.GetString("VpcEndpointId");
m_vpcEndpointIdHasBeenSet = true;
}
if(jsonValue.ValueExists("PrivateLinkEndpoint"))
{
m_privateLinkEndpoint = jsonValue.GetString("PrivateLinkEndpoint");
m_privateLinkEndpointHasBeenSet = true;
}
if(jsonValue.ValueExists("SubnetArns"))
{
Array<JsonView> subnetArnsJsonList = jsonValue.GetArray("SubnetArns");
for(unsigned subnetArnsIndex = 0; subnetArnsIndex < subnetArnsJsonList.GetLength(); ++subnetArnsIndex)
{
m_subnetArns.push_back(subnetArnsJsonList[subnetArnsIndex].AsString());
}
m_subnetArnsHasBeenSet = true;
}
if(jsonValue.ValueExists("SecurityGroupArns"))
{
Array<JsonView> securityGroupArnsJsonList = jsonValue.GetArray("SecurityGroupArns");
for(unsigned securityGroupArnsIndex = 0; securityGroupArnsIndex < securityGroupArnsJsonList.GetLength(); ++securityGroupArnsIndex)
{
m_securityGroupArns.push_back(securityGroupArnsJsonList[securityGroupArnsIndex].AsString());
}
m_securityGroupArnsHasBeenSet = true;
}
return *this;
}
JsonValue PrivateLinkConfig::Jsonize() const
{
JsonValue payload;
if(m_vpcEndpointIdHasBeenSet)
{
payload.WithString("VpcEndpointId", m_vpcEndpointId);
}
if(m_privateLinkEndpointHasBeenSet)
{
payload.WithString("PrivateLinkEndpoint", m_privateLinkEndpoint);
}
if(m_subnetArnsHasBeenSet)
{
Array<JsonValue> subnetArnsJsonList(m_subnetArns.size());
for(unsigned subnetArnsIndex = 0; subnetArnsIndex < subnetArnsJsonList.GetLength(); ++subnetArnsIndex)
{
subnetArnsJsonList[subnetArnsIndex].AsString(m_subnetArns[subnetArnsIndex]);
}
payload.WithArray("SubnetArns", std::move(subnetArnsJsonList));
}
if(m_securityGroupArnsHasBeenSet)
{
Array<JsonValue> securityGroupArnsJsonList(m_securityGroupArns.size());
for(unsigned securityGroupArnsIndex = 0; securityGroupArnsIndex < securityGroupArnsJsonList.GetLength(); ++securityGroupArnsIndex)
{
securityGroupArnsJsonList[securityGroupArnsIndex].AsString(m_securityGroupArns[securityGroupArnsIndex]);
}
payload.WithArray("SecurityGroupArns", std::move(securityGroupArnsJsonList));
}
return payload;
}
} // namespace Model
} // namespace DataSync
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
0150b159960cc391c1e192db19ad6f01aee1c2b2 | 4a79e6d15e47b3233bd16e08c3b1fb8346000566 | /Sources/TextVocabularyAnalyzer.h | 913c675410547b8dd83ec22a7f28b6afc3d05a29 | [] | no_license | MorpheusDong/TextVocabularyAnalyzer | d97b812cb68bee02859b210e4f67bf20995e918b | af7d4e8a348c7d1f7aab4daf2ea7696bb19bcb4e | refs/heads/master | 2023-04-03T00:10:34.481584 | 2021-04-15T06:16:01 | 2021-04-15T06:16:01 | 277,064,902 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | h | #ifndef _TEXT_VOCABULARY_ANALYZER_H_
#define _TEXT_VOCABULARY_ANALYZER_H_
#include "TypeDefine.h"
extern TagWordFrequencyType frequency_classify(const int wfrq);
extern void word_frequency_analyze(array<int, WORD_LEVEL_NUM>& wfrq_array, TagWordFrequencyType wfrq_tag);
extern bool isaletter(const char& c);
class CLetters
{
private:
string m_word;
public:
CLetters();
~CLetters();
void fill(vector<char>& vw);
const string word();
const char firstletter();
void processing();
bool usual_recheck();
bool form_recheck();
};
#endif // !_TEXT_VOCABULARY_ANALYZER_H_
| [
"noreply@github.com"
] | noreply@github.com |
d0dc681f58171a3c86d3fea425e9e5fe58c0b942 | 025e6c97c9316816a83960278aa92f6d44447c54 | /material.h | 2362449ce1679f7142eb42e2bbb1c1cc350b653c | [] | no_license | taoistze/virtual_dataset_maker | bed885f487e40b54b18c0d5d4b2c45ab3c07a096 | fb9717e0cd570c07ab7ade4eeade26402e6618b3 | refs/heads/master | 2023-02-18T08:37:41.804496 | 2021-01-19T08:54:06 | 2021-01-19T08:54:06 | 330,912,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 826 | h | #pragma once
#include <glm/glm.hpp>
#include <assimp/material.h>
#include "shader_m.h"
class Material {
public:
glm::vec3 diffuse;
glm::vec3 specular;
glm::vec3 ambient;
float shininess = 1;
void Set(const Shader& shader) const {
shader.setVec3("material.diffuse", diffuse);
if ((diffuse[0]<0)|(diffuse[1]<0)|(diffuse[2]<0))
cout<<diffuse[0]<<" "<<diffuse[1]<<" "<<diffuse[2]<<endl;
shader.setVec3("material.specular", specular);
if ((specular[0] < 0) | (specular[1] < 0) | (specular[2] < 0))
cout << specular[0] << " " << specular[1] << " " << specular[2] << endl;
shader.setVec3("material.ambient", ambient);
if ((ambient[0] < 0) | (ambient[1] < 0) | (ambient[2] < 0))
cout << ambient[0] << " " << ambient[1] << " " << ambient[2] << endl;
shader.setFloat("material.shininess", shininess);
}
};
| [
"45955563+taoistze@users.noreply.github.com"
] | 45955563+taoistze@users.noreply.github.com |
d9ce30134cd638c0e27f5d81bc09bf7cbfb57f91 | 9467e2502183e843a67736800199e31674b1d8f6 | /HybridCLRData/LocalIl2CppData-OSXEditor/il2cpp/libil2cpp/vm/Method.h | f5e35e1b7b7936d4a6b31ee83e5b5b537ba4d9e3 | [
"Apache-2.0"
] | permissive | yimengfan/BDFramework.Core | 3a046fcd755a84ba55d648dd3ad52c37a1cc1a04 | 81380fce8e84367f912777717665b53f074ab617 | refs/heads/master | 2023-09-04T10:08:47.644992 | 2023-07-05T16:22:11 | 2023-07-05T16:22:11 | 85,928,537 | 2,421 | 497 | Apache-2.0 | 2023-03-21T06:56:21 | 2017-03-23T09:03:48 | C# | UTF-8 | C++ | false | false | 2,073 | h | #pragma once
#include <stdint.h>
#include <string>
#include "il2cpp-config.h"
struct MethodInfo;
struct PropertyInfo;
struct ParameterInfo;
struct Il2CppString;
struct Il2CppType;
struct Il2CppClass;
namespace il2cpp
{
namespace vm
{
class LIBIL2CPP_CODEGEN_API Method
{
public:
static const Il2CppType* GetReturnType(const MethodInfo* method);
static const char* GetName(const MethodInfo *method);
static std::string GetNameWithGenericTypes(const MethodInfo* method);
static std::string GetFullName(const MethodInfo* method);
static bool IsGeneric(const MethodInfo *method);
static bool IsInflated(const MethodInfo *method);
static bool IsInstance(const MethodInfo *method);
static bool IsGenericInstance(const MethodInfo *method);
static uint32_t GetParamCount(const MethodInfo *method);
static uint32_t GetGenericParamCount(const MethodInfo *method);
static const Il2CppType* GetParam(const MethodInfo *method, uint32_t index);
static Il2CppClass* GetClass(const MethodInfo *method);
static bool HasAttribute(const MethodInfo *method, Il2CppClass *attr_class);
static Il2CppClass *GetDeclaringType(const MethodInfo* method);
static uint32_t GetImplementationFlags(const MethodInfo *method);
static uint32_t GetFlags(const MethodInfo *method);
static uint32_t GetToken(const MethodInfo *method);
static const char* GetParamName(const MethodInfo *method, uint32_t index);
static bool IsSameOverloadSignature(const MethodInfo* method1, const MethodInfo* method2);
static bool IsSameOverloadSignature(const PropertyInfo* property1, const PropertyInfo* property2);
static int CompareOverloadSignature(const PropertyInfo* property1, const PropertyInfo* property2);
static const char* GetParameterDefaultValue(const MethodInfo *method, const ParameterInfo* parameter, const Il2CppType** type, bool* isExplicitySetNullDefaultValue);
};
} /* namespace vm */
} /* namespace il2cpp */
| [
"y755737878@gmail.com"
] | y755737878@gmail.com |
849ef24335e0b36d1dfd8c34e290191931572be1 | 0dca3325c194509a48d0c4056909175d6c29f7bc | /kms/src/model/ImportCertificateRequest.cc | 100490fa5a78f2ae98502cbeed579bafc6fa34c4 | [
"Apache-2.0"
] | permissive | dingshiyu/aliyun-openapi-cpp-sdk | 3eebd9149c2e6a2b835aba9d746ef9e6bef9ad62 | 4edd799a79f9b94330d5705bb0789105b6d0bb44 | refs/heads/master | 2023-07-31T10:11:20.446221 | 2021-09-26T10:08:42 | 2021-09-26T10:08:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,459 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* 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 <alibabacloud/kms/model/ImportCertificateRequest.h>
using AlibabaCloud::Kms::Model::ImportCertificateRequest;
ImportCertificateRequest::ImportCertificateRequest() :
RpcServiceRequest("kms", "2016-01-20", "ImportCertificate")
{
setMethod(HttpRequest::Method::Post);
}
ImportCertificateRequest::~ImportCertificateRequest()
{}
std::string ImportCertificateRequest::getPKCS12Blob()const
{
return pKCS12Blob_;
}
void ImportCertificateRequest::setPKCS12Blob(const std::string& pKCS12Blob)
{
pKCS12Blob_ = pKCS12Blob;
setParameter("PKCS12Blob", pKCS12Blob);
}
std::string ImportCertificateRequest::getPassphrase()const
{
return passphrase_;
}
void ImportCertificateRequest::setPassphrase(const std::string& passphrase)
{
passphrase_ = passphrase;
setParameter("Passphrase", passphrase);
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
1797d4cc5198a6698f46e9f838b9fa5fc63dacb0 | 00c64e0967d197d8c6fc3427954e2d0b2ff13ca0 | /clang/test/Driver/sycl-deprecated.cpp | 67cdefc855848ebc5bb77857d1b405582eb6515c | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | triSYCL/sycl | 893048e80158cf3359c1ad8912da9ccf493faf69 | 5a95a7136a11b75f01ef839d9229780032bbeecf | refs/heads/sycl/unified/master | 2023-08-23T22:06:46.238209 | 2023-05-24T22:54:31 | 2023-05-24T22:54:31 | 178,923,006 | 103 | 17 | NOASSERTION | 2023-09-12T20:03:26 | 2019-04-01T18:29:01 | null | UTF-8 | C++ | false | false | 1,058 | cpp | /// Test for any deprecated options
// RUN: %clangxx -fsycl-explicit-simd %s -### 2>&1 | FileCheck %s -DOPTION=-fsycl-explicit-simd
// RUN: %clangxx -fno-sycl-explicit-simd %s -### 2>&1 | FileCheck %s -DOPTION=-fno-sycl-explicit-simd
// CHECK: option '[[OPTION]]' is deprecated and will be removed in a future release
// RUN: %clangxx -fsycl -sycl-std=1.2.1 %s -### 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-ARG -DOPTION=-sycl-std= \
// RUN: -DARGUMENT=1.2.1
// RUN: %clangxx -fsycl -sycl-std=121 %s -### 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-ARG -DOPTION=-sycl-std= \
// RUN: -DARGUMENT=121
// RUN: %clangxx -fsycl -sycl-std=sycl-1.2.1 %s -### 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-ARG -DOPTION=-sycl-std= \
// RUN: -DARGUMENT=sycl-1.2.1
// RUN: %clangxx -fsycl -sycl-std=2017 %s -### 2>&1 \
// RUN: | FileCheck %s -check-prefix=CHECK-ARG -DOPTION=-sycl-std= \
// RUN: -DARGUMENT=2017
// CHECK-ARG: argument '[[ARGUMENT]]' for option '[[OPTION]]' is deprecated and will be removed in a future release
| [
"noreply@github.com"
] | noreply@github.com |
ce4f510a806ff0464dd26230ca4727cbe8c9ed2f | e10d706c40d6b7718c6acf05f2183f46b3b795f7 | /15/web_server_Threadpool/locker.h | a6b4ea87e352447920673a8a37fef71c42796310 | [] | no_license | H00ly666/Linux_server | c1a4acd1e11ae5f1a486b3c97baf2cbcc397a2f8 | 44078e6ff4672316e70f2d6de3e5696ed77bde5d | refs/heads/master | 2021-10-22T08:04:41.840900 | 2018-09-22T04:38:42 | 2018-09-22T04:38:42 | 114,195,759 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,078 | h | #ifndef LOCKER_H
#define LOCKER_H
#include <exception>
#include <pthread.h>
#include <semaphore.h>
/*封装信号量的类*/
class sem
{
public:
/*创建并初始化信号量*/
sem()
{
if( sem_init( &m_sem, 0, 0 ) != 0 )
{
/*构造函数没有返回值 可以通过抛出异常来报告错误*/
throw std::exception();
}
}
~sem()
{
sem_destroy( &m_sem );
}
/*等待信号量*/
bool wait()
{
return sem_wait( &m_sem ) == 0;
}
/*增加信号量*/
bool post()
{
return sem_post( &m_sem ) == 0;
}
/**/
private:
sem_t m_sem;
};
/*封装互斥锁的类*/
class locker
{
public:
locker()
{
if( pthread_mutex_init( &m_mutex, NULL ) != 0 )
{
throw std::exception();
}
}
~locker()
{
pthread_mutex_destroy( &m_mutex );
}
bool lock()
{
return pthread_mutex_lock( &m_mutex ) == 0;
}
bool unlock()
{
return pthread_mutex_unlock( &m_mutex ) == 0;
}
private:
pthread_mutex_t m_mutex;
};
/*封装条件变量的类*/
class cond
{
public:
/*创建并初始化*/
cond()
{
if( pthread_mutex_init( &m_mutex, NULL ) != 0 )
{
throw std::exception();
}
if ( pthread_cond_init( &m_cond, NULL ) != 0 )
{
pthread_mutex_destroy( &m_mutex );
throw std::exception();
}
}
~cond()
{
pthread_mutex_destroy( &m_mutex );
pthread_cond_destroy( &m_cond );
}
/*等待条件变量*/
bool wait()
{
int ret = 0;
pthread_mutex_lock( &m_mutex );
ret = pthread_cond_wait( &m_cond, &m_mutex );
pthread_mutex_unlock( &m_mutex );
return ret == 0;
}
/*唤醒一个等待条件变量的线程*/
bool signal()
{
return pthread_cond_signal( &m_cond ) == 0;
}
/*锁加条件变量*/
private:
pthread_mutex_t m_mutex;
pthread_cond_t m_cond;
};
#endif
| [
"hecai4237@gmail.com"
] | hecai4237@gmail.com |
51a3487f814bae5948abb0e86225d704a6223661 | fd88bf8bf77affc30af4fbd9b2e3916bdaa0789b | /ref-impl/src/impl/ImplAAFSetFileBits.h | 1dedb6b42a22243b4ae9b8a9c0ab57c8e5730755 | [] | no_license | jhliberty/AAF | 6e6a7d898d42e6e91690c76afbc4cf581cc716fc | af8c9d43461ab556bd6cf8d98b0f001eb7b87cfe | refs/heads/master | 2021-01-08T11:37:10.299319 | 2016-08-16T02:49:39 | 2016-08-16T02:49:39 | 65,782,219 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,528 | h | #ifndef __ImplAAFSetFileBits_h__
#define __ImplAAFSetFileBits_h__
//=---------------------------------------------------------------------=
//
// $Id: ImplAAFSetFileBits.h,v 1.4 2009/06/01 11:47:08 stuart_hc Exp $ $Name: V116 $
//
// The contents of this file are subject to the AAF SDK Public Source
// License Agreement Version 2.0 (the "License"); You may not use this
// file except in compliance with the License. The License is available
// in AAFSDKPSL.TXT, or you may obtain a copy of the License from the
// Advanced Media Workflow Association, Inc., or its successor.
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
// the License for the specific language governing rights and limitations
// under the License. Refer to Section 3.3 of the License for proper use
// of this Exhibit.
//
// WARNING: Please contact the Advanced Media Workflow Association,
// Inc., for more information about any additional licenses to
// intellectual property covering the AAF Standard that may be required
// to create and distribute AAF compliant products.
// (http://www.amwa.tv/policies).
//
// Copyright Notices:
// The Original Code of this file is Copyright 1998-2009, licensor of the
// Advanced Media Workflow Association. All rights reserved.
//
// The Initial Developer of the Original Code of this file and the
// licensor of the Advanced Media Workflow Association is
// Avid Technology.
// All rights reserved.
//
//=---------------------------------------------------------------------=
#ifndef __ImplAAFRoot_h__
#include "ImplAAFRoot.h"
#endif
#include "OMRawStorage.h"
class ImplAAFSetFileBits : public ImplAAFRoot
{
public:
//
// Constructor/destructor
//
//********
ImplAAFSetFileBits ();
protected:
virtual ~ImplAAFSetFileBits ();
public:
virtual void
Initialize
(OMRawStorage * prs);
//****************
// WriteAt()
//
virtual AAFRESULT STDMETHODCALLTYPE
WriteAt
(// @parm [in, size_is(bufSize)] Buffer from which data is written
aafMemPtr_t buf,
// @parm [in] Number of bytes
aafUInt32 bufSize,
// @parm [in] The position in bytes at which to read
aafUInt64 position);
//****************
// SetSize()
//
virtual AAFRESULT STDMETHODCALLTYPE
SetSize
// @parm [in] The requested file size
(aafUInt64 size);
private:
OMRawStorage * _rep;
};
#endif // ! __ImplAAFSetFileBits_h__
| [
"johnhenry.liberty@gmail.com"
] | johnhenry.liberty@gmail.com |
ad7182dfa82b6f10cf2e0dfcfe15fcfe6041470f | 9c91ca5f8bb181a219b4583f5efbdc3827d2377c | /Source/MainComponent.cpp | 4a21eef13c7742b2b8d905800bea32dd20f242c0 | [] | no_license | mpue/Synthlab | eb686bc11be9ba707c3cae6da86f915d77520986 | 6a2585920ca9fedbf88e54fcede20ac9f24df678 | refs/heads/master | 2022-12-10T19:16:41.918101 | 2022-12-03T17:06:38 | 2022-12-03T17:06:38 | 127,666,213 | 46 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 38,584 | cpp | /*
==============================================================================
This file was auto-generated!
==============================================================================
*/
#include "Plugins/PluginManager.h"
#include "PluginModule.h"
#include "AudioManager.h"
#include "MainComponent.h"
#include "SynthEditor.h"
#include "PropertyView.h"
#include "MainTabbedComponent.h"
#include "MidiGate.h"
#include "MidiNote.h"
#include "PrefabFactory.h"
#include "Project/Project.h"
#include "Knob.h"
#include "Mixer.h"
#include "Actions/RemoveSelectedAction.h"
#include "Actions/AddModuleAction.h"
#include "ModuleBrowser.h"
#include "PitchBendModule.h"
#include "ModuleUtils.h"
#include "MidiClock.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
using juce::String;
using juce::File;
using juce::MenuBarComponent;
using juce::MidiInput;
using juce::Label;
using juce::Slider;
using juce::ScopedPointer;
using juce::XmlDocument;
using juce::XmlElement;
using juce::Toolbar;
using juce::Colour;
using juce::MouseEvent;
using juce::ChoicePropertyComponent;
using juce::MemoryBlock;
using juce::var;
using juce::Image;
using juce::Logger;
using juce::AudioSourceChannelInfo;
using juce::DragAndDropTarget;
using juce::Time;
using juce::Graphics;
using juce::PopupMenu;
using juce::ResizableWindow;
using juce::JUCEApplication;
using juce::StringArray;
using juce::AudioDeviceSelectorComponent;
using juce::DialogWindow;
using juce::LookAndFeel;
using juce::AudioDeviceManager;
using juce::ModalComponentManager;
using juce::ModalCallbackFunction;
using juce::KeyPress;
using juce::Button;
using juce::ToolbarButton;
//==============================================================================
MainComponent::MainComponent() : resizerBar(&stretchableManager, 1, true)
{
// Make sure you set the size of the component after
// you add any child components.
setSize(1280, 800);
// specify the number of input and output channels that we want to open
setAudioChannels(2, 2);
createConfig();
AudioManager::getInstance()->setDeviceManager(&deviceManager);
Project::getInstance()->setCommandManager(this);
if (Project::getInstance()->getAppMode() == Project::AppMode::STUDIO) {
#if defined(JUCE_PLUGINHOST_AU) || defined(JUCE_PLUGINHOST_VST)
PluginManager::getInstance();
#endif
createToolbar();
createCPUMeter();
createMenu();
createKeyMap();
createStudioLayout();
// a global sampler object which allows us to play audio at any place like for preview for example
defaultSampler = new Sampler(sampleRate, buffersize);
Project::getInstance()->setDefaultSampler(defaultSampler);
}
else if (Project::getInstance()->getAppMode() == Project::AppMode::PLAYER) {
createPlayerLayout();
}
Project::getInstance()->setMain(this);
startTimer(20);
enableAllMidiInputs();
addMouseListener(this, true);
editor->addKeyListener(getKeyMappings());
addKeyListener(getKeyMappings());
addKeyListener(this);
editor->setMouseClickGrabsKeyboardFocus(true);
editor->setWantsKeyboardFocus(true);
resized();
repaint();
initialized = true;
running = true;
if (Project::getInstance()->getAppMode() == Project::AppMode::PLAYER) {
editor->loadFromString(String(BinaryData::_3oscV2_slb));
editor->setCurrentLayer(Module::Layer::GUI);
editor->setLocked(true);
}
}
MainComponent::~MainComponent()
{
running = false;
shutdownAudio();
if (Project::getInstance()->getAppMode() == Project::AppMode::STUDIO) {
loadSlider->setLookAndFeel(nullptr);
#if JUCE_MAC
MenuBarModel::setMacMainMenu(nullptr);
#endif
}
editor->removeAllChangeListeners();
disableAllMidiInputs();
if (moduleBrowser != nullptr) {
if (moduleBrowser->isVisible()) {
moduleBrowser->setVisible(false);
}
delete moduleBrowser;
}
if (Project::getInstance()->getAppMode() == Project::AppMode::STUDIO) {
delete tab;
delete view;
delete propertyView;
delete lockButton;
delete menu;
delete toolbar;
delete toolbarFactory;
delete editorView;
#if defined(JUCE_PLUGINHOST_AU)
delete pluginMenu;
#endif
delete cpuLoadLabel;
delete loadSlider;
}
else if (Project::getInstance()->getAppMode() == Project::AppMode::PLAYER) {
delete editor;
delete tab;
delete propertyView;
delete toolbarFactory;
delete editorView;
delete mixerPanel;
delete lockButton;
}
if (defaultSampler != nullptr) {
delete defaultSampler;
}
PrefabFactory::getInstance()->destroy();
Project::getInstance()->destroy();
// This shuts down the audio device and clears the audio source.
}
void MainComponent::createMenu() {
this->menu = new MenuBarComponent();
#if JUCE_MAC
menu->setModel(nullptr);
MenuBarModel::setMacMainMenu(this);
#else
menu->setModel(this);
menu->setBounds(0, 0, 1000, 25);
addAndMakeVisible(menu);
#endif
}
void MainComponent::createConfig() {
String userHome = File::getSpecialLocation(File::userHomeDirectory).getFullPathName();
File appDir = File(userHome + "/.Synthlab");
if (!appDir.exists()) {
appDir.createDirectory();
}
File configFile = File(userHome + "/.Synthlab/config.xml");
if (configFile.exists()) {
std::unique_ptr<XmlElement> xml = XmlDocument(configFile).getDocumentElement();
deviceManager.initialise(2, 2, xml.get(), true);
}
}
void MainComponent::createToolbar() {
toolbar = new Toolbar();
#if JUCE_MAC
#else
toolbar->setBounds(0, 25, getWidth(), 50);
#endif
addAndMakeVisible(toolbar);
toolbarFactory = new DefaultToolbarItemFactory();
for (int i = 0; i < toolbarFactory->numItems(); i++) {
toolbar->addItem(*toolbarFactory, i + 1);
toolbar->getItemComponent(i)->addListener(this);
if (layerCombobox == nullptr) {
layerCombobox = dynamic_cast<ToolbarComboBox*>(toolbar->getItemComponent(i));
}
if (layerCombobox != nullptr) {
layerCombobox->getComboBox().addListener(this);
}
}
lockButton = new ImageButton("Lock");
Image normalImage = juce::ImageCache::getFromMemory(BinaryData::unlock_png, BinaryData::unlock_pngSize);
Image downImage = juce::ImageCache::getFromMemory(BinaryData::lock_png, BinaryData::lock_pngSize);
lockButton->setImages(false, true, true, normalImage, 1.0f, juce::Colours::white, normalImage, 1.0, juce::Colours::white, downImage, 1.0f, juce::Colours::white);
lockButton->setClickingTogglesState(true);
lockButton->setSize(24, 24);
lockButton->setTopLeftPosition(1600, 10);
toolbar->addAndMakeVisible(lockButton);
lockButton->addListener(this);
}
void MainComponent::createCPUMeter() {
cpuLoadLabel = new Label("0%");
cpuLoadLabel->setText("0%", juce::NotificationType::dontSendNotification);
toolbar->addAndMakeVisible(cpuLoadLabel);
loadSlider = new Slider();
loadSlider->setRange(0, 100, 1);
loadSlider->setSliderStyle(Slider::LinearBar);
loadSlider->setTextBoxStyle(Slider::NoTextBox, false, 80, 20);
loadSlider->setColour(Slider::backgroundColourId, Colour(0xff313131));
loadSlider->setColour(Slider::thumbColourId, Colours::chartreuse);
loadSlider->setColour(Slider::trackColourId, Colour(0xff434242));
loadSlider->setColour(Slider::rotarySliderOutlineColourId, Colour(0x66ffffff));
loadSlider->setColour(Slider::textBoxBackgroundColourId, Colour(0x00ffffff));
loadSlider->setLookAndFeel(Project::getInstance()->getLookAndFeel());
addAndMakeVisible(loadSlider);
}
void MainComponent::createStudioLayout() {
propertyView = new PropertyView();
editorView = new EditorComponent(sampleRate, buffersize, propertyView);
editor = editorView->getEditor();
mixer = editorView->getMixer();
mixerPanel = editorView->getMixerPanel();
#if JUCE_MAC
#else
propertyView->setTopLeftPosition(0, 75);
#endif
editor->addEditorListener(propertyView);
propertyView->getBrowser()->addChangeListener(editor);
Project::getInstance()->setPropertyView(propertyView);
addAndMakeVisible(propertyView);
addAndMakeVisible(resizerBar);
addAndMakeVisible(editorView);
editor->setTab(editorView->getEditorTab());
editorView->getEditorTab()->addChangeListener(this);
editor->addEditorListener(this);
addMouseListener(propertyView->getBrowser(), false);
registerAllCommandsForTarget(editor);
setFirstCommandTarget(editor);
// we have to set up our StretchableLayoutManager so it know the limits and preferred sizes of it's contents
stretchableManager.setItemLayout(0, // for the properties
-0.1, -0.9, // must be between 50 pixels and 90% of the available space
-0.2); // and its preferred size is 30% of the total available space
stretchableManager.setItemLayout(1, // for the resize bar
5, 5, 5); // hard limit to 5 pixels
stretchableManager.setItemLayout(2, // for the main editor
-0.1, -0.9, // size must be between 50 pixels and 90% of the available space
-0.8);
#if defined(JUCE_PLUGINHOST_AU) || defined(JUCE_PLUGINHOST_VST)
pluginMenu = PluginManager::getInstance()->buildPluginMenu();
#endif
editor->updateProject(File());
}
void MainComponent::createPlayerLayout() {
editor = new SynthEditor(sampleRate, buffersize);
mixerPanel = new MixerPanel();
mixer = Mixer::getInstance();
mixerPanel->setMixer(mixer);
editor->setMixer(mixerPanel);
addAndMakeVisible(editor);
addChildComponent(mixerPanel);
}
void MainComponent::timerCallback() {
if (mixerPanel != nullptr) {
for (int i = 0; i < mixer->getChannels().size(); i++) {
mixerPanel->getChannels().at(i)->setMagnitude(0, mixer->getChannels().at(i)->magnitudeLeft);
mixerPanel->getChannels().at(i)->setMagnitude(1, mixer->getChannels().at(i)->magnitudeRight);
}
}
if (Project::getInstance()->getAppMode() == Project::AppMode::STUDIO) {
currentMeasure = (currentMeasure + 1) % 10;
loads[currentMeasure] = cpuLoad;
if (currentMeasure == 0) {
for (int i = 0; i < 10; i++) {
cpuLoad += loads[i];
}
cpuLoad /= 10;
if (cpuLoad < 0) {
cpuLoad = 0;
}
if (cpuLoad == NAN) {
cpuLoad = 0;
}
loadSlider->setValue(cpuLoad);
cpuLoadLabel->setText(String(cpuLoad) + "%", juce::NotificationType::dontSendNotification);
}
}
}
/*
void MainComponent::mouseDrag (const MouseEvent& event) {
if(Project::getInstance()->getAppMode() == Project::AppMode::PLAYER) {
return;
}
var description;
TabBarButton* t = dynamic_cast<TabBarButton*>(event.originalComponent);
if (t != nullptr) {
description.append("tab");
Logger::writeToLog("Drag from tab "+t->getParentComponent()->getName());
startDragging(description,t->getParentComponent());
}
else {
description.append("property");
startDragging(description,propertyView->getBrowser());
//}
}
void MainComponent::dragOperationStarted (const DragAndDropTarget::SourceDetails& details) {
if(Project::getInstance()->getAppMode() == Project::AppMode::PLAYER) {
return;
}
TabbedButtonBar* tbb = dynamic_cast<TabbedButtonBar*>(details.sourceComponent.get());
if(tbb != nullptr) {
int index = tbb->getCurrentTabIndex();
MainTabbedComponent* tab = dynamic_cast<MainTabbedComponent*>(tbb->getParentComponent());
if (tab != nullptr) {
setDragImageForIndex(0,tab->getComponentAt(index)->createComponentSnapshot(tab->getComponentAt(index)->getLocalBounds()));
}
}
else {
setDragImageForIndex(0, Image());
// }
}
*/
//==============================================================================
void MainComponent::prepareToPlay(int samplesPerBlockExpected, double sampleRate)
{
Logger::writeToLog("prepare to play with sample rate " + String(sampleRate) + " kHz and buffer size of " + String(buffersize) + " bytes.");
this->sampleRate = sampleRate;
this->buffersize = samplesPerBlockExpected;
if (editor != nullptr) {
editor->prepareToPlay(samplesPerBlockExpected, sampleRate);
}
}
int MainComponent::getNumActiveChannels(int i) {
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
void MainComponent::getNextAudioBlock(const AudioSourceChannelInfo& bufferToFill)
{
lastTime = (long)Time::getMillisecondCounterHiRes() - currentTime;
currentTime = (long)Time::getMillisecondCounterHiRes();
long startTime = currentTime;
int numSamples = bufferToFill.numSamples;
float** outputChannelData = bufferToFill.buffer->getArrayOfWritePointers();
if (outputChannelData == NULL) {
return;
}
// const float** inputChannelData = bufferToFill.buffer->getArrayOfReadPointers();
if (defaultSampler != nullptr && defaultSampler->isPlaying()) {
for (int j = 0; j < numSamples; j++) {
outputChannelData[0][j] += defaultSampler->getOutput(0);
outputChannelData[1][j] += defaultSampler->getOutput(1);
defaultSampler->nextSample();
}
}
if (!running) {
return;
}
if (editor->getModule() != nullptr)
processModule(editor->getModule());
std::vector<AudioOut*> outputChannels = editor->getMixer()->getOutputChannels();
std::vector<AudioIn*> inputChannels = editor->getMixer()->getInputChannels();
std::vector<AuxOut*> auxChannels = editor->getMixer()->getAuxChannels();
for (int k = 0; k < mixer->getNumInputs(); k++) {
Mixer::Channel* input = mixer->getChannel(Mixer::Channel::Type::IN, k);
if (input != nullptr) {
double pan = input->pan;
float gainLeft = cos((M_PI * (pan + 1) / 4));
float gainRight = sin((M_PI * (pan + 1) / 4));
inputChannels.at(k)->pins.at(0)->getAudioBuffer()->copyFrom(0, bufferToFill.startSample, *bufferToFill.buffer, k, bufferToFill.startSample, numSamples);
inputChannels.at(k)->pins.at(1)->getAudioBuffer()->copyFrom(0, bufferToFill.startSample, *bufferToFill.buffer, k + 1, bufferToFill.startSample, numSamples);
inputChannels.at(k)->pins.at(0)->getAudioBuffer()->applyGain(0, bufferToFill.startSample, numSamples, input->volume * gainLeft);
inputChannels.at(k)->pins.at(1)->getAudioBuffer()->applyGain(0, bufferToFill.startSample, numSamples, input->volume * gainRight);
input->magnitudeLeft = inputChannels.at(k)->pins.at(0)->getAudioBuffer()->getMagnitude(0, bufferToFill.startSample, numSamples);
input->magnitudeRight = inputChannels.at(k)->pins.at(1)->getAudioBuffer()->getMagnitude(0, bufferToFill.startSample, numSamples);
}
}
// mute if there are no channels
if (mixer->getNumOutputs() == 0) {
if (defaultSampler != nullptr && defaultSampler->isPlaying()) {
}
else {
for (int j = 0; j < numSamples; j++) {
if (outputChannelData[0] != NULL) {
outputChannelData[0][j] = 0;
}
if (outputChannelData[1] != NULL) {
outputChannelData[1][j] = 0;
}
}
}
}
else {
Mixer::Channel* outputChannel = mixer->getChannel(Mixer::Channel::Type::OUT, 0);
float channelVolume = outputChannel->mute ? 0 : outputChannel->volume;
double pan = outputChannel->pan;
float gainLeft = cos((M_PI * (pan + 1) / 4));
float gainRight = sin((M_PI * (pan + 1) / 4));
// process all output pins of the connected module
for (int j = 0; j < numSamples; j++) {
float auxLeftOut = 0;
// merge the output of the AUX busses
for (int k = 0; k < auxChannels.size(); k++) {
if (editor->getMixer()->auxChannelIsValid(k, 0)) {
const float* auxL = auxChannels.at(k)->getPins().at(0)->getConnections().at(0)->getAudioBuffer()->getReadPointer(0);
Mixer::Channel* channel = mixer->getChannel(Mixer::Channel::Type::AUX, k);
if (channel != NULL) {
float auxVolume = channel->mute ? 0 : channel->volume;
double auxpan = channel->pan;
float auxgainLeft = cos((M_PI * (auxpan + 1) / 4));
channel->magnitudeLeft = auxVolume * auxgainLeft * auxChannels.at(k)->getPins().at(0)->getConnections().at(0)->getAudioBuffer()->getMagnitude(0, 0, numSamples);
auxLeftOut += auxL[j] * auxVolume * auxgainLeft;
}
}
}
if (editor->getMixer()->channelIsValid(0)) {
// outputChannels.at(0)->getPins().at(0)->connections.at(0)->getAudioBuffer()->applyGain(channelVolume);
const float* outL = outputChannels.at(0)->getPins().at(0)->getConnections().at(0)->getAudioBuffer()->getReadPointer(0);
outputChannelData[0][j] += channelVolume * (outL[j] + auxLeftOut) * gainLeft;
}
else {
outputChannelData[0][j] = auxLeftOut;
}
float auxRightOut = 0;
for (int k = 0; k < auxChannels.size(); k++) {
if (editor->getMixer()->auxChannelIsValid(k, 1)) {
const float* auxR = auxChannels.at(k)->getPins().at(1)->getConnections().at(0)->getAudioBuffer()->getReadPointer(0);
Mixer::Channel* channel = mixer->getChannel(Mixer::Channel::Type::AUX, k);
if (channel != nullptr) {
float auxVolume = channel->mute ? 0 : channel->volume;
double auxpan = channel->pan;
float auxgainRight = sin((M_PI * (auxpan + 1) / 4));
channel->magnitudeRight = auxVolume * auxgainRight * auxChannels.at(k)->getPins().at(1)->getConnections().at(0)->getAudioBuffer()->getMagnitude(0, 0, numSamples);
auxRightOut += auxR[j] * auxVolume * auxgainRight;
}
}
}
if (editor->getMixer()->channelIsValid(1)) {
// outputChannels.at(0)->getPins().at(1)->connections.at(0)->getAudioBuffer()->applyGain(channelVolume);
const float* outR = outputChannels.at(0)->getPins().at(1)->getConnections().at(0)->getAudioBuffer()->getReadPointer(0);
if (outputChannelData[1] != NULL)
outputChannelData[1][j] += channelVolume * (outR[j] + auxRightOut) * gainRight;
}
else {
if (outputChannelData[1] != NULL)
outputChannelData[1][j] = auxRightOut;
}
}
if (editor->getMixer()->channelIsValid(0))
outputChannel->magnitudeLeft = channelVolume * gainLeft * outputChannels.at(0)->getPins().at(0)->getConnections().at(0)->getAudioBuffer()->getMagnitude(0, 0, numSamples);
if (editor->getMixer()->channelIsValid(1))
outputChannel->magnitudeRight = channelVolume * gainRight * outputChannels.at(0)->getPins().at(1)->getConnections().at(0)->getAudioBuffer()->getMagnitude(0, 0, numSamples);
}
long duration = Time::getMillisecondCounterHiRes() - startTime;
cpuLoad = ((float)duration / (float)lastTime) * 100;
currentSample = (currentSample + 1) % numSamples;
if (navigator == nullptr) {
navigator = editorView->getNavigator();
}
if (navigator != nullptr && (navigator->isPlaying() || navigator->isRecording())) {
navigator->setSamplePosition(navigator->getSamplePosition() + numSamples);
}
}
void MainComponent::releaseResources()
{
}
//==============================================================================
void MainComponent::paint(Graphics& g)
{
g.fillAll(Colour(0xff222222));
}
void MainComponent::resized()
{
if (Project::getInstance()->getAppMode() == Project::AppMode::STUDIO) {
auto r = getLocalBounds().reduced(4).removeFromBottom(getHeight() - 55);
if (toolbar != nullptr)
toolbar->setSize(getLocalBounds().getWidth(), 50);
// make a list of two of our child components that we want to reposition
Component* comps[] = { propertyView, &resizerBar, editorView };
// this will position the 3 components, one above the other, to fit
// vertically into the rectangle provided.
stretchableManager.layOutComponents(comps, 3,
r.getX(), r.getY() + 25, r.getWidth(), r.getHeight(),
false, true);
if (propertyView != nullptr && propertyView->getParentComponent() != NULL)
propertyView->setSize(r.getWidth() - editorView->getWidth(), propertyView->getHeight());
if (getParentComponent() != nullptr) {
if (cpuLoadLabel != NULL) {
cpuLoadLabel->setBounds(getParentComponent()->getWidth() - 50, 0, 50, 20);
loadSlider->setBounds(getParentComponent()->getWidth() - 150, 10, 100, 10);
}
if (editorView != NULL) {
editorView->getEditor()->resized();
}
if (menu != NULL) {
menu->setBounds(0, 0, getParentWidth(), 25);
}
}
}
else {
if (getParentComponent() != nullptr && editorView != nullptr) {
editorView->setSize(getParentWidth(), getParentHeight());
editorView->getEditor()->resized();
}
}
}
PopupMenu MainComponent::getMenuForIndex(int index, const String& menuName) {
PopupMenu menu;
if (index == 0) {
menu.addCommandItem(this, SynthEditor::CommandIds::NEW);
menu.addCommandItem(this, SynthEditor::CommandIds::LOAD);
menu.addCommandItem(this, SynthEditor::CommandIds::EXPORT_AUDIO);
menu.addCommandItem(this, SynthEditor::CommandIds::SAVE);
menu.addItem(5, "Settings", true, false, nullptr);
menu.addItem(6, "Import Audio", true, false, nullptr);
menu.addItem(7, "Play", true, false, nullptr);
menu.addItem(8, "Stop", true, false, nullptr);
PopupMenu samplesMenu = PopupMenu();
for (int i = 0; i < BinaryData::namedResourceListSize; i++) {
if (juce::String(BinaryData::namedResourceList[i]).contains("slb")) {
samplesMenu.addItem(1000 + i, String(BinaryData::namedResourceList[i]));
int size;
const char* data = BinaryData::getNamedResource(BinaryData::namedResourceList[i], size);
String xmlData = String(data);
sampleData.add(xmlData);
}
}
menu.addSubMenu("Samples", samplesMenu);
menu.addItem(999, "Exit", true, false, nullptr);
}
else if (index == 1) {
#if defined(JUCE_PLUGINHOST_AU) || defined(JUCE_PLUGINHOST_VST)
menu.addItem(200, "Manage plugins", true, false, nullptr);
#endif
menu.addItem(201, "Tracks", true, false, nullptr);
}
else if (index == 2) {
if (pluginMenu != nullptr)
return *pluginMenu;
}
else if (index == 3) {
menu.addCommandItem(this, SynthEditor::CommandIds::DUPLICATE);
menu.addCommandItem(this, SynthEditor::CommandIds::DELETE_SELECTED);
menu.addCommandItem(this, SynthEditor::CommandIds::RESET_GUI_POS);
PopupMenu alignMenu = PopupMenu();
alignMenu.addCommandItem(this, SynthEditor::CommandIds::ALIGN_X);
alignMenu.addCommandItem(this, SynthEditor::CommandIds::ALIGN_Y);
menu.addItem(8, "Add Audio Track", true, false, nullptr);
menu.addSubMenu("Align", alignMenu);
}
return menu;
}
void MainComponent::menuItemSelected(int menuItemID, int topLevelMenuIndex) {
if (menuItemID == 5) {
openSettings();
}
else if (menuItemID == 6) {
editorView->ImportAudio();
}
else if (menuItemID == 7) {
editorView->getNavigator()->setPlaying(true);
}
else if (menuItemID == 7) {
editorView->getNavigator()->setPlaying(false);
}
#if defined(JUCE_PLUGINHOST_AU) || defined(JUCE_PLUGINHOST_VST)
else if (menuItemID == 200) {
PluginManager::getInstance()->scanPlugins();
}
#endif
else if (menuItemID == 201) {
editorView->OpenTrackView();
editorView->getNavigator()->addChangeListener(this);
}
else if (menuItemID == 8) {
if (editorView->getNavigator() == nullptr) {
editorView->OpenTrackView();
editorView->getNavigator()->addChangeListener(this);
}
editor->createTrack();
editor->repaint();
}
else if (menuItemID == 31) {
editor->duplicateSelected();
}
#if defined(JUCE_PLUGINHOST_AU) || defined(JUCE_PLUGINHOST_VST)
else if (menuItemID > 100 && menuItemID < 999) {
String pluginName = PluginManager::getInstance()->getAvailablePlugins().at(menuItemID - 100);
if (editor->getSelectionModel().getSelectedModule() != nullptr) {
PluginModule* pm = dynamic_cast<PluginModule*>(editor->getSelectionModel().getSelectedModule());
if (pm != NULL) {
pm->selectPlugin(pluginName);
}
}
}
#endif
else if (menuItemID == 999) {
JUCEApplication::getInstance()->shutdown();
}
else if (menuItemID >= 1000) {
String xmlData = sampleData.getReference(menuItemID - 1000);
editor->setRunning(false);
editor->cleanUp();
editor->newFile();
editor->loadFromString(xmlData);
editor->setRunning(true);
}
}
StringArray MainComponent::getMenuBarNames() {
#if defined(JUCE_PLUGINHOST_AU) || defined(JUCE_PLUGINHOST_VST)
const char* const names[] = { "File", "View","Plugins", "Edit", nullptr };
#else
const char* const names[] = { "File", "View", "Edit", nullptr };
#endif
return StringArray(names);
}
void MainComponent::openSettings() {
AudioDeviceSelectorComponent* selector = new AudioDeviceSelectorComponent(deviceManager, 2, 16, 2, 16, true, true, true, false);
DialogWindow::LaunchOptions launchOptions;
selector->setLookAndFeel(Project::getInstance()->getLookAndFeel());
launchOptions.dialogTitle = ("Audio Settings");
launchOptions.escapeKeyTriggersCloseButton = true;
launchOptions.resizable = false;
launchOptions.useNativeTitleBar = false;
launchOptions.useBottomRightCornerResizer = true;
launchOptions.componentToCentreAround = getParentComponent();
launchOptions.content.setOwned(selector);
launchOptions.content->setSize(600, 580);
launchOptions.dialogBackgroundColour = Colour(0xff222222);
DialogWindow* window = launchOptions.launchAsync();
std::function<void(int)> lambda =
[=](int result) {
AudioDeviceManager::AudioDeviceSetup setup;
deviceManager.getAudioDeviceSetup(setup);
deviceManager.restartLastAudioDevice();
AudioManager::getInstance()->setupChannels();
refreshMidiInputs();
std::unique_ptr<XmlElement> config = deviceManager.createStateXml();
String userHome = File::getSpecialLocation(File::userHomeDirectory).getFullPathName();
File appDir = File(userHome + "/.Synthlab");
if (!appDir.exists()) {
appDir.createDirectory();
}
File configFile = File(userHome + "/.Synthlab/config.xml");
if (config != NULL) {
config->writeToFile(configFile, "");
config = nullptr;
}
};
ModalComponentManager::Callback* callback = ModalCallbackFunction::create(lambda);
ModalComponentManager::getInstance()->attachCallback(window, callback);
Project::getInstance()->getOpenWindows().push_back(window);
}
bool MainComponent::keyStateChanged(bool isKeyDown, juce::Component* originatingComponent) {
for (std::map<int, int>::iterator it = keyCodeMidiNote.begin(); it != keyCodeMidiNote.end(); it++) {
if (KeyPress::isKeyCurrentlyDown((*it).first)) {
if (!keyStates[(*it).second]) {
sendNoteMessage(editor->getModule(), 1, (*it).second + 12 * currentOctave);
sendGateMessage(editor->getModule(), 1, 64, (*it).second + 12 * currentOctave, true);
keyStates[(*it).second] = true;
}
}
else {
keyStates[(*it).second] = false;
if (!isKeyDown) {
sendGateMessage(editor->getModule(), 1, 0, (*it).second + 12 * currentOctave, false);
}
}
}
return true;
}
void MainComponent::modifierKeysChanged(const juce::ModifierKeys& modifiers) {
isOptionPressed = modifiers.isAltDown();
}
bool MainComponent::keyPressed(const juce::KeyPress& key, juce::Component* originatingComponent) {
if (key.getTextCharacter() == 'y') {
if (currentOctave > 0) {
currentOctave--;
}
}
if (key.getTextCharacter() == 'x') {
if (currentOctave < 8) {
currentOctave++;
}
}
if (key.getTextCharacter() == 'l') {
layer = (layer + 1) % 4;
editor->setCurrentLayer(layer);
editor->repaint();
}
if (key.getTextCharacter() == 'd' && isOptionPressed) {
editor->duplicateSelected();
editor->repaint();
}
return true;
}
void MainComponent::createKeyMap() {
keyCodeMidiNote['a'] = 36;
keyCodeMidiNote['w'] = 36;
keyCodeMidiNote['s'] = 38;
keyCodeMidiNote['e'] = 39;
keyCodeMidiNote['d'] = 40;
keyCodeMidiNote['f'] = 41;
keyCodeMidiNote['t'] = 42;
keyCodeMidiNote['g'] = 43;
keyCodeMidiNote['z'] = 44;
keyCodeMidiNote['h'] = 45;
keyCodeMidiNote['u'] = 46;
keyCodeMidiNote['j'] = 47;
keyCodeMidiNote['k'] = 48;
keyCodeMidiNote['o'] = 49;
}
void MainComponent::buttonClicked(Button* b)
{
ToolbarButton* tb = dynamic_cast<ToolbarButton*>(b);
if (tb != NULL) {
if (tb->getItemId() == toolbarFactory->delete_element) {
RemoveSelectedAction* rma = new RemoveSelectedAction(editor);
Project::getInstance()->getUndoManager()->beginNewTransaction();
Project::getInstance()->getUndoManager()->perform(rma);
}
else if (tb->getItemId() == toolbarFactory->doc_new) {
Project::getInstance()->setNewFile(true);
editor->setRunning(false);
editor->cleanUp();
editor->newFile();
editor->setRunning(true);
}
else if (tb->getItemId() == toolbarFactory->doc_save) {
editor->saveFile();
}
else if (tb->getItemId() == toolbarFactory->doc_open) {
editor->setRunning(false);
editor->openFile();
editor->setRunning(true);
}
else if (tb->getItemId() == toolbarFactory->app_settings) {
openSettings();
}
else if (tb->getItemId() == toolbarFactory->app_undo) {
Project::getInstance()->getUndoManager()->undo();
}
else if (tb->getItemId() == toolbarFactory->app_redo) {
Project::getInstance()->getUndoManager()->redo();
}
else if (tb->getItemId() == toolbarFactory->mod_sources) {
if (moduleBrowser == nullptr) {
moduleBrowser = new ModuleBrowser();
addChildComponent(moduleBrowser);
}
if (!moduleBrowser->isVisible()) {
moduleBrowser->setTopLeftPosition(b->getX(), b->getY() + b->getHeight());
moduleBrowser->setVisible(true);
moduleBrowser->toFront(true);
}
else {
moduleBrowser->setVisible(false);
}
}
else if (tb->getItemId() == toolbarFactory->app_stop) {
if (navigator != nullptr) {
if (navigator->isPlaying() || navigator->isRecording()) {
navigator->setPlaying(false);
navigator->setRecording(false);
}
else {
navigator->ResetMarkerPosition();
}
}
}
else if (tb->getItemId() == toolbarFactory->app_play) {
if (navigator != nullptr)
navigator->setPlaying(true);
}
else if (tb->getItemId() == toolbarFactory->app_record) {
if (navigator != nullptr)
navigator->setRecording(true);
}
else if (tb->getItemId() == toolbarFactory->app_fast_backwards) {
if (navigator != nullptr)
navigator->ResetMarkerPosition();
}
}
if (b == lockButton) {
editor->setLocked(lockButton->getToggleState());
}
}
void MainComponent::handleIncomingMidiMessage(juce::MidiInput* source, const juce::MidiMessage& message) {
if (message.isNoteOn() && message.getNoteNumber() > 7) {
for (int i = 0; i < editor->getModule()->getModules()->size(); i++) {
sendNoteMessage(editor->getModule()->getModules()->at(i), message.getChannel(), message.getNoteNumber());
sendGateMessage(editor->getModule()->getModules()->at(i), message.getChannel(), message.getVelocity(), message.getNoteNumber(), true);
}
}
else if (message.isNoteOff() && message.getNoteNumber() > 7) {
for (int i = 0; i < editor->getModule()->getModules()->size(); i++) {
sendGateMessage(editor->getModule()->getModules()->at(i), message.getChannel(), message.getVelocity(), message.getNoteNumber(), false);
}
}
else if (message.isController()) {
for (int i = 0; i < editor->getModule()->getModules()->size(); i++) {
sendControllerMessage(editor->getModule()->getModules()->at(i), message.getChannel(), message.getControllerNumber(), message.getControllerValue());
}
}
else if (message.isPitchWheel()) {
for (int i = 0; i < editor->getModule()->getModules()->size(); i++) {
sendPitchBendMessage(editor->getModule()->getModules()->at(i), message.getChannel(), message.getPitchWheelValue());
}
}
else if (message.isMidiClock()) {
for (int i = 0; i < editor->getModule()->getModules()->size(); i++) {
sendClockMessage(editor->getModule()->getModules()->at(i), message.getChannel());
}
}
else if (message.isMidiStart()) {
for (int i = 0; i < editor->getModule()->getModules()->size(); i++) {
sendMidiStartMessage(editor->getModule()->getModules()->at(i), message.getChannel());
}
}
else if (message.isMidiStop()) {
for (int i = 0; i < editor->getModule()->getModules()->size(); i++) {
sendMidiStopMessage(editor->getModule()->getModules()->at(i), message.getChannel());
}
}
else if (message.isMidiMachineControlMessage()) {
MidiMessage::MidiMachineControlCommand command = message.getMidiMachineControlCommand();
switch (command)
{
case MidiMessage::MidiMachineControlCommand::mmc_play:
Logger::writeToLog("mmc_play");
break;
case MidiMessage::MidiMachineControlCommand::mmc_stop:
Logger::writeToLog("mmc_stop");
break;
default:
break;
}
}
else {
Logger::writeToLog(message.getDescription());
}
// deviceManager.getDefaultMidiOutput()->sendMessageNow(message);
}
void MainComponent::sendGateMessage(Module* module, int channel, int velocity, int note, bool on) {
MidiGate* gate;
if ((gate = dynamic_cast<MidiGate*>(module)) != NULL) {
if (gate->getChannel() == channel) {
if (on) {
if (velocity > 0)
gate->gateOn(velocity, note);
}
else {
gate->gateOff(note);
}
}
}
for (int i = 0; i < module->getModules()->size(); i++) {
if ((gate = dynamic_cast<MidiGate*>(module->getModules()->at(i))) != NULL) {
if (gate->getChannel() == channel) {
if (on) {
gate->gateOn(velocity, note);
}
else {
gate->gateOff(note);
}
sendGateMessage(module->getModules()->at(i), channel, velocity, note, on);
}
}
}
}
void MainComponent::sendNoteMessage(Module* module, int channel, int note) {
MidiNote* midiNote;
if ((midiNote = dynamic_cast<MidiNote*>(module)) != NULL) {
if (note > 0)
midiNote->note(note);
}
for (int i = 0; i < module->getModules()->size(); i++) {
if ((midiNote = dynamic_cast<MidiNote*>(module->getModules()->at(i))) != NULL) {
sendNoteMessage(module->getModules()->at(i), channel, note);
}
}
}
void MainComponent::sendClockMessage(Module* module, int channel) {
MidiClock* midiClock;
if ((midiClock = dynamic_cast<MidiClock*>(module)) != NULL) {
midiClock->clock(MidiMessage::midiClock());
}
for (int i = 0; i < module->getModules()->size(); i++) {
if ((midiClock = dynamic_cast<MidiClock*>(module->getModules()->at(i))) != NULL) {
sendClockMessage(module->getModules()->at(i), channel);
}
}
}
void MainComponent::sendMidiStartMessage(Module* module, int channel) {
MidiClock* midiClock;
if ((midiClock = dynamic_cast<MidiClock*>(module)) != NULL) {
midiClock->midiStart();
}
for (int i = 0; i < module->getModules()->size(); i++) {
if ((midiClock = dynamic_cast<MidiClock*>(module->getModules()->at(i))) != NULL) {
sendMidiStartMessage(module->getModules()->at(i), channel);
}
}
}
void MainComponent::sendMidiStopMessage(Module* module, int channel) {
MidiClock* midiClock;
if ((midiClock = dynamic_cast<MidiClock*>(module)) != NULL) {
midiClock->midiStop();
}
for (int i = 0; i < module->getModules()->size(); i++) {
if ((midiClock = dynamic_cast<MidiClock*>(module->getModules()->at(i))) != NULL) {
sendMidiStopMessage(module->getModules()->at(i), channel);
}
}
}
void MainComponent::sendPitchBendMessage(Module* module, int channel, int pitch) {
PitchBendModule* pbm;
if ((pbm = dynamic_cast<PitchBendModule*>(module)) != NULL) {
pbm->setPitch(pitch);
}
for (int i = 0; i < module->getModules()->size(); i++) {
if ((pbm = dynamic_cast<PitchBendModule*>(module->getModules()->at(i))) != NULL) {
sendPitchBendMessage(module->getModules()->at(i), channel, pitch);
}
}
}
void MainComponent::sendControllerMessage(Module* module, int channel, int controller, float value) {
Knob* k;
if ((k = dynamic_cast<Knob*>(module)) != NULL) {
if (k->isLearning()) {
k->setIsMidicontroller(true);
k->setController(controller);
k->setLearning(false);
}
if (k->getController() == controller) {
k->setValue(value);
}
}
for (int i = 0; i < module->getModules()->size(); i++) {
if ((k = dynamic_cast<Knob*>(module->getModules()->at(i))) != NULL) {
sendControllerMessage(module->getModules()->at(i), channel, controller, value);
}
}
}
void MainComponent::processModule(Module* m) {
if (m != nullptr && running) {
m->process();
for (int i = 0; i < m->getModules()->size(); i++) {
if (m->getModules()->at(i) != nullptr) {
processModule(m->getModules()->at(i));
}
}
}
}
void MainComponent::refreshMidiInputs() {
for (int i = 0; i < MidiInput::getDevices().size(); i++) {
if (deviceManager.isMidiInputEnabled(MidiInput::getDevices().getReference(i))) {
deviceManager.removeMidiInputCallback(MidiInput::getDevices().getReference(i), this);
deviceManager.addMidiInputCallback(MidiInput::getDevices().getReference(i), this);
}
}
}
void MainComponent::enableAllMidiInputs() {
for (int i = 0; i < MidiInput::getDevices().size(); i++) {
if (deviceManager.isMidiInputEnabled(MidiInput::getDevices().getReference(i))) {
deviceManager.addMidiInputCallback(MidiInput::getDevices().getReference(i), this);
}
}
}
void MainComponent::disableAllMidiInputs() {
for (int i = 0; i < MidiInput::getDevices().size(); i++) {
if (deviceManager.isMidiInputEnabled(MidiInput::getDevices().getReference(i))) {
deviceManager.removeMidiInputCallback(MidiInput::getDevices().getReference(i), this);
}
}
}
void MainComponent::changeListenerCallback(juce::ChangeBroadcaster* source) {
TrackNavigator* navigator = dynamic_cast<TrackNavigator*>(source);
if (navigator != nullptr) {
currentSample = navigator->getSamplePosition();
}
}
void MainComponent::comboBoxChanged(juce::ComboBox* comboBoxThatHasChanged) {
int id = comboBoxThatHasChanged->getSelectedId() - 1;
editor->setCurrentLayer(id);
}
void MainComponent::selectionChanged(juce::Component* m) {
}
void MainComponent::fileChanged(juce::String name) {
lockButton->setToggleState(editor->isLocked(), juce::NotificationType::dontSendNotification);
if (layerCombobox != NULL)
layerCombobox->getComboBox().setSelectedId(editor->getCurrentLayer() + 1);
}
void MainComponent::dirtyChanged(bool dirty) {
}
| [
"matthias@pueski.de"
] | matthias@pueski.de |
bd8a7823a13963ac2891ed660dd2e23c1d5721d8 | bfaece7c27b5c3a7113918b5743ac16e8caed270 | /tests/performance_tests/main.cpp | c35d78dcde3efad0e8555b5361dedf65d77c9170 | [
"BSD-3-Clause"
] | permissive | enro-project/enro | fe0f38924260f0b5721a2a0e68e72d5cffb9bf49 | 96b709239c5fa059ea6c4c3c8ba0f431964f1344 | refs/heads/master | 2020-04-12T03:34:10.752640 | 2018-12-19T00:08:08 | 2018-12-19T00:08:08 | 162,269,737 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,420 | cpp | // Copyright (c) 2014-2018, The Enro Project Copyright (c) 2014-2018, The Monero Project
//
// 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.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include <boost/regex.hpp>
#include "common/util.h"
#include "common/command_line.h"
#include "performance_tests.h"
#include "performance_utils.h"
// tests
#include "construct_tx.h"
#include "check_tx_signature.h"
#include "cn_slow_hash.h"
#include "derive_public_key.h"
#include "derive_secret_key.h"
#include "ge_frombytes_vartime.h"
#include "generate_key_derivation.h"
#include "generate_key_image.h"
#include "generate_key_image_helper.h"
#include "generate_keypair.h"
#include "signature.h"
#include "is_out_to_acc.h"
#include "subaddress_expand.h"
#include "sc_reduce32.h"
#include "cn_fast_hash.h"
#include "rct_mlsag.h"
#include "equality.h"
#include "range_proof.h"
#include "rct_mlsag.h"
#include "bulletproof.h"
#include "crypto_ops.h"
#include "multiexp.h"
namespace po = boost::program_options;
int main(int argc, char** argv)
{
TRY_ENTRY();
tools::on_startup();
set_process_affinity(1);
set_thread_high_priority();
mlog_configure(mlog_get_default_log_path("performance_tests.log"), true);
po::options_description desc_options("Command line options");
const command_line::arg_descriptor<std::string> arg_filter = { "filter", "Regular expression filter for which tests to run" };
const command_line::arg_descriptor<bool> arg_verbose = { "verbose", "Verbose output", false };
const command_line::arg_descriptor<bool> arg_stats = { "stats", "Including statistics (min/median)", false };
const command_line::arg_descriptor<unsigned> arg_loop_multiplier = { "loop-multiplier", "Run for that many times more loops", 1 };
command_line::add_arg(desc_options, arg_filter);
command_line::add_arg(desc_options, arg_verbose);
command_line::add_arg(desc_options, arg_stats);
command_line::add_arg(desc_options, arg_loop_multiplier);
po::variables_map vm;
bool r = command_line::handle_error_helper(desc_options, [&]()
{
po::store(po::parse_command_line(argc, argv, desc_options), vm);
po::notify(vm);
return true;
});
if (!r)
return 1;
const std::string filter = tools::glob_to_regex(command_line::get_arg(vm, arg_filter));
Params p;
p.verbose = command_line::get_arg(vm, arg_verbose);
p.stats = command_line::get_arg(vm, arg_stats);
p.loop_multiplier = command_line::get_arg(vm, arg_loop_multiplier);
performance_timer timer;
timer.start();
TEST_PERFORMANCE3(filter, p, test_construct_tx, 1, 1, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 1, 2, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 1, 10, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 1, 100, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 1, 1000, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 2, 1, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 2, 2, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 2, 10, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 2, 100, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 10, 1, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 10, 2, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 10, 10, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 10, 100, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 100, 1, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 100, 2, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 100, 10, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 100, 100, false);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 2, 1, true);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 2, 2, true);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 2, 10, true);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 10, 1, true);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 10, 2, true);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 10, 10, true);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 100, 1, true);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 100, 2, true);
TEST_PERFORMANCE3(filter, p, test_construct_tx, 100, 10, true);
TEST_PERFORMANCE4(filter, p, test_construct_tx, 2, 1, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_construct_tx, 2, 2, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_construct_tx, 2, 10, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_construct_tx, 10, 1, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_construct_tx, 10, 2, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_construct_tx, 10, 10, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_construct_tx, 100, 1, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_construct_tx, 100, 2, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_construct_tx, 100, 10, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE3(filter, p, test_check_tx_signature, 1, 2, false);
TEST_PERFORMANCE3(filter, p, test_check_tx_signature, 2, 2, false);
TEST_PERFORMANCE3(filter, p, test_check_tx_signature, 10, 2, false);
TEST_PERFORMANCE3(filter, p, test_check_tx_signature, 100, 2, false);
TEST_PERFORMANCE3(filter, p, test_check_tx_signature, 2, 10, false);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 2, 2, true, rct::RangeProofBorromean);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 10, 2, true, rct::RangeProofBorromean);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 100, 2, true, rct::RangeProofBorromean);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 2, 10, true, rct::RangeProofBorromean);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 2, 2, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 2, 2, true, rct::RangeProofMultiOutputBulletproof);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 10, 2, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 10, 2, true, rct::RangeProofMultiOutputBulletproof);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 100, 2, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 100, 2, true, rct::RangeProofMultiOutputBulletproof);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 2, 10, true, rct::RangeProofPaddedBulletproof);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature, 2, 10, true, rct::RangeProofMultiOutputBulletproof);
TEST_PERFORMANCE3(filter, p, test_check_tx_signature_aggregated_bulletproofs, 2, 2, 64);
TEST_PERFORMANCE3(filter, p, test_check_tx_signature_aggregated_bulletproofs, 10, 2, 64);
TEST_PERFORMANCE3(filter, p, test_check_tx_signature_aggregated_bulletproofs, 100, 2, 64);
TEST_PERFORMANCE3(filter, p, test_check_tx_signature_aggregated_bulletproofs, 2, 10, 64);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature_aggregated_bulletproofs, 2, 2, 62, 4);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature_aggregated_bulletproofs, 10, 2, 62, 4);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature_aggregated_bulletproofs, 2, 2, 56, 16);
TEST_PERFORMANCE4(filter, p, test_check_tx_signature_aggregated_bulletproofs, 10, 2, 56, 16);
TEST_PERFORMANCE0(filter, p, test_is_out_to_acc);
TEST_PERFORMANCE0(filter, p, test_is_out_to_acc_precomp);
TEST_PERFORMANCE0(filter, p, test_generate_key_image_helper);
TEST_PERFORMANCE0(filter, p, test_generate_key_derivation);
TEST_PERFORMANCE0(filter, p, test_generate_key_image);
TEST_PERFORMANCE0(filter, p, test_derive_public_key);
TEST_PERFORMANCE0(filter, p, test_derive_secret_key);
TEST_PERFORMANCE0(filter, p, test_ge_frombytes_vartime);
TEST_PERFORMANCE0(filter, p, test_generate_keypair);
TEST_PERFORMANCE0(filter, p, test_sc_reduce32);
TEST_PERFORMANCE1(filter, p, test_signature, false);
TEST_PERFORMANCE1(filter, p, test_signature, true);
TEST_PERFORMANCE2(filter, p, test_wallet2_expand_subaddresses, 50, 200);
TEST_PERFORMANCE0(filter, p, test_cn_slow_hash);
TEST_PERFORMANCE1(filter, p, test_cn_fast_hash, 32);
TEST_PERFORMANCE1(filter, p, test_cn_fast_hash, 16384);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 3, false);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 5, false);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 10, false);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 100, false);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 3, true);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 5, true);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 10, true);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 100, true);
TEST_PERFORMANCE2(filter, p, test_equality, memcmp32, true);
TEST_PERFORMANCE2(filter, p, test_equality, memcmp32, false);
TEST_PERFORMANCE2(filter, p, test_equality, verify32, false);
TEST_PERFORMANCE2(filter, p, test_equality, verify32, false);
TEST_PERFORMANCE1(filter, p, test_range_proof, true);
TEST_PERFORMANCE1(filter, p, test_range_proof, false);
TEST_PERFORMANCE2(filter, p, test_bulletproof, true, 1); // 1 bulletproof with 1 amount
TEST_PERFORMANCE2(filter, p, test_bulletproof, false, 1);
TEST_PERFORMANCE2(filter, p, test_bulletproof, true, 2); // 1 bulletproof with 2 amounts
TEST_PERFORMANCE2(filter, p, test_bulletproof, false, 2);
TEST_PERFORMANCE2(filter, p, test_bulletproof, true, 15); // 1 bulletproof with 15 amounts
TEST_PERFORMANCE2(filter, p, test_bulletproof, false, 15);
TEST_PERFORMANCE6(filter, p, test_aggregated_bulletproof, false, 2, 1, 1, 0, 4);
TEST_PERFORMANCE6(filter, p, test_aggregated_bulletproof, true, 2, 1, 1, 0, 4); // 4 proofs, each with 2 amounts
TEST_PERFORMANCE6(filter, p, test_aggregated_bulletproof, false, 8, 1, 1, 0, 4);
TEST_PERFORMANCE6(filter, p, test_aggregated_bulletproof, true, 8, 1, 1, 0, 4); // 4 proofs, each with 8 amounts
TEST_PERFORMANCE6(filter, p, test_aggregated_bulletproof, false, 1, 1, 2, 0, 4);
TEST_PERFORMANCE6(filter, p, test_aggregated_bulletproof, true, 1, 1, 2, 0, 4); // 4 proofs with 1, 2, 4, 8 amounts
TEST_PERFORMANCE6(filter, p, test_aggregated_bulletproof, false, 1, 8, 1, 1, 4);
TEST_PERFORMANCE6(filter, p, test_aggregated_bulletproof, true, 1, 8, 1, 1, 4); // 32 proofs, with 1, 2, 3, 4 amounts, 8 of each
TEST_PERFORMANCE6(filter, p, test_aggregated_bulletproof, false, 2, 1, 1, 0, 64);
TEST_PERFORMANCE6(filter, p, test_aggregated_bulletproof, true, 2, 1, 1, 0, 64); // 64 proof, each with 2 amounts
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 3, false);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 5, false);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 10, false);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 100, false);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 3, true);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 5, true);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 10, true);
TEST_PERFORMANCE3(filter, p, test_ringct_mlsag, 1, 100, true);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_sc_add);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_sc_sub);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_sc_mul);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_ge_add_raw);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_ge_add_p3_p3);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_addKeys);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_scalarmultBase);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_scalarmultKey);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_scalarmultH);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_scalarmult8);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_ge_double_scalarmult_base_vartime);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_ge_double_scalarmult_precomp_vartime);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_ge_double_scalarmult_precomp_vartime2);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_addKeys2);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_addKeys3);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_addKeys3_2);
TEST_PERFORMANCE1(filter, p, test_crypto_ops, op_isInMainSubgroup);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 2);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 4);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 8);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 16);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 32);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 64);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 128);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 256);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 512);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 1024);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 2048);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_bos_coster, 4096);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 2);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 4);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 8);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 16);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 32);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 64);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 128);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 256);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 512);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 1024);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 2048);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus, 4096);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 2);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 4);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 8);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 16);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 32);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 64);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 128);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 256);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 512);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 1024);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 2048);
TEST_PERFORMANCE2(filter, p, test_multiexp, multiexp_straus_cached, 4096);
#if 1
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 8, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 16, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 32, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 64, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 128, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 256, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 512, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 1024, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2048, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4096, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 8, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 16, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 32, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 64, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 128, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 256, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 512, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 1024, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2048, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4096, 9);
#else
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 8, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 8, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 8, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 8, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 8, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 8, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 8, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 8, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 8, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 16, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 16, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 16, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 16, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 16, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 16, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 16, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 16, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 16, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 32, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 32, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 32, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 32, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 32, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 32, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 32, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 32, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 32, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 64, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 64, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 64, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 64, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 64, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 64, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 64, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 64, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 64, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 128, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 128, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 128, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 128, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 128, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 128, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 128, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 128, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 128, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 256, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 256, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 256, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 256, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 256, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 256, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 256, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 256, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 256, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 512, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 512, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 512, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 512, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 512, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 512, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 512, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 512, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 512, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 1024, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 1024, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 1024, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 1024, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 1024, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 1024, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 1024, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 1024, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 1024, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2048, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2048, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2048, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2048, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2048, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2048, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2048, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2048, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 2048, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4096, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4096, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4096, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4096, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4096, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4096, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4096, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4096, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger_cached, 4096, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 8, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 8, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 8, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 8, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 8, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 8, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 8, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 8, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 8, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 16, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 16, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 16, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 16, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 16, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 16, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 16, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 16, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 16, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 32, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 32, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 32, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 32, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 32, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 32, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 32, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 32, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 32, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 64, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 64, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 64, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 64, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 64, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 64, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 64, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 64, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 64, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 128, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 128, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 128, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 128, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 128, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 128, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 128, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 128, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 128, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 256, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 256, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 256, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 256, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 256, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 256, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 256, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 256, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 256, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 512, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 512, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 512, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 512, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 512, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 512, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 512, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 512, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 512, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 1024, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 1024, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 1024, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 1024, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 1024, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 1024, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 1024, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 1024, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 1024, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2048, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2048, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2048, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2048, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2048, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2048, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2048, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2048, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 2048, 9);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4096, 1);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4096, 2);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4096, 3);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4096, 4);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4096, 5);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4096, 6);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4096, 7);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4096, 8);
TEST_PERFORMANCE3(filter, p, test_multiexp, multiexp_pippenger, 4096, 9);
#endif
std::cout << "Tests finished. Elapsed time: " << timer.elapsed_ms() / 1000 << " sec" << std::endl;
return 0;
CATCH_ENTRY_L0("main", 1);
}
| [
"enrodev@gmail.com"
] | enrodev@gmail.com |
601ff2d600caccb86c2631a0cf79f57238efd783 | b9845c4ae1f69708b6321ebfd88396be36247777 | /C371GroupProject/C371GroupProject/Robot.h | 4fbce6ca43bd8200a14a8fdc4f7f69cfc94776ed | [] | no_license | dsma1991/371Pro | ed502578ae26834457ed0f225c8ab1dd38d0179c | deca26de5ccefb2b63b67a591d31800625c0f64c | refs/heads/master | 2020-05-26T07:58:13.280143 | 2014-11-21T21:38:24 | 2014-11-21T21:38:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 160 | h | #pragma once
#include "model.h"
class Robot :
public Model
{
public:
Robot(void);
~Robot(void);
void fire();
private:
//vector<Laser> lasersShot;
};
| [
"dsma1991@yahoo.com"
] | dsma1991@yahoo.com |
6f2a86b46876076cac121f1c673227b74b2d5fe8 | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.0025/IC4H8 | e6a7a1e9c6893070f8d409fad3036be604fb08e7 | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 837 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.0025";
object IC4H8;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 0.00195156;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
b304e975737ca74d1edd4ead655a770d7d405c7a | fbba3d17ca75020c92969ff2a7b51d06506f6e62 | /TAttacheCaseFileEncrypt.cpp | a16280fb19a86b6c608f896943229c539c152e43 | [
"BSD-3-Clause"
] | permissive | ochanzz/AttacheCase | 5eebe89d7e7a8971250ab28d813b15e3202fe43a | ba63bdb8ea3366ed1c092be89c79b016e6d2d6ab | refs/heads/master | 2021-01-18T05:17:44.264743 | 2013-02-14T12:15:00 | 2013-02-14T12:15:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,014 | cpp | //===========================================================================
/*
アタッシェケース(AttachéCase)
Copyright (c) 2002-2013, Mitsuhiro Hibara ( http://hibara.org )
All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
・Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
・Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
・Neither the name of the "HIBARA.ORG" 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.
*/
//===========================================================================
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include "TAttacheCaseFileEncrypt.h"
#pragma package(smart_init)
//---------------------------------------------------------------------------
// 注意:異なるスレッドが所有する VCL のメソッド/関数/プロパティを別の
// レッド所有のオブジェクトに対しては Synchronize を使用できます。
//
// Synchronize(&UpdateCaption);
//
// 例えば UpdateCaption を以下のように定義し
//
// void __fastcall TAttacheCaseFileEncode::UpdateCaption()
// {
// Form1->Caption = "スレッドから書き換えました";
// }
//---------------------------------------------------------------------------
__fastcall TAttacheCaseFileEncrypt::TAttacheCaseFileEncrypt
(bool CreateSuspended) : TThread(CreateSuspended)
{
int i;
//オプション(デフォルト値)
CompressRateNum = Z_DEFAULT_COMPRESSION; //圧縮率
fOver4gbOk = true; //4GB超を許可
fExeOutputOption = false; //実行形式出力
fOptBrokenFileOption = false; //ミスタイプでファイルを破壊するか否か
intOptMissTypeLimitsNumOption = 3; //タイプミスできる回数
fConfirmOverwirte = true; //同名ファイルがあるときは上書きの確認をする
fOverwirteYesToAll = false; //同名ファイルはすべて上書きして暗号化する(ダイアログで「すべてはい」を選択 = true)
ProgressPercentNum = -1; //進捗パーセント
ProgressStatusText = ""; //進捗ステータス
ProgressMsgText = ""; //進捗メッセージ
AppExeFilePath = ""; //アタッシェケース本体の場所
OutFilePath = ""; //出力する暗号化ファイル
InputFileList = new TStringList; //暗号化する元ファイルリスト
FilePathList = new TStringList; //ヘッダ生成時に展開されるファイルリスト
for (i = 0; i < 32; i++) {
key[i] = 0;
}
StatusNum = 0; //ステータス表示内容番号
MsgErrorString = ""; //エラーメッセージ
}
//===========================================================================
//デストラクタ
//===========================================================================
__fastcall TAttacheCaseFileEncrypt::~TAttacheCaseFileEncrypt(void)
{
delete InputFileList;
delete FilePathList;
}
//===========================================================================
// スレッド実行
//===========================================================================
void __fastcall TAttacheCaseFileEncrypt::Execute()
{
int i, c;
int res;
float ProgressPercentNumF; //進捗パーセンテージ(浮動小数点)
z_stream z; // zlibライブラリとやりとりするための構造体
int flush, status; // zlib
//出力する暗号化ファイルのタイムスタンプを元ファイルに合わせる
HANDLE hFile;
//_WIN32_FIND_DATAW first_fd;
ZeroMemory(&first_fd, sizeof(_WIN32_FIND_DATAW));
int len, pos;
int FileIndex;
String FilePath;
int HeaderSize; //ヘッダデータサイズ
__int64 CurrentDriveFreeSpaceSize = -1; //保存するドライブの空き容量
//実行可能形式出力ファイルのデータサイズ
__int64 ExeAllSize = 0;
__int64 ExeSize = 0;
//全体のファイルサイズ
AllTotalSize = 0;
__int64 TotalSize = 0;
//バッファ
char source_buffer[BUF_SIZE];
char read_buffer[BUF_SIZE];
char out_buffer[BUF_SIZE];
char chain_buffer[BUF_SIZE]; // IVなどを格納するチェインバッファ
char margin_buffer[BUF_SIZE];
//ファイルストリーム
TFileStream *fsIn;
TFileStream *fsOut;
TFileStream *fsExe;
//オープン中か
bool fOpenIn;
bool fOpenOut;
//メモリストリーム
TMemoryStream *pms = new TMemoryStream;
// マージンバッファサイズ
int MarginBufSize = MARGIN_BUF_SIZE;
// PKCS #7 Pading num.
unsigned char paddingNum = 0;
//---------------------------------------
// 同名ファイルがあるのでダイアログ表示
//---------------------------------------
if ( fConfirmOverwirte == true && fOverwirteYesToAll == false ) {
if (FileExists(OutFilePath) == true) {
//同名ファイルの上書き確認メッセージダイアログ
MsgText = LoadResourceString(&Msgencrypt::_MSG_CONFIRM_OVER_WRITE_SAME_FILE)+"\n"+OutFilePath;
Synchronize(&PostConfirmOverwriteMessageForm);
if ( MsgReturnVal == mrYes ) {
//上書きOKなのでFilePathはそのまま
}
else if ( MsgReturnVal == mrNo ) {
//別名保存でFilePath文字列が書き換えられてきている
OutFilePath = MsgReturnPath;
}
else if ( MsgReturnVal == mrYesToAll ) {
//すべて上書き(YesToAll)
fOverwirteYesToAll = true;
}
else if ( MsgReturnVal == mrCancel ) {
//キャンセル
delete pms;
goto LabelStop;
}
}
}
//---------------------------------------
// ヘッダ情報の生成&ファイル総サイズ取得
//---------------------------------------
//'暗号化するファイルリストの生成中...'
ProgressStatusText = LoadResourceString(&Msgencrypt::_LABEL_STATUS_TITLE_LISTING);
if ( CreateHeaderData( pms, InputFileList, FilePathList, AllTotalSize) == false ){
if (Terminated == true) {
//ユーザーキャンセルで抜けてきた
delete pms;
goto LabelStop;
}
else{
//'暗号化するファイルを開けません。他のアプリケーションが使用中の可能性があります。'
MsgText = LoadResourceString(&Msgencrypt::_MSG_ERROR_FILE_OPEN);
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
delete pms;
goto LabelError;
}
}
//-----------------------------------
// ディスクの空き容量チェック
//-----------------------------------
CurrentDriveFreeSpaceSize = GetDiskFreeSpaceNum(OutFilePath);
if (CurrentDriveFreeSpaceSize > -1 ) {
if ( AllTotalSize > CurrentDriveFreeSpaceSize ) {
//"ディスクの空き容量が足りません! 暗号化ファイルを保存できません。\n
//暗号化を中止します。;"
MsgText = LoadResourceString(&Msgencrypt::_MSG_ERROR_NO_DISK_FREE_SPACE);
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
delete pms;
goto LabelError;
}
}
else{
// -1はネットワークドライブの可能性があるので無視
//(万が一、別のエラーの場合、実際書き込みに移行したときエラーが発生する)
}
//-----------------------------------
// 実行可能形式でかつ
// 合計バイト数が4GBを越えたときのエラー
//-----------------------------------
if ( fExeOutputOption == true && fOver4gbOk == false && AllTotalSize > SIZE_4GB ){
//実行形式ファイルのサイズが4GBを超えてしまう可能性があります!\n
//Win32アプリケーションとして実行できなくなるかもしれませんがよろしいですか?';
MsgText = LoadResourceString(&Msgencrypt::_MSG_ERROR_OVER_4GB_EXE);
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbYes << mbNo;
MsgDefaultButton = mbNo;
Synchronize(&PostConfirmMessageForm);
if ( MsgReturnVal == mbNo) {
//キャンセル
delete pms;
goto LabelStop;
}
}
//-----------------------------------
// 暗号化ファイルの生成開始
//-----------------------------------
//'暗号化しています...'
ProgressStatusText = LoadResourceString(&Msgencrypt::_LABEL_STATUS_TITLE_ENCRYPTING);
ProgressMsgText = ExtractFileName(OutFilePath);
TotalSize = 0;
try{
fsOut = new TFileStream(OutFilePath, fmCreate);
fOpenOut = true;
}
catch(...){
//'保存する先のファイルが開けません。他のアプリケーションが使用中の可能性があります。'
MsgText = LoadResourceString(&Msgencrypt::_MSG_ERROR_OUT_FILE_OPEN) + "\n" + OutFilePath;
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
delete pms;
goto LabelError;
}
//-----------------------------------
// 実行可能形式の出力
//-----------------------------------
if ( fExeOutputOption == true ){
//-----------------------------------
// 自分のお尻から実行データを抽出
//-----------------------------------
//自分自身の実行ファイルを開く
try{
fsExe = new TFileStream(Application->ExeName, fmOpenRead | fmShareDenyWrite);
}
catch(...){
//'実行可能形式出力に失敗しました。暗号化処理を中止します。'
MsgText = LoadResourceString(&Msgencrypt::_MSG_ERROR_EXEOUT_FAILED);
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
delete pms;
goto LabelError;
}
//切り出すサイズを取得
fsExe->Seek(-(__int64)sizeof(__int64), TSeekOrigin::soEnd);
fsExe->Read(&ExeAllSize, sizeof(__int64));
//処理する合計サイズに実行形式分を加える
AllTotalSize += ExeAllSize;
//自己実行可能形式データの境界へ
fsExe->Seek(-(__int64)ExeAllSize-sizeof(__int64), TSeekOrigin::soEnd);
while(fsExe->Read(read_buffer, BUF_SIZE) != 0 ){
ExeSize+=BUF_SIZE;
//書き込む
if ( ExeSize < ExeAllSize ){
fsOut->Write(read_buffer, BUF_SIZE);
TotalSize += BUF_SIZE;
}
else{
fsOut->Write(read_buffer, ExeSize-ExeAllSize);
TotalSize += (ExeSize-ExeAllSize);
}
//進捗表示
ProgressPercentNumF = (float)TotalSize/AllTotalSize;
ProgressPercentNum = (int)(ProgressPercentNumF*100);
if (AllTotalSize < 104857600) { // 100MB未満
ProgressPercentNumText = IntToStr(ProgressPercentNum)+"%";
}
else{
ProgressPercentNumText = FloatToStrF(ProgressPercentNumF*100, ffNumber, 4, 1)+"%";
}
}
//自分自身を閉じる
delete fsExe;
}
//-----------------------------------
// ヘッダ情報の描き込み
//-----------------------------------
pms->SaveToStream(fsOut); //fsOutに追記
delete pms;
//-----------------------------------
// Rijndaelの初期化
//-----------------------------------
gentables();
gkey( 8, 8, key);
// 初期化ベクトルを生成して先頭に書き込む
fillrand(chain_buffer, BUF_SIZE);
if ( fsOut->Write(chain_buffer, BUF_SIZE) < BUF_SIZE ){
//''保存先に指定された暗号化ファイルに書き込めません。
MsgText = LoadResourceString(&Msgencrypt::_MSG_ERROR_OUT_FILE_WRITE) + "\n" + OutFilePath;
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
goto LabelError;
}
//-----------------------------------
// zlib 初期化(圧縮においてすべてのメモリ管理をライブラリに任せる)
z.zalloc = Z_NULL;
z.zfree = Z_NULL;
z.opaque = Z_NULL;
//z.next_in = Z_NULL;
// 第2引数は圧縮の度合。0~9 の範囲の整数で,0 は無圧縮
// Z_DEFAULT_COMPRESSION (= 6) が標準
if (deflateInit(&z, CompressRateNum) != Z_OK){
//zlibエラー表示はラベル先で
goto LabelError;
}
//出力バッファの初期化
for(i = 0; i < BUF_SIZE; i++){
out_buffer[i] = 0;
}
// zlibに入出力バッファをセットする
z.avail_in = 0; // 入力バッファ中のデータのバイト数
z.next_out = out_buffer; // 出力バッファ残量
z.avail_out = BUF_SIZE; // 出力ポインタ
// 通常は deflate() の第2引数は Z_NO_FLUSH にして呼び出す
flush = Z_NO_FLUSH;
FileIndex = 0;
while(!Terminated) {
//-----------------------------------
//入力
//-----------------------------------
if ( z.avail_in == 0 && flush != Z_FINISH){
pos = 0;
for(i = 0; i < BUF_SIZE; i++){
source_buffer[i] = 0;
read_buffer[i] = 0;
}
while ( pos < BUF_SIZE ){
//オープン中のファイルがあればそこから読む
if ( fOpenIn == true ) {
if (pos < BUF_SIZE) {
len = fsIn->Read(read_buffer, BUF_SIZE - pos);
TotalSize+=len;
for (i = 0; i < len; i++) {
source_buffer[pos+i] = read_buffer[i];
}
if (len < BUF_SIZE - pos) {
fOpenIn = false; //ファイルを閉じる
delete fsIn;
}
}
pos += len;
}
//ファイルを開く
else{
if (FileIndex < FilePathList->Count) {
while(FileIndex < FilePathList->Count){
if (FilePathList->Strings[FileIndex] != "") {
try{
fsIn = new TFileStream(FilePathList->Strings[FileIndex], fmOpenRead | fmShareDenyWrite);
fOpenIn = true;
FileIndex++;
break;
}
catch(...){
//'暗号化するファイルを開けません。他のアプリケーションが使用中の可能性があります。'
MsgText = LoadResourceString(&Msgencrypt::_MSG_ERROR_FILE_OPEN);
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
fOpenIn = false;
goto LabelError;
}
}
FileIndex++;
}
}
else{
//読み込むファイルがなくなったので、
//お尻にダミーのマージンデータを挿入する
//
//【補足】
// 本来はここにあるマージンデータ挿入処理は不要ですが、
// 昔に作った際に復号の際に圧縮データ境界のチェックを
// 怠っていたため、このように余分なデータを
// 入れておくという力業を使っています(すみません...)
fillrand(margin_buffer, BUF_SIZE);
for (i = pos; i < BUF_SIZE; i++) {
source_buffer[i] = margin_buffer[i];
}
pos = BUF_SIZE;
MarginBufSize -= BUF_SIZE;
}//end if (FileIndex < FilePathList->Count);
}//end if ( fOpenIn == true );
}//while ( pos < BUF_SIZE && 0 < MarginBufSize );
if (MarginBufSize < 1) {
flush = Z_FINISH; //入力バッファはこれが最後
}
z.next_in = source_buffer;
z.avail_in = pos;
}//end if ( z.avail_in == 0 );
//-----------------------------------
//圧縮
//-----------------------------------
if ( z.avail_out > 0 ){
status = deflate(&z, flush);
}
if (status == Z_STREAM_END){
break;
}
if (status != Z_OK ){
//#define Z_OK 0
//#define Z_STREAM_END 1
//#define Z_NEED_DICT 2
//#define Z_ERRNO (-1)
//#define Z_STREAM_ERROR (-2)
//#define Z_DATA_ERROR (-3)
//#define Z_MEM_ERROR (-4)
//#define Z_BUF_ERROR (-5)
//#define Z_VERSION_ERROR (-6)
goto LabelError;
}
//-----------------------------------
//出力
//-----------------------------------
if ( z.avail_out == 0 ){
// CBC - xor the file bytes with the IV bytes
for(i = 0; i < BUF_SIZE; i++){
out_buffer[i] ^= chain_buffer[i];
}
//encrypt!
rijndael_encrypt(out_buffer);
len = fsOut->Write(out_buffer, BUF_SIZE);
if (len < BUF_SIZE) {
//'保存先に指定された暗号化ファイルに書き込めません。
MsgText = LoadResourceString(&Msgencrypt::_MSG_ERROR_OUT_FILE_WRITE) + "\n" + OutFilePath;
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
goto LabelError;
}
for(i = 0; i < BUF_SIZE; i++){
chain_buffer[i] = out_buffer[i];
out_buffer[i] = 0;
}
z.next_out = out_buffer; // 出力バッファ残量を元に戻す
z.avail_out = BUF_SIZE; // 出力ポインタを元に戻す
}
//-----------------------------------
//進捗状況表示
if (AllTotalSize == 0) {
ProgressPercentNum = 100;
ProgressPercentNumText = "100%";
}
else if (TotalSize == 0) {
ProgressPercentNum = 0;
ProgressPercentNumText = "0%";
}
else{
ProgressPercentNumF = (float)TotalSize/AllTotalSize;
ProgressPercentNum = (int)(ProgressPercentNumF*100);
if (AllTotalSize < 104857600) { // 100MB未満
ProgressPercentNumText = IntToStr(ProgressPercentNum)+"%";
}
else{
ProgressPercentNumText = FloatToStrF(ProgressPercentNumF*100, ffNumber, 4, 1)+"%";
}
}
//-----------------------------------
if ( fOpenIn == true ){
ProgressMsgText = ExtractFileName(fsIn->FileName);
}
else{
ProgressMsgText = ExtractFileName(OutFilePath);
}
}//while(!Terminated);
if (Terminated == true) {
//ユーザーキャンセルで抜けてきた
goto LabelStop;
}
//残りのバッファ
if (z.avail_out > 0) {
// PKCS #7 パディング
len = BUF_SIZE - z.avail_out;
paddingNum = (char)z.avail_out;
for(i = len; i < BUF_SIZE; i++){
out_buffer[i] = paddingNum;
}
// CBC - xor the file bytes with the IV bytes
for(i = 0; i < BUF_SIZE; i++){
out_buffer[i] ^= chain_buffer[i];
}
//encrypt!
rijndael_encrypt(out_buffer);
if ((len = fsOut->Write(out_buffer, BUF_SIZE)) != BUF_SIZE){
//'保存先に指定された暗号化ファイルに書き込めません。
MsgText = LoadResourceString(&Msgencrypt::_MSG_ERROR_OUT_FILE_WRITE) + "\n" + OutFilePath;
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
goto LabelError;
}
}
if (deflateEnd(&z) != Z_OK){
//zlibエラー
goto LabelError;
}
//-----------------------------------
// 実行可能形式ファイルは
// 末尾へ暗号化データサイズを書き込む
//-----------------------------------
if ( fExeOutputOption == true ){
ExeSize = fsOut->Seek((__int64)0, TSeekOrigin::soEnd);
ExeSize = ExeSize-ExeAllSize;
fsOut->Write(&ExeSize, sizeof(__int64));
}
//-----------------------------------
// 完了
//-----------------------------------
ProgressPercentNum = 100;
//'完了'
ProgressStatusText = LoadResourceString(&Msgencrypt::_LABEL_STATUS_TITLE_COMPLETE);
ProgressMsgText = ExtractFileName(OutFilePath);
if (fOpenIn == true) {
delete fsIn;
}
if (fOpenOut == true) {
delete fsOut;
}
//出力する暗号化ファイルのタイムスタンプを元ファイルに合わせる
if ( fKeepTimeStamp == true && first_fd.cFileName[0] != NULL ) {
hFile = CreateFileW(FilePath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
SetFileTime( hFile, &first_fd.ftCreationTime, &first_fd.ftLastAccessTime, &first_fd.ftLastWriteTime);
CloseHandle(hFile);
}
}
StatusNum = 1;
return;
//-----------------------------------
// エラーの後始末
//-----------------------------------
LabelError:
ProgressPercentNum = 0;
if ( status < 0 ){
//'zlibライブラリからエラーを返されました。'
//'エラー番号:'
MsgText = LoadResourceString(&Msgencrypt::_MSG_ERROR_ZLIB) + IntToStr(status) + "\n" + z.msg;
MsgType = mtError;
MsgButtons = TMsgDlgButtons() << mbOK;
MsgDefaultButton = mbOK;
Synchronize(&PostConfirmMessageForm);
}
//'エラー'
ProgressStatusText = LoadResourceString(&Msgencrypt::_LABEL_STATUS_TITLE_ERROR);
//'暗号化に失敗しました。'
ProgressMsgText = LoadResourceString(&Msgencrypt::_LABEL_STATUS_DETAIL_FAILED);
if (fOpenIn == true) {
delete fsIn;
}
if (fOpenOut == true) {
delete fsOut;
}
StatusNum = -1;
return;
//-----------------------------------
// ユーザーキャンセルの後始末
//-----------------------------------
LabelStop:
ProgressPercentNum = 0;
//'キャンセル'
ProgressStatusText = LoadResourceString(&Msgencrypt::_LABEL_STATUS_TITLE_USER_CANCEL);
//'暗号化が中止されました。'
ProgressMsgText = LoadResourceString(&Msgencrypt::_LABEL_STATUS_DETAIL_STOPPED);
if (fOpenIn == true) {
delete fsIn;
}
if (fOpenOut == true) {
delete fsOut;
}
StatusNum = -2;
return;
}
//---------------------------------------------------------------------------
// 初期化ベクトル(IV)の生成
//---------------------------------------------------------------------------
void TAttacheCaseFileEncrypt::fillrand(char *buf, const int len)
{
static unsigned long count = 4;
static char r[4];
int i;
// ISAAC ( Cryptographic Random Number Generator )
randctx ctx;
// init
randinit(&ctx, 1);
for(i = 0; i < len; ++i){
if(count == 4){
*(unsigned long*)r = rand(&ctx);
count = 0;
}
buf[i] = r[count++];
}
}
//===========================================================================
// ヘッダ情報を生成する
//===========================================================================
bool __fastcall TAttacheCaseFileEncrypt::CreateHeaderData
(TMemoryStream *pms, TStringList *FileList, TStringList *FilePathList, __int64 &AllTotalFileSize)
{
int i, c;
int ret;
int Index = 0;
int HeaderSizeAddress = 0;
TSearchRec sr;
String OneLine;
String DirPath, FileName;
String MsgText;
//暗号部トークン
const AnsiString Passcode_AttacheCase = "Passcode:AttacheCase\n";
//暗号化ファイルの作成日
AnsiString LastDateTimeString = "LastDateTime:" + DateTimeToStr(Now()) + "\n";
//旧ヘッダーテキストすべて
AnsiString Fn_HeaderText;
//Unicode用ヘッダーテキストすべて
String U_HeaderText;
int EncryptHeaderSize = 0; //暗号部ヘッダサイズ
char buffer[BUF_SIZE];
char chain_buffer[BUF_SIZE];
TStringList *HeaderDataList;
TMemoryStream* tpms; //テンポラリメモリストリーム
//-----------------------------------
// ヘッダ情報(平文)
//-----------------------------------
const char charReservedValue[4] = { 0, 0, 0, 0 };
const char charDataSubVersion = ATC_DATA_SUB_VERSION;
const char charOptMissTypeLimitsNumOption = intOptMissTypeLimitsNumOption;
const char charOptBrokenFileOption = (fOptBrokenFileOption > 0 ? 1 : 0);
const char charTokenString[17] = "_AttacheCaseData";
const int DataFileVersion = ATC_DATA_FILE_VERSION;
const int AlgorismType = TYPE_ALGORISM_RIJNDAEL;
//データサブバージョン : 1byte
pms->Write(&charDataSubVersion, sizeof(char));
//予約データ(reserved) : 1byte
pms->Write(&charReservedValue, sizeof(char));
//ミスタイプ回数 : 1byte
pms->Write(&charOptMissTypeLimitsNumOption, sizeof(char));
//破壊するか否か : 1byte
pms->Write(&charOptBrokenFileOption, sizeof(char));
//トークン : 16byte
pms->Write(&charTokenString, 16);
//データファイルバージョン : 4byte
pms->Write(&DataFileVersion, sizeof(int));
//アルゴリズムタイプ : 4byte
pms->Write(&AlgorismType, sizeof(int));
//暗号化部分のヘッダデータサイズ(先に確保しておく):4byte
HeaderSizeAddress = pms->Position;
pms->Write(&EncryptHeaderSize, sizeof(int));
//-----------------------------------
// ヘッダ情報(暗号化部分)
//-----------------------------------
//進捗状況表示
ProgressPercentNum = -1;
//'暗号化するファイルリストの生成中...'
ProgressStatusText = LoadResourceString(&Msgencrypt::_LABEL_STATUS_TITLE_LISTING);
//ヘッダデータリスト(文字列)
HeaderDataList = new TStringList;
//パスワード
HeaderDataList->Add(Passcode_AttacheCase);
//作成日
HeaderDataList->Add(LastDateTimeString);
for ( i = 0; i < FileList->Count; i++ ){
//ファイル
if (FileExists(FileList->Strings[i]) == true) {
DirPath = ExtractFileDir(FileList->Strings[i]);
FileName = ExtractFileName(FileList->Strings[i]);
ProgressMsgText = FileName; //処理中のファイル名
AllTotalFileSize +=
GetFileInfoList(Index, DirPath, FileName, FileList->Strings[i], FilePathList, HeaderDataList);
}
//ディレクトリ
else{
DirPath = ExtractFileDir(FileList->Strings[i]);
FileName = ExtractFileName(FileList->Strings[i]);
ProgressMsgText = FileName; //処理中のファイル名
//トップディレクトリ
GetFileInfoList(Index, DirPath, FileName, FileList->Strings[i], FilePathList, HeaderDataList);
//その配下
AllTotalFileSize +=
GetFileInfoList(Index, FileList->Strings[i], "", FileList->Strings[i], FilePathList, HeaderDataList);
}
//ユーザーキャンセル
if (Terminated == true) {
delete HeaderDataList;
return(false);
}
}// end for;
//進捗状況表示
ProgressPercentNum = -1;
//'ヘッダデータを書き込んでいます...'
ProgressStatusText = LoadResourceString(&Msgencrypt::_LABEL_STATUS_TITLE_ENCRYPTING_LIST);
ProgressMsgText = "";
//メモリストリームへ書き込み
tpms = new TMemoryStream;
//------------------------------------------------
// 暗号化時にヘッダデータの互換性維持
//---------------------------------------------------
HeaderDataList->SaveToStream(tpms, TEncoding::GetEncoding(932));
//新バージョン(ver.2.8.0~)用(UTF-8)に保存
for (i = 0; i < HeaderDataList->Count; i++) {
HeaderDataList->Strings[i] = StringReplace(HeaderDataList->Strings[i],"Fn_","U_",TReplaceFlags()<<rfIgnoreCase );
}
HeaderDataList->SaveToStream(tpms, TEncoding::UTF8);
delete HeaderDataList;
//-----------------------------------
//ヘッダ情報の暗号化
//-----------------------------------
//暗号化の準備
gentables();
//キー入力
gkey( 8, 8, key);
for (i = 0; i < BUF_SIZE; i++) {
buffer[i] = 0;
}
//初期化ベクトル(IV)を生成
fillrand(chain_buffer, BUF_SIZE);
pms->Write(chain_buffer, BUF_SIZE);
//先頭にポインタを戻す
tpms->Seek((__int64)0, TSeekOrigin::soBeginning);
EncryptHeaderSize = 0;
//CBCモードで書き込む
while (tpms->Read( buffer, BUF_SIZE ) != NULL){
EncryptHeaderSize += BUF_SIZE;
// xor
for ( i = 0; i < BUF_SIZE; i++ ){
buffer[i] ^= chain_buffer[i];
}
// rijndael
rijndael_encrypt(buffer);
pms->Write(buffer, BUF_SIZE);
//CBC&バッファの初期化
for ( i = 0; i < BUF_SIZE; i++ ){
chain_buffer[i] = buffer[i];
buffer[i] = 0;
}
//ユーザーキャンセル
if (Terminated == true) {
delete tpms;
return(false);
}
}//loop;
delete tpms;
//暗号化部分のヘッダデータサイズ(確保しておいた場所へ改めて書き込む)
pms->Position = HeaderSizeAddress;
pms->Write(&EncryptHeaderSize, sizeof(int));
//先頭にポインタを戻す
pms->Seek((__int64)0, TSeekOrigin::soBeginning);
return(true);
}//end CreateHeaderData;
//===========================================================================
// 暗号化するファイルリストとファイル情報のリストを同時生成する
//===========================================================================
__int64 __fastcall TAttacheCaseFileEncrypt::GetFileInfoList
( int &Index,
String DirPath,
String FileName,
String BasePath,
TStringList *FileList,
TStringList *DataList
)
{
/* ------------------------------------------------
ファイルリストのファイル番号の頭に「Fn_*:」と
なぜ重複するような記号が挿入されているかと言いますと
あまり意味はございません・・・お恥ずかしいかぎり・・・
すみません、これもver.1からの仕様を引きずっているのと、
習作時代にやっちゃった無意味なデータ仕様の一つです。
--------------------------------------------------- */
int ret;
__int64 TotalSize = 0;
bool fParent = false;
String OneLine;
String FilePath;
String FileNameString;
TSearchRec sr;
//_WIN32_FIND_DATAW fd;
DirPath = IncludeTrailingPathDelimiter(DirPath);
if (FileName == "") { //ディレクトリ
FileName = "*.*";
}
else{
fParent = true;
}
ret = FindFirst(DirPath + FileName, faAnyFile, sr);
while (ret == 0) {
if (sr.Name != "." && sr.Name != "..") {
FilePath = DirPath + sr.Name;
FileNameString = ExtractRelativePath(BasePath, FilePath);
//-----------------------------------
//ディレクトリ
if (sr.Attr & faDirectory) {
// Win95/98系(非対応だが一応)
if ( Win32Platform == VER_PLATFORM_WIN32_WINDOWS ){
OneLine =
"Fn_" + IntToStr((int)Index) + ":" + //インデックス
FileNameString + "\\\t" + //ディレクトリ名
"*\t16\t0\t0\t0\t0"; //残りは0
}
else{
// _WIN32_FIND_DATAW 構造体
//fd = sr.FindData;
OneLine =
"Fn_" + IntToStr((int)Index) + ":" + //インデックス
FileNameString + "\\\t" + //ディレクトリの相対パス
"*\t" + //ファイルサイズ(=0)
IntToStr(sr.Attr) + "\t" + //属性
TimeStampToString(sr.FindData.ftLastWriteTime)+"\t"+ //更新日時
TimeStampToString(sr.FindData.ftCreationTime); //作成日時
//出力する暗号化ファイルのタイムスタンプを元ファイルに合わせるため保持
if ( fKeepTimeStamp == true && first_fd.cFileName[0] == NULL ) {
first_fd = sr.FindData;
}
}
FileList->Add(""); //ディレクトリは空行
DataList->Add(OneLine);
Index++;
if (fParent == false) {
//再帰呼び出し
TotalSize += GetFileInfoList(Index, FilePath, "", BasePath, FileList, DataList);
}
}
//-----------------------------------
//ファイル
else{
OneLine =
"Fn_" + IntToStr((int)Index) + ":" + //インデックス
FileNameString + "\t" + //ファイルの相対パス
IntToStr(sr.Size) + "\t" + //ファイルサイズ
IntToStr(sr.Attr) + "\t" + //属性
TimeStampToString(sr.FindData.ftLastWriteTime)+"\t"+ //更新日時
TimeStampToString(sr.FindData.ftCreationTime); //作成日時
//出力する暗号化ファイルのタイムスタンプを元ファイルに合わせるため保持
if ( fKeepTimeStamp == true && first_fd.cFileName[0] == NULL ) {
first_fd = sr.FindData;
}
if (sr.Size > 0) {
FileList->Add(FilePath);
}
else{
FileList->Add(""); //空ファイルは加えない
}
DataList->Add(OneLine);
Index++;
//ファイル総計
TotalSize += sr.Size;
}
//-----------------------------------
}//end if;
ret = FindNext(sr);
}//while;
FindClose(sr);
return(TotalSize);
}//end GetFileInfoList;
//===========================================================================
//FILETIME構造体をTTimeStampに変換して文字列として取得する
//===========================================================================
String __fastcall TAttacheCaseFileEncrypt::TimeStampToString(FILETIME ft)
{
SYSTEMTIME st;
TDateTime dt;
TTimeStamp ts;
//FileTime → SystemFileTime
FileTimeToSystemTime(&ft, &st);
//SystemTime → TDateTime
dt = SystemTimeToDateTime(st);
//TDateTime → TimeStamp
ts = DateTimeToTimeStamp(dt);
/*
//ファイル/ディレクトリの日時をなぜ
//わざわざサイズが大きいTTimeStampに変換して格納したのか?
//ごめんなさい、意味はありません(笑)。
struct TTimeStamp
{
int Time;
int Date;
};
*/
return(IntToStr(ts.Date)+"\t"+IntToStr(ts.Time));
}
//===========================================================================
//ディスクの空き容量を調べる
//===========================================================================
__int64 __fastcall TAttacheCaseFileEncrypt::GetDiskFreeSpaceNum(String FilePath)
{
int i;
int flag;
__int64 FreeSpace;
String DriveName = ExtractFileDrive(FilePath)+":";
String DirPath = IncludeTrailingPathDelimiter(ExtractFileDir(FilePath));
OSVERSIONINFO ovi; // バージョン情報を格納する構造体
ovi.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
// バージョン情報取得
GetVersionEx( (LPOSVERSIONINFO)&ovi );
// Windows95 OSR2以前
if( ( ovi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
&& ( int( ovi.dwBuildNumber & 0xffff ) <= 1000 ) ){
DWORD SCluster,BSector,FCluster,TCluster;
if ( GetDiskFreeSpaceW(String(DriveName).c_str(), &SCluster, &BSector, &FCluster, &TCluster) > 0){
FreeSpace = SCluster*BSector*FCluster;
}
else{
//ネットワークサーバ上は取得できずエラーとなる
FreeSpace = -1;
}
}
// OSR2以降~
else{
ULARGE_INTEGER pqwFreeCaller;
ULARGE_INTEGER pqwTot;
ULARGE_INTEGER pqwFree;
if(::GetDiskFreeSpaceExW(String(DirPath).c_str(), &pqwFreeCaller, &pqwTot, &pqwFree)){
//64bit Integerで返す
FreeSpace = pqwFreeCaller.QuadPart;
}
else{
FreeSpace = -1;
}
}
return(FreeSpace);
}//end GetDiskFreeSpaceNum;
//===========================================================================
//パスワード文字列をセットする
//===========================================================================
/*
void __fastcall TAttacheCaseFileEncrypt::SetPasswordString(AnsiString Password)
{
for (int i = 0; i < 32; i++) {
key[i] = 0;
}
StrCopy(key, Password.c_str());
}
*/
//===========================================================================
//パスワードにバイナリ値をセットする
//===========================================================================
void __fastcall TAttacheCaseFileEncrypt::SetPasswordBinary(char *password)
{
for (int i = 0; i < 32; i++) {
key[i] = 0;
}
memcpy(key, password, 32);
}
//===========================================================================
//現在設定されているパスワードを取得する
//===========================================================================
void __fastcall TAttacheCaseFileEncrypt::GetPasswordBinary(char *password)
{
memcpy(password, key, 32);
}
//===========================================================================
//メインフォームに確認メッセージを投げて処理を中断する
//===========================================================================
void __fastcall TAttacheCaseFileEncrypt::PostConfirmMessageForm()
{
//※以下が、グローバル変数(private)として定義してある
//String MsgText;
//TMsgDlgType MsgType;
//TMsgDlgButtons MsgButtons;
//TMsgDlgBtn MsgDefaultButton;
MsgReturnVal = Form1->ShowConfirmMassageForm(MsgText, MsgType, MsgButtons, MsgDefaultButton);
}
//===========================================================================
//メインフォームに上書きの確認メッセージを投げて処理を中断する
//===========================================================================
void __fastcall TAttacheCaseFileEncrypt::PostConfirmOverwriteMessageForm()
{
//グローバル変数(private)として定義してある
//String MsgText;
//String MsgReturnPath;
MsgReturnVal = Form1->ShowConfirmOverwriteMassageForm(MsgText, MsgReturnPath);
}
//===========================================================================
| [
"m@hibara.org"
] | m@hibara.org |
5207a8392d59fd1acf47a7761a7d8bdd97b7b82d | 6de1e4199216517c9247bd5103476c33a7c98c22 | /AdvanceLevel/1100. Mars Numbers.cpp | 353ce84b74d7a6409f8d3e1e94bba8396c5e6110 | [] | no_license | Aiden68/PAT | 9da832b5999afc5d55c3f58a39bb07dad76c89f9 | a01df198ff75bc1209b86ced79a34a5155efc11d | refs/heads/master | 2021-01-12T10:08:38.073835 | 2017-03-03T07:46:16 | 2017-03-03T07:46:16 | 76,371,489 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,571 | cpp | #include<iostream>
#include<string>
using namespace std;
string marsnum1[13] = { "tret","jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec" };
string marsnum2[13] = { "", "tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou" };
int main()
{
int n;
scanf("%d", &n);
getchar();
for (int i = 0; i < n; i++)
{
string str;
getline(cin, str);
if (str[0] >= '0'&&str[1] <= '9')
{
int num;
sscanf(str.c_str(), "%d", &num);
if (num < 13)
printf("%s\n", marsnum1[num].c_str());
else
{
if (num % 13 != 0)
printf("%s %s\n", marsnum2[num / 13].c_str(), marsnum1[num % 13].c_str());
else
printf("%s\n", marsnum2[num / 13].c_str());
}
}
else if (str.size() > 4)
{
string str1, str2;
int i = 0;
for (; i < str.size(); i++)
{
if (str[i] == ' ')
break;
else
str1 += str[i];
}
i++;
for (; i < str.size(); i++)
str2 += str[i];
int flag = 0;
for (int i = 1; i < 13; i++)
{
if (str1 == marsnum2[i])
{
flag = i;
break;
}
}
for (int i = 0; i < 13; i++)
{
if (str2 == marsnum1[i])
{
printf("%d\n", flag * 13 + i);
break;
}
}
}
else
{
int flag = 0;
for (int i = 0; i < 13; i++)
{
if (str == marsnum1[i])
{
printf("%d\n", i);
flag = 1;
break;
}
}
if (flag == 0)
{
for (int i = 1; i < 13; i++)
{
if (str == marsnum2[i])
{
printf("%d\n", i * 13);
break;
}
}
}
}
}
return 0;
} | [
"jllsjtu@163.com"
] | jllsjtu@163.com |
e857a6f5b2a9d27ea5cb756291a26f49fb489e3a | 1f22d069116b605a3286d9399451f3eb569c7ca3 | /src/cpp_doxygen_sphinx.cpp | 28cfa4faafbd73a5a2338e0806f82b615682fbf6 | [] | no_license | dgitz/cpp_doxygen_sphinx | 69e11a98a44eb9f3d08fdc68462eb87dddfb3173 | e955031840c56950c5daba67264bb561ef746ac7 | refs/heads/master | 2023-03-29T08:19:48.664988 | 2021-04-06T15:53:57 | 2021-04-06T15:53:57 | 355,246,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 146 | cpp | #include "../include/cpp_doxygen_sphinx.hpp"
void Foo::say_hello(std::string message) const {
std::cout << "Hello: " << message << std::endl;
} | [
"gitz_david@cat.com"
] | gitz_david@cat.com |
4ff0b9b81524fa730ee3cb40fd80091e9a59ad50 | e83aaf423d3624748522b9adecdeb15659f5bdee | /ditfw-gfx/deps/glsdk/glmesh/include/glmesh/GenMeshMisc.h | ea1f27d7a612fe742e5cba83dc052aec536239e0 | [
"X11",
"Zlib",
"MIT",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | chartly/portfolio | 4b432c212968b56d6a1514efe3dae87ae9a0c0e0 | bd1782c274604f29f0edaa1407efce2a80d2c58f | refs/heads/master | 2021-01-19T18:33:16.143552 | 2016-11-29T03:03:25 | 2016-11-29T03:03:25 | 30,293,065 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,677 | h | /** Copyright (C) 2011-2013 by Jason L. McKesson **/
/** This file is licensed by the MIT License. **/
#ifndef GLSDK_MESH_GENERATE_MISCELLANEOUS_H
#define GLSDK_MESH_GENERATE_MISCELLANEOUS_H
/**
\file
\brief Various miscellaneous mesh generators.
**/
#include "GenDescriptors.h"
#include "GenCommon.h"
namespace glmesh
{
class Mesh;
namespace gen
{
///\addtogroup module_glmesh_mesh_generator
///@{
/**
\brief A mesh of a full-screen quad. Useful for post-processing effects.
This is a quad that covers the screen. Your vertex shader should pass the positions without
transformation. The positions are already in clip-space.
This mesh has only the position attribute. The position's Z is always 0, and the W is 1.
**/
Mesh *FullScreenQuad();
/**
\brief A mesh ground plane. Can be double-sided and arbitrarily tessellated.
This creates a square, on the range [-1, 1] in the XY plane (faces in the +Z direction).
The quad can be tessellated arbitrarily, via parameters.
Available attributes:
\li normals
\li texture coordinates: The lower-left corner of the texture is in the -X/-Y part of the square.
\param numXVerts Number of vertices along the X axis. Must be 2 or greater.
\param numYVerts Number of vertices along the Y axis. Must be 2 or greater.
\param bDoubleSided Whether the ground is double-sided or not. If not, then CCW will point in the positive-Y.
**/
Mesh *GroundPlane(int numXVerts, int numYVerts, bool bDoubleSided = true);
Mesh * Axes(ColorArray colorSequence);
/**
\name Structures
These generators build larger, complex structures out of smaller functional units. These
shapes are useful for showing off lighting and other effects. These functions are
parameterized, allowing them to produce structures of arbitrary (within reason) sizes.
**/
///@{
/**
\brief Creates a cubical block of cubes in an alternating pattern.
Each cube is a cube of size 2. The entire array will be centered around it's centerpoint.
The array's length on one side will be `2 * (2n - 1)`, where `n` is the number of cubes on an edge.
Available attributes:
\li normals
\li color, if you pass a non-empty \a colorSequence argument.
\param numCubesOnEdge The number of cubes that will appear on each edge. Will be clamped to the range [1, 16384].
\param colorSequence A series of colors used to color the faces of the objects. The order of faces is:
+y, +x, -y, -x, +z, -z. The color used will wrap around, so if you provide 6 colors, then each cube will get
the same six colors.
**/
Mesh *CubeBlock(int numCubesOnEdge, const ColorArray &colorSequence = ColorArray());
/**
\brief Creates a pyramid made of cubes, in an alternating pattern.
Each cube is a cube of size 2. The pyramid will be pointing in the positive y axis.
The entire array will be centered around its X/Z centerpoint, with the zero y at the base of the pyramid.
The height will be `2*n`, where `n` is the number of cubes in height. The width/depth will be
`2 * (2n - 1)`.
Available attributes:
\li normals
\li color, if you pass a non-empty \a colorSequence argument.
\param numCubesTall How many cubes in height the pyramid will be. Will be clamped to the range [1, 16383].
\param colorSequence A series of colors used to color the faces of the objects. The order of faces is:
+y, +x, -y, -x, +z, -z. The color used will wrap around, so if you provide 6 colors, then each cube will get
the same six colors.
**/
Mesh *CubePyramid(int numCubesTall, const ColorArray &colorSequence = ColorArray());
///@}
///@}
}
}
#endif //GLSDK_MESH_GENERATE_MISCELLANEOUS_H
| [
"the.corbin.hart@gmail.com"
] | the.corbin.hart@gmail.com |
df366992f1897b6d3d3a070f01f8fec1433bf1a5 | bf8b47c7726a07beef697de4c7ccd97d9df1cd8a | /testes/map.cpp | 3168e03a40ffa006b41a2b4261fc172e63d867cf | [] | no_license | Vitor-labs/Trabalhos_ufc | 2b5ee23aeb9366646ce1ea5cbb32d2d125de4de1 | 59c579aa45eecb20304448dfd0de121f17ae3263 | refs/heads/main | 2023-08-25T20:24:41.648233 | 2021-09-24T20:42:50 | 2021-09-24T20:42:50 | 404,305,634 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,252 | cpp | #include <iostream>
#include <map>
using namespace std;
/*A classe map funciona como um conteiner associativo. O acesso aos mapas é
bem rápido, pois internamente, eles implementa uma estrutura conhecida como
Red-Black Trees, que usam busca balanceada, usadas paras esses vetores*/
int main(int argc, char const *argv[])
{
cout << "MAPA" << endl;
map<int, string> mapa;
mapa = {{1, "pedro"},
{2, "carlos"},
{3, "jose"},
{4, "henrique"},
{5, "felipe"},
{1, "leandro"},
{2, "mateus"},
{3, "vitor"},
{6, "henrique"},
{1, "erique"}};
map<int, string>::iterator it = mapa.begin();
for (it; it != mapa.end(); it++)
{
cout << it->first << ": " << it->second << endl;
}
cout << endl;
it = mapa.find(2);
mapa.erase(it);
for (int i = 1; i <= mapa.size(); i++)
{
if (mapa.find(i) == mapa.end())
{
cerr << "Elemento vazio" << endl;
mapa.insert({i, "--vazio--"});
continue;
}
cout << mapa.count(i) << " - " << mapa.at(i) << endl;
} // a função count é mais util com multimapas
cout << endl;
for (it = mapa.begin(); it != mapa.end(); it++)
{
cout << it->first << ": " << it->second << endl;
}
cout << endl;
//MULTIMAPAS:
cout << "MULTIMAPAS" << endl;
multimap<int, string> mapa2;
mapa2 = {{1, "pedro"},
{1, "leandro"},
{2, "carlos"},
{2, "mateus"},
{3, "jose"},
{3, "vitor"},
{4, "henrique"},
{5, "felipe"},
{6, "henrique"},
{1, "erique"}};
multimap<int, string>::iterator iter = mapa2.begin();
for (iter; iter != mapa2.end(); iter++)
{
cout << iter->first << ": " << iter->second << endl;
}
cout << endl;
multimap<int, string>::iterator itlow, itup;
itlow = mapa2.lower_bound(2);
itup = mapa2.upper_bound(4);
for (iter = itlow; iter != itup; ++iter)
{
cout << iter->first << ": " << iter->second << endl;
}
} | [
"noreply@github.com"
] | noreply@github.com |
23c974d6c4a5f363ce1c7c55c0e94574095c1945 | 00012c2dd1d3ad97a7e1ba58f946a7b79a4f4862 | /Codechef/HubbyBunny.cpp | a0a50a7110e89652694ed688ddc3d7acf3698d3c | [] | no_license | gautam3000/Competitive-Programming | 9a208d53819cd618ef896b8cdf0d50e069b8ec23 | 0f9ebc4a6823d77cafb71a3f2898d34eb12607b2 | refs/heads/master | 2022-12-01T01:42:42.414584 | 2020-08-15T12:45:46 | 2020-08-15T12:45:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 534 | cpp | //https://www.codechef.com/problems/HOF3
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int t;
cin>>t;
while(t--){
long long int a,b,c,d,e,f;
cin>>a>>b>>c>>d>>e>>f;
double result=(sqrt(((d-a)*(d-a))+((b-e)*(b-e))));
double value=c+f;
if(result==value)
cout<<"tangential"<<endl;
if(result>value)
cout<<"not overlapping"<<endl;
if(result<value)
cout<<"overlapping"<<endl;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
2082c22d6e31d931e0f4c8eb7f7b4ef8e9d236f8 | 325d0ecf79bec8e3d630c26195da689ea5bb567e | /qdude/src/qnode.cpp | 6a1a3ff2ab9f76475965c5f845865887d7c4bb0a | [] | no_license | nvtienanh/Hitechlab_humanoid | ccaac64885967334f41a161f1684ff3a1571ab0f | 34c899f70af7390b9fbdb1a1ad03faf864a550be | refs/heads/master | 2020-04-22T10:34:21.944422 | 2016-08-28T06:02:00 | 2016-08-28T06:02:00 | 66,521,772 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,461 | cpp | /**
* @file /src/qnode.cpp
*
* @brief Ros communication central!
*
* @date February 2011
**/
/*****************************************************************************
** Includes
*****************************************************************************/
#include <ros/ros.h>
#include <ros/network.h>
#include <string>
#include <std_msgs/String.h>
#include <sstream>
#include "../include/qdude/qnode.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace qdude {
/*****************************************************************************
** Implementation
*****************************************************************************/
QNode::QNode(int argc, char** argv ) :
init_argc(argc),
init_argv(argv)
{}
QNode::~QNode() {
if(ros::isStarted()) {
ros::shutdown(); // explicitly needed since we use ros::start();
ros::waitForShutdown();
}
wait();
}
bool QNode::init() {
ros::init(init_argc,init_argv,"qdude");
if ( ! ros::master::check() ) {
return false;
}
ros::start(); // explicitly needed since our nodehandle is going out of scope.
ros::NodeHandle n;
// Add your ros communications here.
chatter_publisher = n.advertise<std_msgs::String>("chatter", 1000);
start();
return true;
}
bool QNode::init(const std::string &master_url, const std::string &host_url) {
std::map<std::string,std::string> remappings;
remappings["__master"] = master_url;
remappings["__hostname"] = host_url;
ros::init(remappings,"qdude");
if ( ! ros::master::check() ) {
return false;
}
ros::start(); // explicitly needed since our nodehandle is going out of scope.
ros::NodeHandle n;
// Add your ros communications here.
chatter_publisher = n.advertise<std_msgs::String>("chatter", 1000);
start();
return true;
}
void QNode::run() {
ros::Rate loop_rate(1);
int count = 0;
while ( ros::ok() ) {
std_msgs::String msg;
std::stringstream ss;
ss << "hello world " << count;
msg.data = ss.str();
chatter_publisher.publish(msg);
log(Info,std::string("I sent: ")+msg.data);
ros::spinOnce();
loop_rate.sleep();
++count;
}
std::cout << "Ros shutdown, proceeding to close the gui." << std::endl;
Q_EMIT rosShutdown(); // used to signal the gui for a shutdown (useful to roslaunch)
}
void QNode::log( const LogLevel &level, const std::string &msg) {
logging_model.insertRows(logging_model.rowCount(),1);
std::stringstream logging_model_msg;
switch ( level ) {
case(Debug) : {
ROS_DEBUG_STREAM(msg);
logging_model_msg << "[DEBUG] [" << ros::Time::now() << "]: " << msg;
break;
}
case(Info) : {
ROS_INFO_STREAM(msg);
logging_model_msg << "[INFO] [" << ros::Time::now() << "]: " << msg;
break;
}
case(Warn) : {
ROS_WARN_STREAM(msg);
logging_model_msg << "[INFO] [" << ros::Time::now() << "]: " << msg;
break;
}
case(Error) : {
ROS_ERROR_STREAM(msg);
logging_model_msg << "[ERROR] [" << ros::Time::now() << "]: " << msg;
break;
}
case(Fatal) : {
ROS_FATAL_STREAM(msg);
logging_model_msg << "[FATAL] [" << ros::Time::now() << "]: " << msg;
break;
}
}
QVariant new_row(QString(logging_model_msg.str().c_str()));
logging_model.setData(logging_model.index(logging_model.rowCount()-1),new_row);
Q_EMIT loggingUpdated(); // used to readjust the scrollbar
}
} // namespace qdude
| [
"nvtienanh@gmail.com"
] | nvtienanh@gmail.com |
71e756d54d5cb007a7bf265a70f3017e42db38ea | 4bb1a23a62bf6dc83a107d4da8daefd9b383fc99 | /work/abc075_d.cpp | c28877e05cfec3c0cfb4f7d409f30a81c994d78d | [] | no_license | takushi-m/atcoder-work | 0aeea397c85173318497e08cb849efd459a9f6b6 | f6769f0be9c085bde88129a1e9205fb817bb556a | refs/heads/master | 2021-09-24T16:52:58.752112 | 2021-09-11T14:17:10 | 2021-09-11T14:17:10 | 144,509,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,035 | cpp | #include<iostream>
#include<vector>
using namespace std;
using ll = long long;
int main(){
int n,k;
cin>>n>>k;
vector<ll> xary,yary;
for(int i=0;i<n;++i){
ll x,y;
cin>>x>>y;
xary.push_back(x);
yary.push_back(y);
}
unsigned long long ret = 0;
for(int xi=0;xi<n;++xi){
for(int xj=xi+1;xj<n;++xj){
for(int yi=0;yi<n;++yi){
for(int yj=yi+1;yj<n;++yj){
int cnt = 0;
ll maxx = max(xary[xi],xary[xj]);
ll minx = min(xary[xi],xary[xj]);
ll maxy = max(yary[yi],yary[yj]);
ll miny = min(yary[yi],yary[yj]);
for(int p=0;p<n;++p){
if(maxx>=xary[p] && xary[p]>=minx && maxy>=yary[p] && yary[p]>=miny){
cnt += 1;
}
if(cnt>=k){
break;
}
}
if(cnt>=k){
unsigned long long s = (maxx-minx) * (maxy-miny);
if(ret==0 || s<ret){
ret = s;
}
}
}
}
}
}
cout<<ret<<endl;
}
| [
"takushi-m@users.noreply.github.com"
] | takushi-m@users.noreply.github.com |
226924314d4ea6e70b8d4e2bafa6b6a119fffdce | 69430698ad5a28ca90b93c6cf5dc0a3385db1578 | /semana4/MergeSort.cpp | f6668bffd0c41f861c80cb60b79e98caebf7b82c | [] | no_license | DouglasCastro21/PAA | 63736d64b3a4f81eca22313bbac5db9beba4275a | 063524d6b1986752b79f4baf18154a9186009f4a | refs/heads/main | 2023-06-15T13:12:18.754490 | 2021-07-14T00:30:52 | 2021-07-14T00:30:52 | 348,187,874 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,204 | cpp | #include <iostream>
#include <vector>
void copiaVolume(std::vector<char> &elementos);
// Mescla dois vetor vetor1 e vetor2
void merge(std::vector<char> &elementos, int vetor1, int num, int vetor2)
{
int v1 = num - vetor1 + 1;
int v2 = vetor2 - num;
// vetor temporario
std::vector<int> vetorEsquerdo(v1, 0), vetorDireito(v2, 0);
// vetor Esquerdo vetor Direito recebe dados
for (int i = 0; i < v1; i++)
vetorEsquerdo[i] = elementos[vetor1 + i];
for (int j = 0; j < v2; j++)
vetorDireito[j] = elementos[num + 1 + j];
// Índice inicial vetor1
int i = 0;
// Índice inicial vetor2
int j = 0;
// Índice vetor mesclado
int l = vetor1;
while (i < v1 && j < v2)
{
if (vetorEsquerdo[i] <= vetorDireito[j])
{
elementos[l] = vetorEsquerdo[i];
i++;
}
else
{
elementos[l] = vetorDireito[j];
j++;
}
l++;
}
//passa os elementos para a esquerda
while (i < v1)
{
elementos[l] = vetorEsquerdo[i];
i++;
l++;
}
//passa os elementos para a direita
while (j < v2)
{
elementos[l] = vetorDireito[j];
j++;
l++;
}
}
// classificação * /
void mergeSort(std::vector<char> &elementos, int a, int b)
{
copiaVolume(elementos);
if (a >= b) // condição de parada
{
return; // retorna recursivamente
}
int numV = a + (b - a) / 2;
mergeSort(elementos, a, numV);
mergeSort(elementos, numV + 1, b);
merge(elementos, a, numV, b);
}
void copiaVolume(std::vector<char> &elementos)
{
std::cout << "[";
for (auto i = 0; i < elementos.size() - 1; i++)
{
std::cout << elementos[i] << " ";
}
std::cout << elementos.back() << "]\n";
}
int main()
{
std::vector<char> elementos = {'E', 'X', 'A', 'M', 'P', 'L', 'E'};
std::cout << "vetor com a palavra:\n";
copiaVolume(elementos);
std::cout << "\n";
std::cout << " Ordenando ...:\n";
mergeSort(elementos, 0, elementos.size() - 1);
std::cout << "\nPalavra ordenada:\n";
copiaVolume(elementos);
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
fbd34d6fa9108b48f293104aa304e45de5809bde | 1b90be9561c10508eea59cb36c1f1665d0ef947f | /test/unit/math/rev/functor/partials_propagator_test.cpp | bc09e38196de8b498e4c5da40cac661422afbce9 | [
"BSD-3-Clause",
"GPL-2.0-only",
"Apache-2.0"
] | permissive | stan-dev/math | 473e7c1eaf11f84eaf2032c2455e12ba65feef39 | bdf281f4e7f8034f47974d14dea7f09e600ac02a | refs/heads/develop | 2023-08-31T09:02:59.224115 | 2023-08-29T15:17:01 | 2023-08-29T15:17:01 | 38,388,440 | 732 | 240 | BSD-3-Clause | 2023-09-14T19:44:20 | 2015-07-01T18:40:54 | C++ | UTF-8 | C++ | false | false | 10,369 | cpp | #include <stan/math/rev/functor/partials_propagator.hpp>
#include <test/unit/util.hpp>
#include <gtest/gtest.h>
#include <vector>
TEST(AgradPartialsVari, PartialsPropagatorScal) {
using stan::math::make_partials_propagator;
using stan::math::var;
double d1;
auto o3 = stan::math::make_partials_propagator(d1);
EXPECT_EQ(2, sizeof(o3));
var v1 = var(0.0);
std::vector<var> v_stdvec;
v_stdvec.push_back(v1);
auto o4 = stan::math::make_partials_propagator(v1);
stan::math::edge<0>(o4).partials_[0] += 10.0;
std::vector<double> grad;
var v = o4.build(10.0);
v.grad(v_stdvec, grad);
EXPECT_FLOAT_EQ(10.0, v.val());
EXPECT_FLOAT_EQ(10.0, grad[0]);
}
TEST(AgradPartialsVari, PartialsPropagatorVec) {
using stan::math::make_partials_propagator;
using stan::math::var;
using stan::math::vector_d;
using stan::math::vector_v;
vector_d d_vec(4);
auto o3 = stan::math::make_partials_propagator(d_vec);
EXPECT_EQ(2, sizeof(o3));
vector_v v_vec(4);
var v1 = var(0.0);
var v2 = var(1.0);
var v3 = var(2.0);
var v4 = var(3.0);
v_vec << v1, v2, v3, v4;
std::vector<var> v_stdvec;
v_stdvec.push_back(v1);
v_stdvec.push_back(v2);
v_stdvec.push_back(v3);
v_stdvec.push_back(v4);
auto o4 = stan::math::make_partials_propagator(v_vec);
stan::math::edge<0>(o4).partials_[0] += 10.0;
stan::math::edge<0>(o4).partials_[1] += 20.0;
stan::math::edge<0>(o4).partials_[2] += 30.0;
stan::math::edge<0>(o4).partials_[3] += 40.0;
std::vector<double> grad;
var v = o4.build(10.0);
v.grad(v_stdvec, grad);
EXPECT_FLOAT_EQ(10.0, v.val());
EXPECT_FLOAT_EQ(10.0, grad[0]);
EXPECT_FLOAT_EQ(20.0, grad[1]);
EXPECT_FLOAT_EQ(30.0, grad[2]);
EXPECT_FLOAT_EQ(40.0, grad[3]);
}
TEST(AgradPartialsVari, PartialsPropagatorStdVec) {
using stan::math::make_partials_propagator;
using stan::math::var;
std::vector<double> d_vec(4);
auto o3 = stan::math::make_partials_propagator(d_vec);
EXPECT_EQ(2, sizeof(o3));
std::vector<var> v_vec;
var v1 = var(0.0);
var v2 = var(1.0);
var v3 = var(2.0);
var v4 = var(3.0);
v_vec.push_back(v1);
v_vec.push_back(v2);
v_vec.push_back(v3);
v_vec.push_back(v4);
auto o4 = stan::math::make_partials_propagator(v_vec);
stan::math::edge<0>(o4).partials_[0] += 10.0;
stan::math::edge<0>(o4).partials_[1] += 20.0;
stan::math::edge<0>(o4).partials_[2] += 30.0;
stan::math::edge<0>(o4).partials_[3] += 40.0;
std::vector<double> grad;
var v = o4.build(10.0);
v.grad(v_vec, grad);
EXPECT_FLOAT_EQ(10.0, v.val());
EXPECT_FLOAT_EQ(10.0, grad[0]);
EXPECT_FLOAT_EQ(20.0, grad[1]);
EXPECT_FLOAT_EQ(30.0, grad[2]);
EXPECT_FLOAT_EQ(40.0, grad[3]);
}
TEST(AgradPartialsVari, PartialsPropagatorMat) {
using stan::math::make_partials_propagator;
using stan::math::matrix_d;
using stan::math::matrix_v;
using stan::math::var;
matrix_d d_mat(2, 2);
d_mat << 10.0, 20.0, 30.0, 40.0;
auto o3 = stan::math::make_partials_propagator(d_mat);
EXPECT_EQ(2, sizeof(o3));
matrix_v v_mat(2, 2);
var v1 = var(0.0);
var v2 = var(1.0);
var v3 = var(2.0);
var v4 = var(3.0);
v_mat << v1, v2, v3, v4;
std::vector<var> v_stdvec;
v_stdvec.push_back(v1);
v_stdvec.push_back(v2);
v_stdvec.push_back(v3);
v_stdvec.push_back(v4);
auto o4 = stan::math::make_partials_propagator(v_mat);
stan::math::edge<0>(o4).partials_ += d_mat;
stan::math::edge<0>(o4).partials_vec_[1] += d_mat;
// Should affect the same vars as the call above
stan::math::edge<0>(o4).partials_vec_[27] += d_mat;
std::vector<double> grad;
var v = o4.build(10.0);
v.grad(v_stdvec, grad);
EXPECT_FLOAT_EQ(10.0, v.val());
EXPECT_FLOAT_EQ(30.0, grad[0]);
EXPECT_FLOAT_EQ(60.0, grad[1]);
EXPECT_FLOAT_EQ(90.0, grad[2]);
EXPECT_FLOAT_EQ(120.0, grad[3]);
}
TEST(AgradPartialsVari, PartialsPropagatorMatMultivar) {
using stan::math::make_partials_propagator;
using stan::math::matrix_d;
using stan::math::matrix_v;
using stan::math::var;
matrix_d d_mat(2, 2);
d_mat << 10.0, 20.0, 30.0, 40.0;
std::vector<matrix_d> d_mat_vec;
d_mat_vec.push_back(d_mat);
auto o3 = stan::math::make_partials_propagator(d_mat_vec);
EXPECT_EQ(2, sizeof(o3));
matrix_v v_mat1(2, 2);
var v1 = var(0.0);
var v2 = var(1.0);
var v3 = var(2.0);
var v4 = var(3.0);
v_mat1 << v1, v2, v3, v4;
matrix_v v_mat2(2, 2);
var v5 = var(0.1);
var v6 = var(1.1);
var v7 = var(2.1);
var v8 = var(3.1);
v_mat2 << v5, v6, v7, v8;
std::vector<matrix_v> v_mat_vec;
v_mat_vec.push_back(v_mat1);
v_mat_vec.push_back(v_mat2);
std::vector<var> v_stdvec;
v_stdvec.push_back(v1);
v_stdvec.push_back(v2);
v_stdvec.push_back(v3);
v_stdvec.push_back(v4);
v_stdvec.push_back(v5);
v_stdvec.push_back(v6);
v_stdvec.push_back(v7);
v_stdvec.push_back(v8);
auto o4 = stan::math::make_partials_propagator(v_mat_vec);
stan::math::edge<0>(o4).partials_vec_[0] += d_mat;
// Should NOT affect the same vars as the call above
stan::math::edge<0>(o4).partials_vec_[1] += d_mat;
stan::math::edge<0>(o4).partials_vec_[1] += d_mat;
std::vector<double> grad;
var v = o4.build(10.0);
v.grad(v_stdvec, grad);
EXPECT_FLOAT_EQ(10.0, v.val());
EXPECT_FLOAT_EQ(10.0, grad[0]);
EXPECT_FLOAT_EQ(20.0, grad[1]);
EXPECT_FLOAT_EQ(30.0, grad[2]);
EXPECT_FLOAT_EQ(40.0, grad[3]);
EXPECT_FLOAT_EQ(20.0, grad[4]);
EXPECT_FLOAT_EQ(40.0, grad[5]);
EXPECT_FLOAT_EQ(60.0, grad[6]);
EXPECT_FLOAT_EQ(80.0, grad[7]);
}
TEST(AgradPartialsVari, PartialsPropagatorMultivar) {
using stan::math::make_partials_propagator;
using stan::math::var;
using stan::math::vector_d;
using stan::math::vector_v;
std::vector<vector_d> d_vec_vec(2);
vector_d d_vec1(2);
d_vec1 << 10.0, 20.0;
vector_d d_vec2(2);
d_vec2 << 30.0, 40.0;
d_vec_vec.push_back(d_vec1);
d_vec_vec.push_back(d_vec2);
auto o3 = stan::math::make_partials_propagator(d_vec_vec);
EXPECT_EQ(2, sizeof(o3));
vector_v v_vec1(2);
var v1 = var(0.0);
var v2 = var(1.0);
v_vec1 << v1, v2;
vector_v v_vec2(2);
var v3 = var(2.0);
var v4 = var(3.0);
v_vec2 << v3, v4;
std::vector<vector_v> v_vec;
v_vec.push_back(v_vec1);
v_vec.push_back(v_vec2);
std::vector<var> v_stdvec;
v_stdvec.push_back(v1);
v_stdvec.push_back(v2);
v_stdvec.push_back(v3);
v_stdvec.push_back(v4);
auto o4 = stan::math::make_partials_propagator(v_vec);
stan::math::edge<0>(o4).partials_vec_[0] += d_vec1;
stan::math::edge<0>(o4).partials_vec_[1] += d_vec2;
std::vector<double> grad;
var v = o4.build(10.0);
v.grad(v_stdvec, grad);
EXPECT_FLOAT_EQ(10.0, v.val());
EXPECT_FLOAT_EQ(10.0, grad[0]);
EXPECT_FLOAT_EQ(20.0, grad[1]);
EXPECT_FLOAT_EQ(30.0, grad[2]);
EXPECT_FLOAT_EQ(40.0, grad[3]);
}
// XXX Test mixed - partials_propagator<std::vector<matrix_v>,
// vector_d, vector_v>
TEST(AgradPartialsVari, PartialsPropagatorMultivarMixed) {
using stan::math::make_partials_propagator;
using stan::math::matrix_v;
using stan::math::var;
using stan::math::vector_d;
using stan::math::vector_v;
std::vector<vector_d> d_vec_vec(2);
vector_d d_vec1(2);
d_vec1 << 10.0, 20.0;
vector_d d_vec2(2);
d_vec2 << 30.0, 40.0;
d_vec_vec.push_back(d_vec1);
d_vec_vec.push_back(d_vec2);
vector_v v_vec1(2);
var v1 = var(0.0);
var v2 = var(1.0);
v_vec1 << v1, v2;
vector_v v_vec2(2);
var v3 = var(2.0);
var v4 = var(3.0);
v_vec2 << v3, v4;
std::vector<vector_v> v_vec;
v_vec.push_back(v_vec1);
std::vector<var> v_stdvec;
v_stdvec.push_back(v1);
v_stdvec.push_back(v2);
v_stdvec.push_back(v3);
v_stdvec.push_back(v4);
auto o4 = make_partials_propagator(v_vec, d_vec_vec, v_vec2);
stan::math::edge<0>(o4).partials_vec_[0] += d_vec1;
stan::math::edge<2>(o4).partials_vec_[0] += d_vec2;
// 2 partials stdvecs, 4 pointers to edges, 2 pointers to operands
// vecs
EXPECT_EQ(112, sizeof(o4));
std::vector<double> grad;
var v = o4.build(10.0);
v.grad(v_stdvec, grad);
EXPECT_FLOAT_EQ(10.0, v.val());
EXPECT_FLOAT_EQ(10.0, grad[0]);
EXPECT_FLOAT_EQ(20.0, grad[1]);
EXPECT_FLOAT_EQ(30.0, grad[2]);
EXPECT_FLOAT_EQ(40.0, grad[3]);
// when given vector_d in place of vector_v all expressions must
// still compile
auto o5 = make_partials_propagator(v_vec, d_vec_vec, d_vec2);
stan::math::edge<0>(o5).partials_vec_[0] += d_vec1;
if (false) {
// the test here is to make things compile as this pattern to
// if-out things when terms are const is used in our functions
stan::math::edge<2>(o5).partials_vec_[0] += vector_d();
stan::math::edge<2>(o5).partials_vec_[0] -= vector_d();
stan::math::edge<2>(o5).partials_vec_[0](0) = 0;
}
// the same needs to work for the nested case
auto o6 = make_partials_propagator(d_vec_vec, d_vec_vec, v_vec2);
if (false) {
// the test here is to make things compile as this pattern to
// if-out things when terms are const is used in our functions
stan::math::edge<0>(o6).partials_vec_[0] += d_vec1;
}
stan::math::edge<2>(o6).partials_vec_[0] += d_vec2;
}
TEST(AgradPartialsVari, PartialsPropagatorVarValueMat) {
using stan::math::make_partials_propagator;
using stan::math::matrix_d;
using stan::math::matrix_v;
using stan::math::var;
Eigen::MatrixXd a(2, 2);
a << 10.0, 20.0, 30.0, 40.0;
stan::math::var_value<Eigen::MatrixXd> av(a);
auto ops = stan::math::make_partials_propagator(av);
stan::math::edge<0>(ops).partials_ = Eigen::MatrixXd::Constant(2, 2, -2);
var lp = ops.build(1);
(2 * lp).grad();
EXPECT_MATRIX_EQ(av.adj(), Eigen::MatrixXd::Constant(2, 2, -4))
}
TEST(AgradPartialsVari, PartialsPropagatorStdVectorVarValueMat) {
using stan::math::make_partials_propagator;
using stan::math::matrix_d;
using stan::math::matrix_v;
using stan::math::var;
Eigen::MatrixXd a(2, 2);
a << 10.0, 20.0, 30.0, 40.0;
std::vector<stan::math::var_value<Eigen::MatrixXd>> av{a, a};
auto ops = make_partials_propagator(av);
stan::math::edge<0>(ops).partials_vec_[0]
= Eigen::MatrixXd::Constant(2, 2, -2);
stan::math::edge<0>(ops).partials_vec_[1]
= Eigen::MatrixXd::Constant(2, 2, -3);
var lp = ops.build(1);
(2 * lp).grad();
EXPECT_MATRIX_EQ(av[0].adj(), Eigen::MatrixXd::Constant(2, 2, -4));
EXPECT_MATRIX_EQ(av[1].adj(), Eigen::MatrixXd::Constant(2, 2, -6));
}
| [
"stevo15025@gmail.com"
] | stevo15025@gmail.com |
881ae49000651284184e428be197d956fa147c27 | 792f2ee67210556f224daf88ef0b9785becadc9b | /codeforces/1278E.cpp | 2031b85e7de05d5c4136a691c9dffe2710d0f96b | [] | no_license | firiexp/contest_log | e5b345286e7d69ebf2a599d4a81bdb19243ca18d | 6474a7127d3a2fed768ebb62031d5ff30eeeef86 | refs/heads/master | 2021-07-20T01:16:47.869936 | 2020-04-30T03:27:51 | 2020-04-30T03:27:51 | 150,196,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,567 | cpp | #include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
#include <cmath>
static const int MOD = 998244353;
using ll = long long;
using u32 = unsigned;
using u64 = unsigned long long;
using namespace std;
template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;
template<u32 M = 1000000007>
struct modint{
u32 val;
modint(): val(0){}
template<typename T>
modint(T t){t %= (T)M; if(t < 0) t += (T)M; val = t;}
modint pow(ll k) const {
modint res(1), x(val);
while(k){
if(k&1) res *= x;
x *= x;
k >>= 1;
}
return res;
}
template<typename T>
modint& operator=(T t){t %= (T)M; if(t < 0) t += (T)M; val = t; return *this; }
modint inv() const {return pow(M-2);}
modint& operator+=(modint a){ val += a.val; if(val >= M) val -= M; return *this;}
modint& operator-=(modint a){ if(val < a.val) val += M-a.val; else val -= a.val; return *this;}
modint& operator*=(modint a){ val = (u64)val*a.val%M; return *this;}
modint& operator/=(modint a){ return (*this) *= a.inv();}
modint operator+(modint a) const {return modint(val) +=a;}
modint operator-(modint a) const {return modint(val) -=a;}
modint operator*(modint a) const {return modint(val) *=a;}
modint operator/(modint a) const {return modint(val) /=a;}
modint operator-(){ return modint(M-val);}
bool operator==(const modint a) const {return val == a.val;}
bool operator!=(const modint a) const {return val != a.val;}
bool operator<(const modint a) const {return val < a.val;}
};
using mint = modint<MOD>;
class Factorial {
vector<mint> facts, factinv;
public:
explicit Factorial(int n) : facts(n+1), factinv(n+1) {
facts[0] = 1;
for (int i = 1; i < n+1; ++i) facts[i] = facts[i-1] * mint(i);
factinv[n] = facts[n].inv();
for (int i = n-1; i >= 0; --i) factinv[i] = factinv[i+1] * mint(i+1);
}
mint fact(int k) const {
if(k >= 0) return facts[k]; else return factinv[-k];
}
mint operator[](const int &k) const {
if(k >= 0) return facts[k]; else return factinv[-k];
}
mint C(int p, int q) const {
if(q < 0 || p < q) return 0;
return facts[p] * factinv[q] * factinv[p-q];
}
mint P(int p, int q) const {
if(q < 0 || p < q) return 0;
return facts[p] * factinv[p-q];
}
mint H(int p, int q) const {
if(p < 0 || q < 0) return 0;
return q == 0 ? 1 : C(p+q-1, q);
}
};
int main() {
int n, m, k;
cin >> n >> m >> k;
vector<mint> v(k+1), powk(k+1), powm(k+1);
Factorial f(k);
for (int i = 0; i <= k; ++i) {
powk[i] = mint(i).pow(k);
if(i) powm[i] = powm[i-1]*mint(m-1);
else powm[i] = 1;
for (int j = 0; j <= i; ++j) {
v[i] += powk[j]*f.C(i, j)*powm[i-j];
}
v[i] *= mint(m).inv().pow(i);
}
mint ans = 0;
if(n <= k){
ans = v[n];
}else {
mint al = 1;
for (int i = 0; i <= k; ++i) {
al *= mint(n-i);
}
for (int i = 0; i <= k; ++i) {
mint p = al * (mint(n-i).inv());
p *= f[-i];
p *= f[i-k];
if((k-i)&1) p = -p;
ans += p * v[i];
}
}
cout << ans.val << "\n";
return 0;
} | [
"firiexp@PC.localdomain"
] | firiexp@PC.localdomain |
8f1d2755613497177880e5b324573c12075385ab | 4e973ffec6c5e03e7daf895845adb539301cacfe | /ViewPort_Redimensionado/ViewPort_Redimensionado/main.cpp | e2dfd5cb9065d6a41d5c1e87830d96b62c6fa828 | [] | no_license | EvandroInocenti/PGII-Exerc-cios | de7a0ec10bf818b08bee9771872ebaaf552de1c5 | e11e48362dc462b32e3314c524816991a0320ed9 | refs/heads/master | 2020-12-29T02:19:28.059719 | 2016-09-26T13:33:24 | 2016-09-26T13:33:24 | 68,410,498 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,632 | cpp | #include <windows.h>
#include <GL/glut.h>
void desenha(){
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_QUADS);
glColor3f(1.0f, 0.0f, 0.0f);// Vermelho
glVertex2f(-0.8f, 0.1f); glVertex2f(-0.2f, 0.1f);
glVertex2f(-0.2f, 0.7f); glVertex2f(-0.8f, 0.7f);
glColor3f(0.0f, 1.0f, 0.0f);// Verde
glVertex2f(-0.7f, -0.6f); glVertex2f(-0.1f, -0.6f);
glVertex2f(-0.1f, 0.0f); glVertex2f(-0.7f, 0.0f);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.0f, 0.0f, 1.0f);// Azul
glVertex2f(0.1f, -0.6f); glVertex2f(0.7f, -0.6f); glVertex2f(0.4f, -0.1f);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0f, 1.0f, 0.0f);// Amarelo
glVertex2f(0.4f, 0.2f); glVertex2f(0.6f, 0.2f); glVertex2f(0.7f, 0.4f);
glVertex2f(0.6f, 0.6f); glVertex2f(0.4f, 0.6f); glVertex2f(0.3f, 0.4f);
glEnd();
glFlush();
}
void redimensiona(GLsizei width, GLsizei height){
if (height == 0){
height = 1;//Evita divisão por 0
}
// Calcula a proporção da janela
GLfloat aspecto = (GLfloat)width / (GLfloat)height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (width >= height){
//Aspecto >= 1, seta altura para -1 to 1, com comprimento maior
gluOrtho2D(-1.0*aspecto, 1.0*aspecto, -1.0, 1.0);
}
else
{
//Aspecto < 1, seta comprimento para -1 to 1, com altura maior
gluOrtho2D(-1.0, 1.0, -1.0 / aspecto, 1.0 / aspecto);
}
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitWindowSize(640, 640);
glutInitWindowPosition(50, 50);
glutCreateWindow("Unoesc -CG");
glutReshapeFunc(redimensiona);
glutDisplayFunc(desenha);
glutMainLoop();
return 0;
}
| [
"inocenti@gmail.com"
] | inocenti@gmail.com |
bb6390fc53e39611c43922473dd43a5fd549a935 | dd50d1a5a3c7e96e83e75f68c7a940f91275f206 | /source/tnn/device/arm/acc/compute_arm82/compute_half.cc | 8204182f7660c13bcbfdcb9e937b322e42b61c58 | [
"BSD-3-Clause"
] | permissive | bluaxe/TNN | 2bfdecc85ac4684e82032a86703eacaed5419ad6 | cafdb8792dc779236ec06dbeb65710073d27ebcd | refs/heads/master | 2023-03-19T02:55:39.007321 | 2021-03-04T02:59:18 | 2021-03-04T02:59:18 | 272,395,487 | 3 | 0 | NOASSERTION | 2020-12-30T08:10:31 | 2020-06-15T09:23:31 | C++ | UTF-8 | C++ | false | false | 43,698 | cc | // Tencent is pleased to support the open source community by making TNN available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "tnn/device/arm/acc/compute_arm82/compute_half.h"
#include <string.h>
#include "tnn/core/macro.h"
#include "tnn/device/arm/acc/compute/compute.h"
#include "tnn/device/arm/acc/Half8.h"
#include "tnn/device/arm/arm_common.h"
#include "tnn/device/arm/arm_util.h"
#include "tnn/utils/half_utils.h"
#include "tnn/utils/naive_compute.h"
#include "tnn/utils/omp_utils.h"
namespace TNN_NS {
/*
[1] Implement functions in compute.h with fp16 version
*/
#if TNN_ARM82
template <>
void PostAddBias<fp16_t, fp16_t>(void* dst, const void* bias, long area, long oc8) {
for (long z = oc8 - 1; z >= 0; --z) {
Half8 vbias = Half8::load(reinterpret_cast<const fp16_t*>(bias) + 8 * z);
auto dst_z = reinterpret_cast<fp16_t*>(dst) + area * 8 * z;
long p = 0;
for (; p < area - 3; p += 4) {
auto dst_p = dst_z + 8 * p;
Half8 dst_0 = Half8::load(dst_p);
Half8 dst_1 = Half8::load(dst_p + 8);
Half8 dst_2 = Half8::load(dst_p + 16);
Half8 dst_3 = Half8::load(dst_p + 24);
dst_0 = dst_0 + vbias;
dst_1 = dst_1 + vbias;
dst_2 = dst_2 + vbias;
dst_3 = dst_3 + vbias;
Half8::save(dst_p, dst_0);
Half8::save(dst_p + 8, dst_1);
Half8::save(dst_p + 16, dst_2);
Half8::save(dst_p + 24, dst_3);
}
for (; p < area; ++p) {
auto dst_p = dst_z + 8 * p;
Half8 dst_0 = Half8::load(dst_p);
dst_0 = dst_0 + vbias;
Half8::save(dst_p, dst_0);
}
}
}
template <>
void PostAddBiasRelu<fp16_t, fp16_t>(void* dst, const void* bias, long area, long oc8) {
Half8 vzero = Half8((fp16_t)0.f);
for (long z = oc8 - 1; z >= 0; --z) {
Half8 vbias = Half8::load(reinterpret_cast<const fp16_t*>(bias) + 8 * z);
auto dst_z = reinterpret_cast<fp16_t*>(dst) + area * 8 * z;
long p = 0;
for (; p < area - 3; p += 4) {
auto dst_p = dst_z + 8 * p;
Half8 dst_0 = Half8::load(dst_p);
Half8 dst_1 = Half8::load(dst_p + 8);
Half8 dst_2 = Half8::load(dst_p + 16);
Half8 dst_3 = Half8::load(dst_p + 24);
dst_0 = Half8::max(dst_0 + vbias, vzero);
dst_1 = Half8::max(dst_1 + vbias, vzero);
dst_2 = Half8::max(dst_2 + vbias, vzero);
dst_3 = Half8::max(dst_3 + vbias, vzero);
Half8::save(dst_p, dst_0);
Half8::save(dst_p + 8, dst_1);
Half8::save(dst_p + 16, dst_2);
Half8::save(dst_p + 24, dst_3);
}
for (; p < area; ++p) {
auto dst_p = dst_z + 8 * p;
Half8 dst_0 = Half8::load(dst_p);
dst_0 = Half8::max(dst_0 + vbias, vzero);
Half8::save(dst_p, dst_0);
}
}
}
template <>
void PostAddBiasRelu6<fp16_t, fp16_t>(void* dst, const void* bias, long area, long oc8) {
Half8 vzero = Half8((fp16_t)0.f);
Half8 vrelu6 = Half8((fp16_t)6.f);
for (long z = oc8 - 1; z >= 0; --z) {
Half8 vbias = Half8::load(reinterpret_cast<const fp16_t*>(bias) + 8 * z);
auto dst_z = reinterpret_cast<fp16_t*>(dst) + area * 8 * z;
long p = 0;
for (; p < area - 3; p += 4) {
auto dst_p = dst_z + 8 * p;
Half8 dst_0 = Half8::load(dst_p);
Half8 dst_1 = Half8::load(dst_p + 8);
Half8 dst_2 = Half8::load(dst_p + 16);
Half8 dst_3 = Half8::load(dst_p + 24);
dst_0 = Half8::min(Half8::max(dst_0 + vbias, vzero), vrelu6);
dst_1 = Half8::min(Half8::max(dst_1 + vbias, vzero), vrelu6);
dst_2 = Half8::min(Half8::max(dst_2 + vbias, vzero), vrelu6);
dst_3 = Half8::min(Half8::max(dst_3 + vbias, vzero), vrelu6);
Half8::save(dst_p, dst_0);
Half8::save(dst_p + 8, dst_1);
Half8::save(dst_p + 16, dst_2);
Half8::save(dst_p + 24, dst_3);
}
for (; p < area; ++p) {
auto dst_p = dst_z + 8 * p;
Half8 dst_0 = Half8::load(dst_p);
dst_0 = Half8::min(Half8::max(dst_0 + vbias, vzero), vrelu6);
Half8::save(dst_p, dst_0);
}
}
}
template <>
void PostAddBiasSwish<fp16_t, fp16_t, true>(void* dst, const void* bias, long area, long oc8) {
if (!bias) {
for (long z = oc8 - 1; z >= 0; --z) {
fp16_t* dst_z = reinterpret_cast<fp16_t*>(dst) + area * 8 * z;
for (long p = 0; p < area; ++p) {
auto dst_p = dst_z + 8 * p;
Half8 val = Half8::load(dst_p);
Half8::save(dst_p, val * Half8::fast_sigmoid(val));
}
}
} else {
for (long z = oc8 - 1; z >= 0; --z) {
Half8 vbias = Half8::load(reinterpret_cast<const fp16_t*>(bias) + 8 * z);
fp16_t* dst_z = reinterpret_cast<fp16_t*>(dst) + area * 8 * z;
for (long p = 0; p < area; ++p) {
auto dst_p = dst_z + 8 * p;
Half8 val = Half8::load(dst_p);
val = val + vbias;
Half8::save(dst_p, val * Half8::fast_sigmoid(val));
}
}
}
}
template <>
void PostAddBiasSwish<fp16_t, fp16_t, false>(void* dst, const void* bias, long area, long oc8) {
if (!bias) {
for (long z = oc8 - 1; z >= 0; --z) {
fp16_t* dst_z = reinterpret_cast<fp16_t*>(dst) + area * 8 * z;
for (long p = 0; p < area; ++p) {
auto dst_p = dst_z + 8 * p;
Half8 val = Half8::load(dst_p);
Half8::save(dst_p, val * Half8::sigmoid(val));
}
}
} else {
for (long z = oc8 - 1; z >= 0; --z) {
Half8 vbias = Half8::load(reinterpret_cast<const fp16_t*>(bias) + 8 * z);
fp16_t* dst_z = reinterpret_cast<fp16_t*>(dst) + area * 8 * z;
for (long p = 0; p < area; ++p) {
auto dst_p = dst_z + 8 * p;
Half8 val = Half8::load(dst_p);
val = val + vbias;
Half8::save(dst_p, val * Half8::sigmoid(val));
}
}
}
}
void MaxPoolingHalf(const fp16_t* src, long iw, long ih, fp16_t* dst, long ow, long oh, long kw, long kh,
long stride_w, long stride_h, long pad_w, long pad_h) {
for (long oy = 0; oy < oh; ++oy) {
for (long ox = 0; ox < ow; ++ox) {
const long srcOriginX = ox * stride_w - pad_w;
const long srcOriginY = oy * stride_h - pad_h;
const long kxs = MAX(0, -srcOriginX);
const long kxe = MIN(kw, iw - srcOriginX);
const long kys = MAX(0, -srcOriginY);
const long kye = MIN(kh, ih - srcOriginY);
const auto src_ptr = src + (srcOriginY * iw + srcOriginX) * 8;
auto dst_ptr = dst + (oy * ow + ox) * 8;
Half8 vmax = Half8(HALF_LOWEST);
for (long ky = kys; ky < kye; ++ky) {
const auto src_ptr_h = src_ptr + (ky * iw) * 8;
for (long kx = kxs; kx < kxe; kx++) {
vmax = Half8::max(vmax, Half8::load(src_ptr_h + kx * 8));
}
}
Half8::save(dst_ptr, vmax);
}
}
}
void AvgPoolingHalf(const fp16_t* src, long iw, long ih, fp16_t* dst, long ow, long oh, long kw, long kh,
long stride_w, long stride_h, long pad_w, long pad_h) {
for (long oy = 0; oy < oh; ++oy) {
for (long ox = 0; ox < ow; ++ox) {
const long srcOriginX = ox * stride_w - pad_w;
const long srcOriginY = oy * stride_h - pad_h;
const long kxs = MAX(0, -srcOriginX);
const long kxe = MIN(kw, iw - srcOriginX);
const long kys = MAX(0, -srcOriginY);
const long kye = MIN(kh, ih - srcOriginY);
const float kernel_count = 1.0 / ((kxe - kxs) * (kye - kys));
const auto src_ptr = src + (srcOriginY * iw + srcOriginX) * 8;
auto dst_ptr = dst + (oy * ow + ox) * 8;
Half8 vavg = Half8(fp16_t(0.f));
for (long ky = kys; ky < kye; ++ky) {
const auto src_ptr_h = src_ptr + (ky * iw) * 8;
for (long kx = kxs; kx < kxe; kx++) {
vavg = vavg + Half8::load(src_ptr_h + kx * 8);
}
}
Half8::save(dst_ptr, vavg * Half8(fp16_t(kernel_count)));
}
}
}
template <>
void DepthwiseUnit<fp16_t, fp16_t>(fp16_t* dst, const fp16_t* src, const fp16_t* weight, long fw, long fh, long weight_y_step, long dilate_x_step,
long dilate_y_step) {
long fx, fy;
Half8 dst_v = Half8((fp16_t)0.0f);
const auto* src_z = src;
const auto* weight_z = weight;
for (fy = 0; fy < fh; ++fy) {
const auto* src_y = src_z + fy * dilate_y_step;
const auto* weight_y = weight_z + fy * weight_y_step;
for (fx = 0; fx < fw; ++fx) {
Half8 src_v = Half8::load(src_y + fx * dilate_x_step);
Half8 weight_v = Half8::load(weight_y + 8 * fx);
Half8::mla(dst_v, src_v, weight_v);
}
}
Half8::save(dst, dst_v);
}
template <>
void DepthwiseConv<fp16_t, fp16_t>(fp16_t* dst, const fp16_t* src, const fp16_t* weight, long width, long src_w_step, long fw, long fh,
long dilate_x_step, long dilate_y_step, long height, long srcHStep, long dstHStep) {
long dx, fx, fy;
for (long y = 0; y < height; ++y) {
auto srcY = src + y * srcHStep;
auto dstY = dst + y * dstHStep;
dx = 0;
for (; dx + 3 < width; dx += 4) {
Half8 dst_v[4];
for (long i = 0; i < 4; i++) {
dst_v[i] = Half8((fp16_t)0.0f);
}
const auto* src_z = srcY + src_w_step * dx;
const auto* weight_z = weight;
for (fy = 0; fy < fh; ++fy) {
const auto* src_y = src_z + fy * dilate_y_step;
const auto* weight_y = weight_z + fy * fw * 8;
for (fx = 0; fx < fw; ++fx) {
Half8 weight_v = Half8::load(weight_y + 8 * fx);
Half8 src_v0 = Half8::load(src_y + fx * dilate_x_step);
Half8 src_v1 = Half8::load(src_y + fx * dilate_x_step + src_w_step);
Half8 src_v2 = Half8::load(src_y + fx * dilate_x_step + 2 * src_w_step);
Half8 src_v3 = Half8::load(src_y + fx * dilate_x_step + 3 * src_w_step);
Half8::mla(dst_v[0], src_v0, weight_v);
Half8::mla(dst_v[1], src_v1, weight_v);
Half8::mla(dst_v[2], src_v2, weight_v);
Half8::mla(dst_v[3], src_v3, weight_v);
}
}
Half8::save(dstY + (dx + 0) * 8, dst_v[0]);
Half8::save(dstY + (dx + 1) * 8, dst_v[1]);
Half8::save(dstY + (dx + 2) * 8, dst_v[2]);
Half8::save(dstY + (dx + 3) * 8, dst_v[3]);
}
for (; dx < width; ++dx) {
Half8 dst_v = Half8((fp16_t)0.0f);
const auto* src_z = srcY + src_w_step * dx;
const auto* weight_z = weight;
for (fy = 0; fy < fh; ++fy) {
const auto* src_y = src_z + fy * dilate_y_step;
const auto* weight_y = weight_z + fy * fw * 8;
for (fx = 0; fx < fw; ++fx) {
Half8 src_v = Half8::load(src_y + fx * dilate_x_step);
Half8 weight_v = Half8::load(weight_y + 8 * fx);
Half8::mla(dst_v, src_v, weight_v);
}
}
Half8::save(dstY + dx * 8, dst_v);
}
}
}
template <>
void DepthwiseUnitDeconv<fp16_t, fp16_t>(const fp16_t* dst, fp16_t* src, const fp16_t* weight, long fw, long fh, long weight_y_step,
long dilate_x_step, long dilate_y_step) {
long fx, fy;
fp16_t* src_z = src;
const fp16_t* weight_z = weight;
Half8 dstV = Half8::load(dst);
for (fy = 0; fy < fh; ++fy) {
fp16_t* src_y = src_z + fy * dilate_y_step;
const fp16_t* weight_y = weight_z + fy * weight_y_step;
for (fx = 0; fx < fw; ++fx) {
Half8 weight_x = Half8::load(weight_y + 8 * fx);
Half8 src_x = Half8::load(src_y + fx * dilate_x_step);
Half8::mla(src_x, weight_x, dstV);
Half8::save(src_y + fx * dilate_x_step, src_x);
}
}
}
template <>
void DepthwiseDeconv<fp16_t, fp16_t>(const fp16_t* dst, fp16_t* src, const fp16_t* weight, long width, long src_w_setup, long fw, long fh,
long dilate_x_step, long dilate_y_step) {
long dx;
for (dx = 0; dx < width; ++dx) {
const fp16_t* dst_x = dst + dx * 8;
fp16_t* src_dx = src + src_w_setup * dx;
DepthwiseUnitDeconv(dst_x, src_dx, weight, fw, fh, fw * 8, dilate_x_step, dilate_y_step);
}
}
template <>
void ScaleBias(fp16_t *src, int channel, int hw, const float *scale, const float *bias, fp16_t *dst) {
if (dst == nullptr) {
dst = src;
}
RawBuffer scale_buffer(ROUND_UP(channel, 8) * sizeof(fp16_t));
RawBuffer bias_buffer(ROUND_UP(channel, 8) * sizeof(fp16_t));
Float2Half(scale_buffer.force_to<fp16_t *>(), scale, channel);
Float2Half(bias_buffer.force_to<fp16_t *>(), bias, channel);
auto local_scale = scale_buffer.force_to<fp16_t *>();
auto local_bias = bias_buffer.force_to<fp16_t *>();
for (int z = 0; z < UP_DIV(channel, 8); ++z) {
auto src_z = src + z * hw * 8;
auto dst_z = dst + z * hw * 8;
auto v_scale = Half8::load(local_scale + z * 8);
auto v_bias = Half8::load(local_bias + z * 8);
for (int s = 0; s < hw; ++s) {
Half8 dst_v = v_bias;
Half8::mla(dst_v, Half8::load(src_z + s * 8), v_scale);
Half8::save(dst_z + s * 8, dst_v);
}
}
}
#endif // TNN_ARM82
#if TNN_ARM82
void FloatC4ToHalfC8(fp16_t* dst, const float* src, long batch, long channel, long hw) {
long c_r4 = UP_DIV(channel, 4);
long c_r8 = UP_DIV(channel, 8);
for (long n = 0; n < batch; n++) {
auto dst_n = dst + n * c_r8 * hw * 8;
auto src_n = src + n * c_r4 * hw * 4;
OMP_PARALLEL_FOR_GUIDED_
for (long ci = 0; ci < c_r4; ++ci) {
long co = ci / 2;
long dst_offset = (ci % 2) ? 4 : 0;
auto dst_c = dst_n + co * hw * 8 + dst_offset;
auto src_c = src_n + ci * hw * 4;
for (long cnt = 0; cnt < hw; cnt++) {
// nchw4 to nchw8
#ifdef TNN_ARM82_A64
vst1_f16(dst_c + cnt * 8, vcvt_f16_f32(vld1q_f32(src_c + cnt * 4)));
#elif defined(TNN_ARM82_A32)
vst1_u16((unsigned short*)(dst_c + cnt * 8), vreinterpret_u16_f16(vcvt_f16_f32(vld1q_f32(src_c + cnt * 4))));
#else
for (long idx = 0; idx < 4; idx++) {
dst_c[cnt * 8 + idx] = src_c[cnt * 4 + idx];
}
#endif
}
}
}
}
void HalfC8ToFloatC4(float* dst, const fp16_t* src, long batch, long channel, long hw) {
long c_r4 = UP_DIV(channel, 4);
long c_r8 = UP_DIV(channel, 8);
for (long n = 0; n < batch; n++) {
auto src_n = src + n * c_r8 * hw * 8;
auto dst_n = dst + n * c_r4 * hw * 4;
OMP_PARALLEL_FOR_GUIDED_
for (long co = 0; co < c_r4; ++co) {
long ci = co / 2;
long src_offset = (co % 2) ? 4 : 0;
auto src_c = src_n + ci * hw * 8 + src_offset;
auto dst_c = dst_n + co * hw * 4;
for (long cnt = 0; cnt < hw; cnt++) {
// nchw8 to nchw4
#ifdef TNN_ARM82_A64
vst1q_f32(dst_c + cnt * 4, vcvt_f32_f16(vld1_f16(src_c + cnt * 8)));
#elif defined(TNN_ARM82_A32)
vst1q_f32(dst_c + cnt * 4, vcvt_f32_f16(vreinterpret_f16_u16(vld1_u16((unsigned short*)src_c + cnt * 8))));
#else
for (long idx = 0; idx < 4; idx++) {
dst_c[cnt * 4 + idx] = src_c[cnt * 8 + idx];
}
#endif
}
}
}
}
#define transpose_4x4(v0, v1, v2, v3, v_zero) \
{ \
float32x4x2_t q01 = vtrnq_f32(v0, v1); \
float32x4x2_t q23 = vtrnq_f32(v2, v_zero); \
float32x2_t d00 = vget_low_f32(q01.val[0]); \
float32x2_t d01 = vget_high_f32(q01.val[0]); \
float32x2_t d10 = vget_low_f32(q01.val[1]); \
float32x2_t d11 = vget_high_f32(q01.val[1]); \
float32x2_t d20 = vget_low_f32(q23.val[0]); \
float32x2_t d21 = vget_high_f32(q23.val[0]); \
float32x2_t d30 = vget_low_f32(q23.val[1]); \
float32x2_t d31 = vget_high_f32(q23.val[1]); \
v0 = vcombine_f32(d00, d20); \
v1 = vcombine_f32(d10, d30); \
v2 = vcombine_f32(d01, d21); \
v3 = vcombine_f32(d11, d31); \
}
int PackNeonC3(fp16_t *dst, const float *src, size_t hw, size_t channel) {
auto src0 = src;
auto src1 = src + hw;
auto src2 = src + hw * 2;
int cur_hw = 0;
#ifdef TNN_ARM82_USE_NEON
float32x4_t v_zero_f32 = vdupq_n_f32(0.f);
#ifdef TNN_ARM82_A64
float16x4_t v_zero_f16 = vdup_n_f16(0.f);
#else
uint16x4_t v_zero_u16 = vdup_n_u16(0x0);
uint16_t *dst_u16 = reinterpret_cast<uint16_t *>(dst);
#endif
for (; cur_hw + 3 < hw; cur_hw += 4) {
float32x4_t v0 = vld1q_f32(src0 + cur_hw);
float32x4_t v1 = vld1q_f32(src1 + cur_hw);
float32x4_t v2 = vld1q_f32(src2 + cur_hw);
float32x4_t v3;
transpose_4x4(v0, v1, v2, v3, v_zero_f32);
#ifdef TNN_ARM82_A64
vst1q_f16(dst + cur_hw * 8, vcombine_f16(vcvt_f16_f32(v0), v_zero_f16));
vst1q_f16(dst + cur_hw * 8 + 8, vcombine_f16(vcvt_f16_f32(v1), v_zero_f16));
vst1q_f16(dst + cur_hw * 8 + 16, vcombine_f16(vcvt_f16_f32(v2), v_zero_f16));
vst1q_f16(dst + cur_hw * 8 + 24, vcombine_f16(vcvt_f16_f32(v3), v_zero_f16));
#else
vst1q_u16(dst_u16 + cur_hw * 8, vcombine_u16(vreinterpret_u16_f16(vcvt_f16_f32(v0)), v_zero_u16));
vst1q_u16(dst_u16 + cur_hw * 8 + 8, vcombine_u16(vreinterpret_u16_f16(vcvt_f16_f32(v1)), v_zero_u16));
vst1q_u16(dst_u16 + cur_hw * 8 + 16, vcombine_u16(vreinterpret_u16_f16(vcvt_f16_f32(v2)), v_zero_u16));
vst1q_u16(dst_u16 + cur_hw * 8 + 24, vcombine_u16(vreinterpret_u16_f16(vcvt_f16_f32(v3)), v_zero_u16));
#endif
}
#endif // TNN_ARM82_USE_NEON
for (; cur_hw < hw; cur_hw++) {
dst[cur_hw * 8 + 0] = src0[cur_hw];
dst[cur_hw * 8 + 1] = src1[cur_hw];
dst[cur_hw * 8 + 2] = src2[cur_hw];
dst[cur_hw * 8 + 3] = 0.f;
dst[cur_hw * 8 + 4] = 0.f;
dst[cur_hw * 8 + 5] = 0.f;
dst[cur_hw * 8 + 6] = 0.f;
dst[cur_hw * 8 + 7] = 0.f;
}
return 0;
}
/*
convert data type from uint8 to half, data format from nhwc 2 nc8hw8
*/
template <bool reverse_channel>
void BGRAToBlobImpl(const uint8_t *src, fp16_t *dst, const float *scale, const float *bias,
int hw, int channel) {
int i = 0;
fp16_t scale_half[4] = {fp16_t(scale[0]), fp16_t(scale[1]), fp16_t(scale[2]), fp16_t(scale[3])};
fp16_t bias_half[4] = {fp16_t(bias[0]), fp16_t(bias[1]), fp16_t(bias[2]), fp16_t(bias[3])};
#ifdef TNN_ARM82_A64
float16x8_t bias_neon_b = vdupq_n_f16(bias_half[0]);
float16x8_t bias_neon_g = vdupq_n_f16(bias_half[1]);
float16x8_t bias_neon_r = vdupq_n_f16(bias_half[2]);
float16x8_t bias_neon_a = vdupq_n_f16(bias_half[3]);
float16x8_t vzero = vdupq_n_f16(0.0f);
float16x8x4_t vf16;
for (; i < hw - 7; i += 8) {
uint8x8x4_t v_u8 = vld4_u8(src + i * 4);
uint16x8_t b_u16 = vmovl_u8(v_u8.val[0]);
uint16x8_t g_u16 = vmovl_u8(v_u8.val[1]);
uint16x8_t r_u16 = vmovl_u8(v_u8.val[2]);
uint16x8_t a_u16 = vmovl_u8(v_u8.val[3]);
vf16.val[0] = vcvtq_f16_u16(reverse_channel ? r_u16 : b_u16);
vf16.val[1] = vcvtq_f16_u16(g_u16);
vf16.val[2] = vcvtq_f16_u16(reverse_channel ? b_u16 : r_u16);
vf16.val[3] = vcvtq_f16_u16(a_u16);
vf16.val[0] = vaddq_f16(bias_neon_b, vmulq_n_f16(vf16.val[0], scale_half[0]));
vf16.val[1] = vaddq_f16(bias_neon_g, vmulq_n_f16(vf16.val[1], scale_half[1]));
vf16.val[2] = vaddq_f16(bias_neon_r, vmulq_n_f16(vf16.val[2], scale_half[2]));
vf16.val[3] = vaddq_f16(bias_neon_a, vmulq_n_f16(vf16.val[3], scale_half[3]));
if (channel == 3) {
vf16.val[3] = vdupq_n_f16(0.0f);
}
float16x8x4_t vf16_dump;
vf16_dump.val[0] = vzip1q_f16(vf16.val[0], vzero);
vf16_dump.val[1] = vzip1q_f16(vf16.val[1], vzero);
vf16_dump.val[2] = vzip1q_f16(vf16.val[2], vzero);
vf16_dump.val[3] = vzip1q_f16(vf16.val[3], vzero);
vst4q_f16(dst + i * 8, vf16_dump);
vf16_dump.val[0] = vzip2q_f16(vf16.val[0], vzero);
vf16_dump.val[1] = vzip2q_f16(vf16.val[1], vzero);
vf16_dump.val[2] = vzip2q_f16(vf16.val[2], vzero);
vf16_dump.val[3] = vzip2q_f16(vf16.val[3], vzero);
vst4q_f16(dst + i * 8 + 32, vf16_dump);
}
#elif defined(TNN_ARM82_A32)
Half4 scale_half4 = Half4(scale_half);
Half8 bias_neon_b = Half8(bias_half[0]);
Half8 bias_neon_g = Half8(bias_half[1]);
Half8 bias_neon_r = Half8(bias_half[2]);
Half8 bias_neon_a = Half8(bias_half[3]);
Half8 vzero = Half8(fp16_t(0.0f));
Half8x4 vf16;
for (; i < hw - 7; i += 8) {
uint8x8x4_t v_u8 = vld4_u8(src + i * 4);
uint16x8_t b_u16 = vmovl_u8(v_u8.val[0]);
uint16x8_t g_u16 = vmovl_u8(v_u8.val[1]);
uint16x8_t r_u16 = vmovl_u8(v_u8.val[2]);
uint16x8_t a_u16 = vmovl_u8(v_u8.val[3]);
Half8 val0 = bias_neon_b;
Half8 val1 = bias_neon_g;
Half8 val2 = bias_neon_r;
Half8 val3 = bias_neon_a;
Half8::mla_4_lanes(val0, Half8::cvt(reverse_channel ? r_u16 : b_u16),
val1, Half8::cvt(g_u16),
val2, Half8::cvt(reverse_channel ? b_u16 : r_u16),
val3, Half8::cvt(a_u16),
scale_half4);
vf16.set_value0(val0);
vf16.set_value1(val1);
vf16.set_value2(val2);
vf16.set_value3(val3);
if (channel == 3) {
vf16.set_value3(vzero);
}
vf16.save_transpose(dst + i * 8, vzero);
}
#endif
for (; i < hw; ++i) {
dst[8 * i + 0] = scale_half[0] * fp16_t(src[4 * i + (reverse_channel ? 2 : 0)]) + bias_half[0];
dst[8 * i + 1] = scale_half[1] * fp16_t(src[4 * i + 1]) + bias_half[1];
dst[8 * i + 2] = scale_half[2] * fp16_t(src[4 * i + (reverse_channel ? 0 : 2)]) + bias_half[2];
dst[8 * i + 3] = scale_half[3] * fp16_t(src[4 * i + 3]) + bias_half[3];
if (channel == 3) {
dst[8 * i + 3] = 0.0f;
}
}
}
template void BGRAToBlobImpl<true>(const uint8_t *src, fp16_t *dst, const float *scale, const float *bias,
int hw, int channel);
template void BGRAToBlobImpl<false>(const uint8_t *src, fp16_t *dst, const float *scale, const float *bias,
int hw, int channel);
/*
convert data type from uint8 to half, data format from nhw3 2 nc8hw8
*/
template <bool reverse_channel>
void BGRToBlobImpl(const uint8_t *src, fp16_t *dst, const float *scale, const float *bias, int hw) {
int i = 0;
fp16_t scale_half[3] = {fp16_t(scale[0]), fp16_t(scale[1]), fp16_t(scale[2])};
fp16_t bias_half[3] = {fp16_t(bias[0]), fp16_t(bias[1]), fp16_t(bias[2])};
#ifdef TNN_ARM82_A64
float16x8_t bias_neon_b = vdupq_n_f16(bias_half[0]);
float16x8_t bias_neon_g = vdupq_n_f16(bias_half[1]);
float16x8_t bias_neon_r = vdupq_n_f16(bias_half[2]);
float16x8_t vzero = vdupq_n_f16(0.0f);
float16x8x4_t vf16;
vf16.val[3] = vzero;
for (; i < hw - 7; i += 8) {
uint8x8x3_t v_u8 = vld3_u8(src + i * 3);
uint16x8_t b_u16 = vmovl_u8(v_u8.val[0]);
uint16x8_t g_u16 = vmovl_u8(v_u8.val[1]);
uint16x8_t r_u16 = vmovl_u8(v_u8.val[2]);
vf16.val[0] = vcvtq_f16_u16(reverse_channel ? r_u16 : b_u16);
vf16.val[1] = vcvtq_f16_u16(g_u16);
vf16.val[2] = vcvtq_f16_u16(reverse_channel ? b_u16 : r_u16);
vf16.val[0] = vaddq_f16(bias_neon_b, vmulq_n_f16(vf16.val[0], scale_half[0]));
vf16.val[1] = vaddq_f16(bias_neon_g, vmulq_n_f16(vf16.val[1], scale_half[1]));
vf16.val[2] = vaddq_f16(bias_neon_r, vmulq_n_f16(vf16.val[2], scale_half[2]));
float16x8x4_t vf16_dump;
vf16_dump.val[0] = vzip1q_f16(vf16.val[0], vzero);
vf16_dump.val[1] = vzip1q_f16(vf16.val[1], vzero);
vf16_dump.val[2] = vzip1q_f16(vf16.val[2], vzero);
vf16_dump.val[3] = vzip1q_f16(vf16.val[3], vzero);
vst4q_f16(dst + i * 8, vf16_dump);
vf16_dump.val[0] = vzip2q_f16(vf16.val[0], vzero);
vf16_dump.val[1] = vzip2q_f16(vf16.val[1], vzero);
vf16_dump.val[2] = vzip2q_f16(vf16.val[2], vzero);
vf16_dump.val[3] = vzip2q_f16(vf16.val[3], vzero);
vst4q_f16(dst + i * 8 + 32, vf16_dump);
}
#elif defined(TNN_ARM82_A32)
Half4 scale_half4 = Half4(scale_half);
Half8 bias_neon_b = Half8(bias_half[0]);
Half8 bias_neon_g = Half8(bias_half[1]);
Half8 bias_neon_r = Half8(bias_half[2]);
Half8 vzero = Half8(fp16_t(0.0f));
Half8x4 vf16;
vf16.set_value3(vzero);
for (; i < hw - 7; i += 8) {
uint8x8x3_t v_u8 = vld3_u8(src + i * 3);
uint16x8_t b_u16 = vmovl_u8(v_u8.val[0]);
uint16x8_t g_u16 = vmovl_u8(v_u8.val[1]);
uint16x8_t r_u16 = vmovl_u8(v_u8.val[2]);
Half8 val0 = bias_neon_b;
Half8 val1 = bias_neon_g;
Half8 val2 = bias_neon_r;
Half8::mla_3_lanes(val0, Half8::cvt(reverse_channel ? r_u16 : b_u16),
val1, Half8::cvt(g_u16),
val2, Half8::cvt(reverse_channel ? b_u16 : r_u16),
scale_half4);
vf16.set_value0(val0);
vf16.set_value1(val1);
vf16.set_value2(val2);
vf16.save_transpose(dst + i * 8, vzero);
}
#endif
for (; i < hw; ++i) {
dst[8 * i + 0] = scale_half[0] * fp16_t(src[3 * i + (reverse_channel ? 2 : 0)]) + bias_half[0];
dst[8 * i + 1] = scale_half[1] * fp16_t(src[3 * i + 1]) + bias_half[1];
dst[8 * i + 2] = scale_half[2] * fp16_t(src[3 * i + (reverse_channel ? 0 : 2)]) + bias_half[2];
dst[8 * i + 3] = 0.0f;
}
}
template void BGRToBlobImpl<true>(const uint8_t *src, fp16_t *dst, const float *scale, const float *bias, int hw);
template void BGRToBlobImpl<false>(const uint8_t *src, fp16_t *dst, const float *scale, const float *bias, int hw);
/*
convert data type from uint8 to half, data format from nhw1 2 nc8hw8
*/
void GrayToBlob(const uint8_t *src, fp16_t *dst, const float scale, const float bias, int hw) {
int i = 0;
fp16_t scale_half = fp16_t(scale);
fp16_t bias_half = fp16_t(bias);
memset(dst, 0, hw * 8 * sizeof(fp16_t));
#ifdef TNN_ARM82_A64
float16x8_t scale_neon = vdupq_n_f16(scale_half);
float16x8_t bias_neon = vdupq_n_f16(bias_half);
for (; i < hw - 7; i += 8) {
uint8x8_t v_u8 = vld1_u8(src + i);
float16x8_t vf16 = vcvtq_f16_u16(vmovl_u8(v_u8));
float16x8_t rf16 = vaddq_f16(bias_neon, vmulq_f16(scale_neon, vf16));
vst1q_lane_f16(dst + (i + 0) * 8, rf16, 0);
vst1q_lane_f16(dst + (i + 1) * 8, rf16, 1);
vst1q_lane_f16(dst + (i + 2) * 8, rf16, 2);
vst1q_lane_f16(dst + (i + 3) * 8, rf16, 3);
vst1q_lane_f16(dst + (i + 4) * 8, rf16, 4);
vst1q_lane_f16(dst + (i + 5) * 8, rf16, 5);
vst1q_lane_f16(dst + (i + 6) * 8, rf16, 6);
vst1q_lane_f16(dst + (i + 7) * 8, rf16, 7);
}
#elif defined(TNN_ARM82_A32)
Half8 scale_neon = Half8(scale_half);
Half8 bias_neon = Half8(bias_half);
for (; i < hw - 7; i += 8) {
uint8x8_t v_u8 = vld1_u8(src + i);
Half8 rf16 = bias_neon;
Half8::mla(rf16, scale_neon, Half8::cvt(vmovl_u8(v_u8)));
rf16.save_lane0(dst + (i + 0) * 8);
rf16.save_lane1(dst + (i + 1) * 8);
rf16.save_lane2(dst + (i + 2) * 8);
rf16.save_lane3(dst + (i + 3) * 8);
rf16.save_lane4(dst + (i + 4) * 8);
rf16.save_lane5(dst + (i + 5) * 8);
rf16.save_lane6(dst + (i + 6) * 8);
rf16.save_lane7(dst + (i + 7) * 8);
}
#endif
for (; i < hw; ++i) {
dst[8 * i] = scale_half * fp16_t(src[i]) + bias_half;
}
}
template <bool reverse_channel>
void BlobToBGRAImpl(const fp16_t *src, uint8_t *dst, const float *scale, const float *bias,
int hw, int channel) {
int i = 0;
fp16_t scale_half[4] = {fp16_t(scale[0]), fp16_t(scale[1]), fp16_t(scale[2]), fp16_t(scale[3])};
fp16_t bias_half[4] = {fp16_t(bias[0]), fp16_t(bias[1]), fp16_t(bias[2]), fp16_t(bias[3])};
#ifdef TNN_ARM82_A64
float16x8_t bias_neon_b = vdupq_n_f16(bias_half[0]);
float16x8_t bias_neon_g = vdupq_n_f16(bias_half[1]);
float16x8_t bias_neon_r = vdupq_n_f16(bias_half[2]);
float16x8_t bias_neon_a = vdupq_n_f16(bias_half[3]);
uint8x8x4_t vi8x4;
float16x8x4_t vf16;
for (; i < hw - 7; i += 8) {
float16x8x4_t vf16_0 = vld4q_f16(src + i * 8);
float16x8x4_t vf16_1 = vld4q_f16(src + i * 8 + 32);
vf16.val[0] = vuzp1q_f16(vf16_0.val[0], vf16_1.val[0]);
vf16.val[1] = vuzp1q_f16(vf16_0.val[1], vf16_1.val[1]);
vf16.val[2] = vuzp1q_f16(vf16_0.val[2], vf16_1.val[2]);
vf16.val[3] = vuzp1q_f16(vf16_0.val[3], vf16_1.val[3]);
vf16.val[0] = vaddq_f16(bias_neon_b, vmulq_n_f16(vf16.val[0], scale_half[0]));
vf16.val[1] = vaddq_f16(bias_neon_g, vmulq_n_f16(vf16.val[1], scale_half[1]));
vf16.val[2] = vaddq_f16(bias_neon_r, vmulq_n_f16(vf16.val[2], scale_half[2]));
vf16.val[3] = vaddq_f16(bias_neon_a, vmulq_n_f16(vf16.val[3], scale_half[3]));
int16x8_t s16_0 = vcvtaq_s16_f16(vf16.val[reverse_channel ? 2 : 0]);
int16x8_t s16_1 = vcvtaq_s16_f16(vf16.val[1]);
int16x8_t s16_2 = vcvtaq_s16_f16(vf16.val[reverse_channel ? 0 : 2]);
int16x8_t s16_3 = vcvtaq_s16_f16(vf16.val[3]);
vi8x4.val[0] = vqmovun_s16(s16_0);
vi8x4.val[1] = vqmovun_s16(s16_1);
vi8x4.val[2] = vqmovun_s16(s16_2);
vi8x4.val[3] = vqmovun_s16(s16_3);
if (channel == 3) {
uint8x8x4_t vi8x4_tmp = vld4_u8(dst + i * 4);
vi8x4.val[3] = vi8x4_tmp.val[3];
}
vst4_u8(dst + i * 4, vi8x4);
}
#endif
for (; i < hw; ++i) {
dst[4 * i + 0] = half2uint8(reverse_channel ? (scale_half[2] * fp16_t(src[8 * i + 2]) + bias_half[2]) :
(scale_half[0] * fp16_t(src[8 * i + 0]) + bias_half[0]));
dst[4 * i + 1] = half2uint8(scale_half[1] * fp16_t(src[8 * i + 1]) + bias_half[1]);
dst[4 * i + 2] = half2uint8(reverse_channel ? (scale_half[0] * fp16_t(src[8 * i + 0]) + bias_half[0]) :
(scale_half[2] * fp16_t(src[8 * i + 2]) + bias_half[2]));
if (channel == 4) {
dst[4 * i + 3] = half2uint8(scale_half[3] * fp16_t(src[8 * i + 3]) + bias_half[3]);
}
}
}
template void BlobToBGRAImpl<true>(const fp16_t *src, uint8_t *dst, const float *scale, const float *bias,
int hw, int channel);
template void BlobToBGRAImpl<false>(const fp16_t *src, uint8_t *dst, const float *scale, const float *bias,
int hw, int channel);
template <bool reverse_channel>
void BlobToBGRImpl(const fp16_t *src, uint8_t *dst, const float *scale, const float *bias, int hw) {
int i = 0;
fp16_t scale_half[3] = {fp16_t(scale[0]), fp16_t(scale[1]), fp16_t(scale[2])};
fp16_t bias_half[3] = {fp16_t(bias[0]), fp16_t(bias[1]), fp16_t(bias[2])};
#ifdef TNN_ARM82_A64
float16x8_t bias_neon_b = vdupq_n_f16(bias_half[0]);
float16x8_t bias_neon_g = vdupq_n_f16(bias_half[1]);
float16x8_t bias_neon_r = vdupq_n_f16(bias_half[2]);
uint8x8x3_t vi8x3;
float16x8x3_t vf16;
for (; i < hw - 7; i += 8) {
float16x8x4_t vf16_0 = vld4q_f16(src + i * 8);
float16x8x4_t vf16_1 = vld4q_f16(src + i * 8 + 32);
vf16.val[0] = vuzp1q_f16(vf16_0.val[0], vf16_1.val[0]);
vf16.val[1] = vuzp1q_f16(vf16_0.val[1], vf16_1.val[1]);
vf16.val[2] = vuzp1q_f16(vf16_0.val[2], vf16_1.val[2]);
vf16.val[0] = vaddq_f16(bias_neon_b, vmulq_n_f16(vf16.val[0], scale_half[0]));
vf16.val[1] = vaddq_f16(bias_neon_g, vmulq_n_f16(vf16.val[1], scale_half[1]));
vf16.val[2] = vaddq_f16(bias_neon_r, vmulq_n_f16(vf16.val[2], scale_half[2]));
int16x8_t s16_0 = vcvtaq_s16_f16(vf16.val[reverse_channel ? 2 : 0]);
int16x8_t s16_1 = vcvtaq_s16_f16(vf16.val[1]);
int16x8_t s16_2 = vcvtaq_s16_f16(vf16.val[reverse_channel ? 0 : 2]);
vi8x3.val[0] = vqmovun_s16(s16_0);
vi8x3.val[1] = vqmovun_s16(s16_1);
vi8x3.val[2] = vqmovun_s16(s16_2);
vst3_u8(dst + i * 3, vi8x3);
}
#endif
for (; i < hw; ++i) {
dst[3 * i + 0] = half2uint8(reverse_channel ? (scale_half[2] * fp16_t(src[8 * i + 2]) + bias_half[2]) :
(scale_half[0] * fp16_t(src[8 * i + 0]) + bias_half[0]));
dst[3 * i + 1] = half2uint8(scale_half[1] * fp16_t(src[8 * i + 1]) + bias_half[1]);
dst[3 * i + 2] = half2uint8(reverse_channel ? (scale_half[0] * fp16_t(src[8 * i + 0]) + bias_half[0]) :
(scale_half[2] * fp16_t(src[8 * i + 2]) + bias_half[2]));
}
}
template void BlobToBGRImpl<true>(const fp16_t *src, uint8_t *dst, const float *scale, const float *bias, int hw);
template void BlobToBGRImpl<false>(const fp16_t *src, uint8_t *dst, const float *scale, const float *bias, int hw);
#endif // TNN_ARM82
/*
[3] Implement asm functions in compute_half.h for simulation
*/
#ifdef TNN_ARM82_SIMU
void ActiveOutput(fp16_t* dst, const Half8* src, long relu, int num) {
for (long i = 0; i < num; i++) {
if (relu == ActivationType_ReLU) {
Half8::save(dst + i * 8, Half8::max(src[i], Half8((fp16_t)0.f)));
} else if (relu == ActivationType_ReLU6) {
Half8::save(dst + i * 8, Half8::min(Half8::max(src[i], Half8((fp16_t)0.f)), Half8((fp16_t)6.0f)));
} else {
// Float4::save(dst + i * 4, src[i]);
Half8::save(dst + i * 8, src[i]);
}
}
}
void GEMM_FP16_N8(fp16_t* dst, const fp16_t* src, const fp16_t* weight, long src_depth,
long dst_step, long dst_depth, long width, fp16_t *bias, long relu) {
long dx, sz, dz;
// NC8HW8
for (dz = 0; dz < dst_depth; dz += 8) {
// dst_step = M * 8 (NC8HW8)
auto dst_z = dst + (dz / 8) * dst_step;
auto weight_dz = weight + dz * src_depth;
Half8 v_bias = Half8::load(bias + dz);
// process 8x16 results in one loop
dx = 0;
for (; dx + 7 < width; dx += 8) {
auto dst_dx = dst_z + dx * 8;
auto src_dx = src + dx * src_depth;
Half8 v_dst[8];
for (int i = 0; i < 8; i++) {
v_dst[i] = v_bias;
}
for (long sz = 0; sz < src_depth; sz++) {
auto src_z = src_dx + sz * 8;
auto weight_sz = weight_dz + sz * 8;
Half8 v_weight = Half8::load(weight_sz);
Half8 v_src = Half8::load(src_z);
Half8::mlaq_lane0(v_dst[0], v_weight, v_src);
Half8::mlaq_lane1(v_dst[1], v_weight, v_src);
Half8::mlaq_lane2(v_dst[2], v_weight, v_src);
Half8::mlaq_lane3(v_dst[3], v_weight, v_src);
Half8::mlaq_lane4(v_dst[4], v_weight, v_src);
Half8::mlaq_lane5(v_dst[5], v_weight, v_src);
Half8::mlaq_lane6(v_dst[6], v_weight, v_src);
Half8::mlaq_lane7(v_dst[7], v_weight, v_src);
}
ActiveOutput(dst_dx, v_dst, relu, 8);
}
// process 4x8 results in one loop
for (; dx + 3 < width; dx += 4) {
auto dst_dx = dst_z + dx * 8;
auto src_dx = src + dx * src_depth;
Half8 v_dst[4];
for (int i = 0; i < 4; i++) {
v_dst[i] = v_bias;
}
for (long sz = 0; sz < src_depth; sz++) {
auto src_z = src_dx + sz * 4;
auto weight_sz = weight_dz + sz * 8;
Half8 v_weight = Half8::load(weight_sz);
Half4 v_src = Half4::load(src_z);
Half8::mla_lane0(v_dst[0], v_weight, v_src);
Half8::mla_lane1(v_dst[1], v_weight, v_src);
Half8::mla_lane2(v_dst[2], v_weight, v_src);
Half8::mla_lane3(v_dst[3], v_weight, v_src);
}
ActiveOutput(dst_dx, v_dst, relu, 4);
}
// // the process 1x4 results
if (dx < width) {
auto dst_dx = dst_z + dx * 8;
auto src_dx = src + dx * src_depth;
Half8 v_dst[3];
for (int i = 0; i < 3; i++) {
v_dst[i] = v_bias;
}
for (long sz = 0; sz < src_depth; sz++) {
auto src_z = src_dx + sz * 4;
auto weight_sz = weight_dz + sz * 8;
Half8 v_weight = Half8::load(weight_sz);
Half4 v_src = Half4::load(src_z);
Half8::mla_lane0(v_dst[0], v_weight, v_src);
Half8::mla_lane1(v_dst[1], v_weight, v_src);
Half8::mla_lane2(v_dst[2], v_weight, v_src);
}
ActiveOutput(dst_dx, v_dst, relu, width - dx);
}
}
}
void GemmFp16SlidewC3(fp16_t* dst, const fp16_t* src, const fp16_t* weight, long width, long src_w_setup, long fw,
long fh, long dilate_x_step, long dilate_y_step) {
long dx, sz, fx, fy;
for (dx = 0; dx < width; ++dx) {
auto dst_x = dst + dx * 8;
dst_x[0] = 0.0f;
dst_x[1] = 0.0f;
dst_x[2] = 0.0f;
dst_x[3] = 0.0f;
dst_x[4] = 0.0f;
dst_x[5] = 0.0f;
dst_x[6] = 0.0f;
dst_x[7] = 0.0f;
auto src_dx = src + src_w_setup * dx;
for (fy = 0; fy < fh; ++fy) {
auto src_y = src_dx + fy * dilate_y_step;
auto weight_y = weight + fy * fw * 24;
for (fx = 0; fx < fw; ++fx) {
auto weight_x = weight_y + 24 * fx;
auto src_x = src_y + fx * dilate_x_step;
for (long i = 0; i < 3; ++i) {
for (long j = 0; j < 8; ++j) {
dst_x[j] = float(dst_x[j]) + float(src_x[i]) * float(weight_x[8 * i + j]);
}
}
}
}
}
}
void ConvDw3x3Fp16SlideW(void* dst_z, void** cache_line, const void* weight_z, long dst_width) {
long dx;
int fy, fx;
fp16_t** cache_line_ptr = (fp16_t**)cache_line;
const fp16_t* weight_z_ptr = (const fp16_t*)weight_z;
for (dx = 0; dx < dst_width; ++dx) {
auto dst_x = (fp16_t*)dst_z + dx * 8;
dst_x[0] = (fp16_t)0.0f;
dst_x[1] = (fp16_t)0.0f;
dst_x[2] = (fp16_t)0.0f;
dst_x[3] = (fp16_t)0.0f;
dst_x[4] = (fp16_t)0.0f;
dst_x[5] = (fp16_t)0.0f;
dst_x[6] = (fp16_t)0.0f;
dst_x[7] = (fp16_t)0.0f;
for (fy = 0; fy < 3; ++fy) {
for (fx = 0; fx < 3; ++fx) {
for (long i = 0; i < 8; ++i) {
dst_x[i] = dst_x[i] + cache_line_ptr[fy][dx * 8 + fx * 8 + i] * weight_z_ptr[3 * fy * 8 + fx * 8 + i];
}
}
}
}
}
/*
general deconv micro kernel fp16_t
*/
void DeconvFp16O8(fp16_t* dst, const fp16_t* src, const fp16_t* weight, long width, long dst_w_step, long src_depth_quad,
long src_depth_step, long fw, long fh, long dilate_x_step, long dilate_y_step) {
long dx, sz, fx, fy;
for (dx = 0; dx < width; ++dx) {
auto dst_dx = dst + dx * dst_w_step;
for (fy = 0; fy < fh; ++fy) {
auto dst_y = dst_dx + fy * dilate_y_step;
auto weight_y = weight + fy * fw * src_depth_quad * 64;
for (fx = 0; fx < fw; ++fx) {
auto dst_x = dst_y + fx * dilate_x_step;
auto weight_x = weight_y + fx * src_depth_quad * 64;
fp16_t temp[8] = {fp16_t(0.0f)};
for (sz = 0; sz < src_depth_quad; ++sz) {
auto weight_z = weight_x + sz * 64;
auto src_z = src + dx * 8 + sz * src_depth_step;
for (long i = 0; i < 8; ++i) {
for (long j = 0; j < 8; ++j) {
temp[j] = temp[j] + src_z[i] * weight_z[8 * i + j];
}
}
}
for (long j = 0; j < 8; ++j) {
dst_x[j] = dst_x[j] + temp[j];
}
}
}
}
}
void DeconvFp16O8C1(fp16_t* dst, const fp16_t* src, const fp16_t* weight, long width, long dst_w_step, long src_depth,
long src_depth_step, long fw, long fh, long dilate_x_step, long dilate_y_step) {
long dx, sz, fx, fy;
for (dx = 0; dx < width; ++dx) {
auto dst_dx = dst + dx * dst_w_step;
for (fy = 0; fy < fh; ++fy) {
auto dst_y = dst_dx + fy * dilate_y_step;
auto weight_y = weight + fy * fw * src_depth * 8;
for (fx = 0; fx < fw; ++fx) {
auto dst_x = dst_y + fx * dilate_x_step;
auto weight_x = weight_y + fx * src_depth * 8;
fp16_t temp[8] = {fp16_t(0.0f)};
for (sz = 0; sz < src_depth; ++sz) {
auto weight_z = weight_x + sz * 8;
auto src_z = src + dx * 1 + sz * src_depth_step;
for (long j = 0; j < 8; ++j) {
temp[j] = temp[j] + src_z[0] * weight_z[j];
}
}
for (long j = 0; j < 8; ++j) {
dst_x[j] = dst_x[j] + temp[j];
}
}
}
}
}
#endif // TNN_ARM82_SIMU
} // namespace TNN_NS
| [
"noreply@github.com"
] | noreply@github.com |
a54d882d1c31c20e4316db94469d2db68536e8b5 | e50f7ad74c021fd798774e0c7cec8e534e321c6a | /oli2_pdu/oli2_pdu.cpp | b6d7b947bf2ab82d408b107d5f03ac77094e225e | [] | no_license | gionatamassibenincasa/oii | 2a8212399c4ab7ef4999231558e189d988393691 | a148b52d80cdcbecefe843194e2a844c59111050 | refs/heads/master | 2021-01-20T11:11:16.896733 | 2017-08-30T22:57:02 | 2017-08-30T22:57:02 | 101,669,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 458 | cpp | #include <cstdio>
int main(int argc, char **argv) {
FILE *in = fopen("input.txt", "r"), *out = fopen("output.txt", "w");
int n, p = 0, d = 0;
fscanf(in, "%d\n", &n);
for (int j = 0; j < n; j++) {
int v;
fscanf(in, "%d", &v);
if (v % 2 == 0) { // pari
p += v;
} else { // dispari
d += v;
}
}
if (p == d)
fputs("U\n", out);
else if (p > d)
fputs("P\n", out);
else
fputs("D\n", out);
return 0;
}
| [
"gionata.massi@savoiabenincasa.it"
] | gionata.massi@savoiabenincasa.it |
a81880021716249e3e409b77a8d23d185b6f8732 | a16da86a4b90cdae3963f6adc46315d7a9056cbb | /Source/Wwise/include/AK/Tools/Common/AkSmartPtr.h | aa58db640ae48335757a16e74cadecbed90f75cd | [
"MIT",
"Unlicense"
] | permissive | Project-3-UPC-DDV-BCN/Project3 | 0b18abfa21c97db1e036b4a20fa125e0243699d7 | 3fb345ce49485ccbc7d03fb320623df6114b210c | refs/heads/master | 2021-07-15T10:55:35.559526 | 2018-10-19T14:35:14 | 2018-10-19T14:35:14 | 114,779,047 | 10 | 1 | MIT | 2018-04-23T21:26:45 | 2017-12-19T15:05:53 | C++ | UTF-8 | C++ | false | false | 3,697 | h | /*******************************************************************************
The content of this file includes portions of the AUDIOKINETIC Wwise Technology
released in source code form as part of the SDK installer package.
Commercial License Usage
Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology
may use this file in accordance with the end user license agreement provided
with the software or, alternatively, in accordance with the terms contained in a
written agreement between you and Audiokinetic Inc.
Apache License Usage
Alternatively, this file may be used under the Apache License, Version 2.0 (the
"Apache License"); you may not use this file except in compliance with the
Apache License. You may obtain a copy of the Apache License at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing, software distributed
under the Apache License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
OR CONDITIONS OF ANY KIND, either express or implied. See the Apache License for
the specific language governing permissions and limitations under the License.
Version: v2017.2.1 Build: 6524
Copyright (c) 2006-2018 Audiokinetic Inc.
*******************************************************************************/
// AkSmartPtr.h
/// \file
/// Helper file.
#ifndef _AK_SMARTPTR_H
#define _AK_SMARTPTR_H
#include <AK/SoundEngine/Common/AkTypes.h>
template <class T> class CAkSmartPtr
{
public:
/// Smart pointer constructor
AkForceInline CAkSmartPtr()
: m_pT( NULL )
{
}
/// Smart pointer constructor
AkForceInline CAkSmartPtr( T* in_pT )
{
m_pT = in_pT;
if (m_pT)
m_pT->AddRef();
}
/// Smart pointer constructor
AkForceInline CAkSmartPtr( const CAkSmartPtr<T>& in_rPtr )
{
m_pT = in_rPtr.m_pT;
if (m_pT)
m_pT->AddRef();
}
/// Smart pointer destructor
~CAkSmartPtr()
{
Release();
}
/// Release
AkForceInline void Release()
{
if( m_pT )
{
m_pT->Release();
m_pT = NULL;
}
}
/// Assign with no Addref.
AkForceInline void Attach( T* in_pObj )
{
_Assign( in_pObj, false );
}
/// Give the pointer without releasing it.
AkForceInline T* Detach()
{
T* pObj = m_pT;
m_pT = NULL;
return pObj;
}
/// Assignation operator
const CAkSmartPtr<T>& operator=( const CAkSmartPtr<T>& in_pObj )
{
_Assign( in_pObj.m_pT );
return *this;
}
/// Assignation operator
const CAkSmartPtr<T>& operator=( T* in_pObj )
{
_Assign( in_pObj );
return *this;
}
/// Operator *
T& operator*() { return *m_pT; }
/// Operator ->
T* operator->() const { return m_pT; }
/// Operator
operator T*() const { return m_pT; }
/// Operators to pass to functions like QueryInterface and other functions returning an addref'd pointer.
T** operator &() { return &m_pT; }
/// Operator *
const T& operator*() const { return *m_pT; }
/// Cast
T* Cast() { return m_pT; }
/// Cast
const T* Cast() const { return m_pT; }
protected:
/// internal use only
void _Assign( T* in_pObj, bool in_bAddRef = true )
{
if (in_pObj != NULL && in_bAddRef)
in_pObj->AddRef();
// Must use a local pointer since we cannot call Release(); without having set the m_pT to its final value.
T* l_Ptr = m_pT;
m_pT = in_pObj;
if (l_Ptr)
l_Ptr->Release();
}
/// internal use only
bool _Compare( const T* in_pObj ) const
{
return m_pT == in_pObj;
}
/// internal use only
T* m_pT;
};
#endif // _AK_SMARTPTR_H
| [
"elsuperchowchow@gmail.com"
] | elsuperchowchow@gmail.com |
1febc3a7b38088a7d3ed05a16b561d7b40d86fc6 | 256c5100914832915192fb1958444389eff4a85f | /sigprocdat/TSnPerCardCalibSet.h | 5f2fc371dac013a9be41cf078769f53f949ea3b3 | [] | no_license | jetatar/snowShovel | ea9a45ddcb182ca6776752e08df9799ac6cd7439 | 69678a46cd8c20a57e4b8d8a8cc19b8900173775 | refs/heads/master | 2020-05-30T19:42:33.193932 | 2014-08-18T06:37:56 | 2014-08-18T06:37:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 994 | h | #ifndef SNS_TSnPerCardCalibSet
#define SNS_TSnPerCardCalibSet
#include "NSnConstants.h"
#include "TSnCalibSet.h"
class TSnPerCardCalibSet : public TSnCalibSet {
private:
virtual Int_t GetCalibIndex(const Int_t smp) const {
// map from sample number to channel number
// (one calib obj per channel)
return (static_cast<Int_t>(smp /
static_cast<Int_t>(NSnConstants::kNsamps)) );
}
public:
TSnPerCardCalibSet() {}
TSnPerCardCalibSet(const Char_t* name,
const Char_t* title) :
TSnCalibSet(name, title,
NSnConstants::kNchans) {
}
virtual ~TSnPerCardCalibSet() {}
virtual TSnCalibSet* NewCopy() const { return new TSnPerCardCalibSet(*this); }
virtual void Print(Option_t* option = "") const;
// see TSnCalibSet for the interface
ClassDef(TSnPerCardCalibSet, 1); // base class storing calib objects on a per card basis
};
#endif // SNS_TSnPerCardCalibSet
| [
"jtatar@uw.edu"
] | jtatar@uw.edu |
74929075a52e6c639b53b24799c025d911e7d54a | 45c59e5f456f11f1714b2ddf976b62dfebecfa7d | /Case16/system/cz_solid_97/fvSchemes | f5caa6da992f54e978f01288279f6f2e67f097a3 | [] | no_license | JoelWright24/Masters-Thesis-in-OpenFOAM | 9224f71cdb38e96a378996996c5c86235db9ee13 | b6c420b5054494a26a7d65a34835b27be9e0da4a | refs/heads/main | 2023-02-20T17:18:13.067439 | 2021-01-22T19:30:36 | 2021-01-22T19:30:36 | 332,039,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 758 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "system/cz_solid_97";
object fvSchemes;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
divSchemes
{
}
gradSchemes
{
}
laplacianSchemes
{
}
// ************************************************************************* //
| [
"67100764+JoelWright24@users.noreply.github.com"
] | 67100764+JoelWright24@users.noreply.github.com | |
802aa76014d93ec8af1e96661a7680c073de613b | 00d69e58470663deef5d9541093ed6af9ad01526 | /Team19/Code19/extensions/spa/src/PKB/Parent.h | 83e0e950f8bef94f8fab9c55a3c2577259ade2a1 | [] | no_license | zixinn/20s2-cp-spa-team-19 | ea4b801d61b8f278a5e1d02f8560cf2487e67a8b | c673145ad68f49f9dd22fd17bbc0315eac5f6b41 | refs/heads/master | 2023-05-08T08:31:09.211600 | 2021-04-16T02:56:02 | 2021-04-16T02:56:02 | 372,253,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,026 | h | #pragma once
#include "../AbstractAPI.h"
class Parent {
public:
// Constructor for Parent
Parent();
// Returns true if Parent(s1, s2)
bool isParent(StmtNum s1, StmtNum s2);
// Returns true if Parent*(s1, s2)
bool isParentStar(StmtNum s1, StmtNum s2);
// Returns s2, the statement that is the child of s1. Returns an empty set if there are no children.
unordered_set<StmtNum> const &getChildren(StmtNum s1) const;
// Returns s1, the statement that is the parent of by s2. Returns -1 if there is no such statement.
StmtNum getParent(StmtNum s2);
// Returns set of s2, the statements that Parent*(s1, s2).
unordered_set<StmtNum> const & getChildrenStar(StmtNum s1) const;
// Returns set of s1, the statements that Parent*(s1, s2).
unordered_set<StmtNum> const &getParentStar(StmtNum s2) const;
// Returns a pair of vectors in the parentMap.
// First vector is vector of s1's. Second is vector of s2's
// e.g. if (1,2), (3,4), (5,6) is in parentMap, then it will return <[1,3,5], [2,4,6]>
pair<vector<StmtNum>, vector<StmtNum> > getAllParent();
// Returns a pair of vectors in the parentStarMap.
// First vector is vector of s1's. Second is vector of s2's
// e.g. if (1,2), (3,4), (5,6) is in parentStarMap, then it will return <[1,3,5], [2,4,6]>
pair<vector<StmtNum>, vector<StmtNum> > getAllParentStar();
// Returns the no. of pairs of Parent relationship.
// E.g. if the parentMap has [1: {2,3}], then the size is 2. Because there are pairs (1,2) and (1,3).
int getParentSize();
// Returns the no. of pairs of Parent* relationship.
// E.g. if the parentStarMap has [1: {2,3}], then the size is 2. Because there are pairs (1,2) and (1,3).
int getParentStarSize();
// Stores <s1, s2> in the parentMap.
// Stores <s2, s1> in reverseParentMap
// Returns true if info is successfully added.
bool storeParent(StmtNum s1, StmtNum s2);
// Returns true if there is a statement s2 such that Parent(s1, s2)
bool hasChild(StmtNum s1) const;
// Returns true if there is a statement s1 such that Parent(s1, s2)
bool hasParent(StmtNum s2) const;
// calculate all Parent* relationships from the ParentMap using BFS and populate the ParentStarMap and ReverseParentStarMap
void populateParentStar();
private:
// Stores <s1, set of s2's> where Parent(s1, s2)
unordered_map<StmtNum, unordered_set<StmtNum> > parentMap;
// Stores <s2, s1> where Parent(s1, s2)
unordered_map<StmtNum, StmtNum> reverseParentMap;
// Stores <s1, set of s2's> where Parent*<s1, s2);
unordered_map<StmtNum, unordered_set<StmtNum> > parentStarMap;
// Stores <s2, set of s1's> where Parent*<s1, s2);
unordered_map<StmtNum, unordered_set<StmtNum> > reverseParentStarMap;
// Stores <s1, s2> in the parentStarMap.
// Stores <s2, s1> in reverseParentStarMap
// Returns true if info is successfully added.
bool storeParentStar(StmtNum s1, StmtNum s2);
};
| [
"voongyuxuan@gmail.com"
] | voongyuxuan@gmail.com |
7cd9d5b4c5cb215c65d429b9aba659024340a574 | dfc6089491650208bc4fe5ccc6e153d770789447 | /Bullet/src/Bullet/Bullet3Dynamics/b3CpuRigidBodyPipeline.cpp | b14c2ab563cfcd0360383759b0ef83690e4e9a70 | [
"MIT",
"Zlib"
] | permissive | BertilBraun/Oath3D | 669aad253eb7c342e8c6226b8d778f056e69efd4 | e713f4f97bd1998d6c7a67414ff5f80d6d30e7f9 | refs/heads/master | 2020-04-15T23:09:57.475019 | 2020-03-08T20:09:01 | 2020-03-08T20:09:01 | 165,096,271 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 14,415 | cpp | #include "b3CpuRigidBodyPipeline.h"
#include "Bullet/Bullet3Dynamics/shared/b3IntegrateTransforms.h"
#include "Bullet/Bullet3Collision/NarrowPhaseCollision/shared/b3RigidBodyData.h"
#include "Bullet/Bullet3Collision/BroadPhaseCollision/b3DynamicBvhBroadphase.h"
#include "Bullet/Bullet3Collision/NarrowPhaseCollision/b3Config.h"
#include "Bullet/Bullet3Collision/NarrowPhaseCollision/b3CpuNarrowPhase.h"
#include "Bullet/Bullet3Collision/BroadPhaseCollision/shared/b3Aabb.h"
#include "Bullet/Bullet3Collision/NarrowPhaseCollision/shared/b3Collidable.h"
#include "Bullet/Bullet3Common/b3Vector3.h"
#include "Bullet/Bullet3Dynamics/shared/b3ContactConstraint4.h"
#include "Bullet/Bullet3Dynamics/shared/b3Inertia.h"
struct b3CpuRigidBodyPipelineInternalData
{
b3AlignedObjectArray<b3RigidBodyData> m_rigidBodies;
b3AlignedObjectArray<b3Inertia> m_inertias;
b3AlignedObjectArray<b3Aabb> m_aabbWorldSpace;
b3DynamicBvhBroadphase* m_bp;
b3CpuNarrowPhase* m_np;
b3Config m_config;
};
b3CpuRigidBodyPipeline::b3CpuRigidBodyPipeline(class b3CpuNarrowPhase* narrowphase, struct b3DynamicBvhBroadphase* broadphaseDbvt, const b3Config& config)
{
m_data = new b3CpuRigidBodyPipelineInternalData;
m_data->m_np = narrowphase;
m_data->m_bp = broadphaseDbvt;
m_data->m_config = config;
}
b3CpuRigidBodyPipeline::~b3CpuRigidBodyPipeline()
{
delete m_data;
}
void b3CpuRigidBodyPipeline::updateAabbWorldSpace()
{
for (int i = 0; i < this->getNumBodies(); i++)
{
b3RigidBodyData* body = &m_data->m_rigidBodies[i];
b3Float4 position = body->m_pos;
b3Quat orientation = body->m_quat;
int collidableIndex = body->m_collidableIdx;
b3Collidable& collidable = m_data->m_np->getCollidableCpu(collidableIndex);
int shapeIndex = collidable.m_shapeIndex;
if (shapeIndex >= 0)
{
b3Aabb localAabb = m_data->m_np->getLocalSpaceAabb(shapeIndex);
b3Aabb& worldAabb = m_data->m_aabbWorldSpace[i];
float margin = 0.f;
b3TransformAabb2(localAabb.m_minVec, localAabb.m_maxVec, margin, position, orientation, &worldAabb.m_minVec, &worldAabb.m_maxVec);
m_data->m_bp->setAabb(i, worldAabb.m_minVec, worldAabb.m_maxVec, 0);
}
}
}
void b3CpuRigidBodyPipeline::computeOverlappingPairs()
{
int numPairs = m_data->m_bp->getOverlappingPairCache()->getNumOverlappingPairs();
m_data->m_bp->calculateOverlappingPairs();
numPairs = m_data->m_bp->getOverlappingPairCache()->getNumOverlappingPairs();
printf("numPairs=%d\n", numPairs);
}
void b3CpuRigidBodyPipeline::computeContactPoints()
{
b3AlignedObjectArray<b3Int4>& pairs = m_data->m_bp->getOverlappingPairCache()->getOverlappingPairArray();
m_data->m_np->computeContacts(pairs, m_data->m_aabbWorldSpace, m_data->m_rigidBodies);
}
void b3CpuRigidBodyPipeline::stepSimulation(float deltaTime)
{
//update world space aabb's
updateAabbWorldSpace();
//compute overlapping pairs
computeOverlappingPairs();
//compute contacts
computeContactPoints();
//solve contacts
//update transforms
integrate(deltaTime);
}
static inline float b3CalcRelVel(const b3Vector3& l0, const b3Vector3& l1, const b3Vector3& a0, const b3Vector3& a1,
const b3Vector3& linVel0, const b3Vector3& angVel0, const b3Vector3& linVel1, const b3Vector3& angVel1)
{
return b3Dot(l0, linVel0) + b3Dot(a0, angVel0) + b3Dot(l1, linVel1) + b3Dot(a1, angVel1);
}
static inline void b3SetLinearAndAngular(const b3Vector3& n, const b3Vector3& r0, const b3Vector3& r1,
b3Vector3& linear, b3Vector3& angular0, b3Vector3& angular1)
{
linear = -n;
angular0 = -b3Cross(r0, n);
angular1 = b3Cross(r1, n);
}
static inline void b3SolveContact(b3ContactConstraint4& cs,
const b3Vector3& posA, b3Vector3& linVelA, b3Vector3& angVelA, float invMassA, const b3Matrix3x3& invInertiaA,
const b3Vector3& posB, b3Vector3& linVelB, b3Vector3& angVelB, float invMassB, const b3Matrix3x3& invInertiaB,
float maxRambdaDt[4], float minRambdaDt[4])
{
b3Vector3 dLinVelA;
dLinVelA.setZero();
b3Vector3 dAngVelA;
dAngVelA.setZero();
b3Vector3 dLinVelB;
dLinVelB.setZero();
b3Vector3 dAngVelB;
dAngVelB.setZero();
for (int ic = 0; ic < 4; ic++)
{
// dont necessary because this makes change to 0
if (cs.m_jacCoeffInv[ic] == 0.f) continue;
{
b3Vector3 angular0, angular1, linear;
b3Vector3 r0 = cs.m_worldPos[ic] - (b3Vector3&)posA;
b3Vector3 r1 = cs.m_worldPos[ic] - (b3Vector3&)posB;
b3SetLinearAndAngular((const b3Vector3&)-cs.m_linear, (const b3Vector3&)r0, (const b3Vector3&)r1, linear, angular0, angular1);
float rambdaDt = b3CalcRelVel((const b3Vector3&)cs.m_linear, (const b3Vector3&)-cs.m_linear, angular0, angular1,
linVelA, angVelA, linVelB, angVelB) +
cs.m_b[ic];
rambdaDt *= cs.m_jacCoeffInv[ic];
{
float prevSum = cs.m_appliedRambdaDt[ic];
float updated = prevSum;
updated += rambdaDt;
updated = b3Max(updated, minRambdaDt[ic]);
updated = b3Min(updated, maxRambdaDt[ic]);
rambdaDt = updated - prevSum;
cs.m_appliedRambdaDt[ic] = updated;
}
b3Vector3 linImp0 = invMassA * linear * rambdaDt;
b3Vector3 linImp1 = invMassB * (-linear) * rambdaDt;
b3Vector3 angImp0 = (invInertiaA * angular0) * rambdaDt;
b3Vector3 angImp1 = (invInertiaB * angular1) * rambdaDt;
#ifdef _WIN32
b3Assert(_finite(linImp0.getX()));
b3Assert(_finite(linImp1.getX()));
#endif
{
linVelA += linImp0;
angVelA += angImp0;
linVelB += linImp1;
angVelB += angImp1;
}
}
}
}
static inline void b3SolveFriction(b3ContactConstraint4& cs,
const b3Vector3& posA, b3Vector3& linVelA, b3Vector3& angVelA, float invMassA, const b3Matrix3x3& invInertiaA,
const b3Vector3& posB, b3Vector3& linVelB, b3Vector3& angVelB, float invMassB, const b3Matrix3x3& invInertiaB,
float maxRambdaDt[4], float minRambdaDt[4])
{
if (cs.m_fJacCoeffInv[0] == 0 && cs.m_fJacCoeffInv[0] == 0) return;
const b3Vector3& center = (const b3Vector3&)cs.m_center;
b3Vector3 n = -(const b3Vector3&)cs.m_linear;
b3Vector3 tangent[2];
b3PlaneSpace1(n, tangent[0], tangent[1]);
b3Vector3 angular0, angular1, linear;
b3Vector3 r0 = center - posA;
b3Vector3 r1 = center - posB;
for (int i = 0; i < 2; i++)
{
b3SetLinearAndAngular(tangent[i], r0, r1, linear, angular0, angular1);
float rambdaDt = b3CalcRelVel(linear, -linear, angular0, angular1,
linVelA, angVelA, linVelB, angVelB);
rambdaDt *= cs.m_fJacCoeffInv[i];
{
float prevSum = cs.m_fAppliedRambdaDt[i];
float updated = prevSum;
updated += rambdaDt;
updated = b3Max(updated, minRambdaDt[i]);
updated = b3Min(updated, maxRambdaDt[i]);
rambdaDt = updated - prevSum;
cs.m_fAppliedRambdaDt[i] = updated;
}
b3Vector3 linImp0 = invMassA * linear * rambdaDt;
b3Vector3 linImp1 = invMassB * (-linear) * rambdaDt;
b3Vector3 angImp0 = (invInertiaA * angular0) * rambdaDt;
b3Vector3 angImp1 = (invInertiaB * angular1) * rambdaDt;
#ifdef _WIN32
b3Assert(_finite(linImp0.getX()));
b3Assert(_finite(linImp1.getX()));
#endif
linVelA += linImp0;
angVelA += angImp0;
linVelB += linImp1;
angVelB += angImp1;
}
{ // angular damping for point constraint
b3Vector3 ab = (posB - posA).normalized();
b3Vector3 ac = (center - posA).normalized();
if (b3Dot(ab, ac) > 0.95f || (invMassA == 0.f || invMassB == 0.f))
{
float angNA = b3Dot(n, angVelA);
float angNB = b3Dot(n, angVelB);
angVelA -= (angNA * 0.1f) * n;
angVelB -= (angNB * 0.1f) * n;
}
}
}
struct b3SolveTask // : public ThreadPool::Task
{
b3SolveTask(b3AlignedObjectArray<b3RigidBodyData>& bodies,
b3AlignedObjectArray<b3Inertia>& shapes,
b3AlignedObjectArray<b3ContactConstraint4>& constraints,
int start, int nConstraints,
int maxNumBatches,
b3AlignedObjectArray<int>* wgUsedBodies, int curWgidx)
: m_bodies(bodies), m_shapes(shapes), m_constraints(constraints), m_wgUsedBodies(wgUsedBodies), m_curWgidx(curWgidx), m_start(start), m_nConstraints(nConstraints), m_solveFriction(true), m_maxNumBatches(maxNumBatches)
{
}
unsigned short int getType() { return 0; }
void run(int tIdx)
{
b3AlignedObjectArray<int> usedBodies;
//printf("run..............\n");
for (int bb = 0; bb < m_maxNumBatches; bb++)
{
usedBodies.resize(0);
for (int ic = m_nConstraints - 1; ic >= 0; ic--)
//for(int ic=0; ic<m_nConstraints; ic++)
{
int i = m_start + ic;
if (m_constraints[i].m_batchIdx != bb)
continue;
float frictionCoeff = b3GetFrictionCoeff(&m_constraints[i]);
int aIdx = (int)m_constraints[i].m_bodyA;
int bIdx = (int)m_constraints[i].m_bodyB;
//int localBatch = m_constraints[i].m_batchIdx;
b3RigidBodyData& bodyA = m_bodies[aIdx];
b3RigidBodyData& bodyB = m_bodies[bIdx];
#if 0
if ((bodyA.m_invMass) && (bodyB.m_invMass))
{
// printf("aIdx=%d, bIdx=%d\n", aIdx,bIdx);
}
if (bIdx==10)
{
//printf("ic(b)=%d, localBatch=%d\n",ic,localBatch);
}
#endif
if (aIdx == 10)
{
//printf("ic(a)=%d, localBatch=%d\n",ic,localBatch);
}
if (usedBodies.size() < (aIdx + 1))
{
usedBodies.resize(aIdx + 1, 0);
}
if (usedBodies.size() < (bIdx + 1))
{
usedBodies.resize(bIdx + 1, 0);
}
if (bodyA.m_invMass)
{
b3Assert(usedBodies[aIdx] == 0);
usedBodies[aIdx]++;
}
if (bodyB.m_invMass)
{
b3Assert(usedBodies[bIdx] == 0);
usedBodies[bIdx]++;
}
if (!m_solveFriction)
{
float maxRambdaDt[4] = {FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX};
float minRambdaDt[4] = {0.f, 0.f, 0.f, 0.f};
b3SolveContact(m_constraints[i], (b3Vector3&)bodyA.m_pos, (b3Vector3&)bodyA.m_linVel, (b3Vector3&)bodyA.m_angVel, bodyA.m_invMass, (const b3Matrix3x3&)m_shapes[aIdx].m_invInertiaWorld,
(b3Vector3&)bodyB.m_pos, (b3Vector3&)bodyB.m_linVel, (b3Vector3&)bodyB.m_angVel, bodyB.m_invMass, (const b3Matrix3x3&)m_shapes[bIdx].m_invInertiaWorld,
maxRambdaDt, minRambdaDt);
}
else
{
float maxRambdaDt[4] = {FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX};
float minRambdaDt[4] = {0.f, 0.f, 0.f, 0.f};
float sum = 0;
for (int j = 0; j < 4; j++)
{
sum += m_constraints[i].m_appliedRambdaDt[j];
}
frictionCoeff = 0.7f;
for (int j = 0; j < 4; j++)
{
maxRambdaDt[j] = frictionCoeff * sum;
minRambdaDt[j] = -maxRambdaDt[j];
}
b3SolveFriction(m_constraints[i], (b3Vector3&)bodyA.m_pos, (b3Vector3&)bodyA.m_linVel, (b3Vector3&)bodyA.m_angVel, bodyA.m_invMass, (const b3Matrix3x3&)m_shapes[aIdx].m_invInertiaWorld,
(b3Vector3&)bodyB.m_pos, (b3Vector3&)bodyB.m_linVel, (b3Vector3&)bodyB.m_angVel, bodyB.m_invMass, (const b3Matrix3x3&)m_shapes[bIdx].m_invInertiaWorld,
maxRambdaDt, minRambdaDt);
}
}
if (m_wgUsedBodies)
{
if (m_wgUsedBodies[m_curWgidx].size() < usedBodies.size())
{
m_wgUsedBodies[m_curWgidx].resize(usedBodies.size());
}
for (int i = 0; i < usedBodies.size(); i++)
{
if (usedBodies[i])
{
//printf("cell %d uses body %d\n", m_curWgidx,i);
m_wgUsedBodies[m_curWgidx][i] = 1;
}
}
}
}
}
b3AlignedObjectArray<b3RigidBodyData>& m_bodies;
b3AlignedObjectArray<b3Inertia>& m_shapes;
b3AlignedObjectArray<b3ContactConstraint4>& m_constraints;
b3AlignedObjectArray<int>* m_wgUsedBodies;
int m_curWgidx;
int m_start;
int m_nConstraints;
bool m_solveFriction;
int m_maxNumBatches;
};
void b3CpuRigidBodyPipeline::solveContactConstraints()
{
int m_nIterations = 4;
b3AlignedObjectArray<b3ContactConstraint4> contactConstraints;
// const b3AlignedObjectArray<b3Contact4Data>& contacts = m_data->m_np->getContacts();
int n = contactConstraints.size();
//convert contacts...
int maxNumBatches = 250;
for (int iter = 0; iter < m_nIterations; iter++)
{
b3SolveTask task(m_data->m_rigidBodies, m_data->m_inertias, contactConstraints, 0, n, maxNumBatches, 0, 0);
task.m_solveFriction = false;
task.run(0);
}
for (int iter = 0; iter < m_nIterations; iter++)
{
b3SolveTask task(m_data->m_rigidBodies, m_data->m_inertias, contactConstraints, 0, n, maxNumBatches, 0, 0);
task.m_solveFriction = true;
task.run(0);
}
}
void b3CpuRigidBodyPipeline::integrate(float deltaTime)
{
float angDamping = 0.f;
b3Vector3 gravityAcceleration = b3MakeVector3(0, -9, 0);
//integrate transforms (external forces/gravity should be moved into constraint solver)
for (int i = 0; i < m_data->m_rigidBodies.size(); i++)
{
b3IntegrateTransform(&m_data->m_rigidBodies[i], deltaTime, angDamping, gravityAcceleration);
}
}
int b3CpuRigidBodyPipeline::registerPhysicsInstance(float mass, const float* position, const float* orientation, int collidableIndex, int userData)
{
b3RigidBodyData body;
int bodyIndex = m_data->m_rigidBodies.size();
body.m_invMass = mass ? 1.f / mass : 0.f;
body.m_angVel.setValue(0, 0, 0);
body.m_collidableIdx = collidableIndex;
body.m_frictionCoeff = 0.3f;
body.m_linVel.setValue(0, 0, 0);
body.m_pos.setValue(position[0], position[1], position[2]);
body.m_quat.setValue(orientation[0], orientation[1], orientation[2], orientation[3]);
body.m_restituitionCoeff = 0.f;
m_data->m_rigidBodies.push_back(body);
if (collidableIndex >= 0)
{
b3Aabb& worldAabb = m_data->m_aabbWorldSpace.expand();
b3Aabb localAabb = m_data->m_np->getLocalSpaceAabb(collidableIndex);
b3Vector3 localAabbMin = b3MakeVector3(localAabb.m_min[0], localAabb.m_min[1], localAabb.m_min[2]);
b3Vector3 localAabbMax = b3MakeVector3(localAabb.m_max[0], localAabb.m_max[1], localAabb.m_max[2]);
b3Scalar margin = 0.01f;
b3Transform t;
t.setIdentity();
t.setOrigin(b3MakeVector3(position[0], position[1], position[2]));
t.setRotation(b3Quaternion(orientation[0], orientation[1], orientation[2], orientation[3]));
b3TransformAabb(localAabbMin, localAabbMax, margin, t, worldAabb.m_minVec, worldAabb.m_maxVec);
m_data->m_bp->createProxy(worldAabb.m_minVec, worldAabb.m_maxVec, bodyIndex, 0, 1, 1);
// b3Vector3 aabbMin,aabbMax;
// m_data->m_bp->getAabb(bodyIndex,aabbMin,aabbMax);
}
else
{
b3Error("registerPhysicsInstance using invalid collidableIndex\n");
}
return bodyIndex;
}
const struct b3RigidBodyData* b3CpuRigidBodyPipeline::getBodyBuffer() const
{
return m_data->m_rigidBodies.size() ? &m_data->m_rigidBodies[0] : 0;
}
int b3CpuRigidBodyPipeline::getNumBodies() const
{
return m_data->m_rigidBodies.size();
}
| [
"braunbertil123@outlook.de"
] | braunbertil123@outlook.de |
5f1f33e858754c2b2f31815a4bf469126599c3ab | 1b1796b0c606e89627f362fa00ecb10c2ae4eefd | /Mylib/Convolution/convolution_multiply.cpp | 186ecd9030b0792a8c1fef251323405258fb43fb | [] | no_license | Haar-you/kyopro-lib | 15c09a78568aa9114258969df93b712b9f7c1958 | 56b7dbe638e27aacd9c31fc95aad40bf2505fd77 | refs/heads/master | 2021-05-18T19:58:09.947307 | 2021-05-10T14:52:28 | 2021-05-10T14:52:28 | 251,378,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 881 | cpp | #pragma once
#include <vector>
#include "Mylib/Number/Prime/primitive_root.cpp"
namespace haar_lib {
template <typename T, const auto &convolve>
std::vector<T> convolution_multiply(const std::vector<T> &A, const std::vector<T> &B, int P) {
const int p_root = primitive_root(P);
std::vector<int> index(P);
{
int64_t s = 1;
for (int i = 0; i < P; ++i) {
index[s] = i;
s *= p_root;
if (s >= P) s %= P;
}
}
std::vector<T> a(P), b(P);
for (int i = 0; i < (int) A.size(); ++i) a[index[i % P]] = A[i];
for (int i = 0; i < (int) B.size(); ++i) b[index[i % P]] = B[i];
auto c = convolve(a, b);
std::vector<T> ret(P);
{
int64_t s = 1;
for (auto x : c) {
ret[s] += x;
s *= p_root;
if (s >= P) s %= P;
}
}
return ret;
}
}; // namespace haar_lib
| [
"haar@haar-pc"
] | haar@haar-pc |
f9e438a704d3190dd2dc02d569718fff2dc7e490 | 2083d747eca0c060aed90f3678b4f8b7cdadd38e | /ui/entpanel.h | aa5c8ff1cffe74c0a15bd93178a919109a922daf | [] | no_license | lstf/sfml3 | ac69a34b829336c49243d58bc7d79f28e584ba4d | 7398ec1bc0db5f8928eac9db400c281e098c3d17 | refs/heads/master | 2021-05-05T07:20:30.688179 | 2019-03-29T08:31:53 | 2019-03-29T08:31:53 | 118,864,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,439 | h | #ifdef EDITOR_BUILD
#ifndef _ENTPANEL_H
#define _ENTPANEL_H
#include <iostream>
#include <SFML/Graphics.hpp>
#include "button.h"
#include "textbox.h"
#include "uiutils.h"
#include "../game.h"
#include "../window.h"
#include "../entities/entity.h"
#include "../entities/keylock.h"
#include "../entities/itement.h"
#include "../utils/txmap.h"
#include "../utils/sfutils.h"
#define ENT_BASE_H 16
#define ENT_B_H 16
#define ENT_B_W 64
#define ENT_TOP_H 128
#define ENT_TOP_W (128 + 16)
#define ENT_BOT_H (480 - ENT_TOP_H - ENT_BASE_H)
#define ENT_BOT_W ENT_TOP_W
#define ENT_B_COUNT 2
#define ENT_B_ITEM 0
#define ENT_B_KEYLOCK 1
struct EntButton {
Button* btn;
string name;
};
enum ENT_TYPE {
ENTT_ITEM,
ENTT_KEYLOCK
};
class Entpanel : public sf::Drawable {
private:
Game* game;
Map* map;
SnapVals* sv;
ItemEntUI* itui;
KeyLockUI* klui;
sf::RectangleShape top_bg;
sf::RectangleShape bottom_bg;
ENT_TYPE et;
sf::Text text;
EntButton* buttons;
bool selected;
EntitySpawner* spawn;
void button_setup();
void key_setup();
virtual void draw(sf::RenderTarget& w, sf::RenderStates states) const;
void draw_key(sf::RenderTarget& w, sf::RenderStates states) const;
bool handle_key_input(sf::Event &event, sf::Vector2i m_pos);
public:
void handle_input(sf::Event &event, sf::Vector2i m_pos,
sf::Vector2f w_pos);
void reset(bool retain_sel = false);
Entpanel(Game* _game, SnapVals* _sv);
};
#endif
#endif
| [
"a@b"
] | a@b |
1634acdd03500aab449757cf12bb6a78ffbac2af | fc9200cb85ed13e5d026f6f9ae3cc6a82b377a21 | /libs/core/program_options/include/hpx/program_options/detail/utf8_codecvt_facet.hpp | eed97f958dfc48b30e882711c3f1075cd5833bd2 | [
"BSL-1.0",
"LicenseRef-scancode-free-unknown"
] | permissive | gonidelis/hpx | 147d636d2a63d2178becc340cd253c9b8a0e776d | db2efee3c36f70e610555bc86c22cc8006724079 | refs/heads/master | 2023-08-17T03:25:03.450931 | 2022-02-01T16:37:32 | 2022-02-01T16:37:32 | 275,136,168 | 0 | 0 | BSL-1.0 | 2022-05-17T03:35:17 | 2020-06-26T11:06:04 | C++ | UTF-8 | C++ | false | false | 7,376 | hpp | // Copyright (c) 2001 Ronald Garcia, Indiana University (garcia@osl.iu.edu)
// Andrew Lumsdaine, Indiana University (lums@osl.iu.edu).
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// utf8_codecvt_facet.hpp
// This header defines class utf8_codecvt_facet, derived from
// std::codecvt<wchar_t, char>, which can be used to convert utf8 data in
// files into wchar_t strings in the application.
//
// The header is NOT STANDALONE, and is not to be included by the USER.
// There are at least two libraries which want to use this functionality, and
// we want to avoid code duplication. It would be possible to create utf8
// library, but:
// - this requires review process first
// - in the case, when linking the a library which uses utf8
// (say 'program_options'), user should also link to the utf8 library.
// This seems inconvenient, and asking a user to link to an unrevieved
// library is strange.
// Until the above points are fixed, a library which wants to use utf8 must:
// - include this header in one of it's headers or sources
// - include the corresponding boost/detail/utf8_codecvt_facet.ipp file in one
// of its sources
// - before including either file, the library must define
// - BOOST_UTF8_BEGIN_NAMESPACE to the namespace declaration that must be used
// - BOOST_UTF8_END_NAMESPACE to the code to close the previous namespace
// declaration.
// - BOOST_UTF8_DECL -- to the code which must be used for all 'exportable'
// symbols.
//
// For example, program_options library might contain:
// #define BOOST_UTF8_BEGIN_NAMESPACE <backslash character>
// namespace boost { namespace program_options {
// #define BOOST_UTF8_END_NAMESPACE }}
// #define BOOST_UTF8_DECL BOOST_PROGRAM_OPTIONS_DECL
// #include <boost/detail/utf8_codecvt_facet.ipp>
//
// Essentially, each library will have its own copy of utf8 code, in
// different namespaces.
// Note:(Robert Ramey). I have made the following alterations in the original
// code.
// a) Rendered utf8_codecvt<wchar_t, char> with using templates
// b) Move longer functions outside class definition to prevent inlining
// and make code smaller
// c) added on a derived class to permit translation to/from current
// locale to utf8
// See http://www.boost.org for updates, documentation, and revision history.
// archives stored as text - note these ar templated on the basic
// stream templates to accommodate wide (and other?) kind of characters
//
// note the fact that on libraries without wide characters, ostream is
// is not a specialization of basic_ostream which in fact is not defined
// in such cases. So we can't use basic_ostream<OStream::char_type> but rather
// use two template parameters
//
// utf8_codecvt_facet
// This is an implementation of a std::codecvt facet for translating
// from UTF-8 externally to UCS-4. Note that this is not tied to
// any specific types in order to allow customization on platforms
// where wchar_t is not big enough.
//
// NOTES: The current implementation jumps through some unpleasant hoops in
// order to deal with signed character types. As a std::codecvt_base::result,
// it is necessary for the ExternType to be convertible to unsigned char.
// I chose not to tie the extern_type explicitly to char. But if any combination
// of types other than <wchar_t,char_t> is used, then std::codecvt must be
// specialized on those types for this to work.
#include <hpx/program_options/config.hpp>
#include <cstddef> // for std::size_t
#include <cwchar> // for mbstate_t
#include <locale>
// maximum length of a multibyte string
#define MB_LENGTH_MAX 8
//----------------------------------------------------------------------------//
// //
// utf8_codecvt_facet //
// //
// See utf8_codecvt_facet.cpp for the implementation. //
//----------------------------------------------------------------------------//
namespace hpx { namespace program_options { namespace detail {
struct HPX_CORE_EXPORT utf8_codecvt_facet
: public std::codecvt<wchar_t, char, std::mbstate_t>
{
public:
explicit utf8_codecvt_facet(std::size_t no_locale_manage = 0);
virtual ~utf8_codecvt_facet();
protected:
std::codecvt_base::result do_in(std::mbstate_t& state, const char* from,
const char* from_end, const char*& from_next, wchar_t* to,
wchar_t* to_end, wchar_t*& to_next) const override;
std::codecvt_base::result do_out(std::mbstate_t& state,
const wchar_t* from, const wchar_t* from_end,
const wchar_t*& from_next, char* to, char* to_end,
char*& to_next) const override;
bool invalid_continuing_octet(unsigned char octet_1) const
{
return (octet_1 < 0x80 || 0xbf < octet_1);
}
bool invalid_leading_octet(unsigned char octet_1) const
{
return (0x7f < octet_1 && octet_1 < 0xc0) || (octet_1 > 0xfd);
}
// continuing octets = octets except for the leading octet
static unsigned int get_cont_octet_count(unsigned char lead_octet)
{
return get_octet_count(lead_octet) - 1;
}
static unsigned int get_octet_count(unsigned char lead_octet);
// How many "continuing octets" will be needed for this word
// == total octets - 1.
int get_cont_octet_out_count(wchar_t word) const;
bool do_always_noconv() const noexcept override
{
return false;
}
// UTF-8 isn't really stateful since we rewind on partial conversions
std::codecvt_base::result do_unshift(std::mbstate_t&, char* from,
char* /*to*/, char*& next) const override
{
next = from;
return ok;
}
int do_encoding() const noexcept override
{
const int variable_byte_external_encoding = 0;
return variable_byte_external_encoding;
}
// How many char objects can I process to get <= max_limit
// wchar_t objects?
int do_length(std::mbstate_t&, const char* from, const char* from_end,
std::size_t max_limit) const noexcept override;
// Nonstandard override
virtual int do_length(const std::mbstate_t& s, const char* from,
const char* from_end, std::size_t max_limit) const noexcept
{
return do_length(
const_cast<std::mbstate_t&>(s), from, from_end, max_limit);
}
// Largest possible value do_length(state,from,from_end,1) could return.
int do_max_length() const noexcept override
{
return 6; // largest UTF-8 encoding of a UCS-4 character
}
};
}}} // namespace hpx::program_options::detail
| [
"mikael.simberg@iki.fi"
] | mikael.simberg@iki.fi |
94c654053962fdf5d35d07d7c4a7548bedf7afb9 | d8eec7c8869fb3b2ab43644c3d4b6142e9a991ab | /Leetcode/Array/Three Sum.cpp | 473e4a0aead876693c3de9028921d898eb651242 | [] | no_license | sujit512/Competitive-Programming | 17f1de686d76ed3f49261cf8201d0edfa77a5ec1 | 479d2b725000e3ecdaa8c16fec8d852aab00f032 | refs/heads/master | 2022-07-08T12:57:43.565743 | 2020-05-14T09:47:29 | 2020-05-14T09:47:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define deb(x) cout<<#x<<" "<<x<"\n"
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
vector<vector<int>> ans;
for(int i=0;i<nums.size()-1;i++)
{
unordered_set<int> s;
for(int j=i+1;j<nums.size();j++)
{
int x=-(nums[i]+nums[j]);
if(s.find(x)!=s.end())
{
vector<int> v;
v.emplace_back(nums[i]);
v.emplace_back(nums[j]);
v.emplace_back(x);
ans.emplace_back(v);
}
else
s.insert(nums[j]);
}
}
return ans;
}
};
main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
vector<int> v{-1,0,1,2,-1,4};
Solution obj;
vector<vector<int>> ans=obj.threeSum(v);
for(int i=0;i<ans.size();i++)
{
for(auto it:ans[i])
cout<<it<<" ";
cout<<"\n";
}
}
| [
"sastava007@gmail.com"
] | sastava007@gmail.com |
8297dfa879411a174b7429fdce16bf08207078fe | 8ec293c17d5a8635c4bf06cdd5b264429ec94d48 | /C++/TD4/Exceptions/Exceptions3/main.cpp | c98053c8e735f9294e71f22c80a61d9a7028d3d2 | [] | no_license | EmelineGOT/Centrale | 79636116ac18e3f5a31e67477d910edb0b105d9d | 8661f5010fbe60db3443ff0fc90e8df44d9dce4d | refs/heads/master | 2020-04-03T15:50:13.616829 | 2018-10-30T12:24:46 | 2018-10-30T12:24:46 | 155,379,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 337 | cpp | #include <iostream>
using namespace std;
#include "VectT.h"
#include "badrange.h"
int main()
{
VectT V(10,3);
//Déclenchement Exception
try{
V.Set(4,-4);
V.Set(6,87);
V.Set(14,-1);
}
catch ( const bad_range & b ){
cerr << b.what() << "\n";
}
cout << endl;
return 0;
}
| [
"got.emeline@gmail.com"
] | got.emeline@gmail.com |
706d8cfe3566a6d03fb2e0084980bcc087e7c2b7 | dea50b935910e3eab7315babf7e21c647c40c599 | /snake/Game.h | 14a1a9401b38a33b01463f0fcaa8d32463eb1a34 | [] | no_license | mitkooo12345/snake | 0568051ee63df1876fde7285cd1436909f930358 | 906ffd82d27f2c505c39b4f3cc676fdaec8aa05b | refs/heads/master | 2020-05-20T09:30:59.680213 | 2017-03-12T17:46:05 | 2017-03-12T17:46:05 | 84,344,761 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 280 | h | #pragma once
#include <conio.h>
#include "Map.h"
#include <windows.h>
class Game {
private:
Map map;
bool hasCollision;
//Snake snake;
//Segment head;
void moveSnake();
void eatFood();
bool isHeadOverFood();
bool isCollided();
public:
Game();
void startGame();
};
| [
"mitko_ap@mail.bg"
] | mitko_ap@mail.bg |
fc0485fa0a25041415e159e51fb1183ad980173c | 7fec4ff41377d5596860c157019dfd5d74b332e8 | /Source/TurretProject/Public/TurretProjectDeveloperSettings.h | 207bfbaeef7a8348ebf96106e1adecbf1cb9a125 | [] | no_license | matthiaslange/TurretProject | ea99d8187cf01501e4fbc2e3fbeadaa3de934736 | ccb6bdaa8356a44e654d8b348dbc0b2e20805223 | refs/heads/main | 2023-02-20T22:33:23.363601 | 2021-01-25T18:19:54 | 2021-01-25T18:19:54 | 332,840,267 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 428 | h | #pragma once
#include "CoreMinimal.h"
#include "Engine/DeveloperSettings.h"
#include "TurretProjectDeveloperSettings.generated.h"
class AEnemy;
UCLASS(BlueprintType, config = Game, defaultconfig)
class TURRETPROJECT_API UTurretProjectDeveloperSettings : public UDeveloperSettings
{
GENERATED_BODY()
public:
UPROPERTY(config, EditAnywhere, BlueprintReadWrite, Category = ProjectConfig)
TSubclassOf<AEnemy> EnemyClass;
};
| [
"matthias.lange@gmail.com"
] | matthias.lange@gmail.com |
02554f28f79e4c63277dcdab270c35ee34ae26f5 | 5d9365859702f68291427fadd02e994c59f1c377 | /examples/5/e5_6/main.cpp | 27cfe8aab51746b039fd8e0c6818060a0da2456d | [] | no_license | agrechnev/cpp-course-2020 | f84306457b75ce1478ed80ba3a2c6cb9e3d42b06 | ae0275ca306b0aea06d013716ba07fe0d8cdd9c7 | refs/heads/master | 2020-12-21T18:05:13.750814 | 2020-04-21T14:39:04 | 2020-04-21T14:39:04 | 236,516,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 520 | cpp | // Example 5_6 : Eigen
// Created by Oleksiy Grechnyev 2020
#include <iostream>
#include <Eigen/Dense>
//=========================
int main() {
using namespace std;
Eigen::MatrixXd m(2, 3); // Double matrix : 2 rows, 3 cols
m << 1 , 2, 3, 4, 5, 6; // Provide values (overloaded operators << and ,)
Eigen::VectorXd v(3); // Column double 3-vector
v << 1, 0, -1;
cout << "m = " << m << endl;
cout << "v = " << v << endl;
cout << "m*v = " << m*v << endl;
return 0;
}
| [
"shrike4625@gmail.com"
] | shrike4625@gmail.com |
0ea03139ccf3e9e4fdc7245b179bcabfe2281054 | 45b223d1d59cb619b0c49e8ddfa323a521e6969a | /trivia_project/Trivia/Server.h | 7ef067d77f620206fa187d2a73535fa2ee3f4393 | [] | no_license | ravivkl/Trivia | ae62098867b5adbf1b1a215a7ce849173cdcaa89 | bf457bf32a485138b6ce19ef64e7f0435c49646a | refs/heads/master | 2023-03-04T09:29:48.603589 | 2021-02-20T18:06:14 | 2021-02-20T18:06:14 | 340,719,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | h | #pragma once
#include "pch.h"
#include "IDatabase.h"
#include "RequestHandlerFactory.h"
#include "Communicator.h"
class Server
{
IDatabase * m_database;
RequestHandlerFactory* m_handlerFactory;
Communicator* m_communicator;
public:
Server() {};
Server(IDatabase * db);
Server(IDatabase * db, RequestHandlerFactory reqHand, Communicator comunic);
~Server();
void run();
};
| [
"ravivklein1@gmail.com"
] | ravivklein1@gmail.com |
6c7ecc616c9cfc7ac2b962525a5e12925d9a6f3d | c08a26d662bd1df1b2beaa36a36d0e9fecc1ebac | /classicui_plat/tsrc/bc/apps/S60_SDK3.0/bctesteditor/inc/bctesteditorapp.h | 4b6634abc750710821380088d10695965f29f251 | [] | no_license | SymbianSource/oss.FCL.sf.mw.classicui | 9c2e2c31023256126bb2e502e49225d5c58017fe | dcea899751dfa099dcca7a5508cf32eab64afa7a | refs/heads/master | 2021-01-11T02:38:59.198728 | 2010-10-08T14:24:02 | 2010-10-08T14:24:02 | 70,943,916 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,346 | h | /*
* Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Declares main application class.
*
*/
#ifndef BCTESTEDITORAPP_H
#define BCTESTEDITORAPP_H
// INCLUDES
#include <aknapp.h>
// CONSTANTS
const TUid KUidBCTestEditor = { 0x20004745 }; // UID of the application.
// CLASS DECLARATION
/**
* CBCTestEditorApp application class.
* Provides factory to create concrete document object.
*/
class CBCTestEditorApp : public CAknApplication
{
private: // From CApaApplication
/**
* From CApaApplication, CreateDocumentL.
* Creates CBCTestEditorDocument document object.
* @return A pointer to the created document object.
*/
CApaDocument* CreateDocumentL();
/**
* From CApaApplication, AppDllUid.
* Returns application's UID ( KUidBCTestEditor ).
* @return The value of KUidBCTestEditor.
*/
TUid AppDllUid() const;
};
#endif
// End of File
| [
"kirill.dremov@nokia.com"
] | kirill.dremov@nokia.com |
b55d531ec775dedc7e7e58566fdefbaf6d808cb4 | 656afbdffff52a1593463a35bb32cd7ad00b5745 | /include/audio/sfx/SSoundEffectFrequencyShifter.h | 13d32a1aa6a38cc294d336a79ca093346cea2644 | [] | no_license | CowPlay/engineSDK | 4273c076f32c09376b5f350293aeb08195b92723 | 1cd421b48a1a386a42e444db0533c7c3ee590e44 | refs/heads/master | 2016-09-03T01:09:16.310179 | 2012-12-14T17:06:29 | 2012-12-14T17:06:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,144 | h | /*
* SSoundEffectFrequencyShifter.h
*
* Created on: Nov 26, 2012
* Author: developer08
*/
#ifndef SSOUNDEFFECTFREQUENCYSHIFTER_H_
#define SSOUNDEFFECTFREQUENCYSHIFTER_H_
#include "SSoundEffect.h"
namespace irrgame
{
namespace audio
{
//! The frequency shifter is a single-sideband modulator, which translates all the component frequencies of the input signal by an equal amount.
struct SSoundEffectFrequencyShifter: public SSoundEffect
{
public:
//! Default constructor
SSoundEffectFrequencyShifter();
//! Destructor
virtual ~SSoundEffectFrequencyShifter();
//! Return effect type
virtual ESoundEffectType getType();
public:
/* This is the carrier frequency. For carrier frequencies below the audible range, the singlesideband
* modulator may produce phaser effects, spatial effects or a slight pitch-shift. As the
* carrier frequency increases, the timbre of the sound is affected; a piano or guitar note becomes
* like a bell's chime, and a human voice sounds extraterrestrial!
* Range: 0.0 to 24000.0
* Default: 1.0
*/
f32 Frequency;
/* These select which internal signals are added together to produce the output. Different
* combinations of values will produce slightly different tonal and spatial effects.
* direction down 0, direction up 1, direction off 2
* Range: 0 to 2
* Default: 0
*/
u32 Left;
/* These select which internal signals are added together to produce the output. Different
* combinations of values will produce slightly different tonal and spatial effects.
* Range: 0 to 2
* Default: 0
*/
u32 Right;
};
//! Default constructor
SSoundEffectFrequencyShifter::SSoundEffectFrequencyShifter() :
SSoundEffect(), Frequency(1), Left(0), Right(0)
{
}
//! Destructor
SSoundEffectFrequencyShifter::~SSoundEffectFrequencyShifter()
{
}
//! Return effect type
ESoundEffectType SSoundEffectFrequencyShifter::getType()
{
return ESET_FREQUENCY_SHIFTER;
}
} // namespace audio
} // namespace irrgame
#endif /* SSOUNDEFFECTFREQUENCYSHIFTER_H_ */
| [
"developer08@developer08-pc.(none)"
] | developer08@developer08-pc.(none) |
e33fbd47a162d801244eb0495b6cffe7cb0e6396 | bb6ebff7a7f6140903d37905c350954ff6599091 | /third_party/libaddressinput/src/cpp/src/validating_util.cc | 6b52e8bb534c6a4da6e169480575b1565ddf7b0c | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 4,097 | cc | // Copyright (C) 2013 Google 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.
//
// ValidatingUtil wraps data with checksum and timestamp. Format:
//
// timestamp=<timestamp>
// checksum=<checksum>
// <data>
//
// The timestamp is the time_t that was returned from time() function. The
// timestamp does not need to be portable because it is written and read only by
// ValidatingUtil. The value is somewhat human-readable: it is the number of
// seconds since the epoch.
//
// The checksum is the 32-character hexadecimal MD5 checksum of <data>. It is
// meant to protect from random file changes on disk.
#include "validating_util.h"
#include <cassert>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <string>
#include "util/md5.h"
namespace i18n {
namespace addressinput {
namespace {
const char kTimestampPrefix[] = "timestamp=";
const size_t kTimestampPrefixLength = sizeof kTimestampPrefix - 1;
const char kChecksumPrefix[] = "checksum=";
const size_t kChecksumPrefixLength = sizeof kChecksumPrefix - 1;
const char kSeparator = '\n';
// Places the header value into |header_value| parameter and erases the header
// from |data|. Returns |true| if the header format is valid.
bool UnwrapHeader(const char* header_prefix,
size_t header_prefix_length,
std::string* data,
std::string* header_value) {
assert(header_prefix != NULL);
assert(data != NULL);
assert(header_value != NULL);
if (data->compare(
0, header_prefix_length, header_prefix, header_prefix_length) != 0) {
return false;
}
std::string::size_type separator_position =
data->find(kSeparator, header_prefix_length);
if (separator_position == std::string::npos) {
return false;
}
header_value->assign(
*data, header_prefix_length, separator_position - header_prefix_length);
data->erase(0, separator_position + 1);
return true;
}
} // namespace
// static
void ValidatingUtil::Wrap(time_t timestamp, std::string* data) {
assert(data != NULL);
char timestamp_string[2 + 3 * sizeof timestamp];
snprintf(timestamp_string, sizeof timestamp_string, "%ld", timestamp);
std::string header;
header.append(kTimestampPrefix, kTimestampPrefixLength);
header.append(timestamp_string);
header.push_back(kSeparator);
header.append(kChecksumPrefix, kChecksumPrefixLength);
header.append(MD5String(*data));
header.push_back(kSeparator);
data->reserve(header.size() + data->size());
data->insert(0, header);
}
// static
bool ValidatingUtil::UnwrapTimestamp(std::string* data, time_t now) {
assert(data != NULL);
if (now < 0) {
return false;
}
std::string timestamp_string;
if (!UnwrapHeader(
kTimestampPrefix, kTimestampPrefixLength, data, ×tamp_string)) {
return false;
}
time_t timestamp = atol(timestamp_string.c_str());
if (timestamp < 0) {
return false;
}
// One month contains:
// 30 days *
// 24 hours per day *
// 60 minutes per hour *
// 60 seconds per minute.
static const double kOneMonthInSeconds = 30.0 * 24.0 * 60.0 * 60.0;
double age_in_seconds = difftime(now, timestamp);
return !(age_in_seconds < 0.0) && age_in_seconds < kOneMonthInSeconds;
}
// static
bool ValidatingUtil::UnwrapChecksum(std::string* data) {
assert(data != NULL);
std::string checksum;
if (!UnwrapHeader(kChecksumPrefix, kChecksumPrefixLength, data, &checksum)) {
return false;
}
return checksum == MD5String(*data);
}
} // namespace addressinput
} // namespace i18n
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.