hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
6926473b43e569d52091c06c3d4d9dfa004429e6
2,103
hpp
C++
test/core/point_comparisons.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
test/core/point_comparisons.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
test/core/point_comparisons.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt #ifndef CYNODELIC_TESELA_TEST_CORE_POINT_COMPARISONS_HPP #define CYNODELIC_TESELA_TEST_CORE_POINT_COMPARISONS_HPP CYNODELIC_TESTER_TEST_CASE(point_equals); CYNODELIC_TESTER_SECTION(point_equals,main) { tsl::point pt1(439,115); tsl::point pt2(439,115); tsl::point pt3(600,412); CYNODELIC_TESTER_MESSAGE << "Values for pt1:" << tst::newline << " pt1.x = " << pt1.x << tst::newline << " pt1.y = " << pt1.y; CYNODELIC_TESTER_MESSAGE << "Values for pt2:" << tst::newline << " pt2.x = " << pt2.x << tst::newline << " pt2.y = " << pt2.y; CYNODELIC_TESTER_MESSAGE << "Values for pt3:" << tst::newline << " pt3.x = " << pt3.x << tst::newline << " pt3.y = " << pt3.y; CYNODELIC_TESTER_CHECK_EQUALS(pt1.x,pt2.x); CYNODELIC_TESTER_CHECK_EQUALS(pt1.y,pt2.y); CYNODELIC_TESTER_CHECK_TRUE(pt1 == pt2); CYNODELIC_TESTER_CHECK_NOT_EQUALS(pt1.x,pt3.x); CYNODELIC_TESTER_CHECK_NOT_EQUALS(pt1.y,pt3.y); CYNODELIC_TESTER_CHECK_FALSE(pt1 == pt3); } CYNODELIC_TESTER_TEST_CASE(point_not_equals); CYNODELIC_TESTER_SECTION(point_not_equals,main) { tsl::point pt1(556,120); tsl::point pt2(901,396); tsl::point pt3(556,120); CYNODELIC_TESTER_MESSAGE << "Values for pt1:" << tst::newline << " pt1.x = " << pt1.x << tst::newline << " pt1.y = " << pt1.y; CYNODELIC_TESTER_MESSAGE << "Values for pt2:" << tst::newline << " pt2.x = " << pt2.x << tst::newline << " pt2.y = " << pt2.y; CYNODELIC_TESTER_MESSAGE << "Values for pt3:" << tst::newline << " pt3.x = " << pt3.x << tst::newline << " pt3.y = " << pt3.y; CYNODELIC_TESTER_CHECK_NOT_EQUALS(pt1.x,pt2.x); CYNODELIC_TESTER_CHECK_NOT_EQUALS(pt1.y,pt2.y); CYNODELIC_TESTER_CHECK_TRUE(pt1 != pt2); CYNODELIC_TESTER_CHECK_EQUALS(pt1.x,pt3.x); CYNODELIC_TESTER_CHECK_EQUALS(pt1.y,pt3.y); CYNODELIC_TESTER_CHECK_FALSE(pt1 != pt3); } #endif // CYNODELIC_TESELA_TEST_CORE_POINT_COMPARISONS_HPP
27.671053
80
0.686638
cynodelic
692c6e26f56afdf089586a6efad5c6577d8200f6
223
cpp
C++
src/filesystem/tempfile.cpp
bunsanorg/testing
2532858878628c9925ddd0e58436bba53e4b6cb9
[ "Apache-2.0" ]
null
null
null
src/filesystem/tempfile.cpp
bunsanorg/testing
2532858878628c9925ddd0e58436bba53e4b6cb9
[ "Apache-2.0" ]
null
null
null
src/filesystem/tempfile.cpp
bunsanorg/testing
2532858878628c9925ddd0e58436bba53e4b6cb9
[ "Apache-2.0" ]
null
null
null
#include <bunsan/test/filesystem/tempfile.hpp> namespace bunsan { namespace test { namespace filesystem { tempfile::tempfile() : path(allocate()) {} } // namespace filesystem } // namespace test } // namespace bunsan
18.583333
46
0.717489
bunsanorg
692dd779f0ef60917299d863b1636a27f2793641
9,551
cpp
C++
runtime/test/dnp3s/test_dnp3_publisher.cpp
kinsamanka/OpenPLC_v3
fc1afcf702eebaf518971b304acf487809c804d4
[ "Apache-2.0" ]
null
null
null
runtime/test/dnp3s/test_dnp3_publisher.cpp
kinsamanka/OpenPLC_v3
fc1afcf702eebaf518971b304acf487809c804d4
[ "Apache-2.0" ]
null
null
null
runtime/test/dnp3s/test_dnp3_publisher.cpp
kinsamanka/OpenPLC_v3
fc1afcf702eebaf518971b304acf487809c804d4
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Smarter Grid Solutions // // 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 permissionsand // limitations under the License. #ifdef OPLC_DNP3_OUTSTATION #include <cstdint> #include <utility> #include <vector> #include <asiodnp3/IOutstation.h> #include "catch.hpp" #include "fakeit.hpp" #include "glue.h" #include "dnp3s/dnp3.h" #include "dnp3s/dnp3_publisher.h" using namespace std; using namespace fakeit; using namespace opendnp3; /// An implementation of the update handler that caches the updates that were /// requested. This implementation allows us to spy on the behaviour and to know /// during the tests whether the correct updates were called. class UpdateCaptureHandler : public opendnp3::IUpdateHandler { public: vector<pair<bool, uint16_t>> binary; vector<pair<bool, uint16_t>> binary_output; vector<pair<double, uint16_t>> analog; vector<pair<double, uint16_t>> analog_output; virtual ~UpdateCaptureHandler() {} virtual bool Update(const Binary& meas, uint16_t index, EventMode mode) { binary.push_back(std::make_pair(meas.value, index)); return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const DoubleBitBinary& meas, uint16_t index, EventMode mode) { return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const Analog& meas, uint16_t index, EventMode mode) { analog.push_back(std::make_pair(meas.value, index)); return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const Counter& meas, uint16_t index, EventMode mode) { return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const FrozenCounter& meas, uint16_t index, EventMode mode) { return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const BinaryOutputStatus& meas, uint16_t index, EventMode mode) { binary_output.push_back(std::make_pair(meas.value, index)); return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const AnalogOutputStatus& meas, uint16_t index, EventMode mode) { analog_output.push_back(std::make_pair(meas.value, index)); return true; } /// Simple mocked implementation. /// @copydoc virtual bool Update(const TimeAndInterval& meas, uint16_t index) { return true; } /// Simple mocked implementation. /// @copydoc virtual bool Modify(FlagsType type, uint16_t start, uint16_t stop, uint8_t flags) { return true; } }; SCENARIO("dnp3 publisher", "ExchangeGlue") { Mock<asiodnp3::IOutstation> mock_outstation; UpdateCaptureHandler update_handler; When(Method(mock_outstation, Apply)).AlwaysDo([&](const asiodnp3::Updates& updates) { updates.Apply(update_handler); }); auto outstation = std::shared_ptr<asiodnp3::IOutstation>(&mock_outstation.get(), [](asiodnp3::IOutstation*) {}); Dnp3MappedGroup measurements = {0}; Dnp3Publisher publisher(outstation, measurements); GIVEN("No glued measurements") { auto num_writes = publisher.ExchangeGlue(); THEN("Writes nothing") { REQUIRE(num_writes == 0); } } GIVEN("Boolean input variable at offset 0") { IEC_BOOL bool_val(0); auto group = GlueBoolGroup { .index = 0, .values = { &bool_val, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr } }; const GlueVariable glue_var = { IECLDT_OUT, IECLST_BIT, 0, 0, IECVT_BOOL, &group }; DNP3MappedGlueVariable mapped_vars[] = { { .group = 1, .point_index_number = 0, .variable = &glue_var } }; Dnp3MappedGroup measurements; measurements.size = 1; measurements.items = mapped_vars; Dnp3Publisher publisher(outstation, measurements); WHEN("value is false") { bool_val = false; auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input false") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.binary.size() == 1); REQUIRE(update_handler.binary[0].first == false); REQUIRE(update_handler.binary[0].second == 0); } } WHEN("value is true") { bool_val = true; auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input true") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.binary.size() == 1); REQUIRE(update_handler.binary[0].first == true); REQUIRE(update_handler.binary[0].second == 0); } } } GIVEN("Boolean output status variable at offset 0") { IEC_BOOL bool_val(0); auto group = GlueBoolGroup { .index = 0, .values = { &bool_val, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr } }; const GlueVariable glue_var = { IECLDT_OUT, IECLST_BIT, 0, 0, IECVT_BOOL, &group }; DNP3MappedGlueVariable mapped_vars[] = { { .group = 10, .point_index_number = 0, .variable = &glue_var } }; Dnp3MappedGroup measurements; measurements.size = 1; measurements.items = mapped_vars; Dnp3Publisher publisher(outstation, measurements); WHEN("value is false") { bool_val = false; auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input false") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.binary_output.size() == 1); REQUIRE(update_handler.binary_output[0].first == false); REQUIRE(update_handler.binary_output[0].second == 0); } } WHEN("value is true") { bool_val = true; auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input true") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.binary_output.size() == 1); REQUIRE(update_handler.binary_output[0].first == true); REQUIRE(update_handler.binary_output[0].second == 0); } } } GIVEN("Real variable at offset 0") { IEC_REAL real_val(9); const GlueVariable glue_var = { IECLDT_OUT, IECLST_DOUBLEWORD, 0, 0, IECVT_REAL, &real_val }; DNP3MappedGlueVariable mapped_vars[] = { { .group = 30, .point_index_number = 0, .variable = &glue_var } }; Dnp3MappedGroup measurements; measurements.size = 1; measurements.items = mapped_vars; Dnp3Publisher publisher(outstation, measurements); WHEN("value is 9") { auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input false") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.analog.size() == 1); REQUIRE(update_handler.analog[0].first == 9); REQUIRE(update_handler.analog[0].second == 0); } } } GIVEN("Real status variable at offset 0") { IEC_REAL real_val(9); const GlueVariable glue_var = { IECLDT_OUT, IECLST_DOUBLEWORD, 0, 0, IECVT_REAL, &real_val }; DNP3MappedGlueVariable mapped_vars[] = { { .group = 40, .point_index_number = 0, .variable = &glue_var } }; Dnp3MappedGroup measurements; measurements.size = 1; measurements.items = mapped_vars; Dnp3Publisher publisher(outstation, measurements); WHEN("value is 9") { auto num_writes = publisher.ExchangeGlue(); THEN("Writes binary input false") { REQUIRE(num_writes == 1); Verify(Method(mock_outstation, Apply)).Exactly(Once); REQUIRE(update_handler.analog_output.size() == 1); REQUIRE(update_handler.analog_output[0].first == 9); REQUIRE(update_handler.analog_output[0].second == 0); } } } } #endif // OPLC_DNP3_OUTSTATION
32.266892
116
0.587373
kinsamanka
692fae95fbbad4c60a0e638f73eea0e614ffc732
5,711
cpp
C++
src/gui/gl/slicerenderer.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
5
2016-03-17T07:02:11.000Z
2021-12-12T14:43:58.000Z
src/gui/gl/slicerenderer.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
null
null
null
src/gui/gl/slicerenderer.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
3
2015-10-29T15:21:01.000Z
2020-11-25T09:41:21.000Z
/* * slicerenderer.cpp * * Created on: 09.05.2012 * @author Ralph Schurade */ #include "slicerenderer.h" #include "glfunctions.h" #include "../../data/enums.h" #include "../../data/models.h" #include "../../data/datasets/dataset.h" #include <QtOpenGL/QGLShaderProgram> #include <QVector3D> #include <QMatrix4x4> SliceRenderer::SliceRenderer() : vbo0( 0 ), vbo1( 0 ), vbo2( 0 ) { } SliceRenderer::~SliceRenderer() { glDeleteBuffers( 1, &vbo0 ); glDeleteBuffers( 1, &vbo1 ); glDeleteBuffers( 1, &vbo2 ); } void SliceRenderer::init() { initializeOpenGLFunctions(); glGenBuffers( 1, &vbo0 ); glGenBuffers( 1, &vbo1 ); glGenBuffers( 1, &vbo2 ); initGeometry(); } void SliceRenderer::initGeometry() { float maxDim = GLFunctions::maxDim; QList< int > tl = GLFunctions::getTextureIndexes( "maingl" ); float x = Models::getGlobal( Fn::Property::G_SAGITTAL ).toFloat(); float y = Models::getGlobal( Fn::Property::G_CORONAL ).toFloat(); float z = Models::getGlobal( Fn::Property::G_AXIAL ).toFloat(); float lx = -maxDim; float ly = -maxDim; float lz = -maxDim; float xb = maxDim; float yb = maxDim; float zb = maxDim; float verticesAxial[] = { lx, ly, z, xb, ly, z, lx, yb, z, xb, yb, z }; // Transfer vertex data to VBO 1 glBindBuffer( GL_ARRAY_BUFFER, vbo0 ); glBufferData( GL_ARRAY_BUFFER, 12 * sizeof(float), verticesAxial, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); float verticesCoronal[] = { lx, y, lz, xb, y, lz, lx, y, zb, xb, y, zb }; // Transfer vertex data to VBO 2 glBindBuffer( GL_ARRAY_BUFFER, vbo1 ); glBufferData( GL_ARRAY_BUFFER, 12 * sizeof(float), verticesCoronal, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); float verticesSagittal[] = { x, ly, lz, x, yb, lz, x, ly, zb, x, yb, zb }; // Transfer vertex data to VBO 3 glBindBuffer( GL_ARRAY_BUFFER, vbo2 ); glBufferData( GL_ARRAY_BUFFER, 12 * sizeof(float), verticesSagittal, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void SliceRenderer::setupTextures() { GLFunctions::setupTextures(); } void SliceRenderer::setShaderVars( QString target ) { QGLShaderProgram* program = GLFunctions::getShader( "slice" ); int vertexLocation = program->attributeLocation( "a_position" ); program->enableAttributeArray( vertexLocation ); glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, 0 ); GLFunctions::setTextureUniforms( program, target ); } void SliceRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, QString target ) { float alpha = GLFunctions::sliceAlpha[target]; switch ( renderMode ) { case 0: break; case 1: { if ( alpha < 1.0 ) // obviously not opaque { return; } break; } default: { if ( alpha == 1.0 ) // not transparent { return; } break; } } if ( !GLFunctions::setupTextures() ) { return; } QGLShaderProgram* program = GLFunctions::getShader( "slice" ); program->bind(); // Set modelview-projection matrix program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix ); program->setUniformValue( "u_alpha", alpha ); program->setUniformValue( "u_renderMode", renderMode ); program->setUniformValue( "u_canvasSize", width, height ); program->setUniformValue( "D0", 9 ); program->setUniformValue( "D1", 10 ); program->setUniformValue( "D2", 11 ); program->setUniformValue( "P0", 12 ); float pAlpha = 1.0; float green = 0.0f; float red = 0.0f; initGeometry(); if ( Models::getGlobal( Fn::Property::G_SHOW_AXIAL ).toBool() ) { float blue = (float)(( 1 ) & 0xFF) / 255.f; GLFunctions::getShader( "slice" )->setUniformValue( "u_pickColor", red, green , blue, pAlpha ); drawAxial( target ); } if ( Models::getGlobal( Fn::Property::G_SHOW_CORONAL ).toBool() ) { float blue = (float)(( 2 ) & 0xFF) / 255.f; GLFunctions::getShader( "slice" )->setUniformValue( "u_pickColor", red, green , blue, pAlpha ); drawCoronal( target ); } if ( Models::getGlobal( Fn::Property::G_SHOW_SAGITTAL ).toBool() ) { float blue = (float)(( 3 ) & 0xFF) / 255.f; GLFunctions::getShader( "slice" )->setUniformValue( "u_pickColor", red, green , blue, pAlpha ); drawSagittal( target ); } } void SliceRenderer::drawAxial( QString target ) { // Tell OpenGL which VBOs to use glBindBuffer( GL_ARRAY_BUFFER, vbo0 ); setShaderVars( target ); glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void SliceRenderer::drawCoronal( QString target ) { // Tell OpenGL which VBOs to use glBindBuffer( GL_ARRAY_BUFFER, vbo1 ); setShaderVars( target ); glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void SliceRenderer::drawSagittal( QString target ) { // Tell OpenGL which VBOs to use glBindBuffer( GL_ARRAY_BUFFER, vbo2 ); setShaderVars( target ); glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); }
27.195238
125
0.589914
mhough
69366e3f8e83342a45fdecb6fea9106253de68aa
5,349
hh
C++
hackt_docker/hackt/src/Object/lang/RTE_base.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/lang/RTE_base.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/lang/RTE_base.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "Object/lang/RTE_base.hh" Structures for production assignments. $Id: RTE_base.hh,v 1.12 2010/07/09 02:14:13 fang Exp $ */ #ifndef __HAC_OBJECT_LANG_RTE_BASE_HH__ #define __HAC_OBJECT_LANG_RTE_BASE_HH__ #include <list> #include "util/memory/excl_ptr.hh" #include "util/memory/count_ptr.hh" #include "util/persistent.hh" #include "util/boolean_types.hh" #include "Object/inst/instance_pool_fwd.hh" #include "Object/lang/PRS_dump_context.hh" namespace HAC { namespace entity { class unroll_context; class scopespace; struct bool_tag; template <class> class state_instance; /** Namespace for RTE objects. There are classes that are stored in process definitions, but not the final result of unroll-creation. */ namespace PRS { struct rule_dump_context; struct expr_dump_context; } namespace RTE { class footprint; // defined in "Object/lang/RTE_footprint.h" using std::list; using std::istream; using std::ostream; using util::good_bool; using util::memory::never_ptr; using util::memory::excl_ptr; using util::memory::count_ptr; using util::memory::sticky_ptr; using util::persistent; using util::persistent_object_manager; //============================================================================= class atomic_assignment; class rte_expr; typedef count_ptr<rte_expr> rte_expr_ptr_type; typedef count_ptr<const rte_expr> const_rte_expr_ptr_type; typedef state_instance<bool_tag> bool_instance_type; typedef instance_pool<bool_instance_type> node_pool_type; typedef size_t node_index_type; //============================================================================= /** Dump modifier for RTE assignments. */ typedef PRS::rule_dump_context assignment_dump_context; /** Helper class for controlling RTE and expression dumps. Reuse from PRS. */ typedef PRS::expr_dump_context expr_dump_context; //============================================================================= /** Abstract base class for a production atomic_assignment. TODO: parent link for upward structure? */ class atomic_assignment : public persistent { public: atomic_assignment() { } virtual ~atomic_assignment() { } virtual ostream& dump(ostream&, const assignment_dump_context&) const = 0; /** Prototype for unroll visiting. */ #define RTE_UNROLL_ASSIGN_PROTO \ good_bool \ unroll(const unroll_context&) const virtual RTE_UNROLL_ASSIGN_PROTO = 0; #define RTE_CHECK_ASSIGN_PROTO \ void check(void) const virtual RTE_CHECK_ASSIGN_PROTO = 0; struct checker; struct dumper; }; // end class atomic_assignment //============================================================================= /** A collection or production assignments. This class wants to be pure-virtual, except that it is instantiated non-dynamically by process_definition. */ class assignment_set_base : public list<sticky_ptr<atomic_assignment> > { protected: typedef list<sticky_ptr<atomic_assignment> > parent_type; public: typedef parent_type::value_type value_type; public: assignment_set_base(); // dtor needs to be polymorphic to dynamic_cast to assignment_set virtual ~assignment_set_base(); #if 0 private: // not copy-constructible, or should be restricted with run-time check explicit assignment_set(_baseconst this_type&); #endif public: ostream& dump(ostream&, const assignment_dump_context& = assignment_dump_context()) const; void append_assignment(excl_ptr<atomic_assignment>&); template <class R> void append_assignment(excl_ptr<R>& r) { excl_ptr<atomic_assignment> tr = r.template as_a_xfer<atomic_assignment>(); this->append_assignment(tr); } // supply these for derived classes RTE_UNROLL_ASSIGN_PROTO; RTE_CHECK_ASSIGN_PROTO; void collect_transient_info_base(persistent_object_manager&) const; void write_object_base(const persistent_object_manager&, ostream&) const; void load_object_base(const persistent_object_manager&, istream&); private: // hide this from user using parent_type::push_back; }; // end class assignment_set_base typedef assignment_set_base nested_assignments; //============================================================================= /** Abstract class of atomic assignment expressions. These expressions are not unrolled. */ class rte_expr : public persistent { public: /** Worry about implementation efficiency later... (Vector of raw pointers or excl_ptr with copy-constructor.) */ typedef list<rte_expr_ptr_type> expr_sequence_type; public: rte_expr() { } virtual ~rte_expr() { } virtual ostream& dump(ostream&, const expr_dump_context&) const = 0; ostream& dump(ostream& o) const { return dump(o, expr_dump_context()); } virtual void check(void) const = 0; // accumulate set of used node indices #define RTE_UNROLL_EXPR_PROTO \ size_t \ unroll(const unroll_context&) const virtual RTE_UNROLL_EXPR_PROTO = 0; #define RTE_UNROLL_COPY_PROTO \ rte_expr_ptr_type \ unroll_copy(const unroll_context&, const rte_expr_ptr_type&) const virtual RTE_UNROLL_COPY_PROTO = 0; protected: struct checker; struct unroller; struct unroll_copier; }; // end class rte_expr //============================================================================= } // end namespace RTE } // end namespace entity } // end namespace HAC #endif // __HAC_OBJECT_LANG_RTE_BASE_HH__
25.112676
82
0.699944
broken-wheel
693aeabc53dcfc994d0188e2eb63a1f5a1f21dab
707
cc
C++
tools/asm.cc
nlewycky/x64asm
66dcdef5dba596cb0a51edde1910194d079e704c
[ "Apache-2.0" ]
453
2015-04-24T13:57:43.000Z
2022-03-16T16:38:53.000Z
tools/asm.cc
nlewycky/x64asm
66dcdef5dba596cb0a51edde1910194d079e704c
[ "Apache-2.0" ]
71
2015-04-15T20:52:13.000Z
2018-07-29T18:08:22.000Z
tools/asm.cc
nlewycky/x64asm
66dcdef5dba596cb0a51edde1910194d079e704c
[ "Apache-2.0" ]
67
2015-05-07T06:44:47.000Z
2022-02-25T03:46:24.000Z
#include <iostream> #include <string> #include "include/x64asm.h" using namespace std; using namespace x64asm; using namespace cpputil; /** A simple test program. Reads att syntax and prints human readable hex. */ int main(int argc, char** argv) { Code c; cin >> c; if(failed(cin)) { cerr << endl << "Parse error encountered." << endl; cerr << fail_msg(cin); return 1; } cout << endl; cout << "Assembling..." << endl << c << endl << endl << endl; auto result = Assembler().assemble(c); if(!result.first) { cout << "Could not assemble; 8-bit jump offset was given but target was further away." << endl; } else { cout << result.second << endl; } return 0; }
21.424242
99
0.623762
nlewycky
693e2dceeaa7ce9a1e380914e119a2923fabe70c
5,311
cc
C++
headless/lib/headless_web_contents_browsertest.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
headless/lib/headless_web_contents_browsertest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
headless/lib/headless_web_contents_browsertest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <string> #include <vector> #include "base/base64.h" #include "content/public/test/browser_test.h" #include "headless/public/devtools/domains/page.h" #include "headless/public/devtools/domains/runtime.h" #include "headless/public/devtools/domains/security.h" #include "headless/public/headless_browser.h" #include "headless/public/headless_devtools_client.h" #include "headless/public/headless_web_contents.h" #include "headless/test/headless_browser_test.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/geometry/size.h" #include "url/gurl.h" using testing::UnorderedElementsAre; namespace headless { class HeadlessWebContentsTest : public HeadlessBrowserTest {}; IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest, Navigation) { EXPECT_TRUE(embedded_test_server()->Start()); HeadlessBrowserContext* browser_context = browser()->CreateBrowserContextBuilder().Build(); HeadlessWebContents* web_contents = browser_context->CreateWebContentsBuilder() .SetInitialURL(embedded_test_server()->GetURL("/hello.html")) .Build(); EXPECT_TRUE(WaitForLoad(web_contents)); EXPECT_THAT(browser_context->GetAllWebContents(), UnorderedElementsAre(web_contents)); } IN_PROC_BROWSER_TEST_F(HeadlessWebContentsTest, WindowOpen) { EXPECT_TRUE(embedded_test_server()->Start()); HeadlessBrowserContext* browser_context = browser()->CreateBrowserContextBuilder().Build(); HeadlessWebContents* web_contents = browser_context->CreateWebContentsBuilder() .SetInitialURL(embedded_test_server()->GetURL("/window_open.html")) .Build(); EXPECT_TRUE(WaitForLoad(web_contents)); EXPECT_EQ(static_cast<size_t>(2), browser_context->GetAllWebContents().size()); } namespace { bool DecodePNG(std::string base64_data, SkBitmap* bitmap) { std::string png_data; if (!base::Base64Decode(base64_data, &png_data)) return false; return gfx::PNGCodec::Decode( reinterpret_cast<unsigned const char*>(png_data.data()), png_data.size(), bitmap); } } // namespace // Parameter specifies whether --disable-gpu should be used. class HeadlessWebContentsScreenshotTest : public HeadlessAsyncDevTooledBrowserTest, public ::testing::WithParamInterface<bool> { public: void SetUp() override { EnablePixelOutput(); if (GetParam()) UseSoftwareCompositing(); HeadlessAsyncDevTooledBrowserTest::SetUp(); } void RunDevTooledTest() override { std::unique_ptr<runtime::EvaluateParams> params = runtime::EvaluateParams::Builder() .SetExpression("document.body.style.background = '#0000ff'") .Build(); devtools_client_->GetRuntime()->Evaluate( std::move(params), base::Bind(&HeadlessWebContentsScreenshotTest::OnPageSetupCompleted, base::Unretained(this))); } void OnPageSetupCompleted(std::unique_ptr<runtime::EvaluateResult> result) { devtools_client_->GetPage()->GetExperimental()->CaptureScreenshot( page::CaptureScreenshotParams::Builder().Build(), base::Bind(&HeadlessWebContentsScreenshotTest::OnScreenshotCaptured, base::Unretained(this))); } void OnScreenshotCaptured( std::unique_ptr<page::CaptureScreenshotResult> result) { std::string base64 = result->GetData(); EXPECT_LT(0U, base64.length()); SkBitmap result_bitmap; EXPECT_TRUE(DecodePNG(base64, &result_bitmap)); EXPECT_EQ(800, result_bitmap.width()); EXPECT_EQ(600, result_bitmap.height()); SkColor actual_color = result_bitmap.getColor(400, 300); SkColor expected_color = SkColorSetRGB(0x00, 0x00, 0xff); EXPECT_EQ(expected_color, actual_color); FinishAsynchronousTest(); } }; HEADLESS_ASYNC_DEVTOOLED_TEST_P(HeadlessWebContentsScreenshotTest); // Instantiate test case for both software and gpu compositing modes. INSTANTIATE_TEST_CASE_P(HeadlessWebContentsScreenshotTests, HeadlessWebContentsScreenshotTest, ::testing::Bool()); class HeadlessWebContentsSecurityTest : public HeadlessAsyncDevTooledBrowserTest, public security::ExperimentalObserver { public: void RunDevTooledTest() override { devtools_client_->GetSecurity()->GetExperimental()->AddObserver(this); devtools_client_->GetSecurity()->GetExperimental()->Enable( security::EnableParams::Builder().Build()); } void OnSecurityStateChanged( const security::SecurityStateChangedParams& params) override { EXPECT_EQ(security::SecurityState::NEUTRAL, params.GetSecurityState()); devtools_client_->GetSecurity()->GetExperimental()->Disable( security::DisableParams::Builder().Build()); devtools_client_->GetSecurity()->GetExperimental()->RemoveObserver(this); FinishAsynchronousTest(); } }; HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessWebContentsSecurityTest); } // namespace headless
34.940789
79
0.73489
google-ar
6945c9c8b7810e43e61f71f5df408da0daf7cb31
356
cc
C++
src/ios_tools/web/test/test_url_constants.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
src/ios_tools/web/test/test_url_constants.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
src/ios_tools/web/test/test_url_constants.cc
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ios/web/test/test_url_constants.h" namespace web { const char kTestWebUIScheme[] = "testwebui"; const char kTestNativeContentScheme[] = "testnativecontent"; } // namespace web
27.384615
73
0.755618
rhencke
69464a87b068e235a75daed0aabf2f5a7d1594e0
3,466
cpp
C++
CA7-Source/userspace/netlink_tester.cpp
dimtass/stm32mp1-rpmsg-netlink-example
998f61db13fa434e97119c751c6958c1eee43727
[ "MIT" ]
7
2020-10-07T12:12:45.000Z
2022-01-27T10:51:48.000Z
CA7-Source/userspace/netlink_tester.cpp
dimtass/stm32mp1-rpmsg-netlink-example
998f61db13fa434e97119c751c6958c1eee43727
[ "MIT" ]
null
null
null
CA7-Source/userspace/netlink_tester.cpp
dimtass/stm32mp1-rpmsg-netlink-example
998f61db13fa434e97119c751c6958c1eee43727
[ "MIT" ]
null
null
null
#include <string> #include <time.h> #include "netlink_tester.h" enum { COM_BUFFER_SIZE=32768, }; enum { CRC16_INIT_VAL=0x8006, }; static uint8_t tx_buffer[COM_BUFFER_SIZE] = {0}; static uint8_t rx_buffer[COM_BUFFER_SIZE] = {0}; /* Function prototypes */ NetlinkTester::NetlinkTester() { L_(linfo) << "Initialized netlink client."; init_buffer(tx_buffer, COM_BUFFER_SIZE); } NetlinkTester::~NetlinkTester() { } void NetlinkTester::init_buffer(uint8_t * buffer, size_t buffer_size) { for (int i=0; i<buffer_size; i++) { buffer[i] = 0xff & i; } // Calculate CRC uint16_t crc = crc16(buffer, buffer_size); L_(linfo) << "Initialized buffer with CRC16: 0x" << std::hex << crc; } void NetlinkTester::add_test(size_t n_bytes) { struct test_item item = {n_bytes, 0}; m_tests.push_back(item); L_(linfo) << "-> Add test: size=" << n_bytes; } size_t NetlinkTester::get_num_of_tests() { return(m_tests.size()); } int NetlinkTester::run_test(size_t index, struct test_item & item) { if (m_tests.size() > index) { item = m_tests.at(index); NetlinkClient nlc; /* prepare packet */ struct packet * out = (struct packet *) &tx_buffer[0]; out->preamble = PREAMBLE; out->length = item.n_bytes; // + sizeof(struct packet); // Nah, nevermind out->crc16 = crc16(&tx_buffer[sizeof(out) - 1], out->length); struct timespec start_time = get_time_ns(); size_t tx_len = nlc.send(tx_buffer, item.n_bytes, rx_buffer); struct timespec stop_time = get_time_ns(); item.time = timespec_diff(start_time, stop_time); L_(linfo) << "-> b: " << item.n_bytes << ", nsec: " << item.time << ", bytes sent: " << std::dec << tx_len; return(0); } return -1; } struct timespec NetlinkTester::get_time_ns() { struct timespec t; clock_gettime(CLOCK_REALTIME, &t); return(t); } long NetlinkTester::timespec_diff (struct timespec t1, struct timespec t2) { struct timespec diff; if (t2.tv_nsec-t1.tv_nsec < 0) { diff.tv_sec = t2.tv_sec - t1.tv_sec - 1; diff.tv_nsec = t2.tv_nsec - t1.tv_nsec + 1000000000; } else { diff.tv_sec = t2.tv_sec - t1.tv_sec; diff.tv_nsec = t2.tv_nsec - t1.tv_nsec; } return (diff.tv_sec * 1000000000.0 + diff.tv_nsec); } uint16_t NetlinkTester::crc16(const uint8_t * buffer, uint16_t len) { unsigned short out = 0; int bits_read = 0, bit_flag; /* Sanity check: */ if( buffer == NULL ) return 0; while( len > 0 ) { bit_flag = out >> 15; /* Get next bit: */ out <<= 1; out |= ( *buffer >> bits_read ) & 1; // item a) work from the least significant bits /* Increment bit counter: */ bits_read++; if( bits_read > 7 ) { bits_read = 0; buffer++; len--; } /* Cycle check: */ if( bit_flag ) out ^= CRC16_INIT_VAL; } // item b) "push out" the last 16 bits int i; for( i = 0; i < 16; ++i ) { bit_flag = out >> 15; out <<= 1; if( bit_flag ) out ^= CRC16_INIT_VAL; } // item c) reverse the bits unsigned short crc = 0; i = 0x8000; int j = 0x0001; for( ; i != 0; i >>= 1, j <<= 1 ) { if( i & out ) crc |= j; } return crc; }
22.653595
92
0.566359
dimtass
69487bfe15f2bd11008fa77ab7d09fc840276e09
616
cpp
C++
5_Classes_Objects/5_7_Using_this.cpp
YinHk-Forks/CPP-Notes
7dd1895d44cd3773e5f2603cbc3b02d174285b05
[ "MIT" ]
4
2020-12-30T15:16:39.000Z
2021-11-07T17:17:02.000Z
5_Classes_Objects/5_7_Using_this.cpp
YinHk-Forks/CPP-Notes
7dd1895d44cd3773e5f2603cbc3b02d174285b05
[ "MIT" ]
null
null
null
5_Classes_Objects/5_7_Using_this.cpp
YinHk-Forks/CPP-Notes
7dd1895d44cd3773e5f2603cbc3b02d174285b05
[ "MIT" ]
3
2021-04-03T08:00:36.000Z
2022-01-01T06:19:58.000Z
// // CPP-Notes // // Created by Akshay Raj Gollahalli on 23/05/16. // Copyright © 2016 Akshay Raj Gollahalli. All rights reserved. // #include <cstdio> class Some_class { int _s = 0; public: void setter(int i) {_s = i;} int getter(); }; int Some_class::getter() { printf("%p\n", this); // pointing to this object return _s; } int main(int argc, char ** argv){ int aa = 10; Some_class a; a.setter(aa); printf("%d\n", a.getter()); printf("%p\n", &a); // pointing to `a` object // The address of `a` should be equal to Some_class return 0; }
17.111111
64
0.573052
YinHk-Forks
694aa5ea782be07cf443d4709085a47bb79d561b
1,106
cpp
C++
Bus/MessageBus.cpp
ngrande/Banshee
4109b546c305a45de3675ddf149dbe64af934940
[ "MIT" ]
null
null
null
Bus/MessageBus.cpp
ngrande/Banshee
4109b546c305a45de3675ddf149dbe64af934940
[ "MIT" ]
null
null
null
Bus/MessageBus.cpp
ngrande/Banshee
4109b546c305a45de3675ddf149dbe64af934940
[ "MIT" ]
null
null
null
// // Copyright (c) 2016 by Niclas Grande. All Rights Reserved. // #include "MessageBus.h" #include <algorithm> MessageBus::MessageBus(void) { this->pStopped = false; this->pMsgThread = std::thread(&MessageBus::processMsgQueue, this); this->pMsgThread.detach(); } void MessageBus::processMsgQueue() { while (!pStopped) { std::unique_lock<std::mutex> lck(cv_m); cv.wait(lck); while (!this->pMsgQueue.empty()) { auto queuedMsg = this->pMsgQueue.front(); this->pMsgQueue.pop(); // process queuedItem here auto msgCode = queuedMsg.getCode(); switch (msgCode) { case Code::PLAY_SOUND: // handle play sound message std::cout << "PLAY_SOUND message received!" << std::endl; break; case Code::STOP_SOUND: std::cout << "STOP_SOUND message receieved!" << std::endl; break; case Code::FLUSH_BUFFER: std::cout << "FLUSH_BUFFER message received!" << std::endl; break; } } } } void MessageBus::sendMessage(Message &msg) { this->pMsgQueue.push(msg); this->cv.notify_all(); }
24.577778
69
0.621157
ngrande
694b5aaf8eeb11d172cebf89000e4b70d0050190
1,572
cpp
C++
lowladb-android/src/main/jni/LDBObjectId.cpp
lowla/lowladb-android-lib
7023e83a67051946a96818c255e9993ef9258b37
[ "MIT" ]
2
2015-04-01T20:56:12.000Z
2015-04-01T23:33:01.000Z
lowladb-android/src/main/jni/LDBObjectId.cpp
lowla/lowladb-android-lib
7023e83a67051946a96818c255e9993ef9258b37
[ "MIT" ]
null
null
null
lowladb-android/src/main/jni/LDBObjectId.cpp
lowla/lowladb-android-lib
7023e83a67051946a96818c255e9993ef9258b37
[ "MIT" ]
null
null
null
#include <jni.h> #include <lowladb.h> extern "C" JNIEXPORT jobject JNICALL Java_io_lowla_lowladb_LDBObjectId_generate(JNIEnv *env, jclass jClazz) { char buffer[CLowlaDBBson::OID_SIZE]; CLowlaDBBson::oidGenerate(buffer); jbyteArray answer = env->NewByteArray(CLowlaDBBson::OID_SIZE); env->SetByteArrayRegion(answer, 0, CLowlaDBBson::OID_SIZE, (jbyte*)buffer); jmethodID ctor = env->GetMethodID(jClazz, "<init>", "([B)V"); jobject ret = env->NewObject(jClazz, ctor, answer); return ret; } extern "C" JNIEXPORT jstring JNICALL Java_io_lowla_lowladb_LDBObjectId_toHexString(JNIEnv *env, jobject jThis) { jclass clazz = env->GetObjectClass(jThis); jfieldID fid = env->GetFieldID(clazz, "data", "[B"); jbyteArray data = (jbyteArray)env->GetObjectField(jThis, fid); jbyte *dataBytes = env->GetByteArrayElements(data, nullptr); char buffer[CLowlaDBBson::OID_STRING_SIZE]; CLowlaDBBson::oidToString((const char *)dataBytes, buffer); env->ReleaseByteArrayElements(data, (jbyte *)dataBytes, 0); return env->NewStringUTF(buffer); } extern "C" JNIEXPORT jbyteArray JNICALL Java_io_lowla_lowladb_LDBObjectId_oidFromString(JNIEnv *env, jclass jClazz, jstring str) { char oid[CLowlaDBBson::OID_SIZE]; const char *szUTF = env->GetStringUTFChars(str, nullptr); CLowlaDBBson::oidFromString(oid, szUTF); env->ReleaseStringUTFChars(str, szUTF); jbyteArray answer = env->NewByteArray(CLowlaDBBson::OID_SIZE); env->SetByteArrayRegion(answer, 0, CLowlaDBBson::OID_SIZE, (jbyte*)oid); return answer; }
35.727273
88
0.736005
lowla
694f982089cc73d568a5877fdc50792cfdcb9515
1,063
cpp
C++
math/gauss_jordan_elimination.cpp
KSkun/OI-Templates
a193da03a531700858fe45d455a946074bda5007
[ "WTFPL" ]
12
2018-03-30T08:44:07.000Z
2021-09-03T07:43:56.000Z
math/gauss_jordan_elimination.cpp
KSkun/OI-Templates
a193da03a531700858fe45d455a946074bda5007
[ "WTFPL" ]
null
null
null
math/gauss_jordan_elimination.cpp
KSkun/OI-Templates
a193da03a531700858fe45d455a946074bda5007
[ "WTFPL" ]
1
2018-08-09T01:39:30.000Z
2018-08-09T01:39:30.000Z
// Code by KSkun, 2018/3 #include <cstdio> #include <cmath> #include <algorithm> const int MAXN = 105; const double EPS = 1e-10; int n; double mat[MAXN][MAXN]; /* * Gauss-Jordan Elimination. */ inline bool gauss() { for(int i = 1; i <= n; i++) { int r = i; for(int j = i + 1; j <= n; j++) { if(std::fabs(mat[r][i]) < std::fabs(mat[j][i])) r = j; } if(r != i) { for(int j = 1; j <= n + 1; j++) std::swap(mat[i][j], mat[r][j]); } if(fabs(mat[i][i]) < EPS) return false; for(int j = 1; j <= n; j++) { if(j != i) { double t = mat[j][i] / mat[i][i]; for(int k = i + 1; k <= n + 1; k++) mat[j][k] -= mat[i][k] * t; } } } for(int i = 1; i <= n; i++) mat[i][n + 1] /= mat[i][i]; return true; } // an example of G-J Elimination // can pass luogu p3389 int main() { scanf("%d", &n); for(int i = 1; i <= n; i++) { for(int j = 1; j <= n + 1; j++) { scanf("%lf", &mat[i][j]); } } if(gauss()) { for(int i = 1; i <= n; i++) { printf("%.2lf\n", mat[i][n + 1]); } } else { puts("No Solution"); } return 0; }
18.982143
67
0.469426
KSkun
694fe8e3d950363ddea27ecc4790bde9216e9409
4,490
cpp
C++
src/util/string_set.cpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
3
2018-10-24T22:15:17.000Z
2019-09-21T22:56:05.000Z
src/util/string_set.cpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
null
null
null
src/util/string_set.cpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
1
2019-10-16T06:13:28.000Z
2019-10-16T06:13:28.000Z
/******************************************************************************* * string_sorting/util/string_set.cpp * * Copyright (C) 2018 Florian Kurpicz <florian.kurpicz@tu-dortmund.de> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <utility> #include "mpi/environment.hpp" #include "util/string_set.hpp" namespace dsss { string_set::string_set() { } string_set::string_set(std::vector<dsss::char_type>&& string_data) : strings_raw_data_(std::move(string_data)) { strings_.emplace_back(strings_raw_data_.data()); for (size_t i = 0; i < strings_raw_data_.size();) { while (strings_raw_data_[i++] != 0) { } strings_.emplace_back(strings_raw_data_.data() + i); } if constexpr (debug) { dsss::mpi::environment env; size_t min_length = strings_raw_data_.size(); size_t max_length = 0; for (size_t i = 0; i < strings_.size() - 1; ++i) { const size_t cur_length = strings_[i + 1] - strings_[i] - 1; min_length = std::min(min_length, cur_length); max_length = std::max(max_length, cur_length); } size_t avg_length = (strings_raw_data_.size() - strings_.size()) / (strings_.size() - 1); for (int32_t rank = 0; rank < env.size(); ++rank) { if (rank == env.rank()) { std::cout << rank << ": min " << min_length << ", max " << max_length << ", avg " << avg_length << ", count " << strings_.size() - 1 << std::endl; } env.barrier(); } } // Delete pointer to the end of the local strings. No string does start here. strings_.pop_back(); } string_set::string_set(string_set&& other) { auto* old_ptr = other.strings_raw_data_.data(); strings_raw_data_ = std::move(other.strings_raw_data_); strings_ = std::move(other.strings_); int64_t offset = std::distance(old_ptr, strings_raw_data_.data()); for (auto& str : strings_) { str -= offset; } } string_set& string_set::operator =(string_set&& other) { if (this != &other) { const auto* old_ptr = other.strings_raw_data_.data(); strings_raw_data_ = std::move(other.strings_raw_data_); strings_ = std::move(other.strings_); const auto* new_ptr = strings_raw_data_.data(); int64_t offset = std::distance(old_ptr, new_ptr); for (auto& str : strings_) { str -= offset; } } return *this; } void string_set::update(std::vector<dsss::char_type>&& string_data) { strings_raw_data_ = std::move(string_data); strings_.clear(); strings_.emplace_back(strings_raw_data_.data()); for (size_t i = 0; i < strings_raw_data_.size(); ++i) { while (strings_raw_data_[i++] != 0) { } strings_.emplace_back(strings_raw_data_.data() + i); } if constexpr (debug) { dsss::mpi::environment env; size_t min_length = strings_raw_data_.size(); size_t max_length = 0; for (size_t i = 0; i < strings_.size() - 1; ++i) { const size_t cur_length = strings_[i + 1] - strings_[i] - 1; min_length = std::min(min_length, cur_length); max_length = std::max(max_length, cur_length); } size_t avg_length = (strings_raw_data_.size() - strings_.size()) / (strings_.size() - 1); for (int32_t rank = 0; rank < env.size(); ++rank) { if (rank == env.rank()) { std::cout << rank << ": min " << min_length << ", max " << max_length << ", avg " << avg_length << ", count " << strings_.size() - 1 << std::endl; } env.barrier(); } } // Delete pointer to the end of the local strings. No string does start here. strings_.pop_back(); } void string_set::update(std::vector<dsss::string>&& string_data) { strings_ = std::move(string_data); } dsss::string string_set::operator [](const size_t idx) const { return strings_[idx]; } std::vector<dsss::string>::const_iterator string_set::cbegin() { return strings_.cbegin(); } size_t string_set::size() const { return strings_.size(); } dsss::string* string_set::strings() { return strings_.data(); } dsss::string string_set::front() { return strings_.front(); } dsss::string string_set::back() { return strings_.back(); } std::vector<dsss::char_type>& string_set::data_container() { return strings_raw_data_; } dsss::string string_set::raw_data() { return strings_raw_data_.data(); } } // namespace dsss /******************************************************************************/
34.274809
80
0.607572
bingmann
695b9a895adff5f436cf6a143d90726e4ba03eb8
460
cpp
C++
tests/mutex/mutexes/timed_mutex/basic.cpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
1
2018-07-01T07:54:37.000Z
2018-07-01T07:54:37.000Z
tests/mutex/mutexes/timed_mutex/basic.cpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
null
null
null
tests/mutex/mutexes/timed_mutex/basic.cpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
null
null
null
#include <srook/mutex.hpp> #include <iostream> int main() { using namespace srook::mutexes::includes; srook::timed_mutex m; m.lock(); m.unlock(); if (m.try_lock_for(chrono::seconds(3))) { m.unlock(); } else { std::cerr << "time outed" << std::endl; return EXIT_FAILURE; } if (m.try_lock_until(chrono::system_clock::now() + chrono::seconds(3))) { m.unlock(); } else { std::cerr << "time outed" << std::endl; return EXIT_FAILURE; } }
17.692308
74
0.630435
falgon
695d2429c239313e0a659752b1e56fc266b7c4e5
3,615
hpp
C++
include/battery.hpp
findNextStep/next_dwm_status
cef24ec51c2a856bb4c7b113a7f2a791b85c432f
[ "MIT" ]
null
null
null
include/battery.hpp
findNextStep/next_dwm_status
cef24ec51c2a856bb4c7b113a7f2a791b85c432f
[ "MIT" ]
null
null
null
include/battery.hpp
findNextStep/next_dwm_status
cef24ec51c2a856bb4c7b113a7f2a791b85c432f
[ "MIT" ]
null
null
null
#pragma once #include <barPerSeconds.hpp> #include <fstream> #include <vector> #include <sstream> namespace nextDwmStatus { const std::string battery_file = "/sys/class/power_supply/"; const std::string power = "/current_now"; const std::string stat = "/status"; const std::string full = "/charge_full"; const std::string now = "/charge_now"; class battery : public barPerSeconds { private: const std::string battery_name; const std::string power_file; const std::string stat_file; const std::string full_file; const std::string now_file; std::string message; protected: static long long read_data(const std::string &file) { long long result; std::ifstream fs(file); fs >> result; return result; } virtual void per_second_task() { // copy from libqtile widget battery.py // see https://github.com/qtile/qtile/blob/v0.13.0/libqtile/widget/battery.py std::string stat; std::ifstream fs(stat_file); const std::vector<std::string> charging_icon = { "", "", "", "", "", "", "", }; const std::vector<std::string> discharging_icon = { "", "", "", "", "", "", "", "", "", "" }; const std::string unknow = ""; fs >> stat; using namespace std; if(stat == "Full") { // full charge message = "100%"; } else if(stat == "Discharging" || stat == "Not charging") { // work in battery const double full = read_data(full_file), now = read_data(now_file), power = read_data(power_file); if(power == 0) { message = "charge fail"; } else { const double time = now / power, perc = now / full; std::stringstream ss; ss << discharging_icon.at((perc - 0.001) * (discharging_icon.size() - 1)) << (int)(perc * 100) << "%" << (int)time << ":" << ((int)(time * 60) % 60); message = ss.str(); } } else if(stat == "Charging") { // charging const double full = read_data(full_file), now = read_data(now_file), power = read_data(power_file); if(power == 0) { message = "charge fail"; } else { const double time = (full - now) / power, perc = now / full; std::stringstream ss; ss << charging_icon.at((perc - 0.001) * (charging_icon.size() - 1)) << (int)(perc * 100) << "%" << (int)time << ":" << ((int)(time * 60) % 60); message = ss.str(); } } else if(stat == "Unknown") { const double full = read_data(full_file), now = read_data(now_file); const double perc = now / full; std::stringstream ss; ss << unknow << (int)(perc * 100) << "%"; message = ss.str(); } else { message = "unknow status " + stat; } } public: battery(): battery("BAT0") {} battery(const std::string &batteryName): battery_name(batteryName), power_file(battery_file + battery_name + power), stat_file(battery_file + battery_name + stat), full_file(battery_file + battery_name + full), now_file(battery_file + battery_name + now) {} virtual const std::string getStatus()const { return message; } }; }
36.15
165
0.506224
findNextStep
695d57e61440836679c80df7ae93a777714650fc
4,225
cpp
C++
source/FullView3dRenderer.cpp
xzrunner/wmv
dfa38476e6f8ca67ee1ba4486e5bd610b9f45eee
[ "MIT" ]
null
null
null
source/FullView3dRenderer.cpp
xzrunner/wmv
dfa38476e6f8ca67ee1ba4486e5bd610b9f45eee
[ "MIT" ]
null
null
null
source/FullView3dRenderer.cpp
xzrunner/wmv
dfa38476e6f8ca67ee1ba4486e5bd610b9f45eee
[ "MIT" ]
null
null
null
#include "terrainlab/FullView3dRenderer.h" #include <SM_Calc.h> #include <unirender/Device.h> #include <unirender/ShaderProgram.h> #include <unirender/DrawState.h> #include <unirender/Context.h> #include <shadertrans/ShaderTrans.h> #include <renderpipeline/UniformNames.h> #include <painting0/ModelMatUpdater.h> #include <painting3/Shader.h> #include <painting3/ViewMatUpdater.h> #include <painting3/ProjectMatUpdater.h> #include <terraintiler/GeoMipMapping.h> namespace { const char* vs = R"( #version 330 core layout (location = 0) in vec4 position; layout(std140) uniform UBO_VS { mat4 projection; mat4 view; mat4 model; } ubo_vs; out VS_OUT { vec3 frag_pos; } vs_out; void main() { vs_out.frag_pos = vec3(ubo_vs.model * position); gl_Position = ubo_vs.projection * ubo_vs.view * ubo_vs.model * position; } )"; const char* fs = R"( #version 330 core out vec4 FragColor; in VS_OUT { vec3 frag_pos; } fs_in; void main() { vec3 fdx = dFdx(fs_in.frag_pos); vec3 fdy = dFdy(fs_in.frag_pos); vec3 N = normalize(cross(fdx, fdy)); vec3 light_dir = normalize(vec3(0, -10, 10) - fs_in.frag_pos); float diff = max(dot(N, light_dir), 0.0); vec3 diffuse = diff * vec3(1.0, 1.0, 1.0); FragColor = vec4(diffuse, 1.0); } )"; } namespace terrainlab { FullView3dRenderer::FullView3dRenderer(const ur::Device& dev) { InitShader(dev); m_mipmap = std::make_shared<terraintiler::GeoMipMapping>(5, 5); } void FullView3dRenderer::Setup(std::shared_ptr<pt3::WindowContext>& wc) const { // static_cast<pt3::Shader*>(m_shader.get())->AddNotify(wc); } void FullView3dRenderer::Update(const ur::Device& dev) { auto w = m_mipmap->GetWidth(); auto h = m_mipmap->GetHeight(); for (size_t y = 0; y < h; ++y) { for (size_t x = 0; x < w; ++x) { m_mipmap->UpdateTile(dev, x, y); } } } void FullView3dRenderer::Draw(ur::Context& ctx, const sm::vec3& cam_pos, const sm::mat4& mt, bool debug_draw) const { // m_shader->Bind(); auto model_updater = m_shader->QueryUniformUpdater(ur::GetUpdaterTypeID<pt0::ModelMatUpdater>()); if (model_updater) { std::static_pointer_cast<pt0::ModelMatUpdater>(model_updater)->Update(mt); } ur::DrawState ds; ds.program = m_shader; if (debug_draw) { ds.render_state.rasterization_mode = ur::RasterizationMode::Line; } auto w = m_mipmap->GetWidth(); auto h = m_mipmap->GetHeight(); for (size_t y = 0; y < h; ++y) { for (size_t x = 0; x < w; ++x) { const float dist = sm::dis_pos3_to_pos3(cam_pos, sm::vec3(static_cast<float>(x), 0, static_cast<float>(y))); size_t lod_level = 5; if (dist < 2) { lod_level = 0; } else if (dist < 4) { lod_level = 1; } else if (dist < 8) { lod_level = 2; } else if (dist < 16) { lod_level = 3; } else if (dist < 32) { lod_level = 4; } else if (dist < 64) { lod_level = 5; } auto rd = m_mipmap->QueryRenderable(x, y, lod_level); if (!rd.va) { continue; } ds.vertex_array = rd.va; ctx.Draw(ur::PrimitiveType::Triangles, ds, nullptr); } } } void FullView3dRenderer::InitShader(const ur::Device& dev) { //std::vector<ur::VertexAttrib> layout; //layout.push_back(ur::VertexAttrib(rp::VERT_POSITION_NAME, 3, 4, 12, 0)); //rc.CreateVertexLayout(layout); std::vector<unsigned int> _vs, _fs; shadertrans::ShaderTrans::GLSL2SpirV(shadertrans::ShaderStage::VertexShader, vs, _vs); shadertrans::ShaderTrans::GLSL2SpirV(shadertrans::ShaderStage::PixelShader, fs, _fs); m_shader = dev.CreateShaderProgram(_vs, _fs); assert(m_shader); m_shader->AddUniformUpdater(std::make_shared<pt0::ModelMatUpdater>(*m_shader, "ubo_vs.model")); m_shader->AddUniformUpdater(std::make_shared<pt3::ViewMatUpdater>(*m_shader, "ubo_vs.view")); m_shader->AddUniformUpdater(std::make_shared<pt3::ProjectMatUpdater>(*m_shader, "ubo_vs.projection")); } }
25.920245
120
0.622722
xzrunner
695d8067491218d4501ece1e70ff73b4d287fea0
2,372
cpp
C++
spoj.3110.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
spoj.3110.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
spoj.3110.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
/* * spoj.3110.cpp * Copyright (C) 2021 Woshiluo Luo <woshiluo.luo@outlook.com> * * 「Two roads diverged in a wood,and I— * I took the one less traveled by, * And that has made all the difference.」 * * Distributed under terms of the GNU AGPLv3+ license. */ #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> typedef long long ll; typedef unsigned long long ull; inline bool isdigit( const char cur ) { return cur >= '0' && cur <= '9'; }/*{{{*/ template <class T> T Max( T a, T b ) { return a > b? a: b; } template <class T> T Min( T a, T b ) { return a < b? a: b; } template <class T> void chk_Max( T &a, T b ) { if( b > a ) a = b; } template <class T> void chk_Min( T &a, T b ) { if( b < a ) a = b; } template <typename T> T read() { T sum = 0, fl = 1; char ch = getchar(); for (; isdigit(ch) == 0; ch = getchar()) if (ch == '-') fl = -1; for (; isdigit(ch); ch = getchar()) sum = sum * 10 + ch - '0'; return sum * fl; } template <class T> T pow( T a, int p ) { T res = 1; while( p ) { if( p & 1 ) res = res * a; a = a * a; p >>= 1; } return res; }/*}}}*/ ll pow10[50]; int int_len( ll cur ) { int res = 0; while( cur ) { res ++; cur /= 10; } return res; } int get_pos( ll cur, int pos ) { int res = 0; while( pos ) { pos --; res = ( cur % 10 ); cur /= 10; } return res; } int len_allow( int cur ) { return ( cur / 2 ) + ( cur & 1 ); } void check( int bit[], int len ) { int cnt = 0; for( int i = 1; i <= len; i ++ ) { if( bit[i] > 18 ) return ; if( bit[i] != bit[ i - 1 ] ) cnt ++; } if( cnt == 1 ) { for( int i = 1; i <= 9; i ++ ) { } } } int main() { #ifdef woshiluo freopen( "spoj.3110.in", "r", stdin ); freopen( "spoj.3110.out", "w", stdout ); #endif int T = read<int>(); pow10[1] = 1; for( int i = 2; i <= 20; i ++ ) { pow10[i] = pow10[ i - 1 ] * 10LL; } while( T -- ) { ll n = read<ll>(); int len = int_len(n); for( int i = 1; i <= len; i ++ ) { bit[i] = ( n % 10 ); n /= 10; } for( int sta = 0; sta <= full_pow(len); sta ++ ) { ll cur = n; for( int i = 1; i <= len; i ++ ) { if( sta & ( 1 << ( i - 1 ) ) ) { bit[i] += 10; bit[ i + 1 ] -= 1; } } check(bit); for( int i = 1; i <= len; i ++ ) { if( sta & ( 1 << ( i - 1 ) ) ) { bit[i] -= 10; bit[ i + 1 ] += 1; } } } } }
18.825397
81
0.483558
woshiluo
695e5d32ce89b112824ffb0002b2145098deae67
1,210
cpp
C++
console/src/boost_1_78_0/libs/core/test/allocator_allocate_hint_test.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
106
2015-08-07T04:23:50.000Z
2020-12-27T18:25:15.000Z
console/src/boost_1_78_0/libs/core/test/allocator_allocate_hint_test.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
130
2016-06-22T22:11:25.000Z
2020-11-29T20:24:09.000Z
Libs/boost_1_76_0/libs/core/test/allocator_allocate_hint_test.cpp
Antd23rus/S2DE
47cc7151c2934cd8f0399a9856c1e54894571553
[ "MIT" ]
41
2015-07-08T19:18:35.000Z
2021-01-14T16:39:56.000Z
/* Copyright 2020 Glen Joseph Fernandes (glenjofe@gmail.com) Distributed under the Boost Software License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt) */ #include <boost/core/allocator_access.hpp> #include <boost/core/lightweight_test.hpp> template<class T> struct A1 { typedef T value_type; typedef std::size_t size_type; typedef T* pointer; typedef const T* const_pointer; template<class U> struct rebind { typedef A1<U> other; }; A1() : value() { } T* allocate(std::size_t n, const void*) { value = n; return 0; } std::size_t value; }; #if !defined(BOOST_NO_CXX11_ALLOCATOR) template<class T> struct A2 { typedef T value_type; A2() : value() { } T* allocate(std::size_t n) { value = n; return 0; } std::size_t value; }; #endif int main() { { A1<int> a; BOOST_TEST_NOT(boost::allocator_allocate(a, 5, 0)); BOOST_TEST_EQ(a.value, 5); } #if !defined(BOOST_NO_CXX11_ALLOCATOR) { A2<int> a; BOOST_TEST_NOT(boost::allocator_allocate(a, 5, 0)); BOOST_TEST_EQ(a.value, 5); } #endif return boost::report_errors(); }
20.166667
59
0.608264
vany152
69676198e764d8b2ddb74da6d92eee3001210006
5,442
cpp
C++
src/English/parse/en_DescOracle.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/English/parse/en_DescOracle.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/English/parse/en_DescOracle.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright 2008 by BBN Technologies Corp. // All Rights Reserved. #include "Generic/common/leak_detection.h" #include "English/parse/en_DescOracle.h" #include "Generic/parse/ParserTags.h" #include "English/parse/en_STags.h" #include "Generic/common/UnexpectedInputException.h" #include "Generic/common/UTF8Token.h" #include "Generic/common/SymbolHash.h" #include <boost/scoped_ptr.hpp> using namespace std; EnglishDescOracle::EnglishDescOracle(KernelTable* kernelTable, ExtensionTable* extensionTable, const char *inventoryFile) { _NP_NPPOS_Symbol = Symbol (L"S=NPPOS"); _S_NPPOS_Symbol = Symbol (L"NP=NPPOS"); _npChains = _new SymbolHash(1000); _wordNet = WordNet::getInstance(); ExtensionTable::iterator i; for (i = extensionTable->table->begin(); i != extensionTable->table->end(); ++i) { int numExtensions = (*i).second.length; BridgeExtension* be = (*i).second.data; for (int j = 0; j < numExtensions; j++) { wstring s_string = be[j].modifierChain.to_string(); if (s_string.find(L"=NP") != std::wstring::npos || s_string.find(L"NP") == 0 || s_string.find(L"NPA") == 0 || s_string.find(L"NPPOS") == 0) _npChains->add(be[j].modifierChain); } } KernelTable::iterator k; for (k = kernelTable->table->begin(); k != kernelTable->table->end(); ++k) { int numKernels = (*k).second.length; BridgeKernel* bk = (*k).second.data; for (int j = 0; j < numKernels; j++) { wstring s_string = bk[j].headChain.to_string(); if (s_string.find(L"=NP") != std::wstring::npos || s_string.find(L"NP") == 0 || s_string.find(L"NPA") == 0 || s_string.find(L"NPPOS") == 0) _npChains->add(bk[j].headChain); s_string = bk[j].modifierChain.to_string(); if (s_string.find(L"=NP") != std::wstring::npos || s_string.find(L"NP") == 0 || s_string.find(L"NPA") == 0 || s_string.find(L"NPPOS") == 0) _npChains->add(bk[j].modifierChain); } } readInventory(inventoryFile); } void EnglishDescOracle::readInventory(const char *filename) { boost::scoped_ptr<UTF8InputStream> stream_scoped_ptr(UTF8InputStream::build()); UTF8InputStream& stream(*stream_scoped_ptr); stream.open(filename); _significantHeadWords = _new SymbolHash(1000); UTF8Token token; while (!stream.eof()) { stream >> token; // ( if (token.symValue() != ParserTags::leftParen) break; stream >> token; // word _significantHeadWords->add(token.symValue()); //cout << token.chars() << " "; stream >> token; // ( stream >> token; // synsets stream >> token; // ( while (true) { stream >> token; // word or ) if (token.symValue() == ParserTags::rightParen) { stream >> token; // ) break; } if (token.symValue() == ParserTags::leftParen) { std::string msg = ""; msg += "In file: "; msg += filename; msg += "\nERROR: ill-formed synset"; throw UnexpectedInputException("EnglishDescOracle::readInventory", msg.c_str()); } _significantHeadWords->add(token.symValue()); } stream >> token; // ( stream >> token; // referent stream >> token; // type stream >> token; // ) stream >> token; // ( or ) if (token.symValue() == ParserTags::rightParen) continue; stream >> token; // relations stream >> token; // ( while (true) { stream >> token; // type stream >> token; // arg1 stream >> token; // arg2 stream >> token; // ) stream >> token; // ( or ) if (token.symValue() == ParserTags::rightParen) { stream >> token; // ) break; } if (token.symValue() != ParserTags::leftParen) { std::string msg = ""; msg += "In file: "; msg += filename; msg += "\nERROR: ill-formed inventory record"; throw UnexpectedInputException("EnglishDescOracle::readInventory", msg.c_str()); } } } stream.close(); } bool EnglishDescOracle::isPossibleDescriptor(ChartEntry *entry, Symbol chain) const { if (entry->constituentCategory == EnglishSTags::NPPOS || chain == _NP_NPPOS_Symbol || chain == _S_NPPOS_Symbol) { if (entry->isPreterminal) return false; // special fix for POSSESSIVES ChartEntry *entryIteratorParent = entry; ChartEntry *entryIterator = entry->rightChild; while (entryIterator->rightChild != 0) { entryIteratorParent= entryIterator; entryIterator = entryIterator->rightChild; } return entryIteratorParent->leftChild->headIsSignificant; } else if (isNounPhrase(entry, chain)) { // ALL OTHER NPs return entry->headIsSignificant; } else return false; } bool EnglishDescOracle::isPossibleDescriptorHeadWord(Symbol word) const { return _wordNet->isPerson(word) || _significantHeadWords->lookup(lowercaseSymbol(word)) || _significantHeadWords->lookup(_wordNet->stem_noun(word)); } bool EnglishDescOracle::isNounPhrase(ChartEntry *entry, Symbol chain) const { Symbol category = entry->constituentCategory; return category == EnglishSTags::NP || category == EnglishSTags::NPA || _npChains->lookup(chain); } Symbol EnglishDescOracle::lowercaseSymbol(Symbol s) const { wstring str = s.to_string(); wstring::size_type length = str.length(); for (unsigned i = 0; i < length; ++i) { str[i] = towlower(str[i]); } return Symbol(str.c_str()); }
28.793651
86
0.632672
BBN-E
69682c17cdab970b875faaae09fb844bed849ec8
3,377
cpp
C++
OverEngine/src/OverEngine/Physics/Collider2D.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
159
2020-03-16T14:46:46.000Z
2022-03-31T23:38:14.000Z
OverEngine/src/OverEngine/Physics/Collider2D.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
5
2020-11-22T14:40:20.000Z
2022-01-16T03:45:54.000Z
OverEngine/src/OverEngine/Physics/Collider2D.cpp
larrymason01/OverEngine
4e44fe8385cc1780f2189ee5135f70b1e69104fd
[ "MIT" ]
17
2020-06-01T05:58:32.000Z
2022-02-10T17:28:36.000Z
#include "pcheader.h" #include "Collider2D.h" #include "RigidBody2D.h" #include "OverEngine/Scene/TransformComponent.h" #include <box2d/b2_polygon_shape.h> #include <box2d/b2_circle_shape.h> namespace OverEngine { Ref<BoxCollisionShape2D> BoxCollisionShape2D::Create(const Vector2& size, const Vector2& offset, float rotation) { return CreateRef<BoxCollisionShape2D>(size, offset, rotation); } BoxCollisionShape2D::BoxCollisionShape2D(const Vector2& size, const Vector2& offset, float rotation) : m_Size(size), m_Rotation(rotation) { } void BoxCollisionShape2D::Invalidate(const Mat4x4& transform) { m_Shape.SetAsBox( m_Size.x / 2.0f, m_Size.y / 2.0f, { m_Offset.x, m_Offset.y }, m_Rotation ); std::array<b2Vec2, b2_maxPolygonVertices> transformedVertices; for (int i = 0; i < m_Shape.m_count; i++) { Vector4 vertex = Vector4{ m_Shape.m_vertices[i].x, m_Shape.m_vertices[i].y, 0.0f, 0.0f } * transform; transformedVertices[i] = b2Vec2(vertex.x, vertex.y); } m_Shape.Set(transformedVertices.data(), m_Shape.m_count); } Ref<CircleCollisionShape2D> CircleCollisionShape2D::Create(float radius) { return CreateRef<CircleCollisionShape2D>(radius); } CircleCollisionShape2D::CircleCollisionShape2D(float radius) : m_Radius(radius) { } void CircleCollisionShape2D::Invalidate(const Mat4x4& transform) { // TODO: Dynamic size m_Shape.m_p.Set(m_Offset.x, m_Offset.y); m_Shape.m_radius = m_Radius; } Ref<Collider2D> Collider2D::Create(const Collider2DProps& props) { return CreateRef<Collider2D>(props); } Collider2D::Collider2D(const Collider2DProps& props) : m_Props(props) { } Collider2D::~Collider2D() { if (m_FixtureHandle && m_BodyHandle && m_BodyHandle->m_BodyHandle) UnDeploy(); } void Collider2D::Deploy(RigidBody2D* rigidBody) { rigidBody->m_Colliders.push_back(shared_from_this()); m_BodyHandle = rigidBody; Invalidate(); } void Collider2D::UnDeploy() { m_BodyHandle->m_Colliders.erase(STD_CONTAINER_FIND(m_BodyHandle->m_Colliders, shared_from_this())); m_BodyHandle->m_BodyHandle->DestroyFixture(m_FixtureHandle); m_FixtureHandle = nullptr; m_BodyHandle = nullptr; } void Collider2D::Invalidate() { OE_CORE_ASSERT(m_BodyHandle && m_BodyHandle->m_BodyHandle, "Cannot (re)build a collider without a body or with an undeployed one.") OE_CORE_ASSERT(m_Props.Shape, "Cannot (re)build a collider with empty shape!"); if (m_FixtureHandle) m_BodyHandle->m_BodyHandle->DestroyFixture(m_FixtureHandle); b2FixtureDef def; auto& bodyTransform = m_BodyHandle->GetProps().AttachedEntity.GetComponent<TransformComponent>(); Mat4x4 shapeTransform = glm::inverse( glm::translate(Mat4x4(1.0f), { bodyTransform.GetPosition().x, bodyTransform.GetPosition().y, 0.0f }) * glm::rotate(Mat4x4(1.0f), glm::radians(bodyTransform.GetLocalEulerAngles().z), Vector3(0, 0, 1)) ) * m_Props.AttachedEntity.GetComponent<TransformComponent>().GetLocalToWorld(); def.shape = m_Props.Shape->GetBox2DShape(shapeTransform); def.friction = m_Props.Friction; def.restitution = m_Props.Bounciness; def.restitutionThreshold = m_Props.BouncinessThreshold; def.density = m_Props.Density; def.isSensor = m_Props.IsTrigger; m_FixtureHandle = m_BodyHandle->m_BodyHandle->CreateFixture(&def); } }
28.863248
133
0.73438
larrymason01
696a61fbdd22f698b70d7eabccf9db757f3d95a7
8,200
cxx
C++
xp_comm_proj/rd_dxf/src/dxfcir.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
3
2020-08-03T08:52:20.000Z
2021-04-10T11:55:49.000Z
xp_comm_proj/rd_dxf/src/dxfcir.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
null
null
null
xp_comm_proj/rd_dxf/src/dxfcir.cxx
avs/express-community
c699a68330d3b678b7e6bcea823e0891b874049c
[ "Apache-2.0" ]
1
2021-06-08T18:16:45.000Z
2021-06-08T18:16:45.000Z
/***************************************************************************** Copyright (c) 1995 by Advanced Visual Systems Inc. All Rights Reserved This software comprises unpublished confidential information of Advanced Visual Systems Inc. and may not be used, copied or made available to anyone, except in accordance with the license under which it is furnished. ****************************************************************************** Implementation of the DXFCircle class, which represents DXF circle objects. ****************************************************************************** *****************************************************************************/ #include <math.h> #include "dxfcir.hxx" #include "dxfprim.hxx" #include "blistcpp.hxx" #include "blistcpp.cxx" //## AWD: Added to resolve templates problem #include "dxfdefine.hxx" /********************* Macros and Manifest Constants **********************/ /* <none> */ /************************ Public Global Variables *************************/ /* <none> */ /************************ Private Type Definitions ************************/ /* <none> */ /******************* Private (Static) Global Variables ********************/ /* <none> */ /***************************************************************************** *********-------- Implementations of "DXFCircle" Methods --------********* *****************************************************************************/ /***************************************************************************** Method: DXFCircle::Make() Purpose: This is the static "virtual constructor" for the DXFCircle class. If the contents of the specified "group" object is recognized by this function as the start of the definition of a circle, then an instance of DXFCircle is created, and its attributes are read from the DXF file (via the "group" object). Params: group The DXFGroup object being used to read the DXF file. It is assumed that this object will initially contain the group that terminated the previous object definition. On exit, it will contain the group that terminates this object definition. State: It is assumed that the file pointer into the DXF file has been advanced into the BLOCKS or ENTITIES section. Returns: A pointer to a DXFCircle object (cast to DXFPrim *) if the current object was recognized as a DXF circle, or NULL if it wasn't. *****************************************************************************/ DXFPrim *DXFCircle::Make(DXFGroup &group,CLIST <DXFLayer> *firstLayer) { DXFPrim *instance = 0; if (group.DataCmp("CIRCLE")) instance = new DXFCircle(group, firstLayer); return instance; } /***************************************************************************** Method: DXFCircle::DXFCircle() Purpose: A Constructor for the DXFCircle class. Reads the center point and radius from the DXF file. Params: group The DXFGroup object being used to read the DXF file. It is assumed that this object will initially contain the group that terminated the previous object definition. On exit, it will contain the group that terminates this object definition. firstLayer start of the linked list fo LAYER information. This will be used to assign color if appropriate State: It is assumed that the file pointer into the DXF file has been advanced into the BLOCKS or ENTITIES section. *****************************************************************************/ DXFCircle::DXFCircle(DXFGroup &group, CLIST <DXFLayer> *firstLayer) : center(), radius(0.0) { isValid = 0; extrusion.SetX(0); extrusion.SetY(0); extrusion.SetZ(1); while (group.Read()) { if (group.Code() == 0) // stop at next entity definition break; switch (group.Code()) { case 10: // circle center x coordinate center.SetX(group.DataAsFloat()); break; case 20: // circle center y coordinate center.SetY(group.DataAsFloat()); break; case 30: // circle center z coordinate center.SetZ(group.DataAsDouble()); break; case 40: // circle radius radius = group.DataAsFloat(); break; case 210: extrusion.SetX(group.DataAsFloat()); break; case 220: extrusion.SetY(group.DataAsFloat()); break; case 230: extrusion.SetZ(group.DataAsFloat()); break; default: // we don't care about this group code DXFPrim::ReadCommon(group, firstLayer); // see if the base class wants it break; } } // Now that we have the circle data (radius, center), we need to // generate the connectivity information. // int m = GetNumPoints(); if (AddCellSet(m, 1, DXF_CELL_CHOOSE, DXF_CLOSED_POLYGON + DXF_CONVEX_POLYGON)) { if (group.ReverseNormals()) { for (int q = m - 1; q >= 0; q--) cellSetsTail->AddVertexIndex(q); } else { for (int q = 0; q < m; q++) cellSetsTail->AddVertexIndex(q); } isValid = 1; } } /***************************************************************************** Method: DXFCircle::GetPoints() Purpose: This function generates the vertices associated with this circle. The center and radius are given. The circle is assumed to lie in a plane parallel to the x-z plane. Params: array A float array in which to place the coordinates. It is assumed that this array is at least < GetNumPoints() > floats in length. offset An optional offset into the array, at which to start placing coordinates. Thus, if this parameter is supplied the array length must be < GetNumPoints() + offset > floats long. State: --- Returns: The number of *NUMBERS* (i.e. 3 times the number of vertices) placed in the array PLUS the starting offset, if any. *****************************************************************************/ int DXFCircle::GetPoints(float *array, int offset) { int i; DXFPoint3D Ax,Ay; int n = GetNumPoints(); float inc = 6.28318530718 / (float)(n-1); // 2*PI / n float X,Y,Z; float c=(extrusion.GetX()<0) ? (extrusion.GetX()*(-1)) : extrusion.GetX(); float d=(extrusion.GetY()<0) ? (extrusion.GetY()*(-1)) : extrusion.GetY(); float e=1.0/64.0; if((c<e) && (d<e)) { Ax.SetX(extrusion.GetZ()); Ax.SetY(0); Ax.SetZ(-1*extrusion.GetX()); } else { Ax.SetX(-1*extrusion.GetY()); Ax.SetY(extrusion.GetX()); Ax.SetZ(0); } float k=sqrt(1/(Ax.GetX()*Ax.GetX()+Ax.GetY()*Ax.GetY()+Ax.GetZ()*Ax.GetZ())); Ax.SetX(Ax.GetX()*k); Ax.SetY(Ax.GetY()*k); Ax.SetZ(Ax.GetZ()*k); Ay.SetX(extrusion.GetY()*Ax.GetZ()-extrusion.GetZ()*Ax.GetY()); Ay.SetY(extrusion.GetZ()*Ax.GetX()-extrusion.GetX()*Ax.GetZ()); Ay.SetZ(extrusion.GetX()*Ax.GetY()-extrusion.GetY()*Ax.GetX()); k=sqrt(1/(Ay.GetX()*Ay.GetX()+Ay.GetY()*Ay.GetY()+Ay.GetZ()*Ay.GetZ())); Ay.SetX(Ay.GetX()*k); Ay.SetY(Ay.GetY()*k); Ay.SetZ(Ay.GetZ()*k); printf("DXFCircle::GetPoints Az: %f %f %f Ax: %f %f %f Ay: %f %f %f \n",extrusion.GetX(),extrusion.GetY(),extrusion.GetZ(), Ax.GetX(),Ax.GetY(),Ax.GetZ(),Ay.GetX(),Ay.GetY(),Ay.GetZ()); for (i = 0, d = 0.0; i < n-1; i++, d += inc) { X = (radius * cos(d)) + center.GetX(); Y = (radius * sin(d)) + center.GetY(); Z = center.GetZ(); array[offset++]=X*Ax.GetX()+Y*Ay.GetX()+Z*extrusion.GetX(); array[offset++]=X*Ax.GetY()+Y*Ay.GetY()+Z*extrusion.GetY(); array[offset++]=X*Ax.GetZ()+Y*Ay.GetZ()+Z*extrusion.GetZ(); } X = radius + center.GetX(); Y = center.GetY(); Z = center.GetZ(); array[offset++]=X*Ax.GetX()+Y*Ay.GetX()+Z*extrusion.GetX(); array[offset++]=X*Ax.GetY()+Y*Ay.GetY()+Z*extrusion.GetY(); array[offset++]=X*Ax.GetZ()+Y*Ay.GetZ()+Z*extrusion.GetZ(); Dump(); return offset; } void DXFCircle::Dump() { float x, y, z; center.Get(&x, &y, &z); // printf(" Circle\n"); // printf(" Center = (%f, %f, %f)\n", x, y, z); // printf(" Radius = %f\n", radius); }
31.660232
126
0.547195
avs
696e2adb1c856cbe6e933baf77cee6137e5e2544
1,960
cpp
C++
openbabel-2.4.1/test/mmff94validate.cpp
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
1
2017-09-16T07:36:29.000Z
2017-09-16T07:36:29.000Z
openbabel-2.4.1/test/mmff94validate.cpp
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
null
null
null
openbabel-2.4.1/test/mmff94validate.cpp
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
null
null
null
/********************************************************************** obmmff94validate.cpp - Validate the MMFF94 implementation This program assumes that the following files are in the current working directory: MMFF94_dative.mol2 MMFF94_opti.log Both these files are from the MMFF94 validation suite wich can be found here: http://server.ccl.net/cca/data/MMFF94/ For Each molecule in the .mol2 file the energy is calculated using the openbabel MMFF94 implementation. The energy values of indivudual energy terms are also calculated (total bond energy, totral angle energy, ...). These resulults are compared with values from the MMFF94_opti.log file. The difference is geven and the relative error. The atomtypes are also checked, when succesfull, PASSED will be printed. When an atom has a wrong type, XXXX FAILED XXXX will be printed next to its type. Copyright (C) 2006 Tim Vandermeersch This file is part of the Open Babel project. For more information, see <http://openbabel.org/> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***********************************************************************/ // used to set import/export for Cygwin DLLs #ifdef WIN32 #define USING_OBDLL #endif #include <openbabel/babelconfig.h> #include <openbabel/base.h> #include <openbabel/mol.h> #include <openbabel/forcefield.h> #include <unistd.h> using namespace std; using namespace OpenBabel; int main(int argc,char **argv) { OBForceField* pFF = OBForceField::FindForceField("MMFF94"); pFF->Validate(); // test passed return 0; }
33.220339
74
0.714286
sxhexe
696faac99d2c95ddade3fad87333224c891deae0
2,345
cpp
C++
C++/08_Heap/MEDIUM_MEETING_ROOMS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/08_Heap/MEDIUM_MEETING_ROOMS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/08_Heap/MEDIUM_MEETING_ROOMS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
// Time complexity - O(n) // Space complexity - O(n), where n = number of intervals int minMeetingRooms(vector<Interval>& intervals) { int len = intervals.size(); int count = 0, maxCount = 0; vector<pair<int, int>> table; // total len of table should be 2xlen since we have both start and end for(int i=0; i<len; i++) { // pick up the start, mark with 1 table.push_back(pair<int, int>(intervals[i].start, 1)); // pick up the end, mark with -1 table.push_back(pair<int, int>(intervals[i].end, -1)); } // sort the vector with first - exactly what we need sort(table.begin(), table.end()); for(int i=0; i<table.size(); i++) { if(table[i].second == 1) count++; else count--; maxCount = max(count, maxCount); } return maxCount; } // Without using pairs int minMeetingRooms(vector<Interval>& intervals) { vector<int> starts, ends; for (const auto& i : intervals) { starts.push_back(i.start); ends.push_back(i.end); } sort(starts.begin(), starts.end()); sort(ends.begin(), ends.end()); int min_rooms = 0, cnt_rooms = 0; int s = 0, e = 0; while (s < starts.size()) { if (starts[s] < ends[e]) { ++cnt_rooms; // Acquire a room. // Update the min number of rooms. min_rooms = max(min_rooms, cnt_rooms); ++s; } else { --cnt_rooms; // Release a room. ++e; } } return min_rooms; } // There's another solution using min-heap or priority queue int minMeetingRooms(vector<Interval>& intervals) { sort(intervals.begin(), intervals.end(), [](Interval i1, Interval i2) {return i1.start < i2.start || (i1.start == i2.start && i1.end < i2.end);}) ; // Min heap // Why is there a greater than sign? auto comp = [](Interval i1, Interval i2){return i1.end > i2.end;}; priority_queue<Interval, vector<Interval>, decltype(comp)>pq(comp); int ans = 0; // Size of the heap correpsonds to the number of rooms currently in use for(auto interval : intervals) { while(!pq.empty() && pq.top().end <= interval.start) pq.pop(); pq.push(interval); ans = max(ans, pq.size()); } return ans; }
30.064103
104
0.565885
animeshramesh
69702480d8b79ff4e694a2454ca6fbdb760ac59d
4,163
hpp
C++
include/r3/tiled/r3-tiled-defn.hpp
ryantherileyman/riley-tiled-json-loader
b03edf3e375480d937f2692ae54f0046149a8f66
[ "MIT" ]
null
null
null
include/r3/tiled/r3-tiled-defn.hpp
ryantherileyman/riley-tiled-json-loader
b03edf3e375480d937f2692ae54f0046149a8f66
[ "MIT" ]
null
null
null
include/r3/tiled/r3-tiled-defn.hpp
ryantherileyman/riley-tiled-json-loader
b03edf3e375480d937f2692ae54f0046149a8f66
[ "MIT" ]
null
null
null
#include <optional> #include <string> #include <vector> #pragma once namespace r3 { namespace tiled { typedef enum class Tiled_CustomPropertyType { UNKNOWN, BOOLEAN, INTEGER, FLOAT, STRING, COLOR, OBJECT, FILE, } CustomPropertyType; typedef struct Tiled_CustomPropertyDefn { std::string name; CustomPropertyType type = CustomPropertyType::UNKNOWN; bool boolValue = false; int intValue = 0; double decimalValue = 0.0; std::string stringValue; } CustomPropertyDefn; namespace CustomPropertyDefnUtils { const CustomPropertyDefn& find(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); bool contains(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); bool containsOfType(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName, CustomPropertyType type); bool getBoolValue(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); int getIntValue(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); double getDecimalValue(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); const std::string& getStringValue(const std::vector<CustomPropertyDefn>& propertyDefnList, const std::string& propertyName); } typedef struct Tiled_TilesetImageDefn { std::string imagePath; int imageWidth = 0; int imageHeight = 0; } TilesetImageDefn; typedef struct Tiled_TilesetTileDefn { int id = 0; TilesetImageDefn imageDefn; std::vector<CustomPropertyDefn> propertyDefnList; } TilesetTileDefn; typedef enum class Tiled_TilesetType { UNKNOWN, IMAGE, TILE_LIST, } TilesetType; typedef struct Tiled_TilesetDefn { double version = 0.0; TilesetType type = TilesetType::UNKNOWN; std::string name; int columns = 0; int tileCount = 0; int tileWidth = 0; int tileHeight = 0; int margin = 0; int spacing = 0; TilesetImageDefn imageDefn; std::vector<TilesetTileDefn> tileDefnList; std::vector<CustomPropertyDefn> propertyDefnList; } TilesetDefn; typedef enum class Tiled_MapOrientationType { UNKNOWN, ORTHOGONAL, ISOMETRIC, STAGGERED, HEXAGONAL, } MapOrientationType; typedef enum class Tiled_MapLayerType { UNKNOWN, TILE, OBJECT, GROUP, } MapLayerType; typedef enum class Tiled_MapLayerObjectType { UNKNOWN, POINT, RECTANGLE, ELLIPSE, POLYLINE, POLYGON, TILE, TEXT, } MapLayerObjectType; namespace MapLayerObjectTypeUtils { bool expectsDimensions(MapLayerObjectType objectType); } typedef struct Tiled_MapLayerObjectPointDefn { double x = 0.0; double y = 0.0; } MapLayerObjectPointDefn; typedef struct Tiled_MapLayerObjectDefn { int id = 0; MapLayerObjectPointDefn position; double rotationDegrees = 0.0; double width = 0; double height = 0; MapLayerObjectType objectType = MapLayerObjectType::UNKNOWN; int tileGid = 0; std::vector<MapLayerObjectPointDefn> pointDefnList; std::string name; std::string type; std::vector<CustomPropertyDefn> propertyDefnList; } MapLayerObjectDefn; typedef struct Tiled_MapLayerDefn { int id = 0; MapLayerType type = MapLayerType::UNKNOWN; std::string name; int width = 0; int height = 0; std::vector<int> data; std::vector<MapLayerObjectDefn> objectDefnList; std::vector<struct Tiled_MapLayerDefn> layerDefnList; std::vector<CustomPropertyDefn> propertyDefnList; } MapLayerDefn; typedef struct Tiled_MapTilesetDefn { int firstGid = 0; std::string sourcePath; } MapTilesetDefn; typedef struct Tiled_MapDefn { double version = 0.0; MapOrientationType orientation = MapOrientationType::UNKNOWN; bool infinite = false; int width = 0; int height = 0; int tileWidth = 0; int tileHeight = 0; std::string backgroundColor; std::vector<MapTilesetDefn> tilesetDefnList; std::vector<MapLayerDefn> layerDefnList; std::vector<CustomPropertyDefn> propertyDefnList; } MapDefn; } }
25.539877
138
0.730963
ryantherileyman
69790fede38b797cbdb4c3c8b5aaf501bcaeb03d
4,553
cpp
C++
src/GeneralizedSolver.cpp
RokKos/eol-cloth
b9c6f55f25ba17f33532ea5eefa41fedd29c5206
[ "MIT" ]
null
null
null
src/GeneralizedSolver.cpp
RokKos/eol-cloth
b9c6f55f25ba17f33532ea5eefa41fedd29c5206
[ "MIT" ]
null
null
null
src/GeneralizedSolver.cpp
RokKos/eol-cloth
b9c6f55f25ba17f33532ea5eefa41fedd29c5206
[ "MIT" ]
null
null
null
#include "GeneralizedSolver.h" #include "matlabOutputs.h" #ifdef EOLC_MOSEK #include "external/SolverWrappers/Mosek/QuadProgMosek.h" #endif #ifdef EOLC_GUROBI #include "external/SolverWrappers/Gurobi/Gurobi.h" #endif using namespace std; using namespace Eigen; namespace EOL { GeneralizedSolver::GeneralizedSolver() : whichSolver(GeneralizedSolver::NoSolver) { } void generateMatlab(const SparseMatrix<double>& MDK, const VectorXd& b, const SparseMatrix<double>& Aeq, const VectorXd& beq, const SparseMatrix<double>& Aineq, const VectorXd& bineq, VectorXd& v) { mat_s2s_file(MDK, "MDK", "solver.m", true); vec_to_file(b, "b", "solver.m", false); mat_s2s_file(Aeq, "Aeq", "solver.m", false); vec_to_file(beq, "beq", "solver.m", false); mat_s2s_file(Aineq, "Aineq", "solver.m", false); vec_to_file(bineq, "bineq", "solver.m", false); vec_to_file(v, "v_input", "solver.m", false); } #ifdef EOLC_MOSEK bool mosekSolve(const SparseMatrix<double>& MDK, const VectorXd& b, const SparseMatrix<double>& Aeq, const VectorXd& beq, const SparseMatrix<double>& Aineq, const VectorXd& bineq, VectorXd& v) { QuadProgMosek* program = new QuadProgMosek(); double inf = numeric_limits<double>::infinity(); VectorXd xl; VectorXd xu; xl.setConstant(b.size(), -inf); xu.setConstant(b.size(), inf); program->setNumberOfVariables(b.size()); program->setNumberOfEqualities(beq.size()); program->setNumberOfInequalities(bineq.size()); program->setObjectiveMatrix(MDK); program->setObjectiveVector(b); program->setInequalityMatrix(Aineq); program->setInequalityVector(bineq); program->setEqualityMatrix(Aeq); program->setEqualityVector(beq); bool success = program->solve(); v = program->getPrimalSolution(); return success; } #endif #ifdef EOLC_GUROBI bool gurobiSolve(SparseMatrix<double>& MDK, const VectorXd& b, SparseMatrix<double>& Aeq, const VectorXd& beq, SparseMatrix<double>& Aineq, const VectorXd& bineq, VectorXd& v) { GurobiSparse qp(b.size(), beq.size(), bineq.size()); qp.displayOutput(false); SparseMatrix<double> Sb(b.sparseView()); SparseVector<double> Sbeq(beq.sparseView()); SparseVector<double> Sbineq(bineq.sparseView()); MDK.makeCompressed(); Sb.makeCompressed(); Aeq.makeCompressed(); Aineq.makeCompressed(); VectorXd XL, XU; double inf = numeric_limits<double>::infinity(); XL.setConstant(b.size(), -inf); XU.setConstant(b.size(), inf); bool success = qp.solve(MDK, Sb, Aeq, Sbeq, Aineq, Sbineq, XL, XU); v = qp.result(); return success; } #endif bool GeneralizedSolver::velocitySolve(const bool& fixedPoints, const bool& collisions, SparseMatrix<double>& MDK, const VectorXd& b, SparseMatrix<double>& Aeq, const VectorXd& beq, SparseMatrix<double>& Aineq, const VectorXd& bineq, VectorXd& v) { //if (true) { // generateMatlab(MDK, b, // Aeq, beq, // Aineq, bineq, // v); //} if (!collisions && false) { // Simplest case, a cloth with no fixed points and no collisions if (!fixedPoints) { ConjugateGradient<SparseMatrix<double>, Lower | Upper> cg; cg.compute(MDK); v = cg.solve(-b); //cout << v << endl; return true; } else { // If there are fixed points we can use KKT which is faster than solving a quadprog // the assumption is made that MDK and b have been built properly uppon making it here LeastSquaresConjugateGradient<SparseMatrix<double> > lscg; lscg.compute(MDK); v = lscg.solve(-b); return true; } } else { if (whichSolver == GeneralizedSolver::NoSolver) { cout << "The simulation has encountered a collision, but a quadratic programming solver has not been specified." << endl; cout << "Please either set an external quadratic programming solver, or avoid collisions in your simulation." << endl; abort(); } else if (whichSolver == GeneralizedSolver::Mosek) { #ifdef EOLC_MOSEK bool success = mosekSolve(MDK, b, Aeq, beq, Aineq, bineq, v); return success; #else cout << "ERROR:" << endl; cout << "Attempting to use the mosek solver without mosek support enabled" << endl; abort(); #endif } else if (whichSolver == GeneralizedSolver::Gurobi) { #ifdef EOLC_GUROBI bool success = gurobiSolve(MDK, b, Aeq, beq, Aineq, bineq, v); return success; #else cout << "ERROR:" << endl; cout << "Attempting to use the gurobi solver without gurobi support enabled" << endl; abort(); #endif } } return false; } }
26.166667
125
0.685702
RokKos
69799e0bd6ef9b0cf91ee2a66de9372578a70e1c
541
hpp
C++
include/member_thunk/details/heap/memory.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
9
2019-12-02T11:59:24.000Z
2022-02-28T06:34:59.000Z
include/member_thunk/details/heap/memory.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
29
2019-11-26T17:12:33.000Z
2020-10-06T04:58:53.000Z
include/member_thunk/details/heap/memory.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
null
null
null
#pragma once #include <cstddef> #include <cstdint> namespace member_thunk::details { struct memory_layout { std::uint32_t page_size, allocation_granularity; static memory_layout get_for_current_system(); }; void flush_instruction_cache(void* ptr, std::size_t size); void* virtual_alloc(void* address, std::size_t size, std::uint32_t type, std::uint32_t protection); std::uint32_t virtual_protect(void* ptr, std::size_t size, std::uint32_t protection); void virtual_free(void* ptr, std::size_t size, std::uint32_t free_type); }
28.473684
100
0.767098
sylveon
697b77a61fc476a64d7de58cdaa491b50f3d2fd9
3,361
cpp
C++
CCC/Stage2/15/2015 CCO solutions/CarsonIce.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
1
2017-10-01T00:51:39.000Z
2017-10-01T00:51:39.000Z
CCC/Stage2/15/2015 CCO solutions/CarsonIce.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
CCC/Stage2/15/2015 CCO solutions/CarsonIce.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
/* * CarsonIce.cpp * * Created on: May 8, 2015 * Author: Andy Y.F. Huang (azneye) */ #include <bits/stdc++.h> using namespace std; void make_case() { const int N = 200; freopen("input.txt", "w", stdout); printf("%d %d\n", N, N); for (int r = 0; r < N; r++) printf("%s\n", string(N, r % 2 ? 'S' : 'E').c_str()); fflush(stdout); } int main() { #ifdef AZN //make_case(); double start_t = clock(); freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); //freopen("azn.txt", "w", stderr); #endif ios::sync_with_stdio(false); cin.tie(NULL); int N, M; assert(cin >> N >> M); assert(1 <= min(N, M) && max(N, M) <= 2000); vector<string> grid(N); for (int r = 0; r < N; r++) { assert(cin >> grid[r]); assert((int )grid[r].size() == M); for (int c = 0; c < M; c++) assert(string("NSEW.").find(grid[r][c]) != string::npos); } vector<vector<int> > id(N, vector<int>(M, -1)); vector<pair<int, int> > loc; for (int r = 0; r < N; r++) { for (int c = 0; c < M; c++) { if (grid[r][c] != '.') { loc.push_back(make_pair(r, c)); id[r][c] = loc.size() - 1; } } } const int V = loc.size(); vector<vector<int> > adj(V); vector<int> deg(V, 0); for (int r = 0; r < N; r++) { for (int c = 0; c < M; c++) { if (grid[r][c] == '.') continue; const int at = id[r][c]; if (grid[r][c] == 'N') { for (int rr = r - 1; rr >= 0; rr--) { if (grid[rr][c] != '.') { adj[id[rr][c]].push_back(at); deg[at]++; if (grid[rr][c] == grid[r][c]) break; } } } else if (grid[r][c] == 'S') { for (int rr = r + 1; rr < N; rr++) { if (grid[rr][c] != '.') { adj[id[rr][c]].push_back(at); deg[at]++; if (grid[rr][c] == grid[r][c]) break; } } } else if (grid[r][c] == 'E') { for (int cc = c + 1; cc < M; cc++) { if (grid[r][cc] != '.') { adj[id[r][cc]].push_back(at); deg[at]++; if (grid[r][cc] == grid[r][c]) break; } } } else if (grid[r][c] == 'W') { for (int cc = c - 1; cc >= 0; cc--) { if (grid[r][cc] != '.') { adj[id[r][cc]].push_back(at); deg[at]++; if (grid[r][cc] == grid[r][c]) break; } } } } } srand(time(NULL)); queue<int> q; vector<int> temp; vector<pair<int, int> > res; for (int v = 0; v < V; v++) random_shuffle(adj[v].begin(), adj[v].end()); for (int v = 0; v < V; v++) if (deg[v] == 0) temp.push_back(v); random_shuffle(temp.begin(), temp.end()); for (int i = 0; i < (int) temp.size(); i++) q.push(temp[i]); while (!q.empty()) { const int at = q.front(); q.pop(); res.push_back(loc[at]); for (int i = 0; i < (int) adj[at].size(); i++) if (--deg[adj[at][i]] == 0) q.push(adj[at][i]); } if (V != (int) res.size()) { cerr << "Error: Cycle in graph" << endl; return 1; } for (int i = 0; i < (int) res.size(); i++) cout << '(' << res[i].first << ',' << res[i].second << ")\n"; #ifdef AZN cerr << "Took: " << ((clock() - start_t) / CLOCKS_PER_SEC); #endif return 0; }
25.270677
65
0.427551
zzh8829
697c3d3e82fe5126df47fa1f69582553efb1e9c3
3,775
cpp
C++
src/services/pcn-nat/src/serializer/RulePortForwardingAppendInputJsonObject.cpp
francescomessina/polycube
38f2fb4ffa13cf51313b3cab9994be738ba367be
[ "ECL-2.0", "Apache-2.0" ]
337
2018-12-12T11:50:15.000Z
2022-03-15T00:24:35.000Z
src/services/pcn-nat/src/serializer/RulePortForwardingAppendInputJsonObject.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
253
2018-12-17T21:36:15.000Z
2022-01-17T09:30:42.000Z
src/services/pcn-nat/src/serializer/RulePortForwardingAppendInputJsonObject.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
90
2018-12-19T15:49:38.000Z
2022-03-27T03:56:07.000Z
/** * nat API * nat API generated from nat.yang * * OpenAPI spec version: 1.0.0 * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/polycube-network/swagger-codegen.git * branch polycube */ /* Do not edit this file manually */ #include "RulePortForwardingAppendInputJsonObject.h" #include <regex> namespace io { namespace swagger { namespace server { namespace model { RulePortForwardingAppendInputJsonObject::RulePortForwardingAppendInputJsonObject() { m_externalIpIsSet = false; m_externalPortIsSet = false; m_protoIsSet = false; m_internalIpIsSet = false; m_internalPortIsSet = false; } RulePortForwardingAppendInputJsonObject::RulePortForwardingAppendInputJsonObject(const nlohmann::json &val) : JsonObjectBase(val) { m_externalIpIsSet = false; m_externalPortIsSet = false; m_protoIsSet = false; m_internalIpIsSet = false; m_internalPortIsSet = false; if (val.count("external-ip")) { setExternalIp(val.at("external-ip").get<std::string>()); } if (val.count("external-port")) { setExternalPort(val.at("external-port").get<uint16_t>()); } if (val.count("proto")) { setProto(val.at("proto").get<std::string>()); } if (val.count("internal-ip")) { setInternalIp(val.at("internal-ip").get<std::string>()); } if (val.count("internal-port")) { setInternalPort(val.at("internal-port").get<uint16_t>()); } } nlohmann::json RulePortForwardingAppendInputJsonObject::toJson() const { nlohmann::json val = nlohmann::json::object(); if (!getBase().is_null()) { val.update(getBase()); } if (m_externalIpIsSet) { val["external-ip"] = m_externalIp; } if (m_externalPortIsSet) { val["external-port"] = m_externalPort; } if (m_protoIsSet) { val["proto"] = m_proto; } if (m_internalIpIsSet) { val["internal-ip"] = m_internalIp; } if (m_internalPortIsSet) { val["internal-port"] = m_internalPort; } return val; } std::string RulePortForwardingAppendInputJsonObject::getExternalIp() const { return m_externalIp; } void RulePortForwardingAppendInputJsonObject::setExternalIp(std::string value) { m_externalIp = value; m_externalIpIsSet = true; } bool RulePortForwardingAppendInputJsonObject::externalIpIsSet() const { return m_externalIpIsSet; } uint16_t RulePortForwardingAppendInputJsonObject::getExternalPort() const { return m_externalPort; } void RulePortForwardingAppendInputJsonObject::setExternalPort(uint16_t value) { m_externalPort = value; m_externalPortIsSet = true; } bool RulePortForwardingAppendInputJsonObject::externalPortIsSet() const { return m_externalPortIsSet; } std::string RulePortForwardingAppendInputJsonObject::getProto() const { return m_proto; } void RulePortForwardingAppendInputJsonObject::setProto(std::string value) { m_proto = value; m_protoIsSet = true; } bool RulePortForwardingAppendInputJsonObject::protoIsSet() const { return m_protoIsSet; } void RulePortForwardingAppendInputJsonObject::unsetProto() { m_protoIsSet = false; } std::string RulePortForwardingAppendInputJsonObject::getInternalIp() const { return m_internalIp; } void RulePortForwardingAppendInputJsonObject::setInternalIp(std::string value) { m_internalIp = value; m_internalIpIsSet = true; } bool RulePortForwardingAppendInputJsonObject::internalIpIsSet() const { return m_internalIpIsSet; } uint16_t RulePortForwardingAppendInputJsonObject::getInternalPort() const { return m_internalPort; } void RulePortForwardingAppendInputJsonObject::setInternalPort(uint16_t value) { m_internalPort = value; m_internalPortIsSet = true; } bool RulePortForwardingAppendInputJsonObject::internalPortIsSet() const { return m_internalPortIsSet; } } } } }
21.571429
109
0.747285
francescomessina
697d81bf8257a86975e608626fe0149054138534
63
cc
C++
ld/unit-tests/test-cases/llvm-integration/main13.cc
kastiglione/zld
d3323188a8df4ac70d5c703f7fbad620a93de236
[ "MIT" ]
985
2020-02-25T19:53:08.000Z
2022-03-31T19:23:35.000Z
ld/unit-tests/test-cases/llvm-integration/main13.cc
kastiglione/zld
d3323188a8df4ac70d5c703f7fbad620a93de236
[ "MIT" ]
90
2020-02-28T03:06:05.000Z
2022-03-21T19:27:16.000Z
ld/unit-tests/test-cases/llvm-integration/main13.cc
kastiglione/zld
d3323188a8df4ac70d5c703f7fbad620a93de236
[ "MIT" ]
37
2020-02-27T11:52:16.000Z
2022-03-22T03:43:37.000Z
#include "a13.h" int main() { A a; a.foo(); return 0; }
7
16
0.492063
kastiglione
698119be3feede1485cbed6427d09f78b488859b
1,969
cpp
C++
src/raft/command_log.cpp
CheranMahalingam/Distributed-Video-Processor
2940b1d92f6f6d940304de24d79680f01c888c47
[ "MIT" ]
null
null
null
src/raft/command_log.cpp
CheranMahalingam/Distributed-Video-Processor
2940b1d92f6f6d940304de24d79680f01c888c47
[ "MIT" ]
null
null
null
src/raft/command_log.cpp
CheranMahalingam/Distributed-Video-Processor
2940b1d92f6f6d940304de24d79680f01c888c47
[ "MIT" ]
1
2022-01-09T22:43:46.000Z
2022-01-09T22:43:46.000Z
#include "command_log.h" namespace raft { CommandLog::CommandLog(const std::vector<std::string>& peer_ids) : commit_index_(-1), last_applied_(-1) { for (auto peer_id:peer_ids) { next_index_[peer_id] = 0; match_index_[peer_id] = -1; } } void CommandLog::AppendLog(const rpc::LogEntry& entry) { logger(LogLevel::Debug) << "Appending entry to log"; entries_.push_back(entry); } void CommandLog::InsertLog(int idx, const std::vector<rpc::LogEntry>& new_entries) { logger(LogLevel::Debug) << "Inserting entries to log, index =" << idx; entries_.insert(entries_.begin() + idx, new_entries.begin(), new_entries.end()); } int CommandLog::LastLogIndex() { return entries_.size() - 1; } int CommandLog::LastLogTerm() { if (entries_.size() > 0) { return entries_[LastLogIndex()].term(); } else { return -1; } } void CommandLog::set_entries(const std::vector<rpc::LogEntry>& entries) { entries_ = entries; } void CommandLog::set_next_index(const std::string peer_id, const int new_index) { next_index_[peer_id] = new_index; } void CommandLog::set_match_index(const std::string peer_id, const int new_index) { match_index_[peer_id] = new_index; } void CommandLog::set_commit_index(const int idx) { commit_index_ = idx; } void CommandLog::increment_last_applied() { last_applied_++; } std::vector<rpc::LogEntry> CommandLog::entries() const { return entries_; } std::vector<rpc::LogEntry> CommandLog::entries(const int begin) const { std::vector<rpc::LogEntry> new_entries(entries_.begin() + begin, entries_.end()); return new_entries; } int CommandLog::next_index(const std::string peer_id) { return next_index_[peer_id]; } int CommandLog::match_index(const std::string peer_id) { return match_index_[peer_id]; } int CommandLog::commit_index() const { return commit_index_; } int CommandLog::last_applied() const { return last_applied_; } }
24.308642
85
0.69223
CheranMahalingam
698142765169324076c34cf8ef418a1d8c2fb258
2,254
cpp
C++
Source/JsonHelper.cpp
NEWorldProject/Common
167d69e80aee5e86a8892bcfaec6bcd988f97493
[ "BSL-1.0", "Apache-2.0", "MIT" ]
null
null
null
Source/JsonHelper.cpp
NEWorldProject/Common
167d69e80aee5e86a8892bcfaec6bcd988f97493
[ "BSL-1.0", "Apache-2.0", "MIT" ]
null
null
null
Source/JsonHelper.cpp
NEWorldProject/Common
167d69e80aee5e86a8892bcfaec6bcd988f97493
[ "BSL-1.0", "Apache-2.0", "MIT" ]
null
null
null
// // Core: JsonHelper.cpp // NEWorld: A Free Game with Similar Rules to Minecraft. // Copyright (C) 2015-2018 NEWorld Team // // NEWorld is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // NEWorld is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General // Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with NEWorld. If not, see <http://www.gnu.org/licenses/>. // #include "Core/JsonHelper.h" #include "Core/Logger.h" #include <fstream> namespace { class JsonSaveHelper { public: JsonSaveHelper(Json& json, std::string filename) : mJson(json), mFilename(std::move(filename)) {} JsonSaveHelper(const JsonSaveHelper&) = delete; JsonSaveHelper& operator=(const JsonSaveHelper&) = delete; ~JsonSaveHelper() { writeJsonToFile(mFilename, mJson); } private: Json& mJson; std::string mFilename; }; } NWCOREAPI Json readJsonFromFile(std::string filename) { std::ifstream file(filename); if (file) { std::string content = std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()); if (!content.empty()) { try { return Json::parse(content); } catch (std::invalid_argument& exception) { warningstream << "Failed to load json " << filename << ": " << exception.what(); } } } return Json(); } NWCOREAPI void writeJsonToFile(std::string filename, Json& json) { const std::string& dump = json.dump(); if (!json.is_null()) std::ofstream(filename).write(dump.c_str(), dump.length()); } NWCOREAPI Json& getSettings() { static Json settings = readJsonFromFile(SettingsFilename + ".json"); static JsonSaveHelper helper(settings, SettingsFilename + ".json"); return settings; }
34.151515
96
0.653505
NEWorldProject
69814c6c4a87af20a91c217a5d17374af977e042
662
cpp
C++
bit_manipulation/binary_or_operator.cpp
mohitbaran/CPP-Programming
ee70007d8eaffbb82b297984a07dd6f65999a435
[ "MIT" ]
30
2020-09-30T19:16:04.000Z
2022-02-20T14:28:13.000Z
bit_manipulation/binary_or_operator.cpp
mohitbaran/CPP-Programming
ee70007d8eaffbb82b297984a07dd6f65999a435
[ "MIT" ]
168
2020-09-30T19:52:42.000Z
2021-10-22T03:55:57.000Z
bit_manipulation/binary_or_operator.cpp
mohitbaran/CPP-Programming
ee70007d8eaffbb82b297984a07dd6f65999a435
[ "MIT" ]
123
2020-09-30T19:16:12.000Z
2021-11-12T18:49:18.000Z
#include <stdio.h> /* g++ 64 bit int size is 4 bytes or operator table 1|1 = 1 1|0 = 1 0|1 = 1 0|0 = 0 */ int main() { int a = 15; /* 60 = 0000 0000 0000 0000 0000 0000 0000 1111 */ int b = 13; /* 13 = 0000 0000 0000 0000 0000 0000 0000 1101 */ int c = -1; /* -1 = 1111 1111 1111 1111 1111 1111 1111 1111*/ int d = -2; /* -2 = 1111 1111 1111 1111 1111 1111 1111 1110*/ /* Negative numbers are represented in 2's compliment form.*/ printf("Value of a | b is %d\n", a | b); /* 15 = 0000 0000 0000 0000 0000 0000 0000 1111 */ printf("Value of b | c is %d\n", c | d); /* -1 = 1111 1111 1111 1111 1111 1111 1111 1111*/ return 0; }
26.48
95
0.584592
mohitbaran
69826780a977a5bd09b4de0f7ac9e8d06f701019
18,465
cpp
C++
source/ocl.cpp
EwanC/WeeChess
8b9b69d5d9d2c2a873670d450230ad0e5c526494
[ "MIT" ]
1
2015-05-24T20:26:41.000Z
2015-05-24T20:26:41.000Z
source/ocl.cpp
EwanC/WeeChess
8b9b69d5d9d2c2a873670d450230ad0e5c526494
[ "MIT" ]
null
null
null
source/ocl.cpp
EwanC/WeeChess
8b9b69d5d9d2c2a873670d450230ad0e5c526494
[ "MIT" ]
null
null
null
#include "ocl.hpp" #include <cstring> #include <iostream> #include "types.hpp" OCL* OCL::m_instance = nullptr; // Singleton instance uint OCL::possible_pawn_moves = 12; uint OCL::possible_piece_moves = 30; #define QUOTE(name) #name #define STR(macro) QUOTE(macro) #define KERNEL_DIR STR(__DIR__) #define EVALKERNEL "evalKernel" #define PIECEMOVEKERNEL "moveKernel" #define WPAWNMOVEKERNEL "WhitePawnKernel" #define BPAWNMOVEKERNEL "BlackPawnKernel" #define PIECECAPTUREKERNEL "moveCapture" #define WPAWNCAPTUREKERNEL "WhitePawnCapture" #define BPAWNCAPTUREKERNEL "BlackPawnCapture" #define EVAL_PROGRAM_FILE "/EvalKernel.cl" #define MOVE_PROGRAM_FILE "/moveKernel.cl" // Most Valuable attacker, least valuable victim static int32_t MvvLvaScores[13][13] = { {141743112, 32767, -37664, 32767, -141682440, 32767, 54012236, 0, -37680, 32767, -136429924, 32767, 0}, {0, 105, 104, 103, 102, 101, 100, 105, 104, 103, 102, 101, 100}, {-37824, 205, 204, 203, 202, 201, 200, 205, 204, 203, 202, 201, 200}, {32767, 305, 304, 303, 302, 301, 300, 305, 304, 303, 302, 301, 300}, {4301065, 405, 404, 403, 402, 401, 400, 405, 404, 403, 402, 401, 400}, {32767, 505, 504, 503, 502, 501, 500, 505, 504, 503, 502, 501, 500}, {0, 605, 604, 603, 602, 601, 600, 605, 604, 603, 602, 601, 600}, {0, 105, 104, 103, 102, 101, 100, 105, 104, 103, 102, 101, 100}, {-1, 205, 204, 203, 202, 201, 200, 205, 204, 203, 202, 201, 200}, {0, 305, 304, 303, 302, 301, 300, 305, 304, 303, 302, 301, 300}, {16, 405, 404, 403, 402, 401, 400, 405, 404, 403, 402, 401, 400}, {0, 505, 504, 503, 502, 501, 500, 505, 504, 503, 502, 501, 500}, {1, 605, 604, 603, 602, 601, 600, 605, 604, 603, 602, 601, 600}}; std::string OCL::getSourceDir() { #ifdef KERNEL_DIR std::string file(KERNEL_DIR); #else std::string file(__FILE__); // assume .cl files in same dir size_t last_slash_idx = file.rfind('\\'); if (std::string::npos != last_slash_idx) { return file.substr(0, last_slash_idx); } last_slash_idx = file.rfind('/'); if (std::string::npos != last_slash_idx) { return file.substr(0, last_slash_idx); } #endif return file; } // Singleton class OCL* OCL::getInstance() { if (!m_instance) { m_instance = new OCL; } return m_instance; } OCL::OCL() { int err; /* Identify a platform */ err = clGetPlatformIDs(1, &m_platform, NULL); if (err < 0) { std::cout << "Couldn't locate an OCL platform " << err << "\n"; exit(1); } /* Access a device */ err = clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_GPU, 1, &m_device, NULL); if (err == CL_DEVICE_NOT_FOUND) { err = clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_CPU, 1, &m_device, NULL); } if (err < 0) { std::cout << "Couldn't locate an OCL device\n"; exit(1); } m_context = clCreateContext(NULL, 1, &m_device, NULL, NULL, &err); if (err < 0) { std::cout << "Couldn't create an OCL context\n"; exit(1); } char buffer[1024]; err = clGetDeviceInfo(m_device, CL_DEVICE_NAME, sizeof(buffer), buffer, NULL); std::cout << "OpenCL Device: " << buffer << std::endl; m_queue = clCreateCommandQueue(m_context, m_device, 0, &err); if (err < 0) { std::cout << "Couldn't create an OCL command queue\n"; exit(1); } BuildProgram(); m_evalKernel = clCreateKernel(m_evalProgram, EVALKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << EVALKERNEL << " " << err << std::endl; exit(1); } m_pieceMoveKernel = clCreateKernel(m_moveProgram, PIECEMOVEKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << PIECEMOVEKERNEL << " " << err << std::endl; exit(1); } m_wPawnMoveKernel = clCreateKernel(m_moveProgram, WPAWNMOVEKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << WPAWNMOVEKERNEL << " " << err << std::endl; exit(1); } m_bPawnMoveKernel = clCreateKernel(m_moveProgram, BPAWNMOVEKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << BPAWNMOVEKERNEL << " " << err << std::endl; exit(1); } m_pieceCaptureKernel = clCreateKernel(m_moveProgram, PIECECAPTUREKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << PIECECAPTUREKERNEL << " " << err << std::endl; exit(1); } m_wPawnCaptureKernel = clCreateKernel(m_moveProgram, WPAWNCAPTUREKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << WPAWNCAPTUREKERNEL << " " << err << std::endl; exit(1); } m_bPawnCaptureKernel = clCreateKernel(m_moveProgram, BPAWNCAPTUREKERNEL, &err); if (err < 0) { std::cout << "Couldn't create OCL kernel " << BPAWNCAPTUREKERNEL << " " << err << std::endl; exit(1); } } void OCL::BuildProgram() { int err; std::string evalFile = OCL::getSourceDir().append(EVAL_PROGRAM_FILE); FILE* fp = fopen(evalFile.c_str(), "r"); if (!fp) { std::cout << "Failed to read kernel file " << evalFile << std::endl; exit(1); } fseek(fp, 0, SEEK_END); size_t programSize = ftell(fp); rewind(fp); char* program_buffer = new char[programSize + 1]; program_buffer[programSize] = '\0'; size_t read_size = fread(program_buffer, sizeof(char), programSize, fp); if (read_size != programSize) std::cout << "Reading Error\n"; fclose(fp); /* Create program from file */ m_evalProgram = clCreateProgramWithSource(m_context, 1, (const char**)&program_buffer, &programSize, &err); if (err < 0) { std::cout << "Couldn't create the program\n"; exit(1); } /* Build program */ err = clBuildProgram(m_evalProgram, 0, NULL, NULL, NULL, NULL); if (err < 0) { std::cout << "Couldn't build program" << EVAL_PROGRAM_FILE << "\n"; char buffer[2048]; size_t length; clGetProgramBuildInfo(m_evalProgram, m_device, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &length); std::cout << "--- Build log ---\n " << buffer << std::endl; exit(1); } std::string moveFile = OCL::getSourceDir().append(MOVE_PROGRAM_FILE); fp = fopen(moveFile.c_str(), "r"); if (!fp) { std::cout << "Failed to read kernel file " << moveFile << std::endl; exit(1); } fseek(fp, 0, SEEK_END); programSize = ftell(fp); rewind(fp); program_buffer = new char[programSize + 1]; program_buffer[programSize] = '\0'; read_size = fread(program_buffer, sizeof(char), programSize, fp); if (read_size != programSize) std::cout << "Reading Error\n"; fclose(fp); /* Create program from file */ m_moveProgram = clCreateProgramWithSource(m_context, 1, (const char**)&program_buffer, &programSize, &err); if (err < 0) { std::cout << "Couldn't create the program\n"; exit(1); } /* Build program */ char macro_str[128]; sprintf(macro_str, "-DMAX_PAWN_MOVES=%u -DMAX_PIECE_MOVES=%u", OCL::possible_pawn_moves, OCL::possible_piece_moves); err = clBuildProgram(m_moveProgram, 0, NULL, macro_str, NULL, NULL); if (err < 0) { std::cout << "Couldn't build program" << MOVE_PROGRAM_FILE << "\n"; char buffer[2048]; size_t length; clGetProgramBuildInfo(m_moveProgram, m_device, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &length); std::cout << "--- Build log ---\n " << buffer << std::endl; exit(1); } } std::vector<Move> OCL::RunPawnMoveKernel(const Board& b, const bool capture) { std::vector<Move> pawn_move_vec; bitboard Bitboard = b.m_side == Colour::WHITE ? b.m_pList[Piece::wP] : b.m_pList[Piece::bP]; int pawns = Bitboard::countBits(Bitboard); if (pawns == 0) { return pawn_move_vec; } unsigned int* pawn_squares = new unsigned int[pawns]; for (int pceNum = 0; pceNum < pawns; ++pceNum) { int sq64 = (Bitboard::popBit(&Bitboard)); pawn_squares[pceNum] = SQ120(sq64); } int err = CL_SUCCESS; cl_mem square_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, pawns * sizeof(unsigned int), (void*)pawn_squares, &err); if (err < 0) { std::cout << "Couldn't create cl pawn square buffer " << err << "\n"; exit(1); } cl_mem pieces_buffer = clCreateBuffer(m_context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, TOTAL_SQUARES * sizeof(int), (void*)b.m_board, &err); if (err < 0) { std::cout << "Couldn't create cl pawn peices buffer\n"; exit(1); } cl_mem Enpass_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(unsigned int), (void*)&b.m_enPas, &err); if (err < 0) { std::cout << "Couldn't create cl pawn enpass buffer\n"; exit(1); } const uint move_buffer_size = pawns * OCL::possible_pawn_moves; unsigned long moves[move_buffer_size]; for (int i = 0; i < move_buffer_size; ++i) { moves[i] = 0; } cl_mem moves_buffer = clCreateBuffer(m_context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, move_buffer_size * sizeof(unsigned long), moves, &err); if (err < 0) { std::cout << "Couldn't create cl wp moves buffer\n"; exit(1); } const size_t global_size = pawns; const size_t local_size = pawns; cl_kernel kernel; if (capture) { kernel = b.m_side == Colour::WHITE ? m_wPawnCaptureKernel : m_bPawnCaptureKernel; } else { kernel = b.m_side == Colour::WHITE ? m_wPawnMoveKernel : m_bPawnMoveKernel; } /* Set kernel args */ err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &square_buffer); err |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &pieces_buffer); err |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &Enpass_buffer); err |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &moves_buffer); if (err < 0) { std::cout << "Couldn't set pawn move kernel arg\n"; exit(1); } /* Enqueue Kernel*/ err = clEnqueueNDRangeKernel(m_queue, kernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't enqueue the kernel " << err << "\n"; exit(1); } /* Enqueue ReadBuffer */ err = clEnqueueReadBuffer(m_queue, moves_buffer, CL_TRUE, 0, move_buffer_size * sizeof(unsigned long), moves, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't read cl buffer\n"; exit(1); } err = clFinish(m_queue); if (err < 0) { std::cout << "Couldn't wait for CL tae finish\n"; exit(1); } for (int i = 0; i < move_buffer_size; ++i) { if (moves[i] == 0) { continue; } Move m; m.m_move = moves[i]; if (m.m_move & MFLAGEP) m.m_score = 105 + 1000000; if (CAPTURED(m.m_move)) m.m_score = MvvLvaScores[CAPTURED(m.m_move)][b.m_board[FROMSQ(m.m_move)]] + 1000000; else if (b.m_searchKillers[0][b.m_ply] == m.m_move) m.m_score = 900000; else if (b.m_searchKillers[1][b.m_ply] == m.m_move) m.m_score = 800000; else m.m_score = b.m_searchHistory[b.m_board[FROMSQ(m.m_move)]][TOSQ(m.m_move)]; pawn_move_vec.push_back(m); } clReleaseMemObject(square_buffer); clReleaseMemObject(pieces_buffer); clReleaseMemObject(Enpass_buffer); clReleaseMemObject(moves_buffer); delete[] pawn_squares; return pawn_move_vec; } void OCL::SetPieceHostBuffer(unsigned int* pieces, bitboard bb, unsigned int& itr, const unsigned short piece_count) { int count = Bitboard::countBits(bb); for (int pceNum = 0; pceNum < piece_count; ++pceNum) { if (pceNum < count) { int sq120 = SQ120(Bitboard::popBit(&bb)); pieces[itr++] = sq120; } else { itr++; } } } std::vector<Move> OCL::RunPieceMoveKernel(const Board& b, const bool capture) { static const Piece SlidePce[2][3] = {{wB, wR, wQ}, {bB, bR, bQ}}; static const Piece NonSlidePce[2][2] = {{wN, wK}, {bN, bK}}; std::vector<Move> piece_move_vec; ushort max_pieces = 0; bitboard Nbb = b.m_pList[static_cast<int>(NonSlidePce[b.m_side][0])]; ushort bbCount = Bitboard::countBits(Nbb); max_pieces = bbCount > max_pieces ? bbCount : max_pieces; bitboard Bbb = b.m_pList[static_cast<int>(SlidePce[b.m_side][0])]; bbCount = Bitboard::countBits(Bbb); max_pieces = bbCount > max_pieces ? bbCount : max_pieces; bitboard Rbb = b.m_pList[static_cast<int>(SlidePce[b.m_side][1])]; bbCount = Bitboard::countBits(Rbb); max_pieces = bbCount > max_pieces ? bbCount : max_pieces; bitboard Qbb = b.m_pList[static_cast<int>(SlidePce[b.m_side][2])]; bbCount = Bitboard::countBits(Qbb); max_pieces = bbCount > max_pieces ? bbCount : max_pieces; if (max_pieces == 0) { max_pieces = 1; } const size_t global_size = 5 * max_pieces; const size_t local_size = max_pieces; // Piece Buffer // WB, WB, WR, WR, WQ, WN, WN, WK unsigned int* pieces = new unsigned int[global_size]; unsigned int itr = 0; for (int i = 0; i < global_size; ++i) { pieces[i] = Square::NO_SQ; } SetPieceHostBuffer(pieces, Nbb, itr, local_size); SetPieceHostBuffer(pieces, Bbb, itr, local_size); SetPieceHostBuffer(pieces, Rbb, itr, local_size); SetPieceHostBuffer(pieces, Qbb, itr, local_size); bitboard Kbb = b.m_pList[static_cast<int>(NonSlidePce[b.m_side][1])]; SetPieceHostBuffer(pieces, Kbb, itr, local_size); int err; cl_mem square_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, global_size * sizeof(unsigned int), (void*)pieces, &err); if (err < 0) { std::cout << "Couldn't create cl side square buffer\n"; exit(1); } cl_mem side_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int), (void*)&b.m_side, &err); if (err < 0) { std::cout << "Couldn't create cl piece side buffer\n"; exit(1); } cl_mem pieces_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, TOTAL_SQUARES * sizeof(int), (void*)b.m_board, &err); if (err < 0) { std::cout << "Couldn't create cl pawn peices buffer\n"; exit(1); } const uint move_buffer_size = global_size * OCL::possible_piece_moves; unsigned long moves[move_buffer_size]; for (int i = 0; i < move_buffer_size; ++i) moves[i] = 0; cl_mem moves_buffer = clCreateBuffer(m_context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, move_buffer_size * sizeof(unsigned long), moves, &err); if (err < 0) { std::cout << "Couldn't create cl side moves buffer\n"; exit(1); } cl_kernel kernel = capture ? m_pieceCaptureKernel : m_pieceMoveKernel; /* Set kernel args */ err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &square_buffer); if (err < 0) { std::cout << "A Couldn't set Piece move kernel arg\n"; exit(1); } err |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &side_buffer); if (err < 0) { std::cout << "B Couldn't set Piece move kernel arg\n"; exit(1); } err |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &pieces_buffer); if (err < 0) { std::cout << "C Couldn't set Piece move kernel arg: " << err << "\n"; exit(1); } err |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &moves_buffer); if (err < 0) { std::cout << "D Couldn't set Piece move kernel arg\n"; exit(1); } /* Enqueue Kernel*/ err = clEnqueueNDRangeKernel(m_queue, kernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't enqueue the kernel " << err << "\n"; exit(1); } /* Enqueue ReadBuffer */ err = clEnqueueReadBuffer(m_queue, moves_buffer, CL_TRUE, 0, move_buffer_size * sizeof(unsigned long), moves, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't read cl buffer\n"; exit(1); } err = clFinish(m_queue); if (err < 0) { std::cout << "Couldn't wait for CL tae finish\n"; exit(1); } for (int i = 0; i < move_buffer_size; ++i) { if (moves[i] == 0) { continue; } Move m; m.m_move = moves[i]; if (CAPTURED(m.m_move)) m.m_score = MvvLvaScores[CAPTURED(m.m_move)][b.m_board[FROMSQ(m.m_move)]] + 1000000; else if (b.m_searchKillers[0][b.m_ply] == m.m_move) m.m_score = 900000; else if (b.m_searchKillers[1][b.m_ply] == m.m_move) m.m_score = 800000; else m.m_score = b.m_searchHistory[b.m_board[FROMSQ(m.m_move)]][TOSQ(m.m_move)]; piece_move_vec.push_back(m); } clReleaseMemObject(square_buffer); clReleaseMemObject(pieces_buffer); clReleaseMemObject(side_buffer); clReleaseMemObject(moves_buffer); delete[] pieces; return piece_move_vec; } int OCL::RunEvalKernel(const Board& board) { /* local vars */ const unsigned int bitboards_per_board = 13; const unsigned int num_boards = 1; const size_t global_size = bitboards_per_board * num_boards; const size_t local_size = bitboards_per_board; int scores[num_boards] = {0}; /* Create Buffers */ int err; cl_mem bitboard_buffer = clCreateBuffer(m_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, bitboards_per_board * sizeof(bitboard), (void*)board.m_pList, &err); if (err < 0) { std::cout << "Couldn't create cl buffer\n"; exit(1); } cl_mem score_buffer = clCreateBuffer(m_context, CL_MEM_READ_WRITE, num_boards * sizeof(int), scores, &err); if (err < 0) { std::cout << "Couldn't create cl buffer\n"; exit(1); } /* Set kernel args */ err = clSetKernelArg(m_evalKernel, 0, sizeof(cl_mem), &bitboard_buffer); err |= clSetKernelArg(m_evalKernel, 1, sizeof(cl_mem), &score_buffer); err |= clSetKernelArg(m_evalKernel, 2, num_boards * sizeof(cl_int), NULL); if (err < 0) { std::cout << "Couldn't set kernel arg\n"; exit(1); } /* Enqueue Kernel*/ err = clEnqueueNDRangeKernel(m_queue, m_evalKernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't enqueue the kernel " << err << "\n"; exit(1); } /* Enqueue ReadBuffer */ err = clEnqueueReadBuffer(m_queue, score_buffer, CL_TRUE, 0, num_boards * sizeof(int), scores, 0, NULL, NULL); if (err < 0) { std::cout << "Couldn't read cl buffer\n"; exit(1); } err = clFinish(m_queue); if (err < 0) { std::cout << "Couldn't wait for CL tae finish\n"; exit(1); } clReleaseMemObject(bitboard_buffer); clReleaseMemObject(score_buffer); // Just one board for now return scores[0]; } OCL::~OCL() { /* Deallocate resources */ clReleaseContext(m_context); clReleaseCommandQueue(m_queue); clReleaseKernel(m_evalKernel); }
31.403061
120
0.64013
EwanC
698271f513e4b240e986900576659d242cb9b2da
2,849
cpp
C++
quantitative_finance/L2/tests/InflationBlackCapFloorEngine/kernel/INFLATION_k0.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2021-06-14T17:02:06.000Z
2021-06-14T17:02:06.000Z
quantitative_finance/L2/tests/InflationBlackCapFloorEngine/kernel/INFLATION_k0.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
null
null
null
quantitative_finance/L2/tests/InflationBlackCapFloorEngine/kernel/INFLATION_k0.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2021-04-28T05:58:38.000Z
2021-04-28T05:58:38.000Z
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "inflation_capfloor_engine_kernel.hpp" #ifndef __SYNTHESIS__ #include <iostream> using namespace std; #endif extern "C" void INFLATION_k0(int type, DT forwardRate, DT cfRate[2], DT nomial, DT gearing, DT accrualTime, int size, DT time[LEN], DT rate[LEN], int optionlets, DT NPV[N]) { #pragma HLS INTERFACE m_axi port = NPV bundle = gmem0 offset = slave num_read_outstanding = 16 num_write_outstanding = \ 16 max_read_burst_length = 32 max_write_burst_length = 32 #pragma HLS INTERFACE m_axi port = cfRate bundle = gmem1 offset = slave num_read_outstanding = \ 16 num_write_outstanding = 16 max_read_burst_length = 32 max_write_burst_length = 32 #pragma HLS INTERFACE m_axi port = time bundle = gmem2 offset = slave num_read_outstanding = \ 16 num_write_outstanding = 16 max_read_burst_length = 32 max_write_burst_length = 32 #pragma HLS INTERFACE m_axi port = rate bundle = gmem3 offset = slave num_read_outstanding = \ 16 num_write_outstanding = 16 max_read_burst_length = 32 max_write_burst_length = 32 #pragma HLS INTERFACE s_axilite port = type bundle = control #pragma HLS INTERFACE s_axilite port = forwardRate bundle = control #pragma HLS INTERFACE s_axilite port = cfRate bundle = control #pragma HLS INTERFACE s_axilite port = nomial bundle = control #pragma HLS INTERFACE s_axilite port = gearing bundle = control #pragma HLS INTERFACE s_axilite port = accrualTime bundle = control #pragma HLS INTERFACE s_axilite port = size bundle = control #pragma HLS INTERFACE s_axilite port = time bundle = control #pragma HLS INTERFACE s_axilite port = rate bundle = control #pragma HLS INTERFACE s_axilite port = optionlets bundle = control #pragma HLS INTERFACE s_axilite port = NPV bundle = control #pragma HLS INTERFACE s_axilite port = return bundle = control InflationCapFloorEngine<DT, LEN> cf; cf.init(type, forwardRate, cfRate, nomial, gearing, accrualTime, size, time, rate); NPV[0] = cf.calcuNPV(optionlets); }
47.483333
120
0.689365
vmayoral
6982a79a7ed4d4c347f9fa0b118d184a642e8f62
8,832
cpp
C++
beringei/lib/PersistentKeyList.cpp
pidb/Gorilla
75c3002b179d99c8709323d605e7d4b53484035c
[ "BSD-3-Clause" ]
2,780
2016-12-22T19:25:26.000Z
2018-05-21T11:29:42.000Z
beringei/lib/PersistentKeyList.cpp
pidb/Gorilla
75c3002b179d99c8709323d605e7d4b53484035c
[ "BSD-3-Clause" ]
57
2016-12-23T09:22:18.000Z
2018-05-04T06:26:48.000Z
beringei/lib/PersistentKeyList.cpp
pidb/Gorilla
75c3002b179d99c8709323d605e7d4b53484035c
[ "BSD-3-Clause" ]
254
2016-12-22T20:53:12.000Z
2018-05-16T06:14:10.000Z
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "beringei/lib/PersistentKeyList.h" #include <folly/compression/Compression.h> #include <folly/io/IOBuf.h> #include <gflags/gflags.h> #include <glog/logging.h> #include "beringei/lib/GorillaStatsManager.h" namespace facebook { namespace gorilla { // For reads and compaction. Can probably be arbitrarily large. const static size_t kLargeBufferSize = 1 << 24; // Flush after 4k of keys. const static size_t kSmallBufferSize = 1 << 12; const static int kTempFileId = 0; const int KRetryFileOpen = 3; constexpr static char kCompressedFileWithTimestampsMarker = '2'; constexpr static char kUncompressedFileWithTimestampsMarker = '3'; constexpr static char kAppendMarker = 'a'; constexpr static char kDeleteMarker = 'd'; const static std::string kFileType = "key_list"; const static std::string kFailedCounter = "failed_writes." + kFileType; // Marker bytes to determine if the file is compressed or not and if // there are categories or not. const static uint32_t kHardFlushIntervalSecs = 120; PersistentKeyList::PersistentKeyList( int64_t shardId, const std::string& dataDirectory) : activeList_({nullptr, ""}), files_(shardId, kFileType, dataDirectory), lock_(), shard_(shardId) { GorillaStatsManager::addStatExportType(kFailedCounter, SUM); // Randomly select the next flush time within the interval to spread // the fflush calls between shards. nextHardFlushTimeSecs_ = time(nullptr) + random() % kHardFlushIntervalSecs; openNext(); } bool PersistentKeyList::appendKey( uint32_t id, const char* key, uint16_t category, int32_t timestamp) { std::lock_guard<std::mutex> guard(lock_); if (activeList_.file == nullptr) { return false; } writeKey(id, key, category, timestamp); return true; } bool PersistentKeyList::compactToFile( FILE* f, const std::string& fileName, std::function<std::tuple<uint32_t, const char*, uint16_t, int32_t>()> generator) { folly::fbstring buffer; for (auto key = generator(); std::get<1>(key) != nullptr; key = generator()) { appendBuffer( buffer, std::get<0>(key), std::get<1>(key), std::get<2>(key), std::get<3>(key)); } if (buffer.length() == 0) { fclose(f); return false; } try { auto ioBuffer = folly::IOBuf::wrapBuffer(buffer.data(), buffer.length()); auto codec = folly::io::getCodec( folly::io::CodecType::ZLIB, folly::io::COMPRESSION_LEVEL_BEST); auto compressed = codec->compress(ioBuffer.get()); compressed->coalesce(); if (fwrite(&kCompressedFileWithTimestampsMarker, sizeof(char), 1, f) != 1 || fwrite(compressed->data(), sizeof(char), compressed->length(), f) != compressed->length()) { PLOG(ERROR) << "Could not write to the temporary key file " << fileName; GorillaStatsManager::addStatValue(kFailedCounter, 1); fclose(f); return false; } LOG(INFO) << "Compressed key list from " << buffer.length() << " bytes to " << compressed->length(); } catch (std::exception& e) { LOG(ERROR) << "Compression failed:" << e.what(); fclose(f); return false; } // Swap the new data in for the old. fclose(f); return true; } bool PersistentKeyList::compactToBuffer( std::function<std::tuple<uint32_t, const char*, uint16_t, int32_t>()> generator, uint64_t seq, folly::fbstring& out) { folly::fbstring buffer; for (auto key = generator(); std::get<1>(key) != nullptr; key = generator()) { appendBuffer( buffer, std::get<0>(key), std::get<1>(key), std::get<2>(key), std::get<3>(key)); } if (buffer.empty()) { return false; } try { auto ioBuffer = folly::IOBuf::wrapBuffer(buffer.data(), buffer.length()); auto codec = folly::io::getCodec( folly::io::CodecType::ZLIB, folly::io::COMPRESSION_LEVEL_BEST); auto compressed = codec->compress(ioBuffer.get()); compressed->coalesce(); out.reserve(compressed->length() + 1 + 8); out.append((char*)(&seq), 8); out.append(&kCompressedFileWithTimestampsMarker, 1); out.append((char*)compressed->data(), compressed->length()); } catch (const std::exception& e) { LOG(ERROR) << "Compression failed:" << e.what(); return false; } return true; } void PersistentKeyList::compact( std::function<std::tuple<uint32_t, const char*, uint16_t, int32_t>()> generator) { // Direct appends to a new file. int64_t prev = openNext(); // Create a temporary compressed file. auto tempFile = files_.open(kTempFileId, "wb", kLargeBufferSize); if (!tempFile.file) { PLOG(ERROR) << "Could not open a temp file for writing keys"; GorillaStatsManager::addStatValue(kFailedCounter, 1); return; } if (!compactToFile(tempFile.file, tempFile.name, generator)) { return; } files_.rename(kTempFileId, prev); // Clean up remaining files. files_.clearTo(prev); } void PersistentKeyList::flush(bool hardFlush) { if (activeList_.file == nullptr) { openNext(); } if (activeList_.file != nullptr) { if (buffer_.length() > 0) { size_t written = fwrite( buffer_.data(), sizeof(char), buffer_.length(), activeList_.file); if (written != buffer_.length()) { PLOG(ERROR) << "Failed to flush key list file " << activeList_.name; GorillaStatsManager::addStatValue(kFailedCounter, 1); } buffer_ = ""; } if (hardFlush) { fflush(activeList_.file); } } else { // No file to flush to. LOG(ERROR) << "Could not flush key list for shard " << shard_ << " to disk. No open key_list file"; GorillaStatsManager::addStatValue(kFailedCounter, 1); } } void PersistentKeyList::clearEntireListForTests() { files_.clearAll(); openNext(); } int64_t PersistentKeyList::openNext() { std::lock_guard<std::mutex> guard(lock_); if (activeList_.file != nullptr) { fclose(activeList_.file); } std::vector<int64_t> ids = files_.ls(); int64_t activeId = ids.empty() ? 1 : ids.back() + 1; activeList_ = files_.open(activeId, "wb", kSmallBufferSize); int i = 0; while (activeList_.file == nullptr && i < KRetryFileOpen) { activeList_ = files_.open(activeId, "wb", kSmallBufferSize); i++; } if (activeList_.file == nullptr) { PLOG(ERROR) << "Couldn't open key_list." << activeId << " for writes (shard " << shard_ << ")"; return activeId - 1; } if (fwrite( &kUncompressedFileWithTimestampsMarker, sizeof(char), 1, activeList_.file) != 1) { PLOG(ERROR) << "Could not write to the key list file " << activeList_.name; GorillaStatsManager::addStatValue(kFailedCounter, 1); } return activeId - 1; } void PersistentKeyList::appendBuffer( folly::fbstring& buffer, uint32_t id, const char* key, uint16_t category, int32_t timestamp) { const char* bytes = (const char*)&id; for (int i = 0; i < sizeof(id); i++) { buffer += bytes[i]; } const char* categoryBytes = (const char*)&category; for (int i = 0; i < sizeof(category); i++) { buffer += categoryBytes[i]; } const char* timestampBytes = (const char*)&timestamp; for (int i = 0; i < sizeof(timestamp); i++) { buffer += timestampBytes[i]; } buffer += key; buffer += '\0'; } void PersistentKeyList::writeKey( uint32_t id, const char* key, uint16_t category, int32_t timestamp) { // Write to the internal buffer and only flush when needed. appendBuffer(buffer_, id, key, category, timestamp); bool flushHard = time(nullptr) > nextHardFlushTimeSecs_; if (flushHard) { nextHardFlushTimeSecs_ = time(nullptr) + kHardFlushIntervalSecs; } if (buffer_.length() >= kSmallBufferSize || flushHard) { flush(flushHard); } } std::unique_ptr<PersistentKeyListIf> LocalPersistentKeyListFactory::getPersistentKeyList( int64_t shardId, const std::string& dir) const { return std::make_unique<PersistentKeyList>(shardId, dir); } void PersistentKeyList::appendMarker(folly::fbstring& buffer, bool compressed) { if (compressed) { buffer += kCompressedFileWithTimestampsMarker; } else { buffer += kUncompressedFileWithTimestampsMarker; } } void PersistentKeyList::appendOpMarker(folly::fbstring& buffer, bool append) { if (append) { buffer += kAppendMarker; } else { buffer += kDeleteMarker; } } } // namespace gorilla } // namespace facebook
28.127389
80
0.657043
pidb
6982ae7daea8bc7ac6ef3a9e090b5eb2fe8ccd3b
18,104
cpp
C++
engine/rendering/interface_renderer.cpp
jose-villegas/VCT_Engine
5ac2077e6ffc240a6d1f0ac0f033ac81e8ed57e3
[ "MIT" ]
459
2016-03-16T04:11:37.000Z
2022-03-31T08:05:21.000Z
engine/rendering/interface_renderer.cpp
jose-villegas/VCT_Engine
5ac2077e6ffc240a6d1f0ac0f033ac81e8ed57e3
[ "MIT" ]
2
2016-08-08T18:26:27.000Z
2017-05-08T23:42:22.000Z
engine/rendering/interface_renderer.cpp
jose-villegas/VCT_Engine
5ac2077e6ffc240a6d1f0ac0f033ac81e8ed57e3
[ "MIT" ]
47
2016-05-31T15:55:52.000Z
2022-03-28T14:49:40.000Z
#include <GL/glew.h> #include <GLFW/glfw3.h> #include "interface_renderer.h" #ifdef _WIN32 #undef APIENTRY #define GLFW_EXPOSE_NATIVE_WIN32 #define GLFW_EXPOSE_NATIVE_WGL #include <GLFW/glfw3native.h> #endif #include "../rendering/render_window.h" #include <glm/mat4x4.hpp> #include <glm/gtc/type_ptr.hpp> std::unique_ptr<InterfaceRenderer::RendererData> InterfaceRenderer::renderer = nullptr; InterfaceRenderer::InterfaceRenderer() { } InterfaceRenderer::~InterfaceRenderer() { } void InterfaceRenderer::RenderDrawList(ImDrawData * drawData) { // Backup GL state GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src); GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst); GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); GLboolean last_enable_blend = glIsEnabled(GL_BLEND); GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); // Setup render state: alpha-blending enabled, // no face culling, no depth testing, scissor enabled glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); // Handle cases of screen coordinates != from // framebuffer coordinates (e.g. retina displays) ImGuiIO &io = ImGui::GetIO(); float fb_height = io.DisplaySize.y * io.DisplayFramebufferScale.y; drawData->ScaleClipRects(io.DisplayFramebufferScale); // Setup orthographic projection matrix static glm::mat4x4 ortho_projection = { { 7.7f, 0.0f, 0.0f, 0.0f }, { 0.0f, 7.7f, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, { -1.0f, 1.0f, 0.0f, 1.0f }, }; ortho_projection[0][0] = 2.0f / io.DisplaySize.x; ortho_projection[1][1] = 2.0f / -io.DisplaySize.y; glUseProgram(renderer->shaderHandle); glUniform1i(renderer->attribLocationTex, 0); glUniformMatrix4fv(renderer->attribLocationProjMtx, 1, GL_FALSE, glm::value_ptr(ortho_projection)); glBindVertexArray(renderer->vaoHandle); for (int index = 0; index < drawData->CmdListsCount; index++) { const ImDrawList * cmd_list = drawData->CmdLists[index]; const ImDrawIdx * idx_buffer_offset = 0; glBindBuffer(GL_ARRAY_BUFFER, renderer->vboHandle); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid *)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, renderer->elementsHandle); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid *)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW); for (const ImDrawCmd * pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++) { if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer_offset); } idx_buffer_offset += pcmd->ElemCount; } } // Restore modified GL state glUseProgram(last_program); glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); glBindVertexArray(last_vertex_array); glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); glBlendFunc(last_blend_src, last_blend_dst); if (last_enable_blend) { glEnable(GL_BLEND); } else { glDisable(GL_BLEND); } if (last_enable_cull_face) { glEnable(GL_CULL_FACE); } else { glDisable(GL_CULL_FACE); } if (last_enable_depth_test) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } if (last_enable_scissor_test) { glEnable(GL_SCISSOR_TEST); } else { glDisable(GL_SCISSOR_TEST); } } void InterfaceRenderer::Initialize(const RenderWindow &activeWindow, bool instantCallbacks /* = true */) { if (!renderer) { renderer = std::make_unique<RendererData>(); } renderer->window = activeWindow.Handler(); ImGuiIO &io = ImGui::GetIO(); // Keyboard mapping. ImGui will use those indices to peek // into the io.KeyDown[] array. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; io.RenderDrawListsFn = RenderDrawList; io.SetClipboardTextFn = SetClipboardText; io.GetClipboardTextFn = GetClipboardText; #ifdef _WIN32 io.ImeWindowHandle = glfwGetWin32Window(renderer->window); #endif if (instantCallbacks) { glfwSetMouseButtonCallback(renderer->window, MouseButtonCallback); glfwSetScrollCallback(renderer->window, ScrollCallback); glfwSetKeyCallback(renderer->window, KeyCallback); glfwSetCharCallback(renderer->window, CharCallback); } int w, h, display_w, display_h;; glfwGetWindowSize(renderer->window, &w, &h); glfwGetFramebufferSize(renderer->window, &display_w, &display_h); io.DisplaySize.x = static_cast<float>(w); io.DisplaySize.y = static_cast<float>(h); io.DisplayFramebufferScale.x = static_cast<float>(display_w) / w; io.DisplayFramebufferScale.y = static_cast<float>(display_h) / h; } void InterfaceRenderer::Render() { if (renderer->disabled) { return; } ImGui::Render(); } void InterfaceRenderer::NewFrame() { if (renderer->disabled) { return; } if (!renderer->fontTexture) { CreateDeviceObjects(); } static auto &io = ImGui::GetIO(); if (glfwGetWindowAttrib(renderer->window, GLFW_RESIZABLE)) { // setup display size (every frame to accommodate for window resizing) static int w, h, display_w, display_h; glfwGetWindowSize(renderer->window, &w, &h); glfwGetFramebufferSize(renderer->window, &display_w, &display_h); io.DisplaySize.x = static_cast<float>(w); io.DisplaySize.y = static_cast<float>(h);; io.DisplayFramebufferScale.x = static_cast<float>(display_w) / w; io.DisplayFramebufferScale.y = static_cast<float>(display_h) / h; } // setup time step auto current_time = glfwGetTime(); io.DeltaTime = renderer->time > 0.0 ? static_cast<float>(current_time - renderer->time) : static_cast<float>(1.0f / 60.0f); renderer->time = current_time; // setup inputs // (we already got mouse wheel, keyboard keys // & characters from glfw callbacks polled in glfwPollEvents()) if (glfwGetWindowAttrib(renderer->window, GLFW_FOCUSED)) { // Mouse position in screen coordinates // (set to -1,-1 if no mouse / on another screen, etc.) double mouse_x, mouse_y; glfwGetCursorPos(renderer->window, &mouse_x, &mouse_y); io.MousePosPrev = io.MousePos; io.MousePos = ImVec2(static_cast<float>(mouse_x), static_cast<float>(mouse_y)); } else { io.MousePos = ImVec2(-1, -1); } for (auto i = 0; i < 3; i++) { io.MouseDown[i] = renderer->mousePressed[i] || glfwGetMouseButton(renderer->window, i) != 0; // If a mouse press event came, always pass it as // "this frame", so we don't miss click-release events // that are shorter than 1 frame. renderer->mousePressed[i] = false; } io.MouseWheel = renderer->mouseWheel; renderer->mouseWheel = 0.0f; // Hide OS mouse cursor if ImGui is drawing it if(io.MouseDrawCursor) { glfwSetInputMode(renderer->window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } else { glfwSetInputMode(renderer->window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); } // Start the frame ImGui::NewFrame(); } void InterfaceRenderer::CreateFontsTexture() { ImGuiIO &io = ImGui::GetIO(); // Build texture atlas unsigned char * pixels; int width, height; // Load as RGBA 32-bits for OpenGL3 demo because it is more // likely to be compatible with user's existing shader. io.Fonts->AddFontFromFileTTF("assets\\fonts\\DroidSans.ttf", 13); io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Create OpenGL texture glGenTextures(1, &renderer->fontTexture); glBindTexture(GL_TEXTURE_2D, renderer->fontTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // Store our identifier io.Fonts->TexID = (void *)(intptr_t)renderer->fontTexture; } void InterfaceRenderer::CreateDeviceObjects() { // Backup GL state GLint last_texture, last_array_buffer, last_vertex_array; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); auto vertex_shader = "#version 330\n" "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; auto fragment_shader = "#version 330\n" "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n" "}\n"; renderer->shaderHandle = glCreateProgram(); renderer->vertHandle = glCreateShader(GL_VERTEX_SHADER); renderer->fragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(renderer->vertHandle, 1, &vertex_shader, 0); glShaderSource(renderer->fragHandle, 1, &fragment_shader, 0); glCompileShader(renderer->vertHandle); glCompileShader(renderer->fragHandle); glAttachShader(renderer->shaderHandle, renderer->vertHandle); glAttachShader(renderer->shaderHandle, renderer->fragHandle); glLinkProgram(renderer->shaderHandle); renderer->attribLocationTex = glGetUniformLocation (renderer->shaderHandle, "Texture"); renderer->attribLocationProjMtx = glGetUniformLocation (renderer->shaderHandle, "ProjMtx"); renderer->attribLocationPosition = glGetAttribLocation (renderer->shaderHandle, "Position"); renderer->attribLocationUV = glGetAttribLocation (renderer->shaderHandle, "UV"); renderer->attribLocationColor = glGetAttribLocation (renderer->shaderHandle, "Color"); glGenBuffers(1, &renderer->vboHandle); glGenBuffers(1, &renderer->elementsHandle); glGenVertexArrays(1, &renderer->vaoHandle); glBindVertexArray(renderer->vaoHandle); glBindBuffer(GL_ARRAY_BUFFER, renderer->vboHandle); glEnableVertexAttribArray(renderer->attribLocationPosition); glEnableVertexAttribArray(renderer->attribLocationUV); glEnableVertexAttribArray(renderer->attribLocationColor); #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) glVertexAttribPointer(renderer->attribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid *) OFFSETOF(ImDrawVert, pos)); glVertexAttribPointer(renderer->attribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid *) OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(renderer->attribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid *) OFFSETOF(ImDrawVert, col)); #undef OFFSETOF CreateFontsTexture(); // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindVertexArray(last_vertex_array); } void InterfaceRenderer::Terminate() { if (renderer->vaoHandle) { glDeleteVertexArrays(1, &renderer->vaoHandle); } if (renderer->vboHandle) { glDeleteBuffers(1, &renderer->vboHandle); } if (renderer->elementsHandle) { glDeleteBuffers(1, &renderer->elementsHandle); } renderer->vaoHandle = renderer->vboHandle = renderer->elementsHandle = 0; glDetachShader(renderer->shaderHandle, renderer->vertHandle); glDeleteShader(renderer->vertHandle); renderer->vertHandle = 0; glDetachShader(renderer->shaderHandle, renderer->fragHandle); glDeleteShader(renderer->fragHandle); renderer->fragHandle = 0; glDeleteProgram(renderer->shaderHandle); renderer->shaderHandle = 0; if (renderer->fontTexture) { glDeleteTextures(1, &renderer->fontTexture); ImGui::GetIO().Fonts->TexID = 0; renderer->fontTexture = 0; } ImGui::Shutdown(); delete renderer.release(); } void InterfaceRenderer::InvalidateDeviceObjects() { if (renderer->vaoHandle) { glDeleteVertexArrays(1, &renderer->vaoHandle); } if (renderer->vboHandle) { glDeleteBuffers(1, &renderer->vboHandle); } if (renderer->elementsHandle) { glDeleteBuffers(1, &renderer->elementsHandle); } renderer->vaoHandle = renderer->vboHandle = renderer->elementsHandle = 0; glDetachShader(renderer->shaderHandle, renderer->vertHandle); glDeleteShader(renderer->vertHandle); renderer->vertHandle = 0; glDetachShader(renderer->shaderHandle, renderer->fragHandle); glDeleteShader(renderer->fragHandle); renderer->fragHandle = 0; glDeleteProgram(renderer->shaderHandle); renderer->shaderHandle = 0; if (renderer->fontTexture) { glDeleteTextures(1, &renderer->fontTexture); ImGui::GetIO().Fonts->TexID = 0; renderer->fontTexture = 0; } ImGui::Shutdown(); } void InterfaceRenderer::MouseButtonCallback(GLFWwindow * window, int button, int action, int mods) { auto &io = ImGui::GetIO(); if (action == GLFW_PRESS && button >= 0 && button < 3) { renderer->mousePressed[button] = true; } io.MouseClickedPos[button] = io.MousePos; } void InterfaceRenderer::ScrollCallback(GLFWwindow * window, double xoffset, double yoffset) { // Use fractional mouse wheel, 1.0 unit 5 lines. renderer->mouseWheel += static_cast<float>(yoffset); } void InterfaceRenderer::KeyCallback(GLFWwindow * window, int key, int scancode, int action, int mods) { auto &io = ImGui::GetIO(); if (action == GLFW_PRESS) { io.KeysDown[key] = true; } if (action == GLFW_RELEASE) { io.KeysDown[key] = false; } (void)mods; // Modifiers are not reliable across systems io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL]; io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT]; io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT]; if (io.KeysDown[GLFW_KEY_H]) { renderer->disabled = !renderer->disabled; } } void InterfaceRenderer::CharCallback(GLFWwindow * window, unsigned int c) { auto &io = ImGui::GetIO(); if (c > 0 && c < 0x10000) { io.AddInputCharacter(static_cast<unsigned short>(c)); } } void InterfaceRenderer::SetClipboardText(const char * text) { glfwSetClipboardString(renderer->window, text); } const char * InterfaceRenderer::GetClipboardText() { return glfwGetClipboardString(renderer->window); }
36.280561
84
0.664936
jose-villegas
6983ba511c2e7204d3a89160d6319fb3373edc98
2,502
cpp
C++
src/mntRegridAxis.cpp
bjlittle/mint
fe4862951e0c570caef6e86440b090650dca000b
[ "0BSD" ]
null
null
null
src/mntRegridAxis.cpp
bjlittle/mint
fe4862951e0c570caef6e86440b090650dca000b
[ "0BSD" ]
null
null
null
src/mntRegridAxis.cpp
bjlittle/mint
fe4862951e0c570caef6e86440b090650dca000b
[ "0BSD" ]
null
null
null
#include <mntRegridAxis.h> extern "C" int mnt_regridaxis_new(RegridAxis_t** self) { *self = new RegridAxis_t(); (*self)->spline = vtkCardinalSpline::New(); // let the the spline estimate the second derivative at the boundaries (*self)->spline->SetLeftConstraint(3); (*self)->spline->SetRightConstraint(3); return 0; } extern "C" int mnt_regridaxis_del(RegridAxis_t** self) { // destroy the spline object (*self)->spline->Delete(); delete *self; return 0; } extern "C" int mnt_regridaxis_build(RegridAxis_t** self, int numValues, const double srcValues[]) { (*self)->spline->RemoveAllPoints(); if (numValues < 2) { // need at least two values (one interval) return 1; } (*self)->numValues = numValues; (*self)->tLo = 0; (*self)->tHi = numValues - 1; // axis is monotonically increasing (*self)->increasing = true; if (srcValues[numValues - 1] < srcValues[0]) { // axis is monotonically decreasing (*self)->increasing = false; } // construct the spline object. Note that the spline object maps the // axis values to indices. This will allow us to quickly find the // float index of a target axis value. int ier = 0; for (int i = 0; i < numValues - 1; ++i) { (*self)->spline->AddPoint(srcValues[i], double(i)); if ((*self)->increasing && srcValues[i + 1] < srcValues[i]) { ier++; } else if (!(*self)->increasing && srcValues[i + 1] > srcValues[i]) { ier++; } } // add last value (*self)->spline->AddPoint(srcValues[numValues - 1], double(numValues - 1)); // compute the spline coefficients (*self)->spline->Compute(); return ier; } extern "C" int mnt_regridaxis_getPointWeights(RegridAxis_t** self, double target, int indices[2], double weights[2]) { double t = (*self)->spline->Evaluate(target); // low side of the interval indices[0] = std::max(0, std::min((*self)->numValues - 2, int(floor(t)))); // high side of the interval indices[1] = indices[0] + 1; // linear interpolation weights weights[0] = indices[1] - t; weights[1] = t - indices[0]; return 0; } extern "C" int mnt_regridaxis_getCellIndexBounds(RegridAxis_t** self, const double targets[2], double indexBounds[2]) { indexBounds[0] = (*self)->spline->Evaluate(targets[0]); indexBounds[1] = (*self)->spline->Evaluate(targets[1]); return 0; }
24.529412
108
0.611111
bjlittle
69842144a324549cc2ff5058fbe25fcd8ff10ce4
67
cpp
C++
Source/Cross/Common/MoCore/TNetPackageHead.cpp
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
3
2016-10-26T11:48:58.000Z
2017-10-24T18:35:17.000Z
Source/Cross/Common/MoCore/TNetPackage.cpp
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
null
null
null
Source/Cross/Common/MoCore/TNetPackage.cpp
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
6
2015-03-24T06:40:20.000Z
2019-03-18T13:56:13.000Z
#include "MoCrNetMessage.h" MO_NAMESPACE_BEGIN MO_NAMESPACE_END
9.571429
27
0.835821
favedit
69851858aa479b61453717cd35502afcefdd8237
218
cpp
C++
CGraphMan.cpp
Satervalley/Kamac-git
83b916684c1397f10319793f87d8c3ab90edbad4
[ "WTFPL" ]
1
2019-12-08T02:20:12.000Z
2019-12-08T02:20:12.000Z
CGraphMan.cpp
Satervalley/Kamac-git
83b916684c1397f10319793f87d8c3ab90edbad4
[ "WTFPL" ]
null
null
null
CGraphMan.cpp
Satervalley/Kamac-git
83b916684c1397f10319793f87d8c3ab90edbad4
[ "WTFPL" ]
null
null
null
#include "pch.h" #include "CGraphMan.h" int CDataGroup_3::nPos[]{ nMargin, nMargin + nColumnWidth + nGap, nMargin + (nColumnWidth + nGap) * 2 }; //DWORD CDataGroup_3::clrColors[]{ 0x00ff5252, 0x0069f0ae, 0x448aff };
31.142857
104
0.711009
Satervalley
698690eb282cc9b44f4d29017ab2b7844738c242
764
cpp
C++
src/copentimelineio/deserialization.cpp
hisergiorojas/OpenTimelineIO-C-Bindings
78e52d9d9f0f03adc04e586655bb2a4151b541be
[ "Apache-2.0" ]
1
2022-02-03T02:49:00.000Z
2022-02-03T02:49:00.000Z
src/copentimelineio/deserialization.cpp
hisergiorojas/OpenTimelineIO-C-Bindings
78e52d9d9f0f03adc04e586655bb2a4151b541be
[ "Apache-2.0" ]
32
2021-07-26T00:42:57.000Z
2022-03-28T00:29:39.000Z
src/copentimelineio/deserialization.cpp
hisergiorojas/OpenTimelineIO-C-Bindings
78e52d9d9f0f03adc04e586655bb2a4151b541be
[ "Apache-2.0" ]
4
2021-02-10T18:28:25.000Z
2022-03-18T03:14:47.000Z
#include "copentimelineio/deserialization.h" #include <opentimelineio/deserialization.h> OTIO_API bool deserialize_json_from_string( const char *input, Any *destination, OTIOErrorStatus *error_status) { std::string str = input; return OTIO_NS::deserialize_json_from_string( str, reinterpret_cast<OTIO_NS::any *>(destination), reinterpret_cast<OTIO_NS::ErrorStatus *>(error_status)); } OTIO_API bool deserialize_json_from_file( const char *file_name, Any *destination, OTIOErrorStatus *error_status) { return OTIO_NS::deserialize_json_from_file( file_name, reinterpret_cast<OTIO_NS::any *>(destination), reinterpret_cast<OTIO_NS::ErrorStatus *>(error_status)); }
38.2
81
0.709424
hisergiorojas
698c48897d4fdb7cb59faa69d3995c746bed30be
260
hpp
C++
lib/include/operation_strategy.hpp
vladiant/test_cpp_ci
2481b0623d8df44e32ebbfb8081b4a17a8ca3a7f
[ "MIT" ]
null
null
null
lib/include/operation_strategy.hpp
vladiant/test_cpp_ci
2481b0623d8df44e32ebbfb8081b4a17a8ca3a7f
[ "MIT" ]
null
null
null
lib/include/operation_strategy.hpp
vladiant/test_cpp_ci
2481b0623d8df44e32ebbfb8081b4a17a8ca3a7f
[ "MIT" ]
null
null
null
#pragma once #include "i_warper.hpp" namespace vva { class OperationStrategy { public: OperationStrategy(IOperationWarper& warper); int16_t operator()(const int16_t& a, const int16_t& b); private: IOperationWarper& warper_; }; } // namespace vva
15.294118
57
0.730769
vladiant
698d42cecdb6674b371b7b5bf5e9d2319ec19075
1,263
hpp
C++
wiring_utils/include/wiring_utils/jsnsr04t_distance_sensor.hpp
Yanick-Salzmann/carpi
29f5e1bf1eb6243e45690f040e4df8e7c228e897
[ "Apache-2.0" ]
2
2020-06-07T16:47:20.000Z
2021-03-20T10:41:34.000Z
wiring_utils/include/wiring_utils/jsnsr04t_distance_sensor.hpp
Yanick-Salzmann/carpi
29f5e1bf1eb6243e45690f040e4df8e7c228e897
[ "Apache-2.0" ]
null
null
null
wiring_utils/include/wiring_utils/jsnsr04t_distance_sensor.hpp
Yanick-Salzmann/carpi
29f5e1bf1eb6243e45690f040e4df8e7c228e897
[ "Apache-2.0" ]
null
null
null
#ifndef CARPI_WIRING_UTILS_JSNSR04T_DISTANCE_HPP #define CARPI_WIRING_UTILS_JSNSR04T_DISTANCE_HPP #include <thread> #include <memory> #include <cstdint> #include <common_utils/log.hpp> #include "gpio.hpp" namespace carpi::wiring { class JSNSR04TDistanceSensor { LOGGER; public: struct Measurement { bool has_signal; float distance; }; private: Measurement _cur_measurement{.has_signal = false}; std::thread _listen_thread; std::thread _trigger_thread; std::unique_ptr<GpioPin> _trigger_pin; std::unique_ptr<GpioPin> _echo_pin; bool _is_running = true; void trigger_callback(); void echo_callback(); public: JSNSR04TDistanceSensor(uint32_t trigger_pin, uint32_t echo_pin); ~JSNSR04TDistanceSensor(); JSNSR04TDistanceSensor(JSNSR04TDistanceSensor&) = delete; JSNSR04TDistanceSensor(JSNSR04TDistanceSensor&&) = delete; void operator = (JSNSR04TDistanceSensor&) = delete; void operator = (JSNSR04TDistanceSensor&&) = delete; Measurement current_distance() const { return _cur_measurement; } }; } #endif //CARPI_WIRING_UTILS_JSNSR04T_DISTANCE_HPP
24.764706
72
0.673793
Yanick-Salzmann
698dfd407cff4168ce393de15c57e62d52f989b1
1,360
cpp
C++
test/ssvr/srv_dev_mng.cpp
walkthetalk/libem
6619b48716b380420157c4021f9943b153998e09
[ "Apache-2.0" ]
2
2015-03-13T14:49:13.000Z
2017-09-18T12:38:59.000Z
test/ssvr/srv_dev_mng.cpp
walkthetalk/libem
6619b48716b380420157c4021f9943b153998e09
[ "Apache-2.0" ]
null
null
null
test/ssvr/srv_dev_mng.cpp
walkthetalk/libem
6619b48716b380420157c4021f9943b153998e09
[ "Apache-2.0" ]
null
null
null
#include <limits> #include <exemodel/poll_tools.hpp> #include "srv_dev_mng.hpp" #include <iostream> #include <fstream> #include <string.h> #include <openssl/md5.h> namespace svcDevMng { svcDeviceManager::svcDeviceManager(uint16_t port) : serverExt(port) , m_pkgc(0) { register_callback<bmid_t::sendUpdateData>( [this](std::vector<uint8_t> & data) { std::cout << "sendUpdateData" << std::endl; std::string pos_str; //data [0-31] std::string size_str; //data [32-63] std::vector<uint8_t>::iterator iter; for (int i=0; i < 64; i++) { iter = data.begin(); if (i < 32) { pos_str += *iter; } else { size_str += *iter; } data.erase(iter); } int pos = std::atoi(pos_str.c_str()); int size = std::atoi(size_str.c_str()); std::cout << pos << "," << size << std::endl; std::ofstream file; file.open("/tmp/udisk/updatePackage.tar.gz", std::ios::out|std::ios::in|std::ios::binary); if (!file.is_open()) { file.open("/tmp/udisk/updatePackage.tar.gz",std::ios::out|std::ios::binary); } file.seekp(pos, std::ios::beg); for (int i=0; i < size; i++) { file << data[i]; } file.close(); m_pkgc++; std::cout << m_pkgc << std::endl; } ); } svcDeviceManager::~svcDeviceManager() { } void svcDeviceManager::fifo_processer(std::vector<uint8_t> &) { } }
19.710145
93
0.602941
walkthetalk
698e5837bba52095c90b808c90252db6253d15e2
3,266
cpp
C++
opengl_4_shading_language_cookbook/017-compiling_a_shader/CompilingAShader.cpp
mickbeaver/graphics
2b95c03677dfbb808048f53326e8c98e2d8775e1
[ "BSD-2-Clause" ]
null
null
null
opengl_4_shading_language_cookbook/017-compiling_a_shader/CompilingAShader.cpp
mickbeaver/graphics
2b95c03677dfbb808048f53326e8c98e2d8775e1
[ "BSD-2-Clause" ]
null
null
null
opengl_4_shading_language_cookbook/017-compiling_a_shader/CompilingAShader.cpp
mickbeaver/graphics
2b95c03677dfbb808048f53326e8c98e2d8775e1
[ "BSD-2-Clause" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <SDL2/SDL.h> #include "glsys.h" #include "FileUtil.h" #define WINDOW_SIZE 640 void printShaderInfoLog(GLuint shaderHandle) { GLint logLength; glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 0) { char* logBuffer = new char[logLength]; GLsizei bytesCopied; glGetShaderInfoLog(shaderHandle, logLength, &bytesCopied, logBuffer); (void)fprintf(stderr, "Shader info log:\n%s\n", logBuffer); delete [] logBuffer; exit(EXIT_FAILURE); } } int main(int argc, char** argv) { (void)argc; (void)argv; int retval = SDL_Init(SDL_INIT_VIDEO); if (retval != 0) { (void)fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); Uint32 glContextFlags = SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG; #ifdef DEBUG glContextFlags |= SDL_GL_CONTEXT_DEBUG_FLAG; #endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, glContextFlags); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_ClearError(); SDL_Window* mainWindow = SDL_CreateWindow("Compiling a Shader", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_SIZE, WINDOW_SIZE, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN); if (mainWindow == NULL) { (void)fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } SDL_GLContext mainContext = SDL_GL_CreateContext(mainWindow); if (mainContext == NULL) { (void)fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } retval = glsysLoadFunctions((glsysFunctionLoader)SDL_GL_GetProcAddress); if (retval != 0) { (void)fprintf(stderr, "Error loading GL functions\n"); exit(EXIT_FAILURE); } GLuint vertShader = glCreateShader(GL_VERTEX_SHADER); if (vertShader == 0) { (void)fprintf(stderr, "Error creating vertex shader.\n"); exit(EXIT_FAILURE); } const GLchar* shaderCode = FileUtil::loadFileAsString("basic.vert"); glShaderSource(vertShader, 1, &shaderCode, NULL); delete [] shaderCode; glCompileShader(vertShader); GLint result; glGetShaderiv(vertShader, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { (void)fprintf(stderr, "Vertex shader compilation failed!\n"); printShaderInfoLog(vertShader); } else { (void)printf("Shader compiled successfully!\n"); // Print warnings, if available printShaderInfoLog(vertShader); } SDL_GL_DeleteContext(mainContext); SDL_DestroyWindow(mainWindow); SDL_Quit(); return 0; }
33.670103
86
0.621249
mickbeaver
7e340d4f8cc297b7eca2bd071e59ffff82567685
1,482
cpp
C++
LibCarla/source/carla/Exception.cpp
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
7,883
2017-11-10T16:49:23.000Z
2022-03-31T18:48:47.000Z
LibCarla/source/carla/Exception.cpp
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
4,558
2017-11-10T17:45:30.000Z
2022-03-31T23:30:02.000Z
LibCarla/source/carla/Exception.cpp
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
2,547
2017-11-13T03:22:44.000Z
2022-03-31T10:39:30.000Z
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "carla/Exception.h" // ============================================================================= // -- Define boost::throw_exception -------------------------------------------- // ============================================================================= #ifdef BOOST_NO_EXCEPTIONS namespace boost { void throw_exception(const std::exception &e) { carla::throw_exception(e); } } // namespace boost #endif // BOOST_NO_EXCEPTIONS // ============================================================================= // -- Workaround for Boost.Asio bundled with rpclib ---------------------------- // ============================================================================= #ifdef ASIO_NO_EXCEPTIONS #include <exception> #include <system_error> #include <typeinfo> namespace clmdep_asio { namespace detail { template <typename Exception> void throw_exception(const Exception& e) { carla::throw_exception(e); } template void throw_exception<std::bad_cast>(const std::bad_cast &); template void throw_exception<std::exception>(const std::exception &); template void throw_exception<std::system_error>(const std::system_error &); } // namespace detail } // namespace clmdep_asio #endif // ASIO_NO_EXCEPTIONS
29.058824
80
0.539811
adelbennaceur
7e36c09a63af28d59cf7322130589d231a1ebe4e
900
cc
C++
UX/src/Point.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
UX/src/Point.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
UX/src/Point.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
/* * Copyright (C) 2022 Frank Mertens. * * Distribution and use is allowed under the terms of the zlib license * (see cc/LICENSE-zlib). * */ #include <cc/Point> #include <limits> namespace cc { template class Vector<double, 2>; /** Get positive angle of vector \a v * \return Angle in range [0, 2*PI) */ double angle(Point v) { using std::numbers::pi; if (v[0] == 0) { if (v[1] == 0) return std::numeric_limits<double>::quiet_NaN(); if (v[1] > 0) return pi/2; return 3 * pi / 2; } else if (v[1] == 0) { if (v[0] > 0) return 0; return pi; } double alpha = std::atan(v[1]/v[0]); if (v[0] < 0) alpha += pi; else if (v[1] < 0) alpha += 2 * pi; return alpha; } double abs(Point v) { if (v[0] == 0) return std::abs(v[1]); else if (v[1] == 0) return std::abs(v[0]); return v.abs(); } } // namespace cc
19.565217
71
0.538889
frankencode
7e39eb52a5dda75eb6f304a1b3bbc6686046148f
240
cpp
C++
src/analysis/parts/resample.cpp
autumnsault/speech-analysis
6d2b683f0afa47d098b95f6be59534ed7d277361
[ "MIT" ]
null
null
null
src/analysis/parts/resample.cpp
autumnsault/speech-analysis
6d2b683f0afa47d098b95f6be59534ed7d277361
[ "MIT" ]
null
null
null
src/analysis/parts/resample.cpp
autumnsault/speech-analysis
6d2b683f0afa47d098b95f6be59534ed7d277361
[ "MIT" ]
1
2020-04-02T11:58:29.000Z
2020-04-02T11:58:29.000Z
// // Created by rika on 16/11/2019. // #include "../Analyser.h" #include "Signal/Resample.h" using namespace Eigen; void Analyser::resampleAudio(double newFs) { x = std::move(Resample::resample(x, fs, newFs, 50)); fs = newFs; }
17.142857
56
0.654167
autumnsault
7e3aa7b4ded7f1cffe37f511219cb0a16af34f0e
401
cc
C++
tools/Packers/source/ContainerEvolved.cc
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
8
2015-01-23T05:41:46.000Z
2019-11-20T05:10:27.000Z
tools/Packers/source/ContainerEvolved.cc
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
null
null
null
tools/Packers/source/ContainerEvolved.cc
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
4
2015-05-05T05:15:43.000Z
2020-03-07T11:10:56.000Z
/********************************************************************************************************* * ContainerEvolved.cc * Note: Phoenix Container Evolved * Date: @2015.05 * Author: Force Charlie * E-mail:<forcemz@outlook.com> * Copyright (C) 2015 The ForceStudio All Rights Reserved. **********************************************************************************************************/
44.555556
107
0.349127
fstudio
7e448e24a7743ac2f2c79c0b3aa5d270f2fce2b7
8,253
cpp
C++
src/systems/scalar_wave.cpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
null
null
null
src/systems/scalar_wave.cpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
2
2022-02-18T22:43:06.000Z
2022-02-18T22:43:19.000Z
src/systems/scalar_wave.cpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
null
null
null
#include "scalar_wave.hpp" #include "fields/algorithms.hpp" #include "fields/selector.hpp" #include "real3_operators.hpp" #include <cmath> #include <numbers> #include <sol/sol.hpp> #include "operators/discrete_operator.hpp" #include <range/v3/algorithm/max_element.hpp> #include <range/v3/view/transform.hpp> namespace ccs::systems { namespace { constexpr auto abs = lift([](auto&& x) { return std::abs(x); }); // system variables to be used in this system enum class scalars : int { u }; constexpr real twoPI = 2 * std::numbers::pi_v<real>; // negative gradient - coefficients of gradient template <int I> constexpr auto neg_G(const real3& center, real radius) { return vs::transform([=](auto&& location) { return -(get<I>(location) - get<I>(center)) / length(location - center); }); } constexpr auto solution(const real3& center, real radius, real time) { return vs::transform([=](auto&& location) { return std::sin(twoPI * (length(location - center) - radius - time)); }); } } // namespace scalar_wave::scalar_wave(mesh&& m_, bcs::Grid&& grid_bcs, bcs::Object&& object_bcs, stencil st, real3 center, real radius, real max_error, bool enable_logging) : m{MOVE(m_)}, grid_bcs{MOVE(grid_bcs)}, object_bcs{MOVE(object_bcs)}, grad{gradient(this->m, st, this->grid_bcs, this->object_bcs, enable_logging)}, center{center}, radius{radius}, grad_G{m.vs()}, du{m.vs()}, error{m.ss()}, max_error{max_error}, logger{enable_logging, "system", "logs/system.csv"} { // Initialize wave speeds grad_G | m.fluid = m.vxyz | tuple{neg_G<0>(center, radius), neg_G<1>(center, radius), neg_G<2>(center, radius)}; grad_G | sel::xR = m.vxyz | neg_G<0>(center, radius); grad_G | sel::yR = m.vxyz | neg_G<1>(center, radius); grad_G | sel::zR = m.vxyz | neg_G<2>(center, radius); grad_G | m.dirichlet(this->grid_bcs, this->object_bcs) = 0; spdlog::debug("-grad_G {}\n", get<vi::xRx>(grad_G)[0]); logger.set_pattern("%v"); logger(spdlog::level::info, "Timestamp,Time,Step,Linf,Min,Max,Domain_Linf,Domain_ic,Rx_Linf,Rx_ic,Ry_" "Linf,Ry_ic,Rz_Linf,Rz_ic"); logger.set_pattern("%Y-%m-%d %H:%M:%S.%f,%v"); } real scalar_wave::timestep_size(const field&, const step_controller& step) const { const auto h_min = rs::min(m.h()); return step.hyperbolic_cfl() * h_min; } // // sets the field f to the solution // void scalar_wave::operator()(field& f, const step_controller& c) { // extract the field components to initialize auto&& u = f.scalars(scalars::u); auto sol = m.xyz | solution(center, radius, c); u | sel::D = 0; u | m.fluid = sol; u | sel::R = sol; } // // Compute the linf error as well as the min/max of the field // system_stats scalar_wave::stats(const field&, const field& f, const step_controller& c) const { auto&& u = f.scalars(scalars::u); auto sol = m.xyz | solution(center, radius, c); auto [u_min, u_max] = minmax(u | m.fluid_all(object_bcs)); real err = max(abs(u - sol) | m.fluid_all(object_bcs)); // Extra info for debugging: auto linf = abs(u - sol); auto fluid_error = linf | m.fluid_all(object_bcs); auto max_el = transform(rs::max_element, fluid_error); auto err_pairs = transform( [](auto&& rng, auto&& max_el) { if (rs::end(rng) != max_el) return std::pair{ *max_el, (real)rs::distance(rs::begin(rng.base()), max_el.base())}; else return std::pair{0.0, (real)0}; }, fluid_error, max_el); auto&& [d, rx, ry, rz] = err_pairs; return system_stats{.stats = {err, u_min, u_max, d.first, d.second, rx.first, rx.second, ry.first, ry.second, rz.first, rz.second}}; } // // Determine if the computed field is valid by checking the linf error // bool scalar_wave::valid(const system_stats& stats) const { const auto& v = stats.stats[0]; return std::isfinite(v) && std::abs(v) <= max_error; } // // rhs = - grad(G) . grad(u) -> dot(neg_G, du) // void scalar_wave::rhs(field_view f, real, field_span rhs) { auto&& u = f.scalars(scalars::u); auto&& u_rhs = rhs.scalars(scalars::u); du = grad(u); u_rhs = dot(grad_G, du); } real3 scalar_wave::summary(const system_stats& stats) const { return {stats.stats[0], stats.stats[1], stats.stats[2]}; } // // Must be called before computing the rhs // void scalar_wave::update_boundary(field_span f, real time) { auto&& u = f.scalars(scalars::u); auto sol = m.xyz | solution(center, radius, time); u | m.dirichlet(grid_bcs, object_bcs) = sol; } bool scalar_wave::write(field_io& io, field_view f, const step_controller& c, real dt) { auto&& u = f.scalars(scalars::u); auto sol = m.xyz | solution(center, radius, (real)c); error = 0; error | m.fluid_all(object_bcs) = abs(u - sol); error | m.dirichlet(grid_bcs, object_bcs) = 0; field_view io_view{std::vector<scalar_view>{u, error}, std::vector<vector_view>{}}; return io.write(io_names, io_view, c, dt, m.R()); } void scalar_wave::log(const system_stats& stats, const step_controller& step) { logger(spdlog::level::info, "{},{},{}", (real)step, (int)step, fmt::join(stats.stats, ",")); } system_size scalar_wave::size() const { return {1, 0, m.ss()}; } std::optional<scalar_wave> scalar_wave::from_lua(const sol::table& tbl, const logs& logger) { real max_error = tbl["system"]["max_error"].get_or(100.0); // assume we can only get here if simulation.system.type == "scalar_wave" so check // for the rest real3 center; real radius; // if the center/radius was specified in the system table, use it. if (tbl["system"]["center"].valid() && tbl["system"]["radius"].valid()) { auto c = tbl["system"]["center"]; center = {c[1].get_or(0.0), c[2].get_or(0.0), c[3].get_or(0.0)}; radius = tbl["system"]["radius"]; } else if (tbl["shapes"].valid()) { // attempt to extract the center/radius from the first specified shape in the // shapes table bool found{false}; auto t = tbl["shapes"]; for (int i = 1; t[i].valid() && !found; i++) { found = (t[i]["type"].get_or(std::string{}) == "sphere"); if (found) { center = {t[i]["center"][1].get_or(0.0), t[i]["center"][2].get_or(0.0), t[i]["center"][3].get_or(0.0)}; radius = t[i]["radius"].get_or(0.0); } } if (!found) { logger(spdlog::level::err, "No valid spheres found in simulation.shapes for scalar_wave"); return std::nullopt; } } else { logger(spdlog::level::err, "a system.center / system.radius must be specified for scalar_wave"); return std::nullopt; } auto mesh_opt = mesh::from_lua(tbl, logger); if (!mesh_opt) return std::nullopt; auto bc_opt = bcs::from_lua(tbl, mesh_opt->extents(), logger); auto st_opt = stencil::from_lua(tbl, logger); if (bc_opt && st_opt) { return scalar_wave{MOVE(*mesh_opt), MOVE(bc_opt->first), MOVE(bc_opt->second), *st_opt, center, radius, max_error, logger}; } return std::nullopt; } } // namespace ccs::systems
30.794776
87
0.548043
lanl
7e48283e598d93887a1a5f41d0405008aa7e686a
545
cpp
C++
src/Qir/Runtime/lib/QIR/QirRange.cpp
AllSafeCybercurity/qtime
353058e0708355bddb2458d6d2a27a981bcb6d02
[ "MIT" ]
null
null
null
src/Qir/Runtime/lib/QIR/QirRange.cpp
AllSafeCybercurity/qtime
353058e0708355bddb2458d6d2a27a981bcb6d02
[ "MIT" ]
null
null
null
src/Qir/Runtime/lib/QIR/QirRange.cpp
AllSafeCybercurity/qtime
353058e0708355bddb2458d6d2a27a981bcb6d02
[ "MIT" ]
1
2021-07-26T12:35:37.000Z
2021-07-26T12:35:37.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <cstdint> #include "QirTypes.hpp" #include "QirRuntime.hpp" QirRange::QirRange(int64_t st, int64_t sp, int64_t en) : start(st) , step(sp) , end(en) { // An attempt to create a %Range with a zero step should cause a runtime failure. // https://github.com/microsoft/qsharp-language/blob/main/Specifications/QIR/Data-Types.md#simple-types if(sp == 0) { quantum__rt__fail_cstr("Attempt to create a range with 0 step"); } }
27.25
107
0.682569
AllSafeCybercurity
7e548d755ce70aceef0a4a7a7cdacff948c7ec28
5,534
cpp
C++
libevent-example/message.cpp
anancds/rpc
345a93915ec1a02e88e71678df695ee1302869df
[ "MIT" ]
1
2021-01-10T02:34:13.000Z
2021-01-10T02:34:13.000Z
libevent-example/message.cpp
anancds/rpc
345a93915ec1a02e88e71678df695ee1302869df
[ "MIT" ]
1
2021-03-11T02:21:41.000Z
2021-03-11T02:21:41.000Z
libevent-example/message.cpp
anancds/rpc
345a93915ec1a02e88e71678df695ee1302869df
[ "MIT" ]
null
null
null
// // Created by cds on 2020/9/23. // #include "message.h" #include <event2/buffer.h> #include <event2/bufferevent.h> #include <event2/event.h> #include <event2/listener.h> #include <event2/util.h> #include <stdio.h> #include <time.h> #include <iostream> #include <map> #include <string.h> #include <vector> #include <arpa/inet.h> //#include <netinet/in.h> using namespace std; #define PORT 1234 #define HEADER_LENGTH 12 #define BUFFER_SIZE (16 * 1024) #define READ_SIZE (16 * 1024) #define MAX_PACKET_SIZE (256) #define IMTE_INTERVAL (5000) const char ip_address[] = "127.0.0.1"; map<unsigned int, bufferevent *> ClientMap; // client id 对应的bufferevent int conectNumber = 0; int dataSize = 0; int lastTime = 0; int receiveNumber = 0; int sendNumber = 0; int main(int argc, char **argv) { cout << "Server begin running!" << endl; struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.S_un.S_addr = inet_addr(ip_address); sin.sin_port = htons(PORT); struct evconnlistener *listener; struct event_base *base = event_base_new(); if (!base) { cout << "Could not initialize libevent" << endl; ; return 1; } //默认情况下,链接监听器接收新套接字后,会将其设置为非阻塞的 listener = evconnlistener_new_bind(base, listener_cb, (void *)base, LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, -1, (struct sockaddr *)&sin, sizeof(sin)); if (!listener) { cout << "Could not create a listener" << endl; return 1; } event_base_dispatch(base); evconnlistener_free(listener); event_base_free(base); return 0; } void listener_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *sa, int socklen, void *user_data) { cout << "Detect an connection" << endl; struct event_base *base = (struct event_base *)user_data; struct bufferevent *bev; // BEV_OPT_CLOSE_ON_FREE close the file descriptor when this bufferevent is freed bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); if (!bev) { cout << "Could not create a bufferevent" << endl; event_base_loopbreak(base); return; } ClientMap[++conectNumber] = bev; // read write event bufferevent_setcb(bev, conn_readcb, NULL, conn_eventcb, NULL); bufferevent_enable(bev, EV_READ | EV_WRITE); // send a message to client when connect is succeeded string msg = "connedted"; Header header; header.sourceID = 0; header.targetID = conectNumber; header.length = msg.size(); write_buffer(msg, bev, header); } void conn_writecb(struct bufferevent *bev, void *user_data) { Sleep(2000); int len = 0; Header header; unsigned int toID = get_client_id(bev); string msg = "hello client " + inttostr(toID); header.targetID = toID; header.sourceID = 0; header.length = msg.size(); write_buffer(msg, bev, header); } void conn_readcb(struct bufferevent *bev, void *user_data) { struct evbuffer *input = bufferevent_get_input(bev); size_t sz = evbuffer_get_length(input); unsigned int sourceID = get_client_id(bev); while (sz >= MAX_PACKET_SIZE) { char msg[MAX_PACKET_SIZE] = {0}; char *ptr = msg; bufferevent_read(bev, ptr, HEADER_LENGTH); unsigned int len = ((Header *)ptr)->length; unsigned int targetID = ((Header *)ptr)->targetID; ((Header *)ptr)->sourceID = sourceID; ptr += HEADER_LENGTH; if (sz < len + HEADER_LENGTH) { break; } bufferevent_read(bev, ptr, len); receiveNumber++; dataSize += len + HEADER_LENGTH; if (ClientMap.find(targetID) != ClientMap.end()) { sendNumber++; bufferevent_write(ClientMap[targetID], msg, len + HEADER_LENGTH); } else { // can't find } sz = evbuffer_get_length(input); } // calculate the speed of data and packet clock_t nowtime = clock(); if (lastTime == 0) { lastTime = nowtime; } else { cout << "client number: " << ClientMap.size() << " "; cout << "data speed: " << (double)dataSize / (nowtime - lastTime) << "k/s "; cout << "packet speed: receive " << (double)receiveNumber / (nowtime - lastTime) << "k/s "; cout << "send " << (double)sendNumber / (nowtime - lastTime) << "k/s" << endl; if (nowtime - lastTime > TIME_INTERVAL) { dataSize = 0; lastTime = nowtime; receiveNumber = 0; sendNumber = 0; } } } void conn_eventcb(struct bufferevent *bev, short events, void *user_data) { if (events & BEV_EVENT_EOF) { cout << "Connection closed" << endl; } else if (events & BEV_EVENT_ERROR) { cout << "Got an error on the connection: " << strerror(errno) << endl; } bufferevent_free(bev); } unsigned int get_client_id(struct bufferevent *bev) { for (auto p = ClientMap.begin(); p != ClientMap.end(); p++) { if (p->second == bev) { return p->first; } } return 0; } void write_buffer(string &msg, struct bufferevent *bev, Header &header) { char send_msg[BUFFER_SIZE] = {0}; char *ptr = send_msg; int len = 0; memcpy(ptr, &header, sizeof(Header)); len += sizeof(Header); ptr += sizeof(Header); memcpy(ptr, msg.c_str(), msg.size()); len += msg.size(); bufferevent_write(bev, send_msg, len); } string inttostr(int num) { string result; bool neg = false; if (num < 0) { neg = true; num = -num; } if (num == 0) { result += '0'; } else { while (num > 0) { int rem = num % 10; result = (char)(rem + '0') + result; num /= 10; } } if (neg) { result = '-' + result; } return result; }
25.385321
116
0.644742
anancds
7e572a5d74917a2f0dc3bea10ada5dbefe6ed7b0
9,569
cpp
C++
inetcore/setup/ieak5/ieaksie/secauth.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/setup/ieak5/ieaksie/secauth.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/setup/ieak5/ieaksie/secauth.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "precomp.h" #include "rsop.h" #include <tchar.h> ///////////////////////////////////////////////////////////////////// void InitSecAuthDlgInRSoPMode(HWND hDlg, CDlgRSoPData *pDRD) { __try { BOOL bImport = FALSE; _bstr_t bstrClass = L"RSOP_IEAKPolicySetting"; HRESULT hr = pDRD->GetArrayOfPSObjects(bstrClass); if (SUCCEEDED(hr)) { CPSObjData **paPSObj = pDRD->GetPSObjArray(); long nPSObjects = pDRD->GetPSObjCount(); BOOL bImportHandled = FALSE; BOOL bEnableHandled = FALSE; for (long nObj = 0; nObj < nPSObjects; nObj++) { // importAuthenticodeSecurityInfo field _variant_t vtValue; if (!bImportHandled) { hr = paPSObj[nObj]->pObj->Get(L"importAuthenticodeSecurityInfo", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { //TODO: uncomment bImport = (bool)vtValue ? TRUE : FALSE; CheckRadioButton(hDlg, IDC_NOAUTH, IDC_IMPORTAUTH, (bool)vtValue ? IDC_IMPORTAUTH : IDC_NOAUTH); DWORD dwCurGPOPrec = GetGPOPrecedence(paPSObj[nObj]->pObj); pDRD->SetImportedAuthenticodePrec(dwCurGPOPrec); bImportHandled = TRUE; } } // enableTrustedPublisherLockdown field vtValue; if (!bEnableHandled) { hr = paPSObj[nObj]->pObj->Get(L"enableTrustedPublisherLockdown", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) { if ((bool)vtValue) CheckDlgButton(hDlg, IDC_TPL, BST_CHECKED); bEnableHandled = TRUE; } } // no need to process other GPOs since enabled properties have been found if (bImportHandled && bEnableHandled) break; } } EnableDlgItem2(hDlg, IDC_NOAUTH, FALSE); EnableDlgItem2(hDlg, IDC_IMPORTAUTH, FALSE); EnableDlgItem2(hDlg, IDC_MODIFYAUTH, bImport); EnableDlgItem2(hDlg, IDC_TPL, FALSE); } __except(TRUE) { } } ///////////////////////////////////////////////////////////////////// HRESULT InitSecAuthPrecPage(CDlgRSoPData *pDRD, HWND hwndList) { HRESULT hr = NOERROR; __try { _bstr_t bstrClass = L"RSOP_IEAKPolicySetting"; hr = pDRD->GetArrayOfPSObjects(bstrClass); if (SUCCEEDED(hr)) { CPSObjData **paPSObj = pDRD->GetPSObjArray(); long nPSObjects = pDRD->GetPSObjCount(); for (long nObj = 0; nObj < nPSObjects; nObj++) { _bstr_t bstrGPOName = pDRD->GetGPONameFromPS(paPSObj[nObj]->pObj); // importAuthenticodeSecurityInfo field BOOL bImport = FALSE; _variant_t vtValue; hr = paPSObj[nObj]->pObj->Get(L"importAuthenticodeSecurityInfo", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) bImport = (bool)vtValue ? TRUE : FALSE; _bstr_t bstrSetting; if (bImport) { TCHAR szTemp[MAX_PATH]; LoadString(g_hInstance, IDS_IMPORT_AUTHSEC_SETTING, szTemp, countof(szTemp)); bstrSetting = szTemp; } else bstrSetting = GetDisabledString(); InsertPrecedenceListItem(hwndList, nObj, bstrGPOName, bstrSetting); } } } __except(TRUE) { } return hr; } ///////////////////////////////////////////////////////////////////// HRESULT InitAuthLockdownPrecPage(CDlgRSoPData *pDRD, HWND hwndList) { HRESULT hr = NOERROR; __try { _bstr_t bstrClass = L"RSOP_IEAKPolicySetting"; hr = pDRD->GetArrayOfPSObjects(bstrClass); if (SUCCEEDED(hr)) { CPSObjData **paPSObj = pDRD->GetPSObjArray(); long nPSObjects = pDRD->GetPSObjCount(); for (long nObj = 0; nObj < nPSObjects; nObj++) { _bstr_t bstrGPOName = pDRD->GetGPONameFromPS(paPSObj[nObj]->pObj); // enableTrustedPublisherLockdown field BOOL bImport = FALSE; _variant_t vtValue; hr = paPSObj[nObj]->pObj->Get(L"enableTrustedPublisherLockdown", 0, &vtValue, NULL, NULL); if (SUCCEEDED(hr) && !IsVariantNull(vtValue)) bImport = (bool)vtValue ? TRUE : FALSE; _bstr_t bstrSetting; if (bImport) { TCHAR szTemp[MAX_PATH]; LoadString(g_hInstance, IDS_ENABLE_PUB_LOCK_SETTING, szTemp, countof(szTemp)); bstrSetting = szTemp; } else bstrSetting = GetDisabledString(); InsertPrecedenceListItem(hwndList, nObj, bstrGPOName, bstrSetting); } } } __except(TRUE) { } return hr; } ///////////////////////////////////////////////////////////////////// INT_PTR CALLBACK SecurityAuthDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { // Retrieve Property Sheet Page info for each call into dlg proc. LPPROPSHEETCOOKIE psCookie = (LPPROPSHEETCOOKIE)GetWindowLongPtr(hDlg, DWLP_USER); TCHAR szWorkDir[MAX_PATH], szInf[MAX_PATH]; BOOL fImport; switch (uMsg) { case WM_SETFONT: //a change to mmc requires us to do this logic for all our property pages that use common controls INITCOMMONCONTROLSEX iccx; iccx.dwSize = sizeof(INITCOMMONCONTROLSEX); iccx.dwICC = ICC_ANIMATE_CLASS | ICC_BAR_CLASSES | ICC_LISTVIEW_CLASSES |ICC_TREEVIEW_CLASSES; InitCommonControlsEx(&iccx); break; case WM_INITDIALOG: SetPropSheetCookie(hDlg, lParam); // find out if this dlg is in RSoP mode psCookie = (LPPROPSHEETCOOKIE)GetWindowLongPtr(hDlg, DWLP_USER); if (psCookie->pCS->IsRSoP()) { CheckRadioButton(hDlg, IDC_NOAUTH, IDC_IMPORTAUTH, IDC_NOAUTH); CDlgRSoPData *pDRD = GetDlgRSoPData(hDlg, psCookie->pCS); if (pDRD) InitSecAuthDlgInRSoPMode(hDlg, pDRD); } break; case WM_DESTROY: if (psCookie->pCS->IsRSoP()) DestroyDlgRSoPData(hDlg); break; case WM_NOTIFY: switch (((LPNMHDR)lParam)->code) { case PSN_SETACTIVE: // don't do any of this stuff in RSoP mode if (!psCookie->pCS->IsRSoP()) { // authenticode fImport = InsGetBool(IS_SITECERTS, TEXT("ImportAuthCode"), FALSE, GetInsFile(hDlg)); CheckRadioButton(hDlg, IDC_NOAUTH, IDC_IMPORTAUTH, fImport ? IDC_IMPORTAUTH : IDC_NOAUTH); EnableDlgItem2(hDlg, IDC_MODIFYAUTH, fImport); ReadBoolAndCheckButton(IS_SITECERTS, IK_TRUSTPUBLOCK, FALSE, GetInsFile(hDlg), hDlg, IDC_TPL); } break; case PSN_APPLY: if (psCookie->pCS->IsRSoP()) return FALSE; else { if (!AcquireWriteCriticalSection(hDlg)) { SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_INVALID_NOCHANGEPAGE); break; } // process authenticode CreateWorkDir(GetInsFile(hDlg), IEAK_GPE_BRANDING_SUBDIR TEXT("\\AUTHCODE"), szWorkDir); PathCombine(szInf, szWorkDir, TEXT("authcode.inf")); ImportAuthCode(GetInsFile(hDlg), NULL, szInf, IsDlgButtonChecked(hDlg, IDC_IMPORTAUTH) == BST_CHECKED); if (PathIsDirectoryEmpty(szWorkDir)) PathRemovePath(szWorkDir); InsWriteBoolEx(IS_SITECERTS, IK_TRUSTPUBLOCK, (IsDlgButtonChecked(hDlg, IDC_TPL) == BST_CHECKED), GetInsFile(hDlg)); SignalPolicyChanged(hDlg, FALSE, TRUE, &g_guidClientExt, &g_guidSnapinExt); } break; case PSN_HELP: ShowHelpTopic(hDlg); break; default: return FALSE; } break; case WM_COMMAND: if (GET_WM_COMMAND_CMD(wParam, lParam) != BN_CLICKED) return FALSE; switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDC_NOAUTH: DisableDlgItem(hDlg, IDC_MODIFYAUTH); break; case IDC_IMPORTAUTH: EnableDlgItem(hDlg, IDC_MODIFYAUTH); break; case IDC_MODIFYAUTH: ModifyAuthCode(hDlg); break; default: return FALSE; } break; case WM_HELP: ShowHelpTopic(hDlg); break; default: return FALSE; } return TRUE; }
34.175
133
0.51322
npocmaka
7e5799ca381a57dcd3ffbc7a25c21511d137171b
245
hpp
C++
include/member_thunk/error/region_not_empty.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
9
2019-12-02T11:59:24.000Z
2022-02-28T06:34:59.000Z
include/member_thunk/error/region_not_empty.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
29
2019-11-26T17:12:33.000Z
2020-10-06T04:58:53.000Z
include/member_thunk/error/region_not_empty.hpp
sylveon/member_thunk
1ac81a983e951678638be7785de2cce2d9f73151
[ "MIT" ]
null
null
null
#pragma once #include "./exception.hpp" namespace member_thunk { class region_not_empty final : public exception { public: constexpr region_not_empty() noexcept : exception("This region has been destroyed before being emptied.") { } }; }
20.416667
111
0.746939
sylveon
7e579e088b2e565d9c64ae0beb10e2d74a08e90a
5,721
cpp
C++
circballmesh/circballmesh.cpp
Simi4/circball-shader
7c6708624441b507be514f4813fb456c73e7b649
[ "MIT" ]
null
null
null
circballmesh/circballmesh.cpp
Simi4/circball-shader
7c6708624441b507be514f4813fb456c73e7b649
[ "MIT" ]
null
null
null
circballmesh/circballmesh.cpp
Simi4/circball-shader
7c6708624441b507be514f4813fb456c73e7b649
[ "MIT" ]
null
null
null
#include "circballmesh.h" #include <Qt3DRender/qbuffer.h> #include <Qt3DRender/QAttribute> #include <Qt3DRender/QGeometry> #include <qmath.h> QByteArray createCirclesVertexData(float radius, int resolution) { QByteArray bufferBytes; // vec3 pos, vec3 normal, vec4 color const quint32 elementSize = 3 + 3 + 4; const quint32 stride = elementSize * sizeof(float); const int nVerts = (resolution+1) * 3; bufferBytes.resize(stride * nVerts); float* fptr = reinterpret_cast<float*>(bufferBytes.data()); const float dTheta = (M_PI * 2) / static_cast<float>( resolution ); // 1 for ( int lon = 0; lon < resolution+1; ++lon ) { const float theta = static_cast<float>( lon ) * dTheta; const float cosTheta = qCos( theta ); const float sinTheta = qSin( theta ); *fptr++ = radius * cosTheta; *fptr++ = 0.0; *fptr++ = radius * sinTheta; *fptr++ = cosTheta; *fptr++ = 0.0; // *fptr++ = sinTheta; *fptr++ = 1.0f; *fptr++ = 0.0f; *fptr++ = 0.0f; *fptr++ = 1.0f; } // 2 for ( int lon = 0; lon < resolution+1; ++lon ) { const float theta = static_cast<float>( lon ) * dTheta; const float cosTheta = qCos( theta ); const float sinTheta = qSin( theta ); *fptr++ = radius * cosTheta; *fptr++ = radius * sinTheta; *fptr++ = 0.0; *fptr++ = cosTheta; *fptr++ = sinTheta; *fptr++ = 0.0; *fptr++ = 0.0f; *fptr++ = 1.0f; *fptr++ = 0.0f; *fptr++ = 1.0f; } // 3 for ( int lon = 0; lon < resolution+1; ++lon ) { const float theta = static_cast<float>( lon ) * dTheta; const float cosTheta = qCos( theta ); const float sinTheta = qSin( theta ); *fptr++ = 0.0; *fptr++ = radius * cosTheta; *fptr++ = radius * sinTheta; *fptr++ = 0.0; *fptr++ = cosTheta; *fptr++ = sinTheta; *fptr++ = 0.0f; *fptr++ = 0.0f; *fptr++ = 1.0f; *fptr++ = 1.0f; } return bufferBytes; } QByteArray createCirclesIndexData(int resolution) { int linecnt = resolution * 2 * 3; QByteArray indexBytes; indexBytes.resize(linecnt * sizeof(quint16)); quint16 *indexPtr = reinterpret_cast<quint16*>(indexBytes.data()); int j = 0; for (int i = 0; i < resolution; ++i) { *indexPtr++ = j; *indexPtr++ = ++j; } j++; for (int i = 0; i < resolution; ++i) { *indexPtr++ = j; *indexPtr++ = ++j; } j++; for (int i = 0; i < resolution; ++i) { *indexPtr++ = j; *indexPtr++ = ++j; } return indexBytes; } CircBallMesh::CircBallMesh(QNode *parent) : QGeometryRenderer(parent) { auto geometry = new Qt3DRender::QGeometry(this); setPrimitiveType(QGeometryRenderer::Lines); setGeometry(geometry); m_positionAttribute = new Qt3DRender::QAttribute(geometry); m_normalAttribute = new Qt3DRender::QAttribute(geometry); m_colorAttribute = new Qt3DRender::QAttribute(geometry); m_indexAttribute = new Qt3DRender::QAttribute(geometry); m_vertexBuffer = new Qt3DRender::QBuffer(Qt3DRender::QBuffer::VertexBuffer, geometry); m_indexBuffer = new Qt3DRender::QBuffer(Qt3DRender::QBuffer::IndexBuffer, geometry); m_vertexBuffer->setData(createCirclesVertexData(m_radius, m_resolution)); m_indexBuffer->setData(createCirclesIndexData(m_resolution)); const quint32 elementSize = 3 + 3 + 4; const quint32 stride = elementSize * sizeof(float); const int nVerts = (m_resolution+1) * 3; const int faces = m_resolution * 2 * 3; m_positionAttribute->setName(Qt3DRender::QAttribute::defaultPositionAttributeName()); m_positionAttribute->setVertexBaseType(Qt3DRender::QAttribute::Float); m_positionAttribute->setVertexSize(3); m_positionAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute); m_positionAttribute->setBuffer(m_vertexBuffer); m_positionAttribute->setByteStride(stride); m_positionAttribute->setCount(nVerts); m_normalAttribute->setName(Qt3DRender::QAttribute::defaultNormalAttributeName()); m_normalAttribute->setVertexBaseType(Qt3DRender::QAttribute::Float); m_normalAttribute->setVertexSize(3); m_normalAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute); m_normalAttribute->setBuffer(m_vertexBuffer); m_normalAttribute->setByteStride(stride); m_normalAttribute->setByteOffset(3 * sizeof(float)); m_normalAttribute->setCount(nVerts); m_colorAttribute->setName(Qt3DRender::QAttribute::defaultColorAttributeName()); m_colorAttribute->setVertexBaseType(Qt3DRender::QAttribute::Float); m_colorAttribute->setVertexSize(4); m_colorAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute); m_colorAttribute->setBuffer(m_vertexBuffer); m_colorAttribute->setByteStride(stride); m_colorAttribute->setByteOffset(6 * sizeof(float)); m_colorAttribute->setCount(nVerts); m_indexAttribute->setAttributeType(Qt3DRender::QAttribute::IndexAttribute); m_indexAttribute->setVertexBaseType(Qt3DRender::QAttribute::UnsignedShort); m_indexAttribute->setBuffer(m_indexBuffer); m_indexAttribute->setCount(faces); geometry->addAttribute(m_positionAttribute); geometry->addAttribute(m_normalAttribute); geometry->addAttribute(m_colorAttribute); geometry->addAttribute(m_indexAttribute); }
31.607735
91
0.627513
Simi4
7e58b79975cc0b346c9a1625914694555b9d8901
4,173
cxx
C++
PWGJE/EMCALJetTasks/Tracks/AliAnalysisTaskEmcalOutliersGen.cxx
ilyafokin/AliPhysics
7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4
[ "BSD-3-Clause" ]
1
2020-07-18T17:36:58.000Z
2020-07-18T17:36:58.000Z
PWGJE/EMCALJetTasks/Tracks/AliAnalysisTaskEmcalOutliersGen.cxx
ilyafokin/AliPhysics
7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4
[ "BSD-3-Clause" ]
null
null
null
PWGJE/EMCALJetTasks/Tracks/AliAnalysisTaskEmcalOutliersGen.cxx
ilyafokin/AliPhysics
7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4
[ "BSD-3-Clause" ]
1
2022-01-24T11:11:09.000Z
2022-01-24T11:11:09.000Z
#include <sstream> #include "AliAnalysisTaskEmcalOutliersGen.h" #include "AliAnalysisManager.h" #include "AliEmcalJet.h" #include "AliJetContainer.h" #include "AliMCEvent.h" #include "AliParticleContainer.h" #include "AliVParticle.h" ClassImp(PWGJE::EMCALJetTasks::AliAnalysisTaskEmcalOutliersGen) using namespace PWGJE::EMCALJetTasks; AliAnalysisTaskEmcalOutliersGen::AliAnalysisTaskEmcalOutliersGen(): AliAnalysisTaskEmcalJet(), fHistJetPt(nullptr) { } AliAnalysisTaskEmcalOutliersGen::AliAnalysisTaskEmcalOutliersGen(const char *name): AliAnalysisTaskEmcalJet(name, kTRUE), fHistJetPt(nullptr) { SetMakeGeneralHistograms(true); SetGetPtHardBinFromPath(kFALSE); SetIsPythia(true); } void AliAnalysisTaskEmcalOutliersGen::UserCreateOutputObjects() { AliAnalysisTaskEmcalJet::UserCreateOutputObjects(); fHistJetPt = new TH1F("fHistJetPt", "Jet pt", 1000, 0., 1000.); fOutput->Add(fHistJetPt); PostData(1, fOutput); } bool AliAnalysisTaskEmcalOutliersGen::Run() { auto particles = GetParticleContainer("mcparticlesSelected"); //auto particles = GetParticleContainer("mcparticles"); auto jets = GetJetContainer("partjets"); double partptmin[21] = {0., 20., 25., 30., 40., 50., 70., 80., 100., 120., 140., 180., 200., 250., 270., 300., 350., 380., 420., 450., 600.}; //std::cout << "Using pt-hard cut " << partptmin[fPtHardBin] << " for pt-hard bin " << fPtHardBin << std::endl; for(auto j : jets->accepted()){ fHistJetPt->Fill(j->Pt()); if(j->Pt() > partptmin[fPtHardBin]) { std::cout << "Outlier jet found, pt > " << j->Pt() << " GeV/c, NEF = " << j->NEF() << ", " << j->GetNumberOfTracks() << " / " << j->GetNumberOfClusters() << " constituents" << std::endl; for(int i = 0; i < j->GetNumberOfTracks(); i++){ auto part = j->TrackAt(i, particles->GetArray()); auto z = j->GetZ(part->Px(), part->Py(), part->Pz()); auto mother = part->GetMother() > -1 ? MCEvent()->GetTrack(part->GetMother()) : nullptr; std::cout << "Particle " << i << ": pt " << part->Pt() << " GeV/c, z " << z << ", pdg " << part->PdgCode(); if(mother) { std::cout << ", mother pdg " << mother->PdgCode() << ", mother pt " << mother->Pt(); auto grandmother = mother->GetMother() > -1 ? MCEvent()->GetTrack(mother->GetMother()) : nullptr; if(grandmother) { std::cout << ", grandmother pdg " << grandmother->PdgCode() << ", grandmother pt " << grandmother->Pt(); } else { std::cout << ", no grand mother"; } } else { std::cout << ", no mother"; } std::cout << std::endl; } } } return true; } AliAnalysisTaskEmcalOutliersGen *AliAnalysisTaskEmcalOutliersGen::AddTaskEmcalOutliersGen(const char *name) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if(!mgr){ ::Error("EmcalTriggerJets::AliAnalysisTaskEmcalJetEnergyScale::AddTaskJetEnergyScale", "No analysis manager available"); return nullptr; } auto task = new AliAnalysisTaskEmcalOutliersGen(name); mgr->AddTask(task); auto partcont = task->AddMCParticleContainer("mcparticlesSelected"); //auto partcont = task->AddMCParticleContainer("mcparticles"); partcont->SetMinPt(0.); auto contjet = task->AddJetContainer(AliJetContainer::kFullJet, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, 0.2, AliJetContainer::kTPCfid, partcont, nullptr); contjet->SetName("partjets"); contjet->SetMaxTrackPt(1000.); std::stringstream outnamebuilder; outnamebuilder << mgr->GetCommonFileName() << ":Outliers"; mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer("OutlierHists", TList::Class(), AliAnalysisManager::kOutputContainer, outnamebuilder.str().data())); return task; }
40.514563
151
0.615385
ilyafokin
7e5a886dc544675b6477934205740aa2262e7048
4,568
cpp
C++
Source/MLApp/MLNetServiceHub.cpp
afofo/madronalib
14816a124c8d3a225540ffb408e602aa024fdb4b
[ "MIT" ]
null
null
null
Source/MLApp/MLNetServiceHub.cpp
afofo/madronalib
14816a124c8d3a225540ffb408e602aa024fdb4b
[ "MIT" ]
null
null
null
Source/MLApp/MLNetServiceHub.cpp
afofo/madronalib
14816a124c8d3a225540ffb408e602aa024fdb4b
[ "MIT" ]
null
null
null
// MadronaLib: a C++ framework for DSP applications. // Copyright (c) 2013 Madrona Labs LLC. http://www.madronalabs.com // Distributed under the MIT license: http://madrona-labs.mit-license.org/ /* Portions adapted from Oscbonjour: Copyright (c) 2005-2009 RÈmy Muller. 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. Any person wishing to distribute modifications to the Software is requested to send the modifications to the original developer so that they can be incorporated into the canonical version. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "MLPlatform.h" #if ML_WINDOWS // TODO #else #include "MLNetServiceHub.h" using namespace ZeroConf; //------------------------------------------------------------------------------------------------------------ MLNetServiceHub::MLNetServiceHub() : browser(0), resolver(0), service(0) { } MLNetServiceHub::~MLNetServiceHub() { if(browser) delete browser; if(resolver)delete resolver; if(service) delete service; } void MLNetServiceHub::Browse(const char *type, const char *domain) { if(browser) delete browser; browser = 0; browser = new NetServiceBrowser(); browser->setListener(this); browser->searchForServicesOfType(type, domain); } void MLNetServiceHub::Resolve(const char *name, const char *type, const char *domain) { if(resolver) delete resolver; resolver = 0; resolver = new NetService(domain,type,name); resolver->setListener(this); resolver->resolveWithTimeout(10.0, false); // ML temp } bool MLNetServiceHub::pollService(DNSServiceRef dnsServiceRef, double timeOutInSeconds, DNSServiceErrorType &err) { assert(dnsServiceRef); err = kDNSServiceErr_NoError; fd_set readfds; FD_ZERO(&readfds); int dns_sd_fd = DNSServiceRefSockFD(dnsServiceRef); int nfds = dns_sd_fd+1; FD_SET(dns_sd_fd, &readfds); struct timeval tv; tv.tv_sec = long(floor(timeOutInSeconds)); tv.tv_usec = long(1000000*(timeOutInSeconds - tv.tv_sec)); int result = select(nfds,&readfds,NULL,NULL,&tv); if(result>0 && FD_ISSET(dns_sd_fd, &readfds)) { err = DNSServiceProcessResult(dnsServiceRef); return true; } return false; } void MLNetServiceHub::PollNetServices() { if(resolver && resolver->getDNSServiceRef()) { printf("PollNetServices::polling...\n"); DNSServiceErrorType err = kDNSServiceErr_NoError; if(pollService(resolver->getDNSServiceRef(), 0.001, err)) { printf("PollNetServices::stop.\n"); resolver->stop(); } } } void MLNetServiceHub::publishUDPService(const char *name, int port) { if(service) delete service; service = 0; service = new NetService("local.", "_osc._udp", name, port); service->setListener(this); service->publish(false); } void MLNetServiceHub::didFindService(NetServiceBrowser* pNetServiceBrowser, NetService *pNetService, bool moreServicesComing) { veciterator it = std::find(services.begin(),services.end(), pNetService->getName()); if(it!=services.end()) return; // we already have it services.push_back(pNetService->getName()); } void MLNetServiceHub::didRemoveService(NetServiceBrowser *pNetServiceBrowser, NetService *pNetService, bool moreServicesComing) { veciterator it = std::find(services.begin(),services.end(), pNetService->getName()); if(it==services.end()) return; // we don't have it //long index = it-services.begin(); // store the position services.erase(it); } void MLNetServiceHub::didResolveAddress(NetService *pNetService) { // const std::string& hostName = pNetService->getHostName(); // int port = pNetService->getPort(); } void MLNetServiceHub::didPublish(NetService *pNetService) { } #endif // ML_WINDOWS
29.282051
127
0.734895
afofo
7e5e7118af19ed17cd0101f5dca9ff4f5480d793
1,148
cpp
C++
src/spectral_embedding_layout.cpp
erwinvaneijk/bgl-python
6731d1e0e9681e99f1ad0a876b2adb8139d93027
[ "BSL-1.0" ]
18
2015-06-19T08:44:21.000Z
2021-07-23T11:09:05.000Z
src/spectral_embedding_layout.cpp
erwinvaneijk/bgl-python
6731d1e0e9681e99f1ad0a876b2adb8139d93027
[ "BSL-1.0" ]
null
null
null
src/spectral_embedding_layout.cpp
erwinvaneijk/bgl-python
6731d1e0e9681e99f1ad0a876b2adb8139d93027
[ "BSL-1.0" ]
3
2015-07-13T07:50:49.000Z
2020-10-26T15:08:03.000Z
#include <boost/graph/spectral_embedding_3d_layout.hpp> #include "graph_types.hpp" #include <boost/graph/python/point2d.hpp> #include <boost/graph/python/point3d.hpp> #include <boost/graph/python/graph.hpp> #include <boost/python.hpp> namespace boost { namespace graph { namespace python { template <typename Graph> void spectral_embedding_layout (Graph& g, const vector_property_map<point3d, typename Graph::VertexIndexMap>* in_pos) { using boost::python::object; typedef typename property_map<Graph, vertex_index_t>::const_type VertexIndexMap; typedef vector_property_map<point3d, VertexIndexMap> PositionMap; typedef vector_property_map<vertex_index_t, VertexIndexMap> IndexMap; PositionMap pos = *in_pos; boost::spectral_embedding_layout(g, pos); } void export_spectral_embedding_layout() { using boost::python::arg; using boost::python::def; using boost::python::object; def("spectral_embedding_layout", &spectral_embedding_layout<Graph>, (arg("graph"), arg("position") = (vector_property_map<point2d, Graph::VertexIndexMap>*)0)); } } } } // end namespace boost::graph::python
27.333333
82
0.751742
erwinvaneijk
7e601575baaec490902abfffcded67583565afd8
11,044
cpp
C++
sources/leddevice/dev_net/ProviderUdpSSL.cpp
awawa-dev/hyperion.ng
459aa9b81fe04bfd7a259d761a0fdff94178e10d
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
2
2020-08-24T10:02:51.000Z
2020-08-24T20:03:50.000Z
sources/leddevice/dev_net/ProviderUdpSSL.cpp
awawa-dev/hyperion.ng
459aa9b81fe04bfd7a259d761a0fdff94178e10d
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
null
null
null
sources/leddevice/dev_net/ProviderUdpSSL.cpp
awawa-dev/hyperion.ng
459aa9b81fe04bfd7a259d761a0fdff94178e10d
[ "MIT-0", "Apache-2.0", "CC-BY-4.0", "MIT" ]
null
null
null
/* ProviderUdpSSL.cpp * * MIT License * * Copyright (c) 2021 awawa-dev * * Project homesite: https://github.com/awawa-dev/HyperHDR * * 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. */ // STL includes #include <cstdio> #include <exception> #include <algorithm> // Linux includes #include <fcntl.h> #ifndef _WIN32 #include <sys/ioctl.h> #endif #include <QUdpSocket> #include <QThread> // Local HyperHDR includes #include "ProviderUdpSSL.h" const int MAX_RETRY = 20; const ushort MAX_PORT_SSL = 65535; ProviderUdpSSL::ProviderUdpSSL(const QJsonObject& deviceConfig) : LedDevice(deviceConfig) , client_fd() , entropy() , ssl() , conf() , cacert() , ctr_drbg() , timer() , _transport_type("DTLS") , _custom("dtls_client") , _address("127.0.0.1") , _defaultHost("127.0.0.1") , _port(1) , _ssl_port(1) , _server_name() , _psk() , _psk_identity() , _handshake_attempts(5) , _retry_left(MAX_RETRY) , _streamReady(false) , _streamPaused(false) , _handshake_timeout_min(300) , _handshake_timeout_max(1000) { bool error = false; try { mbedtls_ctr_drbg_init(&ctr_drbg); error = !seedingRNG(); } catch (...) { error = true; } if (error) Error(_log, "Failed to initialize mbedtls seed"); } ProviderUdpSSL::~ProviderUdpSSL() { closeConnection(); mbedtls_ctr_drbg_free(&ctr_drbg); mbedtls_entropy_free(&entropy); } bool ProviderUdpSSL::init(const QJsonObject& deviceConfig) { bool isInitOK = false; // Initialise sub-class if (LedDevice::init(deviceConfig)) { //PSK Pre Shared Key _psk = deviceConfig["psk"].toString(); _psk_identity = deviceConfig["psk_identity"].toString(); _port = deviceConfig["sslport"].toInt(2100); _server_name = deviceConfig["servername"].toString(); if (deviceConfig.contains("transport_type")) _transport_type = deviceConfig["transport_type"].toString("DTLS"); if (deviceConfig.contains("seed_custom")) _custom = deviceConfig["seed_custom"].toString("dtls_client"); if (deviceConfig.contains("retry_left")) _retry_left = deviceConfig["retry_left"].toInt(MAX_RETRY); if (deviceConfig.contains("hs_attempts")) _handshake_attempts = deviceConfig["hs_attempts"].toInt(5); if (deviceConfig.contains("hs_timeout_min")) _handshake_timeout_min = deviceConfig["hs_timeout_min"].toInt(300); if (deviceConfig.contains("hs_timeout_max")) _handshake_timeout_max = deviceConfig["hs_timeout_max"].toInt(1000); QString host = deviceConfig["host"].toString(_defaultHost); if (_address.setAddress(host)) { Debug(_log, "Successfully parsed %s as an ip address.", QSTRING_CSTR(host)); } else { Debug(_log, "Failed to parse [%s] as an ip address.", QSTRING_CSTR(host)); QHostInfo info = QHostInfo::fromName(host); if (info.addresses().isEmpty()) { Debug(_log, "Failed to parse [%s] as a hostname.", QSTRING_CSTR(host)); QString errortext = QString("Invalid target address [%1]!").arg(host); this->setInError(errortext); isInitOK = false; } else { Debug(_log, "Successfully parsed %s as a hostname.", QSTRING_CSTR(host)); _address = info.addresses().first(); } } int config_port = deviceConfig["sslport"].toInt(_port); if (config_port <= 0 || config_port > MAX_PORT_SSL) { QString errortext = QString("Invalid target port [%1]!").arg(config_port); this->setInError(errortext); isInitOK = false; } else { _ssl_port = config_port; Debug(_log, "UDP SSL using %s:%u", QSTRING_CSTR(_address.toString()), _ssl_port); isInitOK = true; } } return isInitOK; } const int* ProviderUdpSSL::getCiphersuites() const { return mbedtls_ssl_list_ciphersuites(); } bool ProviderUdpSSL::initNetwork() { if ((!_isDeviceReady || _streamPaused) && _streamReady) closeConnection(); if (!initConnection()) return false; return true; } int ProviderUdpSSL::closeNetwork() { closeConnection(); return 0; } bool ProviderUdpSSL::initConnection() { if (_streamReady) return true; mbedtls_net_init(&client_fd); mbedtls_ssl_init(&ssl); mbedtls_ssl_config_init(&conf); mbedtls_x509_crt_init(&cacert); if (setupStructure()) { _streamReady = true; _streamPaused = false; _isDeviceReady = true; return true; } else return false; } void ProviderUdpSSL::closeConnection() { if (_streamReady) { closeSSLNotify(); freeSSLConnection(); _streamReady = false; } } bool ProviderUdpSSL::seedingRNG() { mbedtls_entropy_init(&entropy); QByteArray customDataArray = _custom.toLocal8Bit(); const char* customData = customDataArray.constData(); int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, reinterpret_cast<const unsigned char*>(customData), std::min(strlen(customData), (size_t)MBEDTLS_CTR_DRBG_MAX_SEED_INPUT)); if (ret != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_ctr_drbg_seed FAILED %1").arg(errorMsg(ret)))); return false; } return true; } bool ProviderUdpSSL::setupStructure() { int transport = (_transport_type == "DTLS") ? MBEDTLS_SSL_TRANSPORT_DATAGRAM : MBEDTLS_SSL_TRANSPORT_STREAM; int ret = mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, transport, MBEDTLS_SSL_PRESET_DEFAULT); if (ret != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_ssl_config_defaults FAILED %1").arg(errorMsg(ret)))); return false; } const int* ciphersuites = getCiphersuites(); mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_REQUIRED); mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL); mbedtls_ssl_conf_handshake_timeout(&conf, _handshake_timeout_min, _handshake_timeout_max); mbedtls_ssl_conf_ciphersuites(&conf, ciphersuites); mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg); if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_ssl_setup FAILED %1").arg(errorMsg(ret)))); return false; } return startUPDConnection(); } bool ProviderUdpSSL::startUPDConnection() { mbedtls_ssl_session_reset(&ssl); if (!setupPSK()) return false; int ret = mbedtls_net_connect(&client_fd, _address.toString().toUtf8(), std::to_string(_ssl_port).c_str(), MBEDTLS_NET_PROTO_UDP); if (ret != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_net_connect FAILED %1").arg(errorMsg(ret)))); return false; } mbedtls_ssl_set_bio(&ssl, &client_fd, mbedtls_net_send, mbedtls_net_recv, mbedtls_net_recv_timeout); mbedtls_ssl_set_timer_cb(&ssl, &timer, mbedtls_timing_set_delay, mbedtls_timing_get_delay); return startSSLHandshake(); } bool ProviderUdpSSL::setupPSK() { QByteArray pskRawArray = QByteArray::fromHex(_psk.toUtf8()); QByteArray pskIdRawArray = _psk_identity.toUtf8(); int ret = mbedtls_ssl_conf_psk(&conf, reinterpret_cast<const unsigned char*> (pskRawArray.constData()), pskRawArray.length(), reinterpret_cast<const unsigned char*> (pskIdRawArray.constData()), pskIdRawArray.length()); if (ret != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_ssl_conf_psk FAILED %1").arg(errorMsg(ret)))); return false; } return true; } bool ProviderUdpSSL::startSSLHandshake() { int ret = 0; for (unsigned int attempt = 1; attempt <= _handshake_attempts; ++attempt) { do { ret = mbedtls_ssl_handshake(&ssl); } while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE); if (ret == 0) { break; } else { Warning(_log, "%s", QSTRING_CSTR(QString("mbedtls_ssl_handshake attempt %1/%2 FAILED. Reason: %3").arg(attempt).arg(_handshake_attempts).arg(errorMsg(ret)))); } QThread::msleep(200); } if (ret != 0) { Error(_log, "%s", QSTRING_CSTR(QString("mbedtls_ssl_handshake FAILED %1").arg(errorMsg(ret)))); return false; } else { if (mbedtls_ssl_get_verify_result(&ssl) != 0) { Error(_log, "SSL certificate verification failed!"); return false; } } return true; } void ProviderUdpSSL::freeSSLConnection() { try { Warning(_log, "Release mbedtls"); mbedtls_ssl_session_reset(&ssl); mbedtls_net_free(&client_fd); mbedtls_ssl_free(&ssl); mbedtls_ssl_config_free(&conf); mbedtls_x509_crt_free(&cacert); } catch (std::exception& e) { Error(_log, "%s", QSTRING_CSTR(QString("SSL Connection clean-up Error: %s").arg(e.what()))); } catch (...) { Error(_log, "SSL Connection clean-up Error: <unknown>"); } } void ProviderUdpSSL::writeBytes(unsigned int size, const uint8_t* data, bool flush) { if (!_streamReady || _streamPaused) return; if (!_streamReady || _streamPaused) return; _streamPaused = flush; int ret = 0; do { ret = mbedtls_ssl_write(&ssl, data, size); } while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE); if (ret <= 0) { Error(_log, "Error while writing UDP SSL stream updates. mbedtls_ssl_write returned: %s", QSTRING_CSTR(errorMsg(ret))); if (_streamReady) { closeConnection(); // look for the host QUdpSocket socket; for (int i = 1; i <= _retry_left; i++) { Warning(_log, "Searching the host: %s (trial %i/%i)", QSTRING_CSTR(this->_address.toString()), i, _retry_left); socket.connectToHost(_address, _ssl_port); if (socket.waitForConnected(1000)) { Warning(_log, "Found host: %s", QSTRING_CSTR(this->_address.toString())); socket.close(); break; } else QThread::msleep(1000); } Warning(_log, "Hard restart of the LED device (host: %s).", QSTRING_CSTR(this->_address.toString())); // hard reset Warning(_log, "Disabling..."); this->disableDevice(false); Warning(_log, "Enabling..."); this->enableDevice(false); if (!_isOn) emit enableStateChanged(false); } } } QString ProviderUdpSSL::errorMsg(int ret) { char error_buf[1024]; mbedtls_strerror(ret, error_buf, 1024); return QString("Last error was: code = %1, description = %2").arg(ret).arg(error_buf); } void ProviderUdpSSL::closeSSLNotify() { /* No error checking, the connection might be closed already */ while (mbedtls_ssl_close_notify(&ssl) == MBEDTLS_ERR_SSL_WANT_WRITE); }
24.930023
161
0.711246
awawa-dev
7e6192e0b4144d477c15f9b0043c03b279b862d5
2,598
hh
C++
include/simlib/path.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
null
null
null
include/simlib/path.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
1
2017-01-05T17:50:32.000Z
2017-01-05T17:50:32.000Z
include/simlib/path.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
1
2017-01-05T15:26:48.000Z
2017-01-05T15:26:48.000Z
#pragma once #include "simlib/string_view.hh" #include <optional> // Returns an absolute path that does not contain any . or .. components, // nor any repeated path separators (/). @p curr_dir can be empty. If path // begins with / then @p curr_dir is ignored. std::string path_absolute(StringView path, std::string curr_dir = "/"); /** * @brief Returns the filename (last non-directory component) of the @p path * @details Examples: * "/my/path/foo.bar" -> "foo.bar" * "/my/path/" -> "" * "/" -> "" * "/my/path/." -> "." * "/my/path/.." -> ".." * "foo" -> "foo" */ template <class T> constexpr auto path_filename(T&& path) noexcept { using RetType = std::conditional_t<std::is_convertible_v<T, CStringView>, CStringView, StringView>; RetType path_str(std::forward<T>(path)); auto pos = path_str.rfind('/'); return path_str.substr(pos == path_str.npos ? 0 : pos + 1); } // Returns extension (without dot) e.g. "foo.cc" -> "cc", "bar" -> "" template <class T> constexpr auto path_extension(T&& path) noexcept { using RetType = std::conditional_t<std::is_convertible_v<T, CStringView>, CStringView, StringView>; RetType path_str(std::forward<T>(path)); size_t start_pos = path_str.rfind('/'); if (start_pos == path_str.npos) { start_pos = 0; } else { ++start_pos; } size_t x = path_str.rfind('.', start_pos); if (x == path_str.npos) { return RetType{}; // No extension } return path_str.substr(x + 1); } /** * @brief Returns prefix of the @p path that is a dirpath of the @p path * @details Examples: * "/my/path/foo.bar" -> "/my/path/" * "/my/path/" -> "/my/path/" * "/" -> "/" * "/my/path/." -> "/my/path/" * "/my/path/.." -> "/my/path/" * "abc/efg" -> "abc/" * "foo" -> "" */ constexpr inline StringView path_dirpath(const StringView& path) noexcept { auto pos = path.rfind('/'); return path.substring(0, pos == StringView::npos ? 0 : pos + 1); } /** * @brief Checks every ancestor (parent) directory of @p path if it has @p * subpath and if true returns path of @p subpath in ancestor directory * @details Examples: * 1) @p path == "a/b/c/file", @p subpath == "/x/y/z", tried paths will be: * "a/b/c/x/y/z" * "a/b/x/y/z" * "a/x/y/z" * "x/y/z" * 2) @p path == "/a/b/c/", @p subpath == "x/y/", tried paths will be: * "/a/b/c/x/y/" * "/a/b/x/y/" * "/a/x/y/" * "/x/y/" */ std::optional<std::string> deepest_ancestor_dir_with_subpath( std::string path, StringView subpath);
30.209302
95
0.583911
varqox
7e621e71d124b15e23b13a09b48b5bf4b41785bd
757
cpp
C++
inference-engine/tests_deprecated/behavior/gna/shared_tests_instances/plugin_tests/behavior_test_plugin_layout.cpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
1
2020-06-21T09:51:42.000Z
2020-06-21T09:51:42.000Z
inference-engine/tests_deprecated/behavior/gna/shared_tests_instances/plugin_tests/behavior_test_plugin_layout.cpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
4
2021-04-01T08:29:48.000Z
2021-08-30T16:12:52.000Z
inference-engine/tests_deprecated/behavior/gna/shared_tests_instances/plugin_tests/behavior_test_plugin_layout.cpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
3
2021-03-09T08:27:29.000Z
2021-04-07T04:58:54.000Z
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "behavior_test_plugin_layout.hpp" layout_test_params activ_test_cases[] = { // layout_test_params(CommonTestUtils::DEVICE_GNA, "FP32", Layout::C, power_params({ { 3 } }, 1, 2, 2)), layout_test_params(CommonTestUtils::DEVICE_GNA, "FP32", Layout::NC, power_params({ { 1, 3 } }, 1, 2, 2)), layout_test_params(CommonTestUtils::DEVICE_GNA, "FP32", Layout::CHW, power_params({ { 3, 32, 16 } }, 1, 2, 2)), layout_test_params(CommonTestUtils::DEVICE_GNA, "FP32", Layout::NCHW, power_params({ { 1, 3, 16, 16 } }, 2, 2, 2)), }; INSTANTIATE_TEST_CASE_P(smoke_BehaviorTest, LayoutTestCanLoadActiv, ::testing::ValuesIn(activ_test_cases), getTestName);
47.3125
119
0.706737
anton-potapov
7e6663467290bb6116f291ae3132fa73dbc32ed3
22,362
cc
C++
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/language/io/gdal/gdal_dataset.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/language/io/gdal/gdal_dataset.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/language/io/gdal/gdal_dataset.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
// ----------------------------------------------------------------------------- // Fern © Geoneric // // This file is part of Geoneric Fern which is available under the terms of // the GNU General Public License (GPL), version 2. If you do not want to // be bound by the terms of the GPL, you may purchase a proprietary license // from Geoneric (http://www.geoneric.eu/contact). // ----------------------------------------------------------------------------- #include "fern/language/io/gdal/gdal_dataset.h" #include "gdal_priv.h" #include "fern/core/io_error.h" #include "fern/core/path.h" #include "fern/core/type_traits.h" #include "fern/core/value_type_traits.h" #include "fern/language/feature/visitor/attribute_type_visitor.h" #include "fern/language/io/core/file.h" #include "fern/language/io/gdal/gdal_data_type_traits.h" #include "fern/language/io/gdal/gdal_type_traits.h" namespace fern { namespace language { namespace { ::GDALDataset* gdal_open_for_read( GDALDriver const& driver, std::string const& name) { GDALOpenInfo open_info(name.c_str(), GA_ReadOnly); ::GDALDataset* dataset = static_cast<::GDALDataset*>(driver.pfnOpen( &open_info)); if(!dataset) { if(!file_exists(name)) { throw IOError(name, Exception::messages()[MessageId::DOES_NOT_EXIST]); } else { throw IOError(name, Exception::messages()[MessageId::CANNOT_BE_READ]); } } return dataset; } ::GDALDataset* gdal_open_for_update( GDALDriver const& driver, std::string const& name) { GDALOpenInfo open_info(name.c_str(), GA_Update); ::GDALDataset* dataset = static_cast<::GDALDataset*>(driver.pfnOpen( &open_info)); if(!dataset) { if(!file_exists(name)) { throw IOError(name, Exception::messages()[MessageId::DOES_NOT_EXIST]); } else { throw IOError(name, Exception::messages()[MessageId::CANNOT_BE_WRITTEN]); } } return dataset; } ::GDALDataset* gdal_open( GDALDriver const& driver, std::string const& name, OpenMode open_mode) { ::GDALDataset* dataset = nullptr; switch(open_mode) { case OpenMode::READ: { dataset = gdal_open_for_read(driver, name); break; } case OpenMode::UPDATE: { dataset = gdal_open_for_update(driver, name); break; } case OpenMode::OVERWRITE: { // The dataset may not yet exist. In any case, we will be // overwriting it. If it exists, we can delete it now. driver.QuietDelete(name.c_str()); break; } } assert(dataset || open_mode == OpenMode::OVERWRITE); return dataset; } template< class T> ::GDALDataset* create_gdal_dataset( GDALDriver& driver, FieldAttribute<T> const& field, std::string const& name) { assert(field.values().size() == 1u); FieldValue<T> const& array(*field.values().cbegin()->second); int nr_rows = array.shape()[0]; int nr_cols = array.shape()[1]; int nr_bands = 1; char** options = NULL; ::GDALDataset* dataset = driver.Create(name.c_str(), nr_cols, nr_rows, nr_bands, GDALTypeTraits<T>::data_type, options); if(!dataset) { throw IOError(name, Exception::messages()[MessageId::CANNOT_BE_CREATED]); } return dataset; } #define GDAL_DATA_TYPE_TO_VALUE_TYPES_CASE( \ gdal_data_type) \ case gdal_data_type: { \ result = TypeTraits<GDALDataTypeTraits< \ gdal_data_type>::type>::value_types; \ break; \ } ValueTypes gdal_data_type_to_value_types( GDALDataType data_type) { ValueTypes result; switch(data_type) { GDAL_DATA_TYPE_TO_VALUE_TYPES_CASE(GDT_Byte) GDAL_DATA_TYPE_TO_VALUE_TYPES_CASE(GDT_UInt16) GDAL_DATA_TYPE_TO_VALUE_TYPES_CASE(GDT_Int16) GDAL_DATA_TYPE_TO_VALUE_TYPES_CASE(GDT_UInt32) GDAL_DATA_TYPE_TO_VALUE_TYPES_CASE(GDT_Int32) GDAL_DATA_TYPE_TO_VALUE_TYPES_CASE(GDT_Float32) GDAL_DATA_TYPE_TO_VALUE_TYPES_CASE(GDT_Float64) default: { assert(false); // TODO Throw error stating the data type is not supported. The // caller should add more info. } // case GDT_CInt16: { // throw IOError(this->name(), // Exception::messages().format_message( // MessageId::UNSUPPORTED_VALUE_TYPE, // path, GDALDataTypeTraits<GDT_CInt16>::name)); // } // case GDT_CInt32: { // throw IOError(this->name(), // Exception::messages().format_message( // MessageId::UNSUPPORTED_VALUE_TYPE, // path, GDALDataTypeTraits<GDT_CInt32>::name)); // } // case GDT_CFloat32: { // throw IOError(this->name(), // Exception::messages().format_message( // MessageId::UNSUPPORTED_VALUE_TYPE, // path, GDALDataTypeTraits<GDT_CFloat32>::name)); // } // case GDT_CFloat64: { // throw IOError(this->name(), // Exception::messages().format_message( // MessageId::UNSUPPORTED_VALUE_TYPE, // path, GDALDataTypeTraits<GDT_CFloat64>::name)); // } // case GDT_TypeCount: { // throw IOError(this->name(), // Exception::messages().format_message( // MessageId::UNSUPPORTED_VALUE_TYPE, // path, GDALDataTypeTraits<GDT_TypeCount>::name)); // } // case GDT_Unknown: { // throw IOError(this->name(), // Exception::messages().format_message( // MessageId::UNSUPPORTED_VALUE_TYPE, // path, GDALDataTypeTraits<GDT_Unknown>::name)); // } } return result; } #undef GDAL_DATA_TYPE_TO_VALUE_TYPES_CASE } // Anonymous namespace GDALDataset::GDALDataset( ::GDALDriver* driver, std::string const& name, OpenMode open_mode) : Dataset(name, open_mode), _driver(driver), _dataset(nullptr) { assert(driver); _dataset = gdal_open(*_driver, this->name(), this->open_mode()); } GDALDataset::GDALDataset( std::string const& format, std::string const& name, OpenMode open_mode) : Dataset(name, open_mode), _driver(GetGDALDriverManager()->GetDriverByName(format.c_str())), _dataset(nullptr) { assert(_driver); _dataset = gdal_open(*_driver, this->name(), this->open_mode()); } GDALDataset::GDALDataset( ::GDALDataset* dataset, std::string const& name, OpenMode open_mode) : Dataset(name, open_mode), _driver(dataset->GetDriver()), _dataset(dataset) { } GDALDataset::~GDALDataset() { // If this instance is created with open mode OVERWRITE, and the dataset // has not been created, then _dataset is still nullptr. if(_dataset) { GDALClose(_dataset); } } size_t GDALDataset::nr_features() const { return 1u; } std::vector<std::string> GDALDataset::feature_names() const { return std::vector<std::string>{Path(this->name()).stem().generic_string()}; } bool GDALDataset::contains_feature( Path const& path) const { // GDAL raster datasets contain one root feature, but no sub-features. // /<raster> return path == Path("/" + Path(this->name()).stem().generic_string()); } bool GDALDataset::contains_attribute( Path const& path) const { // The name of the one attribute in a GDAL raster equals the name of the // dataset without leading path and extension. It is prefixed by the path // to the feature, which is also named after the raster. // /<raster>/<raster> return Path(std::string("/") + Path(this->name()).stem().generic_string() + std::string("/") + Path(this->name()).stem().generic_string()) == path; } ExpressionType GDALDataset::expression_type( Path const& path) const { assert(_dataset); if(!contains_attribute(path)) { throw IOError(this->name(), Exception::messages().format_message( MessageId::DOES_NOT_CONTAIN_FEATURE, path)); } ExpressionType result; // Assume we need the first band only. assert(_dataset->GetRasterCount() == 1); GDALRasterBand* band = _dataset->GetRasterBand(1); assert(band); result = ExpressionType(DataTypes::STATIC_FIELD, gdal_data_type_to_value_types(band->GetRasterDataType())); return result; } std::shared_ptr<Feature> GDALDataset::open_feature( Path const& /* path */) const { std::shared_ptr<Feature> result; // TODO assert(false); return result; } template< class T> std::shared_ptr<FieldAttribute<T>> GDALDataset::open_attribute( GDALRasterBand& /* band */) const { FieldAttributePtr<T> attribute(std::make_shared<FieldAttribute<T>>()); return attribute; } #define OPEN_CASE( \ value_type) \ case value_type: { \ result = open_attribute<ValueTypeTraits<value_type>::type>(*band); \ break; \ } std::shared_ptr<Attribute> GDALDataset::open_attribute( Path const& path) const { GDALRasterBand* band = this->band(path); ValueType value_type = this->value_type(*band, path); std::shared_ptr<Attribute> result; switch(value_type) { OPEN_CASE(VT_UINT8); OPEN_CASE(VT_UINT16); OPEN_CASE(VT_UINT32); OPEN_CASE(VT_INT16); OPEN_CASE(VT_INT32); OPEN_CASE(VT_FLOAT32); OPEN_CASE(VT_FLOAT64); case VT_BOOL: case VT_CHAR: case VT_STRING: case VT_UINT64: case VT_INT8: case VT_INT64: { // These aren't support by gdal, so this shouldn't happen. assert(false); break; } } assert(result); return result; } #undef OPEN_CASE std::shared_ptr<Feature> GDALDataset::read_feature( Path const& path) const { if(!contains_feature(path)) { throw IOError(this->name(), Exception::messages().format_message( MessageId::DOES_NOT_CONTAIN_FEATURE, path)); } Path attribute_path = path / Path(this->name()).stem(); assert(contains_attribute(attribute_path)); std::shared_ptr<Feature> feature(std::make_shared<Feature>()); feature->add_attribute(attribute_path.filename().generic_string(), std::dynamic_pointer_cast<Attribute>(read_attribute(attribute_path))); return feature; } template< class T> std::shared_ptr<Attribute> GDALDataset::read_attribute( GDALRasterBand& band) const { int const nr_rows = _dataset->GetRasterYSize(); int const nr_cols = _dataset->GetRasterXSize(); double geo_transform[6]; if(_dataset->GetGeoTransform(geo_transform) != CE_None) { // According to the gdal docs: // The default transform is (0,1,0,0,0,1) and should be returned even // when a CE_Failure error is returned, such as for formats that don't // support transformation to projection coordinates. geo_transform[0] = 0.0; geo_transform[1] = 1.0; geo_transform[2] = 0.0; geo_transform[3] = 0.0; geo_transform[4] = 0.0; geo_transform[5] = 1.0; } assert(geo_transform[1] == std::abs(geo_transform[5])); double const cell_size = geo_transform[1]; d2::Point south_west, north_east; set<0>(south_west, geo_transform[0]); set<1>(north_east, geo_transform[3]); set<0>(north_east, get<0>(south_west) + nr_cols * cell_size); set<1>(south_west, get<1>(north_east) - nr_rows * cell_size); d2::Box box(south_west, north_east); FieldValuePtr<T> array(std::make_shared<FieldValue<T>>( extents[nr_rows][nr_cols])); assert(band.GetRasterDataType() == GDALTypeTraits<T>::data_type); if(band.RasterIO(GF_Read, 0, 0, nr_cols, nr_rows, array->data(), nr_cols, nr_rows, GDALTypeTraits<T>::data_type, 0, 0) != CE_None) { // This shouldn't happen. throw IOError(this->name(), Exception::messages()[MessageId::UNKNOWN_ERROR]); } // http://trac.osgeo.org/gdal/wiki/rfc15_nodatabitmask int mask_flags = band.GetMaskFlags(); if(!(mask_flags & GMF_ALL_VALID)) { assert(!(mask_flags & GMF_ALPHA)); GDALRasterBand* mask_band = band.GetMaskBand(); assert(mask_band->GetRasterDataType() == GDT_Byte); // The mask band has gdal data type GDT_Byte. A value of zero // means that the value must be masked. ArrayValue<typename GDALDataTypeTraits<GDT_Byte>::type, 2> mask( extents[nr_rows][nr_cols]); if(mask_band->RasterIO(GF_Read, 0, 0, nr_cols, nr_rows, mask.data(), nr_cols, nr_rows, GDT_Byte, 0, 0) != CE_None) { // This shouldn't happen. throw IOError(this->name(), Exception::messages()[MessageId::UNKNOWN_ERROR]); } array->set_mask(mask); } std::shared_ptr<FieldAttribute<T>> attribute(open_attribute<T>(band)); /* typename FieldAttribute<T>::GID gid = */ attribute->add(box, array); return std::dynamic_pointer_cast<Attribute>(attribute); } GDALRasterBand* GDALDataset::band( Path const& path) const { assert(_dataset); if(!contains_attribute(path)) { throw IOError(this->name(), Exception::messages().format_message( MessageId::DOES_NOT_CONTAIN_ATTRIBUTE, path)); } // Assume we need the first band only. assert(_dataset->GetRasterCount() == 1); GDALRasterBand* band = _dataset->GetRasterBand(1); assert(band); return band; } #define RASTER_DATA_TYPE_CASE( \ data_type) \ case data_type: { \ result = TypeTraits<GDALDataTypeTraits<data_type>::type>::value_type; \ break; \ } // TODO exception #define UNSUPPORTED_RASTER_DATA_TYPE_CASE( \ data_type) \ case data_type: { \ throw IOError(this->name(), \ Exception::messages().format_message( \ MessageId::UNSUPPORTED_VALUE_TYPE, \ path, GDALDataTypeTraits<data_type>::name)); \ break; \ } ValueType GDALDataset::value_type( GDALRasterBand& band, Path const& path) const { ValueType result{}; switch(band.GetRasterDataType()) { RASTER_DATA_TYPE_CASE(GDT_Byte); RASTER_DATA_TYPE_CASE(GDT_UInt16); RASTER_DATA_TYPE_CASE(GDT_Int16); RASTER_DATA_TYPE_CASE(GDT_UInt32); RASTER_DATA_TYPE_CASE(GDT_Int32); RASTER_DATA_TYPE_CASE(GDT_Float32); RASTER_DATA_TYPE_CASE(GDT_Float64); UNSUPPORTED_RASTER_DATA_TYPE_CASE(GDT_CInt16); UNSUPPORTED_RASTER_DATA_TYPE_CASE(GDT_CInt32); UNSUPPORTED_RASTER_DATA_TYPE_CASE(GDT_CFloat32); UNSUPPORTED_RASTER_DATA_TYPE_CASE(GDT_CFloat64); UNSUPPORTED_RASTER_DATA_TYPE_CASE(GDT_TypeCount); UNSUPPORTED_RASTER_DATA_TYPE_CASE(GDT_Unknown); } return result; } #undef UNSUPPORTED_RASTER_DATA_TYPE_CASE #undef RASTER_DATA_TYPE_CASE #define READ_CASE( \ value_type) \ case value_type: { \ result = read_attribute<ValueTypeTraits<value_type>::type>(*band); \ break; \ } std::shared_ptr<Attribute> GDALDataset::read_attribute( Path const& path) const { GDALRasterBand* band = this->band(path); ValueType value_type = this->value_type(*band, path); std::shared_ptr<Attribute> result; switch(value_type) { READ_CASE(VT_UINT8); READ_CASE(VT_UINT16); READ_CASE(VT_UINT32); READ_CASE(VT_INT16); READ_CASE(VT_INT32); READ_CASE(VT_FLOAT32); READ_CASE(VT_FLOAT64); case VT_BOOL: case VT_CHAR: case VT_STRING: case VT_UINT64: case VT_INT8: case VT_INT64: { // These aren't support by gdal, so this shouldn't happen. assert(false); break; } } assert(result); return result; } template< class T> void GDALDataset::write_attribute( FieldAttribute<T> const& field, #ifndef NDEBUG Path const& path #else Path const& /* path */ #endif ) { assert((_dataset && (open_mode() == OpenMode::UPDATE)) || (!_dataset && (open_mode() == OpenMode::OVERWRITE))); if(!_dataset && open_mode() == OpenMode::OVERWRITE) { // Upon creation of this instance, the dataset, if it existed, was // deleted. Now create a new dataset. _dataset = create_gdal_dataset(*_driver, field, this->name()); } assert(contains_feature(path.parent_path())); assert(contains_attribute(path)); assert(_dataset); assert(_dataset->GetRasterCount() == 1); assert(field.values().size() == 1u); FieldValue<T> const& array(*field.values().cbegin()->second); int nr_rows = array.shape()[0]; int nr_cols = array.shape()[1]; double geo_transform[6]; { FieldDomain const& domain(field.domain()); assert(domain.size() == 1u); d2::Box const& box(domain.cbegin()->second); geo_transform[0] = get<0>(box.min_corner()); // west geo_transform[1] = (get<0>(box.max_corner()) - get<0>(box.min_corner())) / nr_cols; geo_transform[2] = 0.0; geo_transform[3] = get<1>(box.max_corner()); // north geo_transform[4] = 0.0; geo_transform[5] = (get<1>(box.max_corner()) - get<1>(box.min_corner())) / nr_rows; assert(geo_transform[1] > 0.0); assert(geo_transform[1] == geo_transform[5]); } if(_dataset->SetGeoTransform(geo_transform) != CE_None) { throw IOError(this->name(), Exception::messages()[MessageId::CANNOT_BE_WRITTEN]); } GDALRasterBand* band = _dataset->GetRasterBand(1); assert(band); if(band->RasterIO(GF_Write, 0, 0, nr_cols, nr_rows, const_cast<T*>( array.data()), nr_cols, nr_rows, GDALTypeTraits<T>::data_type, 0, 0) != CE_None) { throw IOError(this->name(), Exception::messages()[MessageId::CANNOT_BE_WRITTEN]); } if(array.has_masked_values()) { // This assumes the dataset contains onle one band. The mask is taken to // be global to the dataset. if(band->CreateMaskBand(GMF_PER_DATASET) != CE_None) { throw IOError(this->name(), Exception::messages()[MessageId::CANNOT_BE_WRITTEN]); } GDALRasterBand* mask_band = band->GetMaskBand(); assert(mask_band->GetRasterDataType() == GDT_Byte); // The mask band has gdal data type GDT_Byte. A value of zero // means that the value must be masked. ArrayValue<typename GDALDataTypeTraits<GDT_Byte>::type, 2> mask( extents[nr_rows][nr_cols]); array.mask(mask); if(mask_band->RasterIO(GF_Write, 0, 0, nr_cols, nr_rows, mask.data(), nr_cols, nr_rows, GDT_Byte, 0, 0) != CE_None) { throw IOError(this->name(), Exception::messages()[MessageId::CANNOT_BE_WRITTEN]); } } } #define WRITE_ATTRIBUTE_CASE( \ value_type) \ case value_type: { \ write_attribute( \ dynamic_cast<FieldAttribute< \ ValueTypeTraits<value_type>::type> const&>(attribute), path); \ break; \ } void GDALDataset::write_attribute( Attribute const& attribute, Path const& path) { AttributeTypeVisitor visitor; attribute.Accept(visitor); switch(visitor.data_type()) { case DT_CONSTANT: { assert(false); // Data type not supported by driver. break; } case DT_STATIC_FIELD: { switch(visitor.value_type()) { WRITE_ATTRIBUTE_CASE(VT_UINT8) WRITE_ATTRIBUTE_CASE(VT_UINT16) WRITE_ATTRIBUTE_CASE(VT_INT16) WRITE_ATTRIBUTE_CASE(VT_UINT32) WRITE_ATTRIBUTE_CASE(VT_INT32) WRITE_ATTRIBUTE_CASE(VT_FLOAT32) WRITE_ATTRIBUTE_CASE(VT_FLOAT64) case VT_BOOL: case VT_CHAR: case VT_INT8: case VT_UINT64: case VT_INT64: case VT_STRING: { assert(false); // Value type not supported by driver. break; } } break; } } } #undef WRITE_ATTRIBUTE_CASE } // namespace language } // namespace fern
31.719149
80
0.568107
quanpands
7e69ada6af6c8ff3f214bc2c84d1c3af9121a2b3
1,148
hh
C++
src/NodeGenerators/generateCylDistributionFromRZ.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/NodeGenerators/generateCylDistributionFromRZ.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/NodeGenerators/generateCylDistributionFromRZ.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//------------------------------------------------------------------------------ // Helper method for the GenerateCylindricalNodeDistribution3d node generator // to generate the spun node distribution. //------------------------------------------------------------------------------ #ifndef __Spheral_generateCylDistributionFromRZ__ #define __Spheral_generateCylDistributionFromRZ__ #include <vector> #include "Geometry/Dimension.hh" namespace Spheral { void generateCylDistributionFromRZ(std::vector<double>& x, std::vector<double>& y, std::vector<double>& z, std::vector<double>& m, std::vector<Dim<3>::SymTensor>& H, std::vector<int>& globalIDs, std::vector<std::vector<double> >& extraFields, const double nNodePerh, const double kernelExtent, const double phi, const int procID, const int nProcs); } #endif
37.032258
80
0.449477
jmikeowen
7e6b5fa4c1238b260faf0d226539588bee795e2a
1,159
cpp
C++
LEDA/test/graphics/geowin/msc/geowin_poly.cpp
2ashish/smallest_enclosing_circle
889916a3011ab2b649ab7f1fc1e042f879acecce
[ "MIT" ]
null
null
null
LEDA/test/graphics/geowin/msc/geowin_poly.cpp
2ashish/smallest_enclosing_circle
889916a3011ab2b649ab7f1fc1e042f879acecce
[ "MIT" ]
null
null
null
LEDA/test/graphics/geowin/msc/geowin_poly.cpp
2ashish/smallest_enclosing_circle
889916a3011ab2b649ab7f1fc1e042f879acecce
[ "MIT" ]
null
null
null
/******************************************************************************* + + LEDA 6.3 + + + geowin_poly.c + + + Copyright (c) 1995-2010 + by Algorithmic Solutions Software GmbH + All rights reserved. + *******************************************************************************/ #include <LEDA/rat_window.h> #include <LEDA/geowin.h> #include <LEDA/plane_alg.h> #include <iostream.h> using namespace leda; static void construct_gen_polygon(const list<rat_polygon>& L, list<rat_gen_polygon>& GL) { GL.clear(); GL.append(rat_gen_polygon(L)); } int main() { list<rat_polygon>* H1; list<rat_gen_polygon>* H2; GeoWin GW("POLYGON DEMO"); GeoWin GW2("A Generalized Polygon"); list<rat_polygon> L; geo_scene input = GW.new_scene(L); geo_scene sc = GW2.new_scene(construct_gen_polygon, input, string("A GENERALIZED POLYGON"),H1,H2); GW2.set_color(sc, grey1); GW2.set_visible(sc, true); GW2.display(window::max,window::min); GW.display(window::min,window::min); GW.edit(input); //GW.close(); GW2.edit(); return 0; }
21.462963
89
0.538395
2ashish
7e6c3e14dbd406ae88fbc09f6f43840cd8160806
2,126
cc
C++
cpp_src/gtests/tests/API/ft_tests.cc
Smolevich/reindexer
139a27a5f07023af40e08b6f9e9b27abb9bc4939
[ "Apache-2.0" ]
null
null
null
cpp_src/gtests/tests/API/ft_tests.cc
Smolevich/reindexer
139a27a5f07023af40e08b6f9e9b27abb9bc4939
[ "Apache-2.0" ]
null
null
null
cpp_src/gtests/tests/API/ft_tests.cc
Smolevich/reindexer
139a27a5f07023af40e08b6f9e9b27abb9bc4939
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <unordered_set> #include "ft_api.h" #include "tools/stringstools.h" using std::unordered_set; TEST_F(FTApi, CompositeSelect) { Add("An entity is something|", "| that in exists entity as itself"); Add("In law, a legal entity is|", "|an entity that is capable of something bearing legal rights"); Add("In politics, entity is used as|", "| term for entity territorial divisions of some countries"); auto res = SimpleCompositeSelect("*entity somethin*"); std::unordered_set<string> data{"An <b>entity</b> is <b>something</b>|", "| that in exists <b>entity</b> as itself", "An <b>entity</b> is <b>something</b>|d", "| that in exists entity as itself", "In law, a legal <b>entity</b> is|", "|an <b>entity</b> that is capable of <b>something</b> bearing legal rights", "al <b>entity</b> id", "|an entity that is capable of something bearing legal rights", "In politics, <b>entity</b> is used as|", "| term for <b>entity</b> territorial divisions of some countries", "s, <b>entity</b> id", "| term for entity territorial divisions of some countries"}; for (size_t i = 0; i < res.size(); ++i) { Item ritem(res.GetItem(i)); for (auto idx = 1; idx < ritem.NumFields(); idx++) { auto field = ritem[idx].Name(); if (field == "id") continue; auto it = data.find(ritem[field].As<string>()); EXPECT_TRUE(it != data.end()); data.erase(it); } } EXPECT_TRUE(data.empty()); } TEST_F(FTApi, NumberToWordsSelect) { auto err = reindexer->ConfigureIndex( "nm1", "ft3", R"xxx({"enable_translit": true,"enable_numbers_search": true,"enable_kb_layout": true,"merge_limit": 20000,"log_level": 1})xxx"); EXPECT_TRUE(err.ok()); Add("оценка 5 майкл джордан 23", ""); auto res = SimpleSelect("пять +двадцать +три"); EXPECT_TRUE(res.size() == 1); const string result = "оценка !5! майкл джордан !23!"; for (size_t i = 0; i < res.size(); ++i) { Item ritem(res.GetItem(i)); string val = ritem["ft1"].As<string>(); std::cout << val << std::endl; EXPECT_TRUE(result == val); } }
36.655172
131
0.632643
Smolevich
7e6cd2376953f623e471e461f5759b9392b8c312
624
cpp
C++
src/visual-scripting/processors/generators/counters/CounterProcessors.cpp
inexorgame/entity-system
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
19
2018-10-11T09:19:48.000Z
2020-04-19T16:36:58.000Z
src/visual-scripting/processors/generators/counters/CounterProcessors.cpp
inexorgame-obsolete/entity-system-inactive
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
132
2018-07-28T12:30:54.000Z
2020-04-25T23:05:33.000Z
src/visual-scripting/processors/generators/counters/CounterProcessors.cpp
inexorgame-obsolete/entity-system-inactive
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
3
2019-03-02T16:19:23.000Z
2020-02-18T05:15:29.000Z
#include "CounterProcessors.hpp" #include <utility> namespace inexor::visual_scripting { CounterProcessors::CounterProcessors(CounterIntProcessorPtr counter_int_processor, CounterFloatProcessorPtr counter_float_processor) : LifeCycleComponent(counter_int_processor, counter_float_processor) { this->counter_int_processor = std::move(counter_int_processor); this->counter_float_processor = std::move(counter_float_processor); } CounterProcessors::~CounterProcessors() = default; std::string CounterProcessors::get_component_name() { return "CounterProcessors"; } } // namespace inexor::visual_scripting
28.363636
132
0.8125
inexorgame
7e6ddfc364527a3c904016f6bb55ec7156a1d901
20,714
hpp
C++
Cxx11/stencil_rajaview.hpp
hattom/Kernels
dae34b73235ccbf150d9b0ed5fb480b924789383
[ "BSD-3-Clause" ]
346
2015-06-07T19:55:15.000Z
2022-03-18T07:55:10.000Z
Cxx11/stencil_rajaview.hpp
hattom/Kernels
dae34b73235ccbf150d9b0ed5fb480b924789383
[ "BSD-3-Clause" ]
202
2015-06-16T15:28:05.000Z
2022-01-06T18:26:13.000Z
Cxx11/stencil_rajaview.hpp
hattom/Kernels
dae34b73235ccbf150d9b0ed5fb480b924789383
[ "BSD-3-Clause" ]
101
2015-06-15T22:06:46.000Z
2022-01-13T02:56:02.000Z
using regular_policy = RAJA::KernelPolicy< RAJA::statement::For<0, thread_exec, RAJA::statement::For<1, RAJA::simd_exec, RAJA::statement::Lambda<0> > > >; void star1(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(1,n-1); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i,j-1) * -0.5 +in(i-1,j) * -0.5 +in(i+1,j) * 0.5 +in(i,j+1) * 0.5; }); } void star2(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(2,n-2); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i,j-2) * -0.125 +in(i,j-1) * -0.25 +in(i-2,j) * -0.125 +in(i-1,j) * -0.25 +in(i+1,j) * 0.25 +in(i+2,j) * 0.125 +in(i,j+1) * 0.25 +in(i,j+2) * 0.125; }); } void star3(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(3,n-3); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i,j-3) * -0.05555555555555555 +in(i,j-2) * -0.08333333333333333 +in(i,j-1) * -0.16666666666666666 +in(i-3,j) * -0.05555555555555555 +in(i-2,j) * -0.08333333333333333 +in(i-1,j) * -0.16666666666666666 +in(i+1,j) * 0.16666666666666666 +in(i+2,j) * 0.08333333333333333 +in(i+3,j) * 0.05555555555555555 +in(i,j+1) * 0.16666666666666666 +in(i,j+2) * 0.08333333333333333 +in(i,j+3) * 0.05555555555555555; }); } void star4(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(4,n-4); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i,j-4) * -0.03125 +in(i,j-3) * -0.041666666666666664 +in(i,j-2) * -0.0625 +in(i,j-1) * -0.125 +in(i-4,j) * -0.03125 +in(i-3,j) * -0.041666666666666664 +in(i-2,j) * -0.0625 +in(i-1,j) * -0.125 +in(i+1,j) * 0.125 +in(i+2,j) * 0.0625 +in(i+3,j) * 0.041666666666666664 +in(i+4,j) * 0.03125 +in(i,j+1) * 0.125 +in(i,j+2) * 0.0625 +in(i,j+3) * 0.041666666666666664 +in(i,j+4) * 0.03125; }); } void star5(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(5,n-5); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i,j-5) * -0.02 +in(i,j-4) * -0.025 +in(i,j-3) * -0.03333333333333333 +in(i,j-2) * -0.05 +in(i,j-1) * -0.1 +in(i-5,j) * -0.02 +in(i-4,j) * -0.025 +in(i-3,j) * -0.03333333333333333 +in(i-2,j) * -0.05 +in(i-1,j) * -0.1 +in(i+1,j) * 0.1 +in(i+2,j) * 0.05 +in(i+3,j) * 0.03333333333333333 +in(i+4,j) * 0.025 +in(i+5,j) * 0.02 +in(i,j+1) * 0.1 +in(i,j+2) * 0.05 +in(i,j+3) * 0.03333333333333333 +in(i,j+4) * 0.025 +in(i,j+5) * 0.02; }); } void grid1(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(1,n-1); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i-1,j-1) * -0.25 +in(i,j-1) * -0.25 +in(i-1,j) * -0.25 +in(i+1,j) * 0.25 +in(i,j+1) * 0.25 +in(i+1,j+1) * 0.25 ; }); } void grid2(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(2,n-2); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i-2,j-2) * -0.0625 +in(i-1,j-2) * -0.020833333333333332 +in(i,j-2) * -0.020833333333333332 +in(i+1,j-2) * -0.020833333333333332 +in(i-2,j-1) * -0.020833333333333332 +in(i-1,j-1) * -0.125 +in(i,j-1) * -0.125 +in(i+2,j-1) * 0.020833333333333332 +in(i-2,j) * -0.020833333333333332 +in(i-1,j) * -0.125 +in(i+1,j) * 0.125 +in(i+2,j) * 0.020833333333333332 +in(i-2,j+1) * -0.020833333333333332 +in(i,j+1) * 0.125 +in(i+1,j+1) * 0.125 +in(i+2,j+1) * 0.020833333333333332 +in(i-1,j+2) * 0.020833333333333332 +in(i,j+2) * 0.020833333333333332 +in(i+1,j+2) * 0.020833333333333332 +in(i+2,j+2) * 0.0625 ; }); } void grid3(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(3,n-3); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i-3,j-3) * -0.027777777777777776 +in(i-2,j-3) * -0.005555555555555556 +in(i-1,j-3) * -0.005555555555555556 +in(i,j-3) * -0.005555555555555556 +in(i+1,j-3) * -0.005555555555555556 +in(i+2,j-3) * -0.005555555555555556 +in(i-3,j-2) * -0.005555555555555556 +in(i-2,j-2) * -0.041666666666666664 +in(i-1,j-2) * -0.013888888888888888 +in(i,j-2) * -0.013888888888888888 +in(i+1,j-2) * -0.013888888888888888 +in(i+3,j-2) * 0.005555555555555556 +in(i-3,j-1) * -0.005555555555555556 +in(i-2,j-1) * -0.013888888888888888 +in(i-1,j-1) * -0.08333333333333333 +in(i,j-1) * -0.08333333333333333 +in(i+2,j-1) * 0.013888888888888888 +in(i+3,j-1) * 0.005555555555555556 +in(i-3,j) * -0.005555555555555556 +in(i-2,j) * -0.013888888888888888 +in(i-1,j) * -0.08333333333333333 +in(i+1,j) * 0.08333333333333333 +in(i+2,j) * 0.013888888888888888 +in(i+3,j) * 0.005555555555555556 +in(i-3,j+1) * -0.005555555555555556 +in(i-2,j+1) * -0.013888888888888888 +in(i,j+1) * 0.08333333333333333 +in(i+1,j+1) * 0.08333333333333333 +in(i+2,j+1) * 0.013888888888888888 +in(i+3,j+1) * 0.005555555555555556 +in(i-3,j+2) * -0.005555555555555556 +in(i-1,j+2) * 0.013888888888888888 +in(i,j+2) * 0.013888888888888888 +in(i+1,j+2) * 0.013888888888888888 +in(i+2,j+2) * 0.041666666666666664 +in(i+3,j+2) * 0.005555555555555556 +in(i-2,j+3) * 0.005555555555555556 +in(i-1,j+3) * 0.005555555555555556 +in(i,j+3) * 0.005555555555555556 +in(i+1,j+3) * 0.005555555555555556 +in(i+2,j+3) * 0.005555555555555556 +in(i+3,j+3) * 0.027777777777777776 ; }); } void grid4(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(4,n-4); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i-4,j-4) * -0.015625 +in(i-3,j-4) * -0.002232142857142857 +in(i-2,j-4) * -0.002232142857142857 +in(i-1,j-4) * -0.002232142857142857 +in(i,j-4) * -0.002232142857142857 +in(i+1,j-4) * -0.002232142857142857 +in(i+2,j-4) * -0.002232142857142857 +in(i+3,j-4) * -0.002232142857142857 +in(i-4,j-3) * -0.002232142857142857 +in(i-3,j-3) * -0.020833333333333332 +in(i-2,j-3) * -0.004166666666666667 +in(i-1,j-3) * -0.004166666666666667 +in(i,j-3) * -0.004166666666666667 +in(i+1,j-3) * -0.004166666666666667 +in(i+2,j-3) * -0.004166666666666667 +in(i+4,j-3) * 0.002232142857142857 +in(i-4,j-2) * -0.002232142857142857 +in(i-3,j-2) * -0.004166666666666667 +in(i-2,j-2) * -0.03125 +in(i-1,j-2) * -0.010416666666666666 +in(i,j-2) * -0.010416666666666666 +in(i+1,j-2) * -0.010416666666666666 +in(i+3,j-2) * 0.004166666666666667 +in(i+4,j-2) * 0.002232142857142857 +in(i-4,j-1) * -0.002232142857142857 +in(i-3,j-1) * -0.004166666666666667 +in(i-2,j-1) * -0.010416666666666666 +in(i-1,j-1) * -0.0625 +in(i,j-1) * -0.0625 +in(i+2,j-1) * 0.010416666666666666 +in(i+3,j-1) * 0.004166666666666667 +in(i+4,j-1) * 0.002232142857142857 +in(i-4,j) * -0.002232142857142857 +in(i-3,j) * -0.004166666666666667 +in(i-2,j) * -0.010416666666666666 +in(i-1,j) * -0.0625 +in(i+1,j) * 0.0625 +in(i+2,j) * 0.010416666666666666 +in(i+3,j) * 0.004166666666666667 +in(i+4,j) * 0.002232142857142857 +in(i-4,j+1) * -0.002232142857142857 +in(i-3,j+1) * -0.004166666666666667 +in(i-2,j+1) * -0.010416666666666666 +in(i,j+1) * 0.0625 +in(i+1,j+1) * 0.0625 +in(i+2,j+1) * 0.010416666666666666 +in(i+3,j+1) * 0.004166666666666667 +in(i+4,j+1) * 0.002232142857142857 +in(i-4,j+2) * -0.002232142857142857 +in(i-3,j+2) * -0.004166666666666667 +in(i-1,j+2) * 0.010416666666666666 +in(i,j+2) * 0.010416666666666666 +in(i+1,j+2) * 0.010416666666666666 +in(i+2,j+2) * 0.03125 +in(i+3,j+2) * 0.004166666666666667 +in(i+4,j+2) * 0.002232142857142857 +in(i-4,j+3) * -0.002232142857142857 +in(i-2,j+3) * 0.004166666666666667 +in(i-1,j+3) * 0.004166666666666667 +in(i,j+3) * 0.004166666666666667 +in(i+1,j+3) * 0.004166666666666667 +in(i+2,j+3) * 0.004166666666666667 +in(i+3,j+3) * 0.020833333333333332 +in(i+4,j+3) * 0.002232142857142857 +in(i-3,j+4) * 0.002232142857142857 +in(i-2,j+4) * 0.002232142857142857 +in(i-1,j+4) * 0.002232142857142857 +in(i,j+4) * 0.002232142857142857 +in(i+1,j+4) * 0.002232142857142857 +in(i+2,j+4) * 0.002232142857142857 +in(i+3,j+4) * 0.002232142857142857 +in(i+4,j+4) * 0.015625 ; }); } void grid5(const int n, const int t, matrix & in, matrix & out) { RAJA::RangeSegment inner1(5,n-5); auto inner2 = RAJA::make_tuple(inner1, inner1); RAJA::kernel<regular_policy>(inner2, [=](int i, int j) { out(i,j) += +in(i-5,j-5) * -0.01 +in(i-4,j-5) * -0.0011111111111111111 +in(i-3,j-5) * -0.0011111111111111111 +in(i-2,j-5) * -0.0011111111111111111 +in(i-1,j-5) * -0.0011111111111111111 +in(i,j-5) * -0.0011111111111111111 +in(i+1,j-5) * -0.0011111111111111111 +in(i+2,j-5) * -0.0011111111111111111 +in(i+3,j-5) * -0.0011111111111111111 +in(i+4,j-5) * -0.0011111111111111111 +in(i-5,j-4) * -0.0011111111111111111 +in(i-4,j-4) * -0.0125 +in(i-3,j-4) * -0.0017857142857142857 +in(i-2,j-4) * -0.0017857142857142857 +in(i-1,j-4) * -0.0017857142857142857 +in(i,j-4) * -0.0017857142857142857 +in(i+1,j-4) * -0.0017857142857142857 +in(i+2,j-4) * -0.0017857142857142857 +in(i+3,j-4) * -0.0017857142857142857 +in(i+5,j-4) * 0.0011111111111111111 +in(i-5,j-3) * -0.0011111111111111111 +in(i-4,j-3) * -0.0017857142857142857 +in(i-3,j-3) * -0.016666666666666666 +in(i-2,j-3) * -0.0033333333333333335 +in(i-1,j-3) * -0.0033333333333333335 +in(i,j-3) * -0.0033333333333333335 +in(i+1,j-3) * -0.0033333333333333335 +in(i+2,j-3) * -0.0033333333333333335 +in(i+4,j-3) * 0.0017857142857142857 +in(i+5,j-3) * 0.0011111111111111111 +in(i-5,j-2) * -0.0011111111111111111 +in(i-4,j-2) * -0.0017857142857142857 +in(i-3,j-2) * -0.0033333333333333335 +in(i-2,j-2) * -0.025 +in(i-1,j-2) * -0.008333333333333333 +in(i,j-2) * -0.008333333333333333 +in(i+1,j-2) * -0.008333333333333333 +in(i+3,j-2) * 0.0033333333333333335 +in(i+4,j-2) * 0.0017857142857142857 +in(i+5,j-2) * 0.0011111111111111111 +in(i-5,j-1) * -0.0011111111111111111 +in(i-4,j-1) * -0.0017857142857142857 +in(i-3,j-1) * -0.0033333333333333335 +in(i-2,j-1) * -0.008333333333333333 +in(i-1,j-1) * -0.05 +in(i,j-1) * -0.05 +in(i+2,j-1) * 0.008333333333333333 +in(i+3,j-1) * 0.0033333333333333335 +in(i+4,j-1) * 0.0017857142857142857 +in(i+5,j-1) * 0.0011111111111111111 +in(i-5,j) * -0.0011111111111111111 +in(i-4,j) * -0.0017857142857142857 +in(i-3,j) * -0.0033333333333333335 +in(i-2,j) * -0.008333333333333333 +in(i-1,j) * -0.05 +in(i+1,j) * 0.05 +in(i+2,j) * 0.008333333333333333 +in(i+3,j) * 0.0033333333333333335 +in(i+4,j) * 0.0017857142857142857 +in(i+5,j) * 0.0011111111111111111 +in(i-5,j+1) * -0.0011111111111111111 +in(i-4,j+1) * -0.0017857142857142857 +in(i-3,j+1) * -0.0033333333333333335 +in(i-2,j+1) * -0.008333333333333333 +in(i,j+1) * 0.05 +in(i+1,j+1) * 0.05 +in(i+2,j+1) * 0.008333333333333333 +in(i+3,j+1) * 0.0033333333333333335 +in(i+4,j+1) * 0.0017857142857142857 +in(i+5,j+1) * 0.0011111111111111111 +in(i-5,j+2) * -0.0011111111111111111 +in(i-4,j+2) * -0.0017857142857142857 +in(i-3,j+2) * -0.0033333333333333335 +in(i-1,j+2) * 0.008333333333333333 +in(i,j+2) * 0.008333333333333333 +in(i+1,j+2) * 0.008333333333333333 +in(i+2,j+2) * 0.025 +in(i+3,j+2) * 0.0033333333333333335 +in(i+4,j+2) * 0.0017857142857142857 +in(i+5,j+2) * 0.0011111111111111111 +in(i-5,j+3) * -0.0011111111111111111 +in(i-4,j+3) * -0.0017857142857142857 +in(i-2,j+3) * 0.0033333333333333335 +in(i-1,j+3) * 0.0033333333333333335 +in(i,j+3) * 0.0033333333333333335 +in(i+1,j+3) * 0.0033333333333333335 +in(i+2,j+3) * 0.0033333333333333335 +in(i+3,j+3) * 0.016666666666666666 +in(i+4,j+3) * 0.0017857142857142857 +in(i+5,j+3) * 0.0011111111111111111 +in(i-5,j+4) * -0.0011111111111111111 +in(i-3,j+4) * 0.0017857142857142857 +in(i-2,j+4) * 0.0017857142857142857 +in(i-1,j+4) * 0.0017857142857142857 +in(i,j+4) * 0.0017857142857142857 +in(i+1,j+4) * 0.0017857142857142857 +in(i+2,j+4) * 0.0017857142857142857 +in(i+3,j+4) * 0.0017857142857142857 +in(i+4,j+4) * 0.0125 +in(i+5,j+4) * 0.0011111111111111111 +in(i-4,j+5) * 0.0011111111111111111 +in(i-3,j+5) * 0.0011111111111111111 +in(i-2,j+5) * 0.0011111111111111111 +in(i-1,j+5) * 0.0011111111111111111 +in(i,j+5) * 0.0011111111111111111 +in(i+1,j+5) * 0.0011111111111111111 +in(i+2,j+5) * 0.0011111111111111111 +in(i+3,j+5) * 0.0011111111111111111 +in(i+4,j+5) * 0.0011111111111111111 +in(i+5,j+5) * 0.01 ; }); }
53.112821
83
0.39273
hattom
7e6e5199750f9df713da118aa8b76ebef75f000e
3,832
hpp
C++
Rx/v2/src/rxcpp/operators/rx-multicast.hpp
guhwanbae/RxCpp
7f97aa901701343593869acad1ee5a02292f39cf
[ "Apache-2.0" ]
2
2022-02-09T19:01:00.000Z
2022-03-11T03:36:29.000Z
Rx/v2/src/rxcpp/operators/rx-multicast.hpp
ivan-cukic/wip-fork-rxcpp
483963939e4a2adf674450dcb829005d84be1d59
[ "Apache-2.0" ]
null
null
null
Rx/v2/src/rxcpp/operators/rx-multicast.hpp
ivan-cukic/wip-fork-rxcpp
483963939e4a2adf674450dcb829005d84be1d59
[ "Apache-2.0" ]
1
2022-02-09T12:00:05.000Z
2022-02-09T12:00:05.000Z
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #pragma once /*! \file rx-multicast.hpp \brief allows connections to the source to be independent of subscriptions. \tparam Subject the subject to multicast the source Observable. \param sub the subject. */ #if !defined(RXCPP_OPERATORS_RX_MULTICAST_HPP) #define RXCPP_OPERATORS_RX_MULTICAST_HPP #include "../rx-includes.hpp" namespace rxcpp { namespace operators { namespace detail { template<class... AN> struct multicast_invalid_arguments {}; template<class... AN> struct multicast_invalid : public rxo::operator_base<multicast_invalid_arguments<AN...>> { using type = observable<multicast_invalid_arguments<AN...>, multicast_invalid<AN...>>; }; template<class... AN> using multicast_invalid_t = typename multicast_invalid<AN...>::type; template<class T, class Observable, class Subject> struct multicast : public operator_base<T> { using source_type = rxu::decay_t<Observable>; using subject_type = rxu::decay_t<Subject>; struct multicast_state : public std::enable_shared_from_this<multicast_state> { multicast_state(source_type o, subject_type sub) : source(std::move(o)) , subject_value(std::move(sub)) { } source_type source; subject_type subject_value; rxu::detail::maybe<typename composite_subscription::weak_subscription> connection; }; std::shared_ptr<multicast_state> state; multicast(source_type o, subject_type sub) : state(std::make_shared<multicast_state>(std::move(o), std::move(sub))) { } template<class Subscriber> void on_subscribe(Subscriber&& o) const { state->subject_value.get_observable().subscribe(std::forward<Subscriber>(o)); } void on_connect(composite_subscription cs) const { if (state->connection.empty()) { auto destination = state->subject_value.get_subscriber(); // the lifetime of each connect is nested in the subject lifetime state->connection.reset(destination.add(cs)); auto localState = state; // when the connection is finished it should shutdown the connection cs.add( [destination, localState](){ if (!localState->connection.empty()) { destination.remove(localState->connection.get()); localState->connection.reset(); } }); // use cs not destination for lifetime of subscribe. state->source.subscribe(cs, destination); } } }; } /*! @copydoc rx-multicast.hpp */ template<class... AN> auto multicast(AN&&... an) -> operator_factory<multicast_tag, AN...> { return operator_factory<multicast_tag, AN...>(std::make_tuple(std::forward<AN>(an)...)); } } template<> struct member_overload<multicast_tag> { template<class Observable, class Subject, class Enabled = rxu::enable_if_all_true_type_t< is_observable<Observable>>, class SourceValue = rxu::value_type_t<Observable>, class Multicast = rxo::detail::multicast<SourceValue, rxu::decay_t<Observable>, rxu::decay_t<Subject>>, class Value = rxu::value_type_t<Multicast>, class Result = connectable_observable<Value, Multicast>> static Result member(Observable&& o, Subject&& sub) { return Result(Multicast(std::forward<Observable>(o), std::forward<Subject>(sub))); } template<class... AN> static operators::detail::multicast_invalid_t<AN...> member(AN...) { std::terminate(); return {}; static_assert(sizeof...(AN) == 10000, "multicast takes (Subject)"); } }; } #endif
30.903226
132
0.658664
guhwanbae
7e73285986d87886ff0f692eb7d26b03aa9eb477
10,420
cpp
C++
private/shell/ext/ftp/ftpefe.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/ext/ftp/ftpefe.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/ext/ftp/ftpefe.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
/***************************************************************************** * * ftpefe.cpp - IEnumFORMATETC interface * *****************************************************************************/ #include "priv.h" #include "ftpefe.h" #include "ftpobj.h" /***************************************************************************** * CFtpEfe::_NextOne *****************************************************************************/ HRESULT CFtpEfe::_NextOne(FORMATETC * pfetc) { HRESULT hr = S_FALSE; while (ShouldSkipDropFormat(m_dwIndex)) m_dwIndex++; ASSERT(m_hdsaFormatEtc); if (m_dwIndex < (DWORD) DSA_GetItemCount(m_hdsaFormatEtc)) { DSA_GetItem(m_hdsaFormatEtc, m_dwIndex, (LPVOID) pfetc); m_dwIndex++; // We are off to the next one hr = S_OK; } if ((S_OK != hr) && m_pfo) { // We finished looking thru the types supported by the IDataObject. // Now look for other items inserted by IDataObject::SetData() if (m_dwExtraIndex < (DWORD) DSA_GetItemCount(m_pfo->m_hdsaSetData)) { FORMATETC_STGMEDIUM fs; DSA_GetItem(m_pfo->m_hdsaSetData, m_dwExtraIndex, (LPVOID) &fs); *pfetc = fs.formatEtc; m_dwExtraIndex++; // We are off to the next one hr = S_OK; } } return hr; } //=========================== // *** IEnumFORMATETC Interface *** //=========================== /***************************************************************************** * * IEnumFORMATETC::Next * * Creates a brand new enumerator based on an existing one. * * * OLE random documentation of the day: IEnumXXX::Next. * * rgelt - Receives an array of size celt (or larger). * * "Receives an array"? No, it doesn't receive an array. * It *is* an array. The array receives *elements*. * * "Or larger"? Does this mean I can return more than the caller * asked for? No, of course not, because the caller didn't allocate * enough memory to hold that many return values. * * No semantics are assigned to the possibility of celt = 0. * Since I am a mathematician, I treat it as vacuous success. * * pcelt is documented as an INOUT parameter, but no semantics * are assigned to its input value. * * The dox don't say that you are allowed to return *pcelt < celt * for reasons other than "no more elements", but the shell does * it everywhere, so maybe it's legal... * *****************************************************************************/ HRESULT CFtpEfe::Next(ULONG celt, FORMATETC * rgelt, ULONG *pceltFetched) { HRESULT hres = S_FALSE; DWORD dwIndex; // Do they want more and do we have more to give? for (dwIndex = 0; dwIndex < celt; dwIndex++) { if (S_FALSE == _NextOne(&rgelt[dwIndex])) // Yes, so give away... break; ASSERT(NULL == rgelt[dwIndex].ptd); // We don't do this correctly. #ifdef DEBUG char szName[MAX_PATH]; GetCfBufA(rgelt[dwIndex].cfFormat, szName, ARRAYSIZE(szName)); //TraceMsg(TF_FTP_IDENUM, "CFtpEfe::Next() - Returning %hs", szName); #endif // DEBUG } if (pceltFetched) *pceltFetched = dwIndex; // Were we able to give any? if ((0 != dwIndex) || (0 == celt)) hres = S_OK; return hres; } /***************************************************************************** * IEnumFORMATETC::Skip *****************************************************************************/ HRESULT CFtpEfe::Skip(ULONG celt) { m_dwIndex += celt; return S_OK; } /***************************************************************************** * IEnumFORMATETC::Reset *****************************************************************************/ HRESULT CFtpEfe::Reset(void) { m_dwIndex = 0; return S_OK; } /***************************************************************************** * * IEnumFORMATETC::Clone * * Creates a brand new enumerator based on an existing one. * *****************************************************************************/ HRESULT CFtpEfe::Clone(IEnumFORMATETC **ppenum) { return CFtpEfe_Create((DWORD) DSA_GetItemCount(m_hdsaFormatEtc), m_hdsaFormatEtc, m_dwIndex, m_pfo, ppenum); } /***************************************************************************** * * CFtpEfe_Create * * Creates a brand new enumerator based on a list of possibilities. * * Note that we are EVIL and know about CFSTR_FILECONTENTS here: * A FORMATETC of FileContents is always valid. This is important, * because CFtpObj doesn't actually have a STGMEDIUM for file contents. * (Due to lindex weirdness.) * *****************************************************************************/ HRESULT CFtpEfe_Create(DWORD dwSize, FORMATETC rgfe[], STGMEDIUM rgstg[], CFtpObj * pfo, CFtpEfe ** ppfefe) { CFtpEfe * pfefe; HRESULT hres = E_OUTOFMEMORY; pfefe = *ppfefe = new CFtpEfe(dwSize, rgfe, rgstg, pfo); if (EVAL(pfefe)) { if (!pfefe->m_hdsaFormatEtc) pfefe->Release(); else hres = S_OK; } if (FAILED(hres) && pfefe) IUnknown_Set(ppfefe, NULL); return hres; } /***************************************************************************** * * CFtpEfe_Create * * Creates a brand new enumerator based on a list of possibilities. * * Note that we are EVIL and know about CFSTR_FILECONTENTS here: * A FORMATETC of FileContents is always valid. This is important, * because CFtpObj doesn't actually have a STGMEDIUM for file contents. * (Due to lindex weirdness.) * *****************************************************************************/ HRESULT CFtpEfe_Create(DWORD dwSize, FORMATETC rgfe[], STGMEDIUM rgstg[], CFtpObj * pfo, IEnumFORMATETC ** ppenum) { CFtpEfe * pfefe; HRESULT hres = CFtpEfe_Create(dwSize, rgfe, rgstg, pfo, &pfefe); if (EVAL(pfefe)) { hres = pfefe->QueryInterface(IID_IEnumFORMATETC, (LPVOID *) ppenum); pfefe->Release(); } return hres; } /***************************************************************************** * * CFtpEfe_Create *****************************************************************************/ HRESULT CFtpEfe_Create(DWORD dwSize, HDSA m_hdsaFormatEtc, DWORD dwIndex, CFtpObj * pfo, IEnumFORMATETC ** ppenum) { CFtpEfe * pfefe; HRESULT hres = E_OUTOFMEMORY; pfefe = new CFtpEfe(dwSize, m_hdsaFormatEtc, pfo, dwIndex); if (EVAL(pfefe)) { hres = pfefe->QueryInterface(IID_IEnumFORMATETC, (LPVOID *) ppenum); pfefe->Release(); } return hres; } /****************************************************\ Constructor \****************************************************/ CFtpEfe::CFtpEfe(DWORD dwSize, FORMATETC rgfe[], STGMEDIUM rgstg[], CFtpObj * pfo) : m_cRef(1) { DllAddRef(); // This needs to be allocated in Zero Inited Memory. // Assert that all Member Variables are inited to Zero. ASSERT(!m_dwIndex); ASSERT(!m_hdsaFormatEtc); ASSERT(!m_pfo); m_hdsaFormatEtc = DSA_Create(sizeof(rgfe[0]), 10); if (EVAL(m_hdsaFormatEtc)) { DWORD dwIndex; for (dwIndex = 0; dwIndex < dwSize; dwIndex++) { #ifdef DEBUG char szNameDebug[MAX_PATH]; GetCfBufA(rgfe[dwIndex].cfFormat, szNameDebug, ARRAYSIZE(szNameDebug)); #endif // DEBUG if (rgfe[dwIndex].tymed == TYMED_ISTREAM || (rgstg && rgfe[dwIndex].tymed == rgstg[dwIndex].tymed)) { #ifdef DEBUG //TraceMsg(TF_FTP_IDENUM, "CFtpEfe() Keeping %hs", szNameDebug); #endif // DEBUG DSA_SetItem(m_hdsaFormatEtc, dwIndex, &rgfe[dwIndex]); } else { #ifdef DEBUG //TraceMsg(TF_FTP_IDENUM, "CFtpEfe() Ignoring %hs", szNameDebug); #endif // DEBUG } } } if (pfo) { m_pfo = pfo; m_pfo->AddRef(); } LEAK_ADDREF(LEAK_CFtpEfe); } /****************************************************\ Constructor \****************************************************/ CFtpEfe::CFtpEfe(DWORD dwSize, HDSA hdsaFormatEtc, CFtpObj * pfo, DWORD dwIndex) : m_cRef(1) { DllAddRef(); // This needs to be allocated in Zero Inited Memory. // Assert that all Member Variables are inited to Zero. ASSERT(!m_dwIndex); ASSERT(!m_hdsaFormatEtc); ASSERT(!m_pfo); ASSERT(hdsaFormatEtc); m_hdsaFormatEtc = DSA_Create(sizeof(FORMATETC), 10); if (EVAL(m_hdsaFormatEtc)) { // BUGBUG: What do we do with dwIndex param? for (dwIndex = 0; dwIndex < (DWORD) DSA_GetItemCount(hdsaFormatEtc); dwIndex++) { DSA_SetItem(m_hdsaFormatEtc, dwIndex, DSA_GetItemPtr(hdsaFormatEtc, dwIndex)); } } if (pfo) { m_pfo = pfo; m_pfo->AddRef(); } LEAK_ADDREF(LEAK_CFtpEfe); } /****************************************************\ Destructor \****************************************************/ CFtpEfe::~CFtpEfe() { DSA_Destroy(m_hdsaFormatEtc); if (m_pfo) m_pfo->Release(); DllRelease(); LEAK_DELREF(LEAK_CFtpEfe); } //=========================== // *** IUnknown Interface *** //=========================== ULONG CFtpEfe::AddRef() { m_cRef++; return m_cRef; } ULONG CFtpEfe::Release() { ASSERT(m_cRef > 0); m_cRef--; if (m_cRef > 0) return m_cRef; delete this; return 0; } HRESULT CFtpEfe::QueryInterface(REFIID riid, void **ppvObj) { if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IEnumFORMATETC)) { *ppvObj = SAFECAST(this, IEnumFORMATETC*); } else { TraceMsg(TF_FTPQI, "CFtpEfe::QueryInterface() failed."); *ppvObj = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; }
27.935657
115
0.485125
King0987654
7e7510ab9af7cb8ee8813cc6dc331eb692fb4657
1,393
cpp
C++
aula19/numeros.cpp
masmangan/refactored-eureka
5698a7e935a4d90f6f7459127e7eb3a72c3904eb
[ "MIT" ]
3
2018-09-12T22:59:34.000Z
2018-10-05T23:38:05.000Z
aula19/numeros.cpp
masmangan/refactored-eureka
5698a7e935a4d90f6f7459127e7eb3a72c3904eb
[ "MIT" ]
null
null
null
aula19/numeros.cpp
masmangan/refactored-eureka
5698a7e935a4d90f6f7459127e7eb3a72c3904eb
[ "MIT" ]
null
null
null
/* Escreva um programa que recebe uma lista de números e a apresenta. A seguir, os números são organizados em duas listas: pares e ímpares. As duas listas devem ser apresentadas em ordem crescente. marco.mangan@pucrs.br */ #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> numeros; vector<int> pares; vector<int> impares; int valor; cout << "STL C++ Vector" << endl; do { cin >> valor; numeros.push_back(valor); } while (valor); numeros.pop_back(); cout << "numeros = "; for (vector<int>::iterator it = numeros.begin() ; it != numeros.end(); ++it) { std::cout << ' ' << *it; } cout << endl; for (vector<int>::iterator it = numeros.begin() ; it != numeros.end(); ++it) { if (*it % 2 == 0) { pares.push_back(*it); } else { impares.push_back(*it); } } sort(pares.begin(), pares.end()); sort(impares.begin(), impares.end()); for (vector<int>::iterator it = pares.begin() ; it != pares.end(); ++it) { cout << ' ' << *it; } cout << endl; for (vector<int>::iterator it = impares.begin() ; it != impares.end(); ++it) { cout << ' ' << *it; } cout << endl; return 0; }
16.011494
53
0.512563
masmangan
7e781742def67dc40fe3b18ea2514984dcd8421b
1,013
hpp
C++
include/regrados.hpp
emanuelmoraes-dev/cpp-learn
4ca99f39e44016784619928cb61187be63586994
[ "MIT" ]
null
null
null
include/regrados.hpp
emanuelmoraes-dev/cpp-learn
4ca99f39e44016784619928cb61187be63586994
[ "MIT" ]
null
null
null
include/regrados.hpp
emanuelmoraes-dev/cpp-learn
4ca99f39e44016784619928cb61187be63586994
[ "MIT" ]
null
null
null
#ifndef REGRADOS_H_INCLUDED #define REGRADOS_H_INCLUDED #include <string> #include <vector> #include <memory> class Membro { public: std::string nome; }; class RegraDos3 { public: Membro membro; Membro* aloc1; Membro* aloc2; std::vector<Membro> membros; RegraDos3(); // Aplicando regra dos 3 RegraDos3(const RegraDos3&); // cópia ~RegraDos3(); // destrutor RegraDos3& operator=(const RegraDos3&); // cópia }; class RegraDos5 { public: Membro membro; Membro* aloc1; Membro* aloc2; std::vector<Membro> membros; RegraDos5(); // Aplicando regra dos 5 RegraDos5(const RegraDos5&); // cópia RegraDos5(RegraDos5&&); // mover ~RegraDos5(); // destrutor RegraDos5& operator=(const RegraDos5&); // cópia RegraDos5& operator=(RegraDos5&&); // mover }; class RegraDos0 { public: Membro membro; std::shared_ptr<Membro> aloc1; std::unique_ptr<Membro> aloc2; std::vector<Membro> membros; }; #endif // REGRADOS_H_INCLUDED
19.862745
52
0.660415
emanuelmoraes-dev
7e7da6a7d3209015d09bf16404f6138ea82c64ce
6,980
cpp
C++
AR_ColorSensor/src/AR_ColorSensor.cpp
fangchuan/AR_Library
c825bf26aa1f31b1537fdcaa382dc7b5b0de1afc
[ "MIT" ]
null
null
null
AR_ColorSensor/src/AR_ColorSensor.cpp
fangchuan/AR_Library
c825bf26aa1f31b1537fdcaa382dc7b5b0de1afc
[ "MIT" ]
null
null
null
AR_ColorSensor/src/AR_ColorSensor.cpp
fangchuan/AR_Library
c825bf26aa1f31b1537fdcaa382dc7b5b0de1afc
[ "MIT" ]
null
null
null
/* ********************************************************************************************************* * * 模块名称 : ColorSensor类库 * 文件名称 : AR_ColorSensor.cpp * 版 本 : V1.0 * 说 明 : * 修订记录 : 2017-3-13: 类内方法不可以被赋值给函数指针,必须将方法声明为static,但一旦将属性也改为static就失去了这个传感器类的意义 * 2017-3-14: 将数据属性全部public,主函数操作这些属性 * 每次扫描RGB都需要3次定时器溢出中断的过程 * 2017-3-16: 采用TC2做定时器,定时周期1ms,1s进行一次扫描,中断服务函数必须放在外部(全局可见) * 采用PCINT中断读取OUT引脚,中断服务函数也得放外部 * 2017-3-19: 颜色传感器读出的数值都差不多,这是为啥... * 2017-3-20: 颜色传感器四个灯换成白色LED,电阻47R * 白平衡结果参数0.01/0.01/0.01较合理 * 离传感器靠的越近区分效果越好 * * 2017-3-22: blue值始终偏高,不是程序问题,买的成品模块也是如此。可以把每次scann周期缩短到10ms,减小blue偏差 * * Copyright (C), 2015-2020, 阿波罗科技 www.apollorobot.cn * ********************************************************************************************************* */ #include <AR_ColorSensor.h> /* ********************************************************************************************************* * 函 数 名: AR_ColorSensor()构造函数 * 功能说明: * 形 参: * 返 回 值: 无 ********************************************************************************************************* */ AR_ColorSensor::AR_ColorSensor() { } /* ********************************************************************************************************* * 函 数 名: initialize * 功能说明: Initialize the pins color sensor used, and TC2 initialize * 形 参: s2: S2 pin * s3:S3 pin * out: OUT pin * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::initialize(uint8_t s2, uint8_t s3, uint8_t out) { s2_pin = s2; s3_pin = s3; out_pin = out; pinMode(s2_pin, OUTPUT); pinMode(s3_pin, OUTPUT); pinMode(out_pin, INPUT); initTime2(); initPCINT(); g_counts = 0; g_flag = 0; g_buffer[0] = 0; g_buffer[1] = 0; g_buffer[2] = 0; g_fac[0] = 0.01; g_fac[1] = 0.01; g_fac[2] = 0.01; } /* ********************************************************************************************************* * 函 数 名: initTime2 * 功能说明: 配置TC2寄存器,普通模式,64分频,定时器初值为6 1ms定时周期 * 1024分频,初值定为100 约10Ms定时周期 * 形 参: * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::initTime2() // { TCCR2A = 0; TIMSK2 = _BV(TOIE2); #if USE_1MS_INTERRUPT TCCR2B = _BV(CS22); TCNT2 = 6; #elif USE_10MS_INTERRUPT TCCR2B = _BV(CS22) | _BV(CS21) | _BV(CS20); //1024分频 TCNT2 = 100; //初值100 #endif sei(); } /* ********************************************************************************************************* * 函 数 名: initPCINT * 功能说明: 配置PCINT寄存器,ennable PCINT0/2 and PCINT pin 0/1/2/23 * PCINT0--8(Arduino) * PCINT1--9(Arduino) * PCINT2--10(Arduino) * PCINT23--7(Arduino) * 形 参: * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::initPCINT() { if (out_pin > 7){ PCICR = 1 << PCIE0; if(8 == out_pin) PCMSK0 = 1 << PCINT0; if(9 == out_pin) PCMSK0 = 1 << PCINT1; if(10 == out_pin) PCMSK0 = 1 << PCINT2; }else{ PCICR = 1 << PCIE2; PCMSK2 = 1 << PCINT23; } } /* ********************************************************************************************************* * 函 数 名: selectFilter * 功能说明: Select the filter color * 形 参: filter_index: 颜色滤波器 index * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::selectFilter(uint8_t filter_index) { switch(filter_index){ case RED_FILTER: digitalWrite(s2_pin, LOW); digitalWrite(s3_pin, LOW); break; case GREEN_FILTER: digitalWrite(s2_pin, HIGH); digitalWrite(s3_pin, HIGH); break; case BLUE_FILTER: digitalWrite(s2_pin, LOW); digitalWrite(s3_pin, HIGH); break; case NON_FILTER: digitalWrite(s2_pin, HIGH); digitalWrite(s3_pin, LOW); break; default:break; } //update the scann queue g_flag ++; if(g_flag > 2) g_flag = 0; } /* ********************************************************************************************************* * 函 数 名: scann * 功能说明: 扫描RGB值,每执行一次scann只能扫R/G/B,所以扫完一个物体要至少执行3次 * 形 参: filter_index: 颜色滤波器 index * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::scann() { switch(g_flag) { case RED_FILTER: #if USE_DEBUG Serial.print("->frequency B="); Serial.println(g_counts); #endif g_buffer[BLUE_INDEX] = g_counts; //store the previous filter out selectFilter(RED_FILTER); //filter red break; case GREEN_FILTER: #if USE_DEBUG Serial.print("->frequency R="); Serial.println(g_counts); #endif g_buffer[RED_INDEX] = g_counts; //store the previous filter out selectFilter(GREEN_FILTER); //filter green break; case BLUE_FILTER: #if USE_DEBUG Serial.print("->frequency G="); Serial.println(g_counts); #endif g_buffer[GREEN_INDEX] = g_counts; //store the previous filter out selectFilter(BLUE_FILTER); //filter blue break; default: break; } g_counts = 0; } /* ********************************************************************************************************* * 函 数 名: whiteBalance * 功能说明: white balance process * 形 参: 无 * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::whiteBalance() { if(g_buffer[0] != 0 && g_buffer[1] != 0 && g_buffer[2] != 0){ g_fac[0] = 255.0 / g_buffer[0]; g_fac[1] = 255.0 / g_buffer[1]; g_fac[2] = 255.0 / g_buffer[2]; #if USE_DEBUG Serial.print("R_Factor:"); Serial.println(g_fac[0]); Serial.print("G_Factor"); Serial.println(g_fac[1]); Serial.print("B_Factor"); Serial.println(g_fac[2]); #endif }else{ g_fac[0] = 0; g_fac[1] = 0; g_fac[2] = 0; } } /* ********************************************************************************************************* * 函 数 名: getResult * 功能说明: print the red/green/blue value * range: 0~255 * 形 参: 无 * 返 回 值: 无 ********************************************************************************************************* */ void AR_ColorSensor::getResult() { float red = g_buffer[RED_INDEX] * g_fac[RED_INDEX]; float green = g_buffer[GREEN_INDEX] * g_fac[GREEN_INDEX]; float blue = g_buffer[BLUE_INDEX] * g_fac[BLUE_INDEX]; #if USE_DEBUG Serial.print("red_result"); Serial.println(red); Serial.print("green_result"); Serial.println(green); Serial.print("blue_result"); Serial.println(blue); #endif } /***************************** 阿波罗科技 www.apollorobot.cn (END OF FILE) *********************************/
28.489796
105
0.440974
fangchuan
7e7ffed3dd0ab2e7a1ebece404b6bcdc8e0bf59e
13,981
cpp
C++
lib/qmmm_aux.cpp
taylor-a-barnes/qmmm_controller
5c072652e091f3a5d15b80088764fd7479cbdbb0
[ "BSD-3-Clause" ]
null
null
null
lib/qmmm_aux.cpp
taylor-a-barnes/qmmm_controller
5c072652e091f3a5d15b80088764fd7479cbdbb0
[ "BSD-3-Clause" ]
null
null
null
lib/qmmm_aux.cpp
taylor-a-barnes/qmmm_controller
5c072652e091f3a5d15b80088764fd7479cbdbb0
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2016 Quantum ESPRESSO group * This file is distributed under the terms of the * GNU General Public License. See the file `License' * in the root directory of the present distribution, * or http://www.gnu.org/copyleft/gpl.txt . */ /* ---------------------------------------------------------------------- This file contains auxiliary fuctions to interface QE with LAMMPS Contributing authors: Axel Kohlmeyer (ICTP), Carlo Cavazzoni (CINECA) ------------------------------------------------------------------------- */ #include "qmmm_aux.h" //#include "c_defs.h" /* ---------------------------------------------------------------------- */ /* Manage the atomic number */ #define QMMM_ISOTOPES 351 static const int FixQMMM_Z[QMMM_ISOTOPES] = { 1, 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 6, 7, 7, 8, 8, 8, 9, 10, 10, 10, 11, 12, 12, 12, 13, 14, 14, 14, 15, 16, 16, 16, 16, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 20, 20, 20, 21, 22, 22, 22, 22, 22, 23, 23, 24, 24, 24, 24, 25, 26, 26, 26, 26, 27, 28, 28, 28, 28, 28, 29, 29, 30, 30, 30, 30, 30, 31, 31, 32, 32, 32, 32, 32, 33, 34, 34, 34, 34, 34, 34, 35, 35, 36, 36, 36, 36, 36, 36, 37, 37, 38, 38, 38, 38, 39, 40, 40, 40, 40, 40, 41, 42, 42, 42, 42, 42, 42, 42, 43, 43, 43, 44, 44, 44, 44, 44, 44, 44, 45, 46, 46, 46, 46, 46, 46, 47, 47, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 53, 54, 54, 54, 54, 54, 54, 54, 54, 54, 55, 56, 56, 56, 56, 56, 56, 56, 57, 57, 58, 58, 58, 58, 59, 60, 60, 60, 60, 60, 60, 60, 61, 61, 62, 62, 62, 62, 62, 62, 62, 63, 63, 64, 64, 64, 64, 64, 64, 64, 65, 66, 66, 66, 66, 66, 66, 66, 67, 68, 68, 68, 68, 68, 68, 69, 70, 70, 70, 70, 70, 70, 70, 71, 71, 72, 72, 72, 72, 72, 72, 73, 73, 74, 74, 74, 74, 74, 75, 75, 76, 76, 76, 76, 76, 76, 76, 77, 77, 78, 78, 78, 78, 78, 78, 79, 80, 80, 80, 80, 80, 80, 80, 81, 81, 82, 82, 82, 82, 83, 84, 84, 85, 85, 86, 86, 86, 87, 88, 88, 88, 88, 89, 90, 90, 91, 92, 92, 92, 92, 92, 93, 93, 94, 94, 94, 94, 94, 94, 95, 95, 96, 96, 96, 96, 96, 96, 97, 97, 98, 98, 98, 98, 99, 100, 101, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115}; static const char FixQMMM_EL[QMMM_ISOTOPES][4] = { "H", "H", "H", "He", "He", "Li", "Li", "Be", "B", "B", "C", "C", "C", "N", "N", "O", "O", "O", "F", "Ne", "Ne", "Ne", "Na", "Mg", "Mg", "Mg", "Al", "Si", "Si", "Si", "P", "S", "S", "S", "S", "Cl", "Cl", "Ar", "Ar", "Ar", "K", "K", "K", "Ca", "Ca", "Ca", "Ca", "Ca", "Ca", "Sc", "Ti", "Ti", "Ti", "Ti", "Ti", "V", "V", "Cr", "Cr", "Cr", "Cr", "Mn", "Fe", "Fe", "Fe", "Fe", "Co", "Ni", "Ni", "Ni", "Ni", "Ni", "Cu", "Cu", "Zn", "Zn", "Zn", "Zn", "Zn", "Ga", "Ga", "Ge", "Ge", "Ge", "Ge", "Ge", "As", "Se", "Se", "Se", "Se", "Se", "Se", "Br", "Br", "Kr", "Kr", "Kr", "Kr", "Kr", "Kr", "Rb", "Rb", "Sr", "Sr", "Sr", "Sr", "Y", "Zr", "Zr", "Zr", "Zr", "Zr", "Nb", "Mo", "Mo", "Mo", "Mo", "Mo", "Mo", "Mo", "Tc", "Tc", "Tc", "Ru", "Ru", "Ru", "Ru", "Ru", "Ru", "Ru", "Rh", "Pd", "Pd", "Pd", "Pd", "Pd", "Pd", "Ag", "Ag", "Cd", "Cd", "Cd", "Cd", "Cd", "Cd", "Cd", "Cd", "In", "In", "Sn", "Sn", "Sn", "Sn", "Sn", "Sn", "Sn", "Sn", "Sn", "Sn", "Sb", "Sb", "Te", "Te", "Te", "Te", "Te", "Te", "Te", "Te", "I", "Xe", "Xe", "Xe", "Xe", "Xe", "Xe", "Xe", "Xe", "Xe", "Cs", "Ba", "Ba", "Ba", "Ba", "Ba", "Ba", "Ba", "La", "La", "Ce", "Ce", "Ce", "Ce", "Pr", "Nd", "Nd", "Nd", "Nd", "Nd", "Nd", "Nd", "Pm", "Pm", "Sm", "Sm", "Sm", "Sm", "Sm", "Sm", "Sm", "Eu", "Eu", "Gd", "Gd", "Gd", "Gd", "Gd", "Gd", "Gd", "Tb", "Dy", "Dy", "Dy", "Dy", "Dy", "Dy", "Dy", "Ho", "Er", "Er", "Er", "Er", "Er", "Er", "Tm", "Yb", "Yb", "Yb", "Yb", "Yb", "Yb", "Yb", "Lu", "Lu", "Hf", "Hf", "Hf", "Hf", "Hf", "Hf", "Ta", "Ta", "W", "W", "W", "W", "W", "Re", "Re", "Os", "Os", "Os", "Os", "Os", "Os", "Os", "Ir", "Ir", "Pt", "Pt", "Pt", "Pt", "Pt", "Pt", "Au", "Hg", "Hg", "Hg", "Hg", "Hg", "Hg", "Hg", "Tl", "Tl", "Pb", "Pb", "Pb", "Pb", "Bi", "Po", "Po", "At", "At", "Rn", "Rn", "Rn", "Fr", "Ra", "Ra", "Ra", "Ra", "Ac", "Th", "Th", "Pa", "U", "U", "U", "U", "U", "Np", "Np", "Pu", "Pu", "Pu", "Pu", "Pu", "Pu", "Am", "Am", "Cm", "Cm", "Cm", "Cm", "Cm", "Cm", "Bk", "Bk", "Cf", "Cf", "Cf", "Cf", "Es", "Fm", "Md", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg", "Cn", "Uut", "Uuq", "Uup"}; static const int FixQMMM_A[QMMM_ISOTOPES] = { 1, 2, 3, 3, 4, 6, 7, 9, 10, 11, 12, 13, 14, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 35, 37, 36, 38, 40, 39, 40, 41, 40, 42, 43, 44, 46, 48, 45, 46, 47, 48, 49, 50, 50, 51, 50, 52, 53, 54, 55, 54, 56, 57, 58, 59, 58, 60, 61, 62, 64, 63, 65, 64, 66, 67, 68, 70, 69, 71, 70, 72, 73, 74, 76, 75, 74, 76, 77, 78, 80, 82, 79, 81, 78, 80, 82, 83, 84, 86, 85, 87, 84, 86, 87, 88, 89, 90, 91, 92, 94, 96, 93, 92, 94, 95, 96, 97, 98, 100, 97, 98, 99, 96, 98, 99, 100, 101, 102, 104, 103, 102, 104, 105, 106, 108, 110, 107, 109, 106, 108, 110, 111, 112, 113, 114, 116, 113, 115, 112, 114, 115, 116, 117, 118, 119, 120, 122, 124, 121, 123, 120, 122, 123, 124, 125, 126, 128, 130, 127, 124, 126, 128, 129, 130, 131, 132, 134, 136, 133, 130, 132, 134, 135, 136, 137, 138, 138, 139, 136, 138, 140, 142, 141, 142, 143, 144, 145, 146, 148, 150, 145, 147, 144, 147, 148, 149, 150, 152, 154, 151, 153, 152, 154, 155, 156, 157, 158, 160, 159, 156, 158, 160, 161, 162, 163, 164, 165, 162, 164, 166, 167, 168, 170, 169, 168, 170, 171, 172, 173, 174, 176, 175, 176, 174, 176, 177, 178, 179, 180, 180, 181, 180, 182, 183, 184, 186, 185, 187, 184, 186, 187, 188, 189, 190, 192, 191, 193, 190, 192, 194, 195, 196, 198, 197, 196, 198, 199, 200, 201, 202, 204, 203, 205, 204, 206, 207, 208, 209, 209, 210, 210, 211, 211, 220, 222, 223, 223, 224, 226, 228, 227, 230, 232, 231, 233, 234, 235, 236, 238, 236, 237, 238, 239, 240, 241, 242, 244, 241, 243, 243, 244, 245, 246, 247, 248, 247, 249, 249, 250, 251, 252, 252, 257, 258, 260, 259, 262, 265, 268, 271, 272, 270, 276, 281, 280, 285, 284, 289, 288}; static const double FixQMMM_MASS[QMMM_ISOTOPES] = { 1.00782503207, 2.0141017778, 3.0160492777, 3.0160293191, 4.00260325415, 6.015122795, 7.01600455, 9.0121822, 10.0129370, 11.0093054, 12.0000000, 13.0033548378, 14.003241989, 14.0030740048, 15.0001088982, 15.99491461956, 16.99913170, 17.9991610, 18.99840322, 19.9924401754, 20.99384668, 21.991385114, 22.9897692809, 23.985041700, 24.98583692, 25.982592929, 26.98153863, 27.9769265325, 28.976494700, 29.97377017, 30.97376163, 31.97207100, 32.97145876, 33.96786690, 35.96708076, 34.96885268, 36.96590259, 35.967545106, 37.9627324, 39.9623831225, 38.96370668, 39.96399848, 40.96182576, 39.96259098, 41.95861801, 42.9587666, 43.9554818, 45.9536926, 47.952534, 44.9559119, 45.9526316, 46.9517631, 47.9479463, 48.9478700, 49.9447912, 49.9471585, 50.9439595, 49.9460442, 51.9405075, 52.9406494, 53.9388804, 54.9380451, 53.9396105, 55.9349375, 56.9353940, 57.9332756, 58.9331950, 57.9353429, 59.9307864, 60.9310560, 61.9283451, 63.9279660, 62.9295975, 64.9277895, 63.9291422, 65.9260334, 66.9271273, 67.9248442, 69.9253193, 68.9255736, 70.9247013, 69.9242474, 71.9220758, 72.9234589, 73.9211778, 75.9214026, 74.9215965, 73.9224764, 75.9192136, 76.9199140, 77.9173091, 79.9165213, 81.9166994, 78.9183371, 80.9162906, 77.9203648, 79.9163790, 81.9134836, 82.914136, 83.911507, 85.91061073, 84.911789738, 86.909180527, 83.913425, 85.9092602, 86.9088771, 87.9056121, 88.9058483, 89.9047044, 90.9056458, 91.9050408, 93.9063152, 95.9082734, 92.9063781, 91.906811, 93.9050883, 94.9058421, 95.9046795, 96.9060215, 97.9054082, 99.907477, 96.906365, 97.907216, 98.9062547, 95.907598, 97.905287, 98.9059393, 99.9042195, 100.9055821, 101.9043493, 103.905433, 102.905504, 101.905609, 103.904036, 104.905085, 105.903486, 107.903892, 109.905153, 106.905097, 108.904752, 105.906459, 107.904184, 109.9030021, 110.9041781, 111.9027578, 112.9044017, 113.9033585, 115.904756, 112.904058, 114.903878, 111.904818, 113.902779, 114.903342, 115.901741, 116.902952, 117.901603, 118.903308, 119.9021947, 121.9034390, 123.9052739, 120.9038157, 122.9042140, 119.904020, 121.9030439, 122.9042700, 123.9028179, 124.9044307, 125.9033117, 127.9044631, 129.9062244, 126.904473, 123.9058930, 125.904274, 127.9035313, 128.9047794, 129.9035080, 130.9050824, 131.9041535, 133.9053945, 135.907219, 132.905451933, 129.9063208, 131.9050613, 133.9045084, 134.9056886, 135.9045759, 136.9058274, 137.9052472, 137.907112, 138.9063533, 135.907172, 137.905991, 139.9054387, 141.909244, 140.9076528, 141.9077233, 142.9098143, 143.9100873, 144.9125736, 145.9131169, 147.916893, 149.920891, 144.912749, 146.9151385, 143.911999, 146.9148979, 147.9148227, 148.9171847, 149.9172755, 151.9197324, 153.9222093, 150.9198502, 152.9212303, 151.9197910, 153.9208656, 154.9226220, 155.9221227, 156.9239601, 157.9241039, 159.9270541, 158.9253468, 155.924283, 157.924409, 159.9251975, 160.9269334, 161.9267984, 162.9287312, 163.9291748, 164.9303221, 161.928778, 163.929200, 165.9302931, 166.9320482, 167.9323702, 169.9354643, 168.9342133, 167.933897, 169.9347618, 170.9363258, 171.9363815, 172.9382108, 173.9388621, 175.9425717, 174.9407718, 175.9426863, 173.940046, 175.9414086, 176.9432207, 177.9436988, 178.9458161, 179.9465500, 179.9474648, 180.9479958, 179.946704, 181.9482042, 182.9502230, 183.9509312, 185.9543641, 184.9529550, 186.9557531, 183.9524891, 185.9538382, 186.9557505, 187.9558382, 188.9581475, 189.9584470, 191.9614807, 190.9605940, 192.9629264, 189.959932, 191.9610380, 193.9626803, 194.9647911, 195.9649515, 197.967893, 196.9665687, 195.965833, 197.9667690, 198.9682799, 199.9683260, 200.9703023, 201.9706430, 203.9734939, 202.9723442, 204.9744275, 203.9730436, 205.9744653, 206.9758969, 207.9766521, 208.9803987, 208.9824304, 209.9828737, 209.987148, 210.9874963, 210.990601, 220.0113940, 222.0175777, 223.0197359, 223.0185022, 224.0202118, 226.0254098, 228.0310703, 227.0277521, 230.0331338, 232.0380553, 231.0358840, 233.0396352, 234.0409521, 235.0439299, 236.0455680, 238.0507882, 236.046570, 237.0481734, 238.0495599, 239.0521634, 240.0538135, 241.0568515, 242.0587426, 244.064204, 241.0568291, 243.0613811, 243.0613891, 244.0627526, 245.0654912, 246.0672237, 247.070354, 248.072349, 247.070307, 249.0749867, 249.0748535, 250.0764061, 251.079587, 252.081626, 252.082980, 257.095105, 258.098431, 260.10365, 259.10103, 262.10963, 265.11670, 268.12545, 271.13347, 272.13803, 270.13465, 276.15116, 281.16206, 280.16447, 285.17411, 284.17808, 289.18728, 288.19249}; /* * This function matches the element which has the least absolute * difference between the masses. delta is set to the difference * between the mass provided and the best match. * * THIS FUNCTION RELIES ON THE CORRECT ORDER OF THE DATA TABLES * IN ORDER TO SKIP ISOTOPES FROM THE MATCH * * */ int match_element (double mass, int search_isotopes, double * delta) { int i; int bestcandidate; double diff, mindiff; int lastz; mindiff = 1e6; bestcandidate = -1; lastz = -1; for(i=0; i<QMMM_ISOTOPES; i++) { if(!search_isotopes && lastz == FixQMMM_Z[i]) continue; diff = fabs(FixQMMM_MASS[i] - mass); if(diff < mindiff) { mindiff = diff; bestcandidate = i; } lastz = FixQMMM_Z[i]; } *delta = mindiff; return bestcandidate; } /* ---------------------------------------------------------------------- */ //! Atomic radii of all atoms. Master/QM only // // /* * Source: wikipedia * [ http://en.wikipedia.org/wiki/Atomic_radii_of_the_elements_(data_page) ] * * Atomic radii for the various elements in picometers. * * A value of -1 has the meaning of "data not available". * * */ /// Number of elements in the arrays #define EC_ELEMENTS 116 static const double ec_r_covalent[EC_ELEMENTS+1] = { -1 /* Z=0 */, 0.38, 0.32, 1.34, 0.90, 0.82, 0.77, 0.75, 0.73, 0.71, 0.69, 1.54, 1.30, 1.18, 1.11, 1.06, 1.02, 0.99, 0.97, 1.96, 1.74, 1.44, 1.36, 1.25, 1.27, 1.39, 1.25, 1.26, 1.21, 1.38, 1.31, 1.26, 1.22, 1.19, 1.16, 1.14, 1.10, 2.11, 1.92, 1.62, 1.48, 1.37, 1.45, 1.56, 1.26, 1.35, 1.31, 1.53, 1.48, 1.44, 1.41, 1.38, 1.35, 1.33, 1.30, 2.25, 1.98, 1.69, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1.60, 1.50, 1.38, 1.46, 1.59, 1.28, 1.37, 1.28, 1.44, 1.49, 1.48, 1.47, 1.46, -1, -1, 1.45, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; //int F77_FUNC(ec_fill_radii,EC_FILL_RADII) //( double *aradii, int *ndata, double *mass, int *type, int *ntypes, int *screen ) int ec_fill_radii( double *aradii, int *ndata, double *mass, int *type, int *ntypes ) { int i, el; int *type2element; type2element = (int *) malloc( sizeof(int) * *ntypes+1 ); type2element[0] = 0; for (i=1; i <= *ntypes; ++i) { double delta; el = match_element(mass[i], 0, &delta); fprintf(stdout,"FixQMMM: type %2d (mass: %8g) matches %2s with:" " Z = %-3d A = %-3d r_cov = %5.2f (error = %-8.2g -> %-.2g%%)\n", i, mass[i], FixQMMM_EL[el], FixQMMM_Z[el], FixQMMM_A[el], ec_r_covalent[FixQMMM_Z[el]], delta, delta/mass[i] * 100.0); type2element[i] = FixQMMM_Z[el]; } for (i=0; i<*ndata; i++) { el = type2element[type[i]]; if (el < 0 || el > EC_ELEMENTS) { fprintf(stderr,"Unable to find element Z=%d in table of covalent radii", el); exit(1); } aradii[i] = ec_r_covalent[el]; if (ec_r_covalent[el] < 0.0) { fprintf(stderr, "Covalent radius for atom of element Z=%d not availabe", el); exit(1); } } free( (void *) type2element ); return 0; }
53.56705
121
0.56727
taylor-a-barnes
7e85fce9e6f1a2ca4ea8e36f0a6f4bbb6a63f24a
8,648
cc
C++
trial/fs-search.cc
louis-tru/Ngui
c1f25d8b6c42e873d5969fb588af22f428c58d4c
[ "BSD-3-Clause-Clear" ]
86
2017-11-21T01:05:30.000Z
2020-05-21T12:30:31.000Z
trial/fs-search.cc
louis-tru/Ngui
c1f25d8b6c42e873d5969fb588af22f428c58d4c
[ "BSD-3-Clause-Clear" ]
14
2020-10-16T11:30:57.000Z
2021-04-16T06:10:06.000Z
trial/fs-search.cc
louis-tru/Ngui
c1f25d8b6c42e873d5969fb588af22f428c58d4c
[ "BSD-3-Clause-Clear" ]
13
2017-11-21T10:18:53.000Z
2019-10-18T09:15:55.000Z
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2015, xuewen.chu * 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 xuewen.chu 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 xuewen.chu 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. * * ***** END LICENSE BLOCK ***** */ #include "trial/fs.h" #include "ftr/util/zlib.h" #include "ftr/util/handle.h" #include "ftr/util/error.h" FX_NS(ftr) // FileSearch implementation String inl_format_part_path(cString& path); class FileSearch::SearchPath { public: virtual ZipInSearchPath* as_zip() { return NULL; } virtual String get_absolute_path(cString& path); virtual Buffer read(cString& path); inline String path() { return m_path; } protected: String m_path; friend class ZipInSearchPath; private: SearchPath(cString& path): m_path(path) { } virtual ~SearchPath() { } friend class FileSearch; }; class FileSearch::ZipInSearchPath: public FileSearch::SearchPath { public: ZipInSearchPath* as_zip() { return this; } String get_absolute_path(cString& path); Buffer read(cString& path); Buffer read_by_in_path(cString& path); bool exists_by_abs(cString& path); inline String zip_path() { return m_zip_path; } static String formatPath(cString& path1, cString& path2); private: ZipInSearchPath(cString& zip_path, cString& path); ~ZipInSearchPath(); String m_zip_path; ZipReader m_zip; friend class FileSearch; }; String FileSearch::SearchPath::get_absolute_path(cString& path) { String p = Path::format("%s/%s", *m_path, *path); if (FileHelper::exists_sync(p)) { return p; } return String(); } Buffer FileSearch::SearchPath::read(cString& path) { String p = Path::format("%s/%s", *m_path, *path); return FileHelper::read_file_sync( p ); } String FileSearch::ZipInSearchPath::formatPath(cString& path1, cString& path2) { return inl_format_part_path(String(path1).push('/').push(path2)); } String FileSearch::ZipInSearchPath::get_absolute_path(cString& path) { String s = formatPath(m_path, path); if (m_zip.exists(s)) { return String::format("zip://%s?/%s", *m_zip_path.substr(7), *s); } return String(); } Buffer FileSearch::ZipInSearchPath::read(cString& path) { return read_by_in_path(formatPath(m_path, path)); } Buffer FileSearch::ZipInSearchPath::read_by_in_path(cString& path) { if (m_zip.jump(path)) { return m_zip.read(); } return Buffer(); } bool FileSearch::ZipInSearchPath::exists_by_abs(cString& path) { return m_zip.exists(path); } FileSearch::ZipInSearchPath::ZipInSearchPath(cString& zip_path, cString& path) : SearchPath(path) , m_zip_path(zip_path) , m_zip (zip_path) { ASSERT( m_zip.open(), "Cannot open zip file, `%s`", *zip_path ); } FileSearch::ZipInSearchPath::~ZipInSearchPath() { } FileSearch::FileSearch() { // 把资源目录加入进来 cString& res = Path::resources(); if (Path::is_local_zip(res)) { // zip pkg int i = res.index_of('?'); if (i != -1) { add_zip_search_path(res, res.substr(i + 1)); } else { FX_WARN("Invalid path, %s", *res); } } else { if (FileHelper::exists_sync(res)) { add_search_path(res); } else { FX_WARN("Resource directory does not exists, %s", *res); } } } FileSearch::~FileSearch() { remove_all_search_path(); } void FileSearch::add_search_path(cString& path) { String str = Path::format(*path); auto it = m_search_paths.begin(); auto end = m_search_paths.end(); for (; it != end; it++) { FileSearch::SearchPath* s = it.value(); if (!s->as_zip()) { if (s->path() == str) { FX_WARN("The repetitive path, \"%s\"", *path); // Fault tolerance, skip the same path return; } } } m_search_paths.push(new FileSearch::SearchPath(str)); } void FileSearch::add_zip_search_path(cString& zip_path, cString& path) { String _zip_path = Path::format("%s", *zip_path); String _path = path; #if FX_WIN _path = path.replace_all('\\', '/'); #endif _path = inl_format_part_path(path); auto it = m_search_paths.begin(); auto end = m_search_paths.end(); for (; it != end; it++) { if (it.value()->as_zip()) { FileSearch::ZipInSearchPath* s = it.value()->as_zip(); if (s->zip_path() == _zip_path && s->path() == _path) { FX_WARN("The repetitive path, ZIP: %s, %s", *zip_path, *path); // Fault tolerance,skip the same path return; } } } m_search_paths.push(new FileSearch::ZipInSearchPath(_zip_path, _path)); } /** * Gets the array of search paths. * * @ret {const Array<String>} The array of search paths. */ Array<String> FileSearch::get_search_paths() const { auto it = m_search_paths.begin(); auto end = m_search_paths.end(); Array<String> rest; for (; it != end; it++) { rest.push(it.value()->path()); } return rest; } /** * remove search path */ void FileSearch::remove_search_path(cString& path) { auto it = m_search_paths.begin(); auto end = m_search_paths.end(); for ( ; it != end; it++) { if (it.value()->path() == path) { delete it.value(); m_search_paths.del(it); return; } } } /** * Removes all search paths. */ void FileSearch::remove_all_search_path() { auto it = m_search_paths.begin(); auto end = m_search_paths.end(); for (; it != end; it++) { delete it.value(); } m_search_paths.clear(); } String FileSearch::get_absolute_path(cString& path) const { if (path.is_empty()) { FX_WARN("Search path cannot be a empty and null"); return String(); } if (Path::is_local_absolute(path)) { return FileHelper::exists_sync(path) ? Path::format(path.c()) : String(); } auto it = m_search_paths.begin(); auto end = m_search_paths.end(); if (path.substr(0, 7).lower_case().index_of("zip:///") == 0) { String path_s = path.substr(7); Array<String> ls = path_s.split("?/"); if (ls.length() > 1) { String zip_path = ls[0]; path_s = ls[1]; for ( ; it != end; it++ ) { auto zip = it.value()->as_zip(); if (zip && zip->zip_path() == zip_path) { if (zip->exists_by_abs(path_s)) { return path; } } } } } else { for ( ; it != end; it++ ) { String abs_path = *it.value()->get_absolute_path(path); if (String() != abs_path) { return abs_path; } } } return String(); } bool FileSearch::exists(cString& path) const { return !get_absolute_path(path).is_empty(); } Buffer FileSearch::read(cString& path) const { if (path.is_empty()) { return Buffer(); } if (Path::is_local_absolute(path)) { // absolute path return FileHelper::read_file_sync(path); } else { auto it = m_search_paths.begin(); auto end = m_search_paths.end(); if (path.substr(0, 7).lower_case().index_of("zip:///") == 0) { // zip pkg inner file String path_s = path.substr(7); Array<String> ls = path_s.split("?/"); if (ls.length() > 1) { String zip_path = ls[0]; path_s = ls[1]; for ( ; it != end; it++ ) { auto zip = it.value()->as_zip(); if (zip && zip->zip_path() == zip_path) { return zip->read_by_in_path(path_s); } } } } else { for ( ; it != end; it++ ) { Buffer data = it.value()->read(path); if (data.length()) { return data; } } } } return Buffer(); } static FileSearch* search = NULL; FileSearch* FileSearch::shared() { if ( ! search ) { search = new FileSearch(); } return search; } FX_END
26.048193
86
0.666512
louis-tru
7e887fee2927fc5e7a30b76c39054a38c34fded0
445
cpp
C++
src/resources/terrain_library.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/resources/terrain_library.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/resources/terrain_library.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
/* * TS Elements * Copyright 2015-2018 M. Newhouse * Released under the MIT license. */ #include "terrain_library.hpp" #include <algorithm> namespace ts { namespace resources { void TerrainLibrary::define_terrain(const TerrainDefinition& terrain) { terrains_[terrain.id] = terrain; } const TerrainDefinition& TerrainLibrary::terrain(TerrainId terrain_id) const { return terrains_[terrain_id]; } } }
17.115385
80
0.696629
mnewhouse
7e89b9689048be6d81a61f59d446635923370799
1,041
hpp
C++
Nacro/SDK/FN_Bedroom_Dresser_02_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_Bedroom_Dresser_02_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_Bedroom_Dresser_02_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Bedroom_Dresser_02.Bedroom_Dresser_02_C.UserConstructionScript struct ABedroom_Dresser_02_C_UserConstructionScript_Params { }; // Function Bedroom_Dresser_02.Bedroom_Dresser_02_C.OnLootRepeat struct ABedroom_Dresser_02_C_OnLootRepeat_Params { }; // Function Bedroom_Dresser_02.Bedroom_Dresser_02_C.OnBeginSearch struct ABedroom_Dresser_02_C_OnBeginSearch_Params { }; // Function Bedroom_Dresser_02.Bedroom_Dresser_02_C.ExecuteUbergraph_Bedroom_Dresser_02 struct ABedroom_Dresser_02_C_ExecuteUbergraph_Bedroom_Dresser_02_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
24.209302
152
0.632085
Milxnor
7e89faa093f24847cdd82eb90b45385703c1210d
6,619
cpp
C++
source/AlgebraicMethods/Term.cpp
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
21
2020-12-08T20:06:01.000Z
2022-02-13T22:52:02.000Z
source/AlgebraicMethods/Term.cpp
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
9
2020-12-20T03:54:55.000Z
2022-03-31T19:30:04.000Z
source/AlgebraicMethods/Term.cpp
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
5
2021-04-25T18:47:17.000Z
2022-01-23T02:37:30.000Z
#include "Term.h" #include "TermStorage.h" #include "TermStorageAvl.h" #include "TermStorageVector.h" #include "XTerm.h" Term::Term() { #if 0 static int cnt = 0; if (cnt == 12237) { int stop = 1; MyTerm = this; } cnt++; //Log::PrintLogF(0, "C:%d:%x\n", cnt++, this); #endif COSTR("term"); } Term::~Term() { #if 0 static int cnt = 0; //Log::PrintLogF(0, "D:%d:%x\n", cnt++, this); #endif for (int ii = 0, size = (int)_powers.size(); ii < size; ii++) { _powers[ii]->Dispose(); } DESTR("term"); } // // Compare two terms // Return values: // -1 : this < other // 0 : this = other // 1 : this > other // int Term::Compare(Term * /* other */) const { return -1; } // // Merge two equal terms // void Term::Merge(Term * /* other */) {} TermKeyType Term::Key() { return this; } TermStorage *Term::CreateTermStorage() { #if TERM_STORAGE_CLASS_VECTOR return new TermStorageVector(); #elif TERM_STORAGE_CLASS_AVL_TREE #ifdef AVLTREE_BANK return AvlTreeBank::AvlTreeFactory.AcquireAvlTree(); #else return new TermStorageAvlTree(); #endif #endif } // // Merge powers from other term. // Several usages: // 1. To add powers (multiplication) // 2. To remove powers (division) // 3. To remove powers (integer division, gcd) // void Term::MergePowers(Term *t, bool add) { uint cnt1 = (uint)_powers.size(); uint cnt2 = (uint)t->_powers.size(); uint ii = 0, jj = 0; int op = add ? 1 : -1; while (ii < cnt1 && jj < cnt2) { Power *w1 = _powers[ii]; Power *w2 = t->_powers[jj]; if (w1->GetIndex() == w2->GetIndex()) { // case 1, w1 == w2 // add/subtract degree int degree = w1->GetDegree() + op * w2->GetDegree(); // degree = max(0, degree); if (degree < 0) degree = 0; if (degree == 0) { // remove power w1->Dispose(); _powers.erase(_powers.begin() + ii); cnt1--; jj++; } else { w1->SetDegree(degree); ii++; jj++; } } else if (w1->GetIndex() < w2->GetIndex()) { // should not happen if add == false // correction - could happen, it means safe division! if (!add) { jj++; continue; // Log::PrintLogF(0, "Attempt to do rational division of powers!\n"); // throw -1; } // case 2, w1 < w2 // insert power and increase powers count _powers.insert(_powers.begin() + ii, w2->Clone()); cnt1++; ii++; jj++; } else { // case 3, w1 > w2 // move on with first iterator ii++; } } // ii < cnt2, nothing to do while (jj < cnt2) { // should not happen if add == false // correction - could happen, it means safe division! if (!add) { jj++; continue; // Log::PrintLogF(0, "Attempt to do rational division of powers!\n"); // throw -1; } // add remaining powers Power *w2 = t->_powers[jj]; _powers.push_back(w2->Clone()); jj++; } } // // Is this term divisible with other term // Check powers // bool Term::Divisible(Term *t) const { uint i1 = 0, i2 = 0; uint s1 = (uint)_powers.size(), s2 = (uint)t->_powers.size(); // constant is divisable only with constant bool divisible = (s1 > 0) || (s2 == 0); while (i1 < s1 && i2 < s2 && divisible) { // check current degree in t uint index2 = t->_powers[i2]->GetIndex(); // must match it in this term while (i1 < s1 && _powers[i1]->GetIndex() > index2) { i1++; } if (i1 >= s1 || _powers[i1]->GetIndex() != index2 || _powers[i1]->GetDegree() < t->_powers[i2]->GetDegree()) { divisible = false; } i2++; } return divisible; } uint Term::GetPowerCount() const { return (uint)_powers.size(); } Power *Term::GetPower(uint index) const { return _powers[index]; } // // degree of variable with given index // int Term::VariableDeg(int index, bool free) const { if (free == true && this->Type() == XTERM) { XTerm *xt = (XTerm *)this; Term *t = xt->GetUFraction()->GetNumerator()->LeadTerm(index, free); if (t) { return t->VariableDeg(index, free); } else { return 0; } } Power *pow = this->GetPowerByIndex(index); if (pow != NULL) { return pow->GetDegree(); } return 0; } // // Find and return power with given variable index // Power *Term::GetPowerByIndex(int index) const { int vecIndex = this->GetIndexOfIndex(index); return vecIndex >= 0 ? this->GetPower(vecIndex) : NULL; } // // Return index in array of power with given index // -1 if power doesn't exists // int Term::GetIndexOfIndex(int index) const { // search power using binary search int l = 0, r = this->GetPowerCount() - 1, m; while (l <= r) { m = (l + r) / 2; Power *pow = this->GetPower(m); if (pow->GetIndex() == (unsigned)index) { return m; } else if ((int)pow->GetIndex() < index) { // array is reversaly sorted r = m - 1; } else { l = m + 1; } } return -1; } // // Change degree of a power with given index // power doesn't have to exists // void Term::ChangePowerDegree(int index, int change) { if (change != 0) { int powIndex = this->GetIndexOfIndex(index); if (powIndex >= 0) { Power *pow = this->GetPower(powIndex); pow->SetDegree(pow->GetDegree() + change); if (pow->GetDegree() == 0) { this->RemovePower(powIndex); } } } } // // Remove power at index // void Term::RemovePower(uint index) { _powers[index]->Dispose(); _powers.erase(_powers.begin() + index); } // // this = GCD(this, t) // void Term::GCDWith(const Term *t) { uint j = 0; uint k, size1, size2; size1 = this->GetPowerCount(); size2 = t->GetPowerCount(); for (k = 0; k < size1; k++) { uint index1 = this->GetPower(k)->GetIndex(); while (j < size2 && index1 < t->GetPower(j)->GetIndex()) { j++; } if (j < size2 && index1 == t->GetPower(j)->GetIndex()) { uint d_k = this->GetPower(k)->GetDegree(); uint d_j = t->GetPower(j)->GetDegree(); uint d = (d_k < d_j ? d_k : d_j); this->GetPower(k)->SetDegree(d); if (this->GetPower(k)->GetDegree() == 0) { this->RemovePower(k); k--; size1--; } } else { this->RemovePower(k); k--; size1--; } } }
22.667808
78
0.536637
CoghettoR
7e8eba9f731da8d8b1c99ff78c14c779cfbb8111
7,991
cpp
C++
src/Client.cpp
nsentout/project-lambda-client
3b6f84e90ebf1319bbbfd6649b1e9e94b96f1469
[ "MIT" ]
null
null
null
src/Client.cpp
nsentout/project-lambda-client
3b6f84e90ebf1319bbbfd6649b1e9e94b96f1469
[ "MIT" ]
null
null
null
src/Client.cpp
nsentout/project-lambda-client
3b6f84e90ebf1319bbbfd6649b1e9e94b96f1469
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> #include "Client.hpp" #include "render/Renderer.hpp" #include <sstream> //#define CONNECTION_TIMEOUT 5000 #define CONNECTION_TIMEOUT 100000 #define NUMBER_CHANNELS 2 #define SPEED 25 Client::Client() : m_host(nullptr), m_server(nullptr) { createClient(); } Client::~Client() { this->disconnect(); delete m_server_address; } void printPacketDescription(const lambda::GameState *gamestate) { printf("\tPacket description:\n"); printf("\tNb players: %d\n", gamestate->nb_players()); for (int i = 0; i < gamestate->nb_players(); i++) { printf("\tPlayer %d: (%d,%d)\n", i + 1, gamestate->players_data(i).x(), gamestate->players_data(i).y()); } } int Client::createClient() { /* Creates a client */ m_host = enet_host_create(NULL /* create a client host */, 1 /* only allow 1 outgoing connection */, NUMBER_CHANNELS /* allow up 2 channels to be used, 0 and 1 */, 0 /* assume any amount of incoming bandwidth */, 0 /* assume any amount of outgoing bandwidth */); if (m_host == NULL) { fprintf(stderr, "An error occurred while trying to create an ENet client host.\n"); return -1; } return 1; } int Client::connectToServer(const char* server_ip, int server_port) { // Set server address m_server_address = new ENetAddress(); enet_address_set_host(m_server_address, server_ip); m_server_address->port = server_port; /* Initiate the connection, allocating the two channels 0 and 1. */ m_server = enet_host_connect(m_host, m_server_address, NUMBER_CHANNELS, 0); if (m_server == NULL) { fprintf(stderr, "No available peers for initiating an ENet connection.\n"); return -1; } /* Wait up to 5 seconds for the connection attempt to succeed. */ ENetEvent net_event; if (enet_host_service(m_host, &net_event, CONNECTION_TIMEOUT) > 0 && net_event.type == ENET_EVENT_TYPE_CONNECT) { printf("Attempt to connecting to %s:%d succeeded. Waiting for server response ...\n", server_ip, server_port); /* Store any relevant server information here. */ net_event.peer->data = (void *)"SERVER"; } else { /* Either the 5 seconds are up or a disconnect event was */ /* received. Reset the peer in the event the 5 seconds */ /* had run out without any significant event. */ enet_peer_reset(m_server); puts("Connection to the server failed."); return -1; } enet_host_flush(m_host); // Why does this have to be here for the server to receive the connection attempt ? //int response = enet_host_service(m_host, &event, 1000); int server_response = enet_host_service(m_host, &net_event, CONNECTION_TIMEOUT); // Server sent game state and the player's positions if (server_response > 0) { printf("Connection to %s:%d accepted.\n", server_ip, server_port); // Update the player's position lambda::GameState received_gamestate = getGamestateFromPacket(net_event.packet); int player_index = received_gamestate.nb_players() - 1; auto player_data = received_gamestate.players_data(player_index); m_id = player_data.id(); m_x = player_data.x(); m_y = player_data.y(); handlePacketReceipt(&net_event); } else { puts("Server did not respond... Good bye"); return -1; } return 1; } /** * Checks if a packet is in the waiting queue. */ void Client::checkPacketBox() { ENetEvent net_event; while (enet_host_service(m_host, &net_event, 0) > 0) { switch (net_event.type) { case ENET_EVENT_TYPE_CONNECT: { printf("Someone connected (why ?)\n"); break; } // The "peer" field contains the peer the packet was received from, "channelID" is the channel on // which the packet was sent, and "packet" is the packet that was sent. case ENET_EVENT_TYPE_RECEIVE: { handlePacketReceipt(&net_event); /* Clean up the packet now that we're done using it. */ enet_packet_destroy(net_event.packet); } } } } void Client::handlePacketReceipt(ENetEvent *net_event) { printf("A packet of length %lu was received from %d on channel %u.\n", net_event->packet->dataLength, net_event->peer->address.host, net_event->channelID); lambda::GameState received_gamestate = getGamestateFromPacket(net_event->packet); printPacketDescription(&received_gamestate); checkPacketFormat(&received_gamestate); updateRenderData(&received_gamestate); } void Client::updateRenderData(lambda::GameState *gamestate) const { if (gamestate->has_player_disconnected_id()) { Renderer::getInstance()->clearPlayer(gamestate->player_disconnected_id() - 1); // minus 1 because the server sends the index + 1 } // Retrieve players positions and send them to the renderer lambda::PlayersData player_data; int nb_players = gamestate->nb_players(); int player_index = -1; Position positions[nb_players]; for (int i = 0; i < nb_players; i++) { if (m_id == gamestate->players_data(i).id()) player_index = i; player_data = gamestate->players_data(i); positions[i] = {player_data.x(), player_data.y()}; } Renderer::getInstance()->updateRenderData(positions, nb_players, player_index); } void Client::disconnect() { ENetEvent net_event; enet_peer_disconnect(m_server, 0); /* Allow up to 3 seconds for the disconnect to succeed * and drop any received packets. */ while (enet_host_service(m_host, &net_event, 3000) > 0) { switch (net_event.type) { case ENET_EVENT_TYPE_RECEIVE: enet_packet_destroy(net_event.packet); break; case ENET_EVENT_TYPE_DISCONNECT: puts("Disconnection succeeded."); return; } } /* We've arrived here, so the disconnect attempt didn't */ /* succeed yet. Force the connection down. */ enet_peer_reset(m_server); enet_host_destroy(m_host); } void Client::moveUp() { m_y -= SPEED; sendPositionToServer(m_x, m_y); } void Client::moveDown() { m_y += SPEED; sendPositionToServer(m_x, m_y); } void Client::moveRight() { m_x += SPEED; sendPositionToServer(m_x, m_y); } void Client::moveLeft() { m_x -= SPEED; sendPositionToServer(m_x, m_y); } void Client::sendPositionToServer(int x, int y) const { lambda::PlayerAction playerAction; playerAction.set_new_x(x); playerAction.set_new_y(y); std::string packet_data = getStringFromPlayerAction(&playerAction); ENetPacket *packet = enet_packet_create(packet_data.data(), packet_data.size(), ENET_PACKET_FLAG_RELIABLE); // Send the packet to the peer over channel id 0. enet_peer_send(m_server, 0, packet); printf("Sending packet '(%d, %d)' to server.\n", playerAction.new_x(), playerAction.new_y()); } /** * Disconnect the client and close the window if the packet received is malformed */ void Client::checkPacketFormat(lambda::GameState *gamestate) { if (gamestate->nb_players() < 1) { printf("Received malformed packet.\n"); disconnect(); exit(-1); } } lambda::GameState Client::getGamestateFromPacket(ENetPacket *packet) const { lambda::GameState gamestate; gamestate.ParseFromArray(packet->data, packet->dataLength); return gamestate; } const std::string Client::getStringFromPlayerAction(lambda::PlayerAction *playeraction) const { std::string serialized_playeraction; playeraction->SerializeToString(&serialized_playeraction); return serialized_playeraction; }
29.058182
137
0.647228
nsentout
7e8f389f2ec72f9f4e69b6e67c0d432dcfd2686f
4,823
cpp
C++
sj_common.cpp
SJ-magic-youtube-VisualProgrammer/103_fft_Visualize__1_Artsin
4d5acdccae24364b173794793c9896c8420f55fb
[ "MIT" ]
null
null
null
sj_common.cpp
SJ-magic-youtube-VisualProgrammer/103_fft_Visualize__1_Artsin
4d5acdccae24364b173794793c9896c8420f55fb
[ "MIT" ]
null
null
null
sj_common.cpp
SJ-magic-youtube-VisualProgrammer/103_fft_Visualize__1_Artsin
4d5acdccae24364b173794793c9896c8420f55fb
[ "MIT" ]
null
null
null
/************************************************************ ************************************************************/ #include "sj_common.h" /************************************************************ ************************************************************/ /******************** ********************/ int GPIO_0 = 0; int GPIO_1 = 0; const float _PI = 3.1415; /******************** ********************/ GUI_GLOBAL* Gui_Global = NULL; FILE* fp_Log = nullptr; /************************************************************ func ************************************************************/ /****************************** ******************************/ double LPF(double LastVal, double CurrentVal, double Alpha_dt, double dt) { double Alpha; if((Alpha_dt <= 0) || (Alpha_dt < dt)) Alpha = 1; else Alpha = 1/Alpha_dt * dt; return CurrentVal * Alpha + LastVal * (1 - Alpha); } /****************************** ******************************/ double LPF(double LastVal, double CurrentVal, double Alpha) { if(Alpha < 0) Alpha = 0; else if(1 < Alpha) Alpha = 1; return CurrentVal * Alpha + LastVal * (1 - Alpha); } /****************************** ******************************/ double sj_max(double a, double b) { if(a < b) return b; else return a; } /****************************** ******************************/ bool checkIf_ContentsExist(char* ret, char* buf) { if( (ret == NULL) || (buf == NULL)) return false; string str_Line = buf; Align_StringOfData(str_Line); vector<string> str_vals = ofSplitString(str_Line, ","); if( (str_vals.size() == 0) || (str_vals[0] == "") ){ // no_data or exist text but it's",,,,,,,". return false; }else{ return true; } } /****************************** ******************************/ void Align_StringOfData(string& s) { size_t pos; while((pos = s.find_first_of("  \t\n\r")) != string::npos){ // 半角・全角space, \t 改行 削除 s.erase(pos, 1); } } /****************************** ******************************/ void print_separatoin() { printf("---------------------------------\n"); } /****************************** ******************************/ void ClearFbo(ofFbo& fbo) { fbo.begin(); ofClear(0, 0, 0, 255); fbo.end(); } /****************************** ******************************/ float toRad(float val){ return val * 3.1415 / 180.0; } /****************************** ******************************/ float toDeg(float val){ return val * 180.0 / 3.1415; } /****************************** ******************************/ float get_val_top_of_artsin_window(){ if(Gui_Global->ArtSin2D_BarHeight == 0) return 1e4; const float Window_H = 200.0; return 1.0 * Window_H / Gui_Global->ArtSin2D_BarHeight; } /************************************************************ class ************************************************************/ /****************************** ******************************/ void GUI_GLOBAL::setup(string GuiName, string FileName, float x, float y) { /******************** ********************/ gui.setup(GuiName.c_str(), FileName.c_str(), x, y); /******************** ********************/ Group_Audio.setup("Audio"); Group_Audio.add(b_Audio_Start.setup("Start", false)); Group_Audio.add(b_Audio_Stop.setup("Stop", false)); Group_Audio.add(b_Audio_Reset.setup("Reset", false)); gui.add(&Group_Audio); Group_FFT.setup("FFT"); Group_FFT.add(FFT__SoftGain.setup("FFT__SoftGain", 1.0, 1.0, 5.0)); Group_FFT.add(FFT__k_smooth.setup("FFT__k_smooth", 0.95, 0.8, 1.0)); Group_FFT.add(FFT__dt_smooth_2.setup("FFT__dt_smooth_2", 167, 10, 300)); Group_FFT.add(FFT__b_Window.setup("FFT__b_Window", true)); gui.add(&Group_FFT); Group_ArtSin.setup("ArtSin"); Group_ArtSin.add(ArtSin_Band_min.setup("ArtSin_Band_min", 1.0, 1.0, 255.0)); Group_ArtSin.add(ArtSin_Band_max.setup("ArtSin_Band_max", 1.0, 1.0, 255.0)); Group_ArtSin.add(ArtSin_PhaseMap_k.setup("ArtSin_PhaseMap_k", 1.0, 0.0, 2.0)); Group_ArtSin.add(b_ArtSin_abs.setup("b_ArtSin_abs", false)); Group_ArtSin.add(b_Window_artSin.setup("b_Window_artSin", false)); Group_ArtSin.add(Tukey_alpha.setup("Tukey_alpha", 0.3, 0.0, 1.0)); gui.add(&Group_ArtSin); Group_ArtSin2D.setup("ArtSin2D"); Group_ArtSin2D.add(b_Draw_ArtSin2D.setup("ArtSin2D:b_Draw", true)); Group_ArtSin2D.add(ArtSin2D_BarHeight.setup("ArtSin2D:BarHeight", 200, 0.0, 1000)); { ofColor initColor = ofColor(255, 255, 255, 140); ofColor minColor = ofColor(0, 0, 0, 0); ofColor maxColor = ofColor(255, 255, 255, 255); Group_ArtSin2D.add(col_ArtSin2D.setup("ArtSin2D:col", initColor, minColor, maxColor)); } gui.add(&Group_ArtSin2D); Group_img.setup("img"); Group_img.add(img_alpha.setup("img:alpha", 20, 0.0, 255.0)); gui.add(&Group_img); /******************** ********************/ gui.minimizeAll(); }
28.040698
97
0.477918
SJ-magic-youtube-VisualProgrammer
7e93ec0bca991f125711ab938417ac023ab4bd8b
8,255
cpp
C++
moses/moses/TranslationModel/CompactPT/PhraseDictionaryCompact.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
3
2018-01-25T00:51:56.000Z
2022-01-07T15:09:38.000Z
moses/moses/TranslationModel/CompactPT/PhraseDictionaryCompact.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
1
2020-06-23T08:29:09.000Z
2020-06-24T12:11:47.000Z
moses/moses/TranslationModel/CompactPT/PhraseDictionaryCompact.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
3
2018-06-08T08:36:27.000Z
2021-12-26T20:36:16.000Z
// $Id$ // vim:tabstop=2 /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <fstream> #include <string> #include <iterator> #include <queue> #include <algorithm> #include <sys/stat.h> #include "PhraseDictionaryCompact.h" #include "moses/FactorCollection.h" #include "moses/Word.h" #include "moses/Util.h" #include "moses/InputFileStream.h" #include "moses/StaticData.h" #include "moses/WordsRange.h" #include "moses/UserMessage.h" #include "moses/ThreadPool.h" using namespace std; namespace Moses { bool PhraseDictionaryCompact::Load(const std::vector<FactorType> &input , const std::vector<FactorType> &output , const string &filePath , const vector<float> &weight , size_t tableLimit , const LMList &languageModels , float weightWP) { m_input = &input; m_output = &output; m_weight = new std::vector<float>(weight); m_tableLimit = tableLimit; m_languageModels = &languageModels; m_weightWP = weightWP; std::string tFilePath = filePath; std::string suffix = ".minphr"; if(tFilePath.substr(tFilePath.length() - suffix.length(), suffix.length()) == suffix) { if(!FileExists(tFilePath)) { std::cerr << "Error: File " << tFilePath << " does not exit." << std::endl; exit(1); } } else { if(FileExists(tFilePath + suffix)) { tFilePath += suffix; } else { std::cerr << "Error: File " << tFilePath << ".minphr does not exit." << std::endl; exit(1); } } m_phraseDecoder = new PhraseDecoder(*this, m_input, m_output, m_feature, m_numScoreComponent, m_weight, m_weightWP, m_languageModels); std::FILE* pFile = std::fopen(tFilePath.c_str() , "r"); size_t indexSize; if(m_inMemory) // Load source phrase index into memory indexSize = m_hash.Load(pFile); else // Keep source phrase index on disk indexSize = m_hash.LoadIndex(pFile); size_t coderSize = m_phraseDecoder->Load(pFile); size_t phraseSize; if(m_inMemory) // Load target phrase collections into memory phraseSize = m_targetPhrasesMemory.load(pFile, false); else // Keep target phrase collections on disk phraseSize = m_targetPhrasesMapped.load(pFile, true); return indexSize && coderSize && phraseSize; } struct CompareTargetPhrase { bool operator() (const TargetPhrase &a, const TargetPhrase &b) { return a.GetFutureScore() > b.GetFutureScore(); } }; const TargetPhraseCollection* PhraseDictionaryCompact::GetTargetPhraseCollection(const Phrase &sourcePhrase) const { // There is no souch source phrase if source phrase is longer than longest // observed source phrase during compilation if(sourcePhrase.GetSize() > m_phraseDecoder->GetMaxSourcePhraseLength()) return NULL; // Retrieve target phrase collection from phrase table TargetPhraseVectorPtr decodedPhraseColl = m_phraseDecoder->CreateTargetPhraseCollection(sourcePhrase, true); if(decodedPhraseColl != NULL && decodedPhraseColl->size()) { TargetPhraseVectorPtr tpv(new TargetPhraseVector(*decodedPhraseColl)); TargetPhraseCollection* phraseColl = new TargetPhraseCollection(); // Score phrases and if possible apply ttable_limit TargetPhraseVector::iterator nth = (m_tableLimit == 0 || tpv->size() < m_tableLimit) ? tpv->end() : tpv->begin() + m_tableLimit; std::nth_element(tpv->begin(), nth, tpv->end(), CompareTargetPhrase()); for(TargetPhraseVector::iterator it = tpv->begin(); it != nth; it++) phraseColl->Add(new TargetPhrase(*it)); // Cache phrase pair for for clean-up or retrieval with PREnc const_cast<PhraseDictionaryCompact*>(this)->CacheForCleanup(phraseColl); return phraseColl; } else return NULL; } TargetPhraseVectorPtr PhraseDictionaryCompact::GetTargetPhraseCollectionRaw(const Phrase &sourcePhrase) const { // There is no souch source phrase if source phrase is longer than longest // observed source phrase during compilation if(sourcePhrase.GetSize() > m_phraseDecoder->GetMaxSourcePhraseLength()) return TargetPhraseVectorPtr(); // Retrieve target phrase collection from phrase table return m_phraseDecoder->CreateTargetPhraseCollection(sourcePhrase, true); } PhraseDictionaryCompact::~PhraseDictionaryCompact() { if(m_phraseDecoder) delete m_phraseDecoder; if(m_weight) delete m_weight; } //TO_STRING_BODY(PhraseDictionaryCompact) void PhraseDictionaryCompact::CacheForCleanup(TargetPhraseCollection* tpc) { #ifdef WITH_THREADS boost::mutex::scoped_lock lock(m_sentenceMutex); PhraseCache &ref = m_sentenceCache[boost::this_thread::get_id()]; #else PhraseCache &ref = m_sentenceCache; #endif ref.push_back(tpc); } void PhraseDictionaryCompact::InitializeForInput(const Moses::InputType&) {} void PhraseDictionaryCompact::AddEquivPhrase(const Phrase &source, const TargetPhrase &targetPhrase) { } void PhraseDictionaryCompact::CleanUp(const InputType &source) { if(!m_inMemory) m_hash.KeepNLastRanges(0.01, 0.2); m_phraseDecoder->PruneCache(); #ifdef WITH_THREADS boost::mutex::scoped_lock lock(m_sentenceMutex); PhraseCache &ref = m_sentenceCache[boost::this_thread::get_id()]; #else PhraseCache &ref = m_sentenceCache; #endif for(PhraseCache::iterator it = ref.begin(); it != ref.end(); it++) delete *it; PhraseCache temp; temp.swap(ref); } }
39.879227
134
0.5404
anshsarkar
7e96c654433e0c3df6bc764637c2400f114f2b57
3,648
cpp
C++
src/IceRay/camera/dof/cone.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
2
2020-09-04T12:27:15.000Z
2022-01-17T14:49:40.000Z
src/IceRay/camera/dof/cone.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
null
null
null
src/IceRay/camera/dof/cone.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
1
2020-09-04T12:27:52.000Z
2020-09-04T12:27:52.000Z
#include "./cone.hpp" #include "IceRay/utility/random.hpp" #include "math/function/function.hpp" using namespace GS_DDMRM::S_IceRay::S_camera::S_dof; GS_DDMRM::S_IceRay::S_utility::S_table::GC_hexagon GC_cone::M2s_hexagon( 20 ); GC_cone::GC_cone() :GC_cone( &Fs_child(), 1, 0, 1 ) { } GC_cone::GC_cone( T_size const& P_sample, T_scalar const& P_aperture ) :GC__parent( nullptr, P_sample ) { F_aperture( P_aperture ); F_gauss( 1 ); } GC_cone::GC_cone( T__pure *P_camera, T_size const& P_sample, T_scalar const& P_aperture ) :GC__parent( P_camera, P_sample ) { F_aperture( P_aperture ); F_gauss( 1 ); } GC_cone::GC_cone( T__pure *P_camera, T_size const& P_sample, T_scalar const& P_aperture, T_scalar const& P_gauss ) :GC__parent( P_camera, P_sample ) { F_aperture( P_aperture ); F_gauss( P_gauss ); } GC_cone::~GC_cone() { } GC_cone::T_size GC_cone::Fv_beam ( T_beam & P_beam ,T_coord2D const& P_uv )const { T_coord2D I_disc; T_affine I_affine; F_child().Fv_system( I_affine, P_uv ); T_coord I_back =::math::linear::vector::fill( T_coord{}, 0 ); T_coord I_front =::math::linear::vector::load( T_coord{}, 0,1,0 ); T_coord I_heading; { T_coord I_base; ::math::linear::matrix::transform( I_base, I_affine.matrix(), I_back ); ::math::linear::matrix::transform( I_heading, I_affine.matrix(), I_front ); ::math::linear::vector::subtraction( I_heading, I_base ); ::math::linear::vector::length( I_heading, T_scalar( 1 ) ); } T_scalar I_summae = 0; for( T_size I_index =0; I_index < F_size(); I_index++ ) { GS_DDMRM::S_IceRay::S_utility::S_random::GF_disc2D( I_disc[0], I_disc[1], M2_randSobol2D ); //GS_DDMRM::S_IceRay::S_utility::S_random::GF_disc2D( I_disc, M2_randStandard2D ); //GS_DDMRM::S_IceRay::S_utility::S_random::GF_disc2D( I_disc, M2_randVaLND ); I_disc = M2s_hexagon.F_spot()[I_index]; ::math::linear::vector::scale( I_disc, T_scalar(1)/M2s_hexagon.F_radius()[M2_index] ); T_scalar const& I_x = I_disc[0]; T_scalar const& I_y = I_disc[1]; T_coord & I_direction = P_beam[I_index].M_direction; T_coord & I_origin = P_beam[I_index].M_origin; I_origin[0]=0; I_origin[1]=0; I_origin[2]=0; I_front[0] = I_x * F_aperture(); I_front[1] = 1; I_front[2] = I_y * F_aperture(); I_origin = I_affine.vector(); ::math::linear::matrix::transform( I_direction, I_affine.matrix(), I_front ); ::math::linear::vector::length( I_direction, T_scalar( 1 ) ); { T_scalar I_intesity = ::math::linear::vector::dot( I_heading, I_direction ); I_intesity = ( 1 < I_intesity ? 1: I_intesity ); I_intesity = ::math::function::pdf<T_scalar>( acos( I_intesity ), F_gauss() ); P_beam[I_index].M_intesity = T_gray{ {I_intesity} }; I_summae += I_intesity; } } I_summae /= F_size(); for( T_size I_index =0; I_index < F_size(); I_index++ ) { P_beam[I_index].M_intesity /= I_summae; } return F_size(); } void GC_cone::Fv_system( T_affine &P_affine, T_coord2D const& P_uv ) { F_child().Fv_system( P_affine, P_uv ); } bool GC_cone::Fv_size( T_size const& P_size ) { F1_size() = M2s_hexagon.F_size()[P_size]; M2_index = P_size; return true; } bool GC_cone::F_aperture ( T_scalar const& P_aperture ) { if( P_aperture < T_scalar( 0 ) )return false; M2_aperture = P_aperture; return true; } bool GC_cone::F_gauss( T_scalar const& P_gauss ) { M2_gauss = P_gauss; return true; }
26.434783
131
0.640077
dmilos
7e98b11215a75e0113d7b3aea462bdeacac0a554
9,075
cc
C++
paddle/fluid/framework/ir/generate_pass_tester.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
11
2016-08-29T07:43:26.000Z
2016-08-29T07:51:24.000Z
paddle/fluid/framework/ir/generate_pass_tester.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
null
null
null
paddle/fluid/framework/ir/generate_pass_tester.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
1
2021-09-24T11:23:36.000Z
2021-09-24T11:23:36.000Z
// Copyright (c) 2021 PaddlePaddle Authors. 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 "gtest/gtest.h" #include "paddle/fluid/framework/ir/generate_pass.h" #include "paddle/fluid/framework/ir/pass_tester_helper.h" REGISTER_GENERATE_PASS(generate_fc_fuse) { paddle::framework::ir::PassPairs pass_pairs; for (bool with_relu : {true, false}) { // pattern SUBGRAPH_(pattern) = [subgraph = &pattern, with_relu](VAR_(x), VAR_(y), VAR_(z)) { VLOG(3) << "exec lambda func."; auto mul = OP_(mul)({{"X", x}, {"Y", y}}).Out("Out"); auto ewadd = OP_(elementwise_add)({{"X", mul}, {"Y", z}}).Out("Out"); if (with_relu) { return OP_(relu)({"X", ewadd}).Out("Out"); } else { return ewadd; } }; // replace SUBGRAPH_(replace) = [subgraph = &replace, with_relu](VAR_(x), VAR_(y), VAR_(z)) { auto& fc = OP_(fc)({{"Input", x}, {"W", y}, {"Bias", z}}); return fc.Out("Out"); }; pass_pairs.AddPassDesc(pattern, replace); } return pass_pairs; } REGISTER_GENERATE_PASS(generate_multi_add_to_addn) { // pattern SUBGRAPH_(pattern) = [subgraph = &pattern](VAR_(x), VAR_(y), VAR_(z)) { auto ewadd1 = OP_(elementwise_add)({{"X", x}, {"Y", y}}).Out("Out"); auto ewadd2 = OP_(elementwise_add)({{"X", ewadd1}, {"Y", z}}).Out("Out"); return ewadd2; }; // replace SUBGRAPH_(replace) = [subgraph = &replace](VAR_(x), VAR_(y), VAR_(z)) { return OP_(sum)({"X", {x, y, z}}).Out("Out"); }; return {pattern, replace}; } REGISTER_GENERATE_PASS(generate_combine_matmul) { // pattern SUBGRAPH_(pattern) = [subgraph = &pattern](VAR_(x), VAR_(y), VAR_(z)) { auto matmul1 = OP_(matmul)({{"X", x}, {"Y", y}}).Out("Out"); auto matmul2 = OP_(matmul)({{"X", x}, {"Y", z}}).Out("Out"); return std::make_tuple(matmul1, matmul2); }; // replace SUBGRAPH_(replace) = [subgraph = &replace](VAR_(x), VAR_(y), VAR_(z)) { auto concat = OP_(concat)({"X", {y, z}}).Out("Out"); auto matmul = OP_(matmul)({{"X", x}, {"Y", concat}}).Out("Out"); auto slice1 = OP_(slice)({"X", matmul}).Out("Out"); auto slice2 = OP_(slice)({"X", matmul}).Out("Out"); return std::make_tuple(slice1, slice2); }; return {pattern, replace}; } namespace paddle { namespace framework { namespace ir { TEST(GeneratePass, construct_with_string) { std::string binary_str; register_generate_fc_fuse().MultiPassDesc().SerializeToString(&binary_str); GeneratePass generate_pass(binary_str); } TEST(GeneratePass, generate_fc_fuse) { // inputs operator output // -------------------------------------------------------- // (a, filters_0 bias_0) conv2d -> conv2d_out // conv2d_out relu -> relu_out_0 // (relu_out_0, weights_0) mul -> mul_out_0 // (mul_out_0, bias_1) elementwise_add -> add_out_0 // add_out_0 relu -> relu_out_1 // (relu_out_1, weights_1) mul -> mul_out_1 // (mul_out_1, bias_2) elementwise_add -> add_out_1 Layers layers; auto* a = layers.data("a"); auto* filters_0 = layers.data("conv2d_filters_0", {}, true); auto* bias_0 = layers.data("conv2d_bias_0", {}, true); auto* conv2d_out = layers.conv2d(a, filters_0, bias_0, false); auto* relu_out_0 = layers.relu(conv2d_out); auto* weights_0 = layers.data("weights_0", {}, true); auto* mul_out_0 = layers.mul(relu_out_0, weights_0); auto* bias_1 = layers.data("bias_1", {}, true); auto* add_out_0 = layers.elementwise_add(mul_out_0, bias_1, nullptr, 1); auto* relu_out_1 = layers.relu(add_out_0); auto* weights_1 = layers.data("weights_1", {}, true); auto* mul_out_1 = layers.mul(relu_out_1, weights_1); auto* bias_2 = layers.data("bias_2", {}, true); auto* add_out_1 = layers.elementwise_add(mul_out_1, bias_2, nullptr, 1); VLOG(4) << add_out_1; std::unique_ptr<ir::Graph> graph(new ir::Graph(layers.main_program())); auto pass = PassRegistry::Instance().Get("generate_fc_fuse"); int num_nodes_before = graph->Nodes().size(); int num_mul_nodes_before = GetNumOpNodes(graph, "mul"); VLOG(3) << DebugString(graph); graph.reset(pass->Apply(graph.release())); int num_nodes_after = graph->Nodes().size(); int num_fc_nodes_after = GetNumOpNodes(graph, "fc"); VLOG(3) << DebugString(graph); PADDLE_ENFORCE_EQ(num_nodes_before, num_nodes_after + 6, platform::errors::InvalidArgument( "num_nodes_before=%d, num_nodes_after=%d.", num_nodes_before, num_nodes_after)); PADDLE_ENFORCE_EQ(num_fc_nodes_after, 2, platform::errors::InvalidArgument("num_fc_nodes_after=%d.", num_fc_nodes_after)); PADDLE_ENFORCE_EQ(num_mul_nodes_before, num_fc_nodes_after, platform::errors::InvalidArgument( "num_mul_nodes_before=%d, num_fc_nodes_after=%d.", num_mul_nodes_before, num_fc_nodes_after)); } TEST(GeneratePass, generate_multi_add_to_addn) { // inputs operator output // -------------------------------------------------------- // (a, b) elementwise_add -> add_out_0 // (add_out_0, c) elementwise_add -> add_out_1 Layers layers; auto* a = layers.data("a"); auto* b = layers.data("b"); auto* c = layers.data("c"); auto* add_out_0 = layers.elementwise_add(a, b); layers.elementwise_add(add_out_0, c); std::unique_ptr<ir::Graph> graph(new ir::Graph(layers.main_program())); auto pass = PassRegistry::Instance().Get("generate_multi_add_to_addn"); int num_nodes_before = graph->Nodes().size(); int num_add_nodes_before = GetNumOpNodes(graph, "elementwise_add"); VLOG(3) << DebugString(graph); graph.reset(pass->Apply(graph.release())); int num_nodes_after = graph->Nodes().size(); int num_addn_nodes_after = GetNumOpNodes(graph, "sum"); VLOG(3) << DebugString(graph); PADDLE_ENFORCE_EQ(num_nodes_before, num_nodes_after + 2, platform::errors::InvalidArgument( "num_nodes_before=%d, num_nodes_after=%d.", num_nodes_before, num_nodes_after)); PADDLE_ENFORCE_EQ(num_addn_nodes_after, 1, platform::errors::InvalidArgument( "num_addn_nodes_after=%d.", num_addn_nodes_after)); PADDLE_ENFORCE_EQ(num_add_nodes_before, num_addn_nodes_after + 1, platform::errors::InvalidArgument( "num_add_nodes_before=%d, num_addn_nodes_after=%d.", num_add_nodes_before, num_addn_nodes_after)); } TEST(GeneratePass, generate_combine_matmul) { // inputs operator output // -------------------------------------------------------- // (a, b) matmul -> matmul_out_0 // (a, c) matmul -> matmul_out_1 Layers layers; auto* a = layers.data("a"); auto* b = layers.data("b"); auto* c = layers.data("c"); layers.matmul(a, b); layers.matmul(a, c); std::unique_ptr<ir::Graph> graph(new ir::Graph(layers.main_program())); auto pass = PassRegistry::Instance().Get("generate_combine_matmul"); int num_nodes_before = graph->Nodes().size(); int num_matmul_nodes_before = GetNumOpNodes(graph, "matmul"); VLOG(3) << DebugString(graph); graph.reset(pass->Apply(graph.release())); int num_nodes_after = graph->Nodes().size(); int num_matmul_nodes_after = GetNumOpNodes(graph, "matmul"); VLOG(3) << DebugString(graph); PADDLE_ENFORCE_EQ(num_nodes_before, num_nodes_after - 4, platform::errors::InvalidArgument( "num_nodes_before=%d, num_nodes_after=%d.", num_nodes_before, num_nodes_after)); PADDLE_ENFORCE_EQ(num_matmul_nodes_after, 1, platform::errors::InvalidArgument( "num_matmul_nodes_after=%d.", num_matmul_nodes_after)); PADDLE_ENFORCE_EQ( num_matmul_nodes_before, num_matmul_nodes_after + 1, platform::errors::InvalidArgument( "num_matmul_nodes_before=%d, num_matmul_nodes_after=%d.", num_matmul_nodes_before, num_matmul_nodes_after)); } } // namespace ir } // namespace framework } // namespace paddle
42.406542
79
0.608485
L-Net-1992
7e99bff8822e5d2d5f18f8c59410f9d2ce56cc5a
2,953
cpp
C++
Button/QCheckBox/mainwindow.cpp
Sakura1221/QtStudy
34d24affada2a10c901fb9571473a33c871201fa
[ "MIT" ]
4
2021-06-17T02:58:18.000Z
2021-11-09T11:40:37.000Z
Button/QCheckBox/mainwindow.cpp
Sakura1221/QtStudy
34d24affada2a10c901fb9571473a33c871201fa
[ "MIT" ]
null
null
null
Button/QCheckBox/mainwindow.cpp
Sakura1221/QtStudy
34d24affada2a10c901fb9571473a33c871201fa
[ "MIT" ]
1
2021-06-26T07:42:20.000Z
2021-06-26T07:42:20.000Z
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); //设置根结点的三态属性 ui->wives->setTristate(true); // 当父结点状态改变后,子结点也要相应改变(只有全选或全未选两种状态) // 为了避免信号冲突,捕获clicked信号 // 需要判断按钮是否被选中了,这里要传入clicked信号返回值 connect(ui->wives, &QCheckBox::clicked, this, [=] (bool st) { if (st) { ui->jianning->setChecked(true); ui->fangyi->setChecked(true); ui->longer->setChecked(true); ui->zengrou->setChecked(true); ui->mujianping->setChecked(true); ui->shuanger->setChecked(true); ui->ake->setChecked(true); } else { ui->jianning->setChecked(false); ui->fangyi->setChecked(false); ui->longer->setChecked(false); ui->zengrou->setChecked(false); ui->mujianping->setChecked(false); ui->shuanger->setChecked(false); ui->ake->setChecked(false); } }); // 信号与槽函数都相同,要使用统一函数,槽函数不能是匿名函数 connect(ui->jianning, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->fangyi, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->longer, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->zengrou, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->mujianping, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->shuanger, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); connect(ui->ake, &QCheckBox::stateChanged, this, &MainWindow::statusChanged); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_cpp_stateChanged(int arg1) { if (arg1 == Qt::Checked) { qDebug() << "我会C++"; } else { qDebug() << "我不会C++"; } } void MainWindow::on_go_stateChanged(int arg1) { // 选中时 if (arg1 == Qt::Checked) { qDebug() << "我会Go"; } // 取消时 else { qDebug() << "我不会Go"; } } void MainWindow::on_python_stateChanged(int arg1) { if (arg1 == Qt::Checked) { qDebug() << "我会Python"; } else { qDebug() << "我不会Python"; } } void MainWindow::on_java_stateChanged(int arg1) { if (arg1 == Qt::Checked) { qDebug() << "我会Java"; } else { qDebug() << "我不会Java"; } } void MainWindow::statusChanged(int state) { // 子结点状态修改计数器 if (state == Qt::Checked) { m_number ++; } else { m_number --; } // 根据计数器修改根结点状态 if (m_number == 7) { ui->wives->setCheckState(Qt::Checked); } else if (m_number == 0) { ui->wives->setCheckState(Qt::Unchecked); } else { ui->wives->setCheckState(Qt::PartiallyChecked); } }
22.203008
88
0.568236
Sakura1221
7e9f61a31dc9853bbab43312588fdb215881f3df
607
cpp
C++
doc/recursion/code/13_dynamic_programming_stairs.cpp
CodeLingoBot/learn
d7ea19cb9a887ec60435698b9e945a110163eea2
[ "CC-BY-4.0" ]
1,235
2015-09-08T20:21:49.000Z
2022-03-28T10:54:28.000Z
doc/recursion/code/13_dynamic_programming_stairs.cpp
fengpf/learn
d7ea19cb9a887ec60435698b9e945a110163eea2
[ "CC-BY-4.0" ]
10
2015-09-08T23:16:52.000Z
2021-12-15T01:15:13.000Z
doc/recursion/code/13_dynamic_programming_stairs.cpp
fengpf/learn
d7ea19cb9a887ec60435698b9e945a110163eea2
[ "CC-BY-4.0" ]
183
2015-09-08T14:46:09.000Z
2022-03-06T07:03:31.000Z
#include <iostream> #include <map> using namespace std; int countDynamic(int n, map<int,int>& mm) { if (n < 0) return 0; else if (n == 0) return 1; else if (mm[n] > 0) return mm[n]; mm[n] = countDynamic(n-1, mm) + \ countDynamic(n-2, mm) + \ countDynamic(n-3, mm); return mm[n]; } int main() { map<int,int> mm; cout << countDynamic(10, mm) << endl; for (map<int,int>::iterator it=mm.begin(); it!=mm.end(); ++it) cout << it->first << " => " << it->second << '\n'; cout << endl; /* 274 1 => 1 2 => 2 3 => 4 4 => 7 5 => 13 6 => 24 7 => 44 8 => 81 9 => 149 10 => 274 */ }
14.804878
63
0.522241
CodeLingoBot
7e9f6cb6cf91773920d9c0461874a0d37d7b8345
1,177
cpp
C++
Actor/Characters/Enemy/E3/StateAI/StateMng_AI_EnemyE3.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
Actor/Characters/Enemy/E3/StateAI/StateMng_AI_EnemyE3.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
Actor/Characters/Enemy/E3/StateAI/StateMng_AI_EnemyE3.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "StateMng_AI_EnemyE3.h" #include "StateRoot_AI_EnemyE3.h" #include "../AIC_EnemyE3.h" UStateMng_AI_EnemyE3::UStateMng_AI_EnemyE3() { } UStateMng_AI_EnemyE3::~UStateMng_AI_EnemyE3() { } void UStateMng_AI_EnemyE3::Init(class AAIController* pRoot) { Super::Init(pRoot); m_pRootCharacter_Override = Cast<AAIC_EnemyE3>(pRoot); if (m_pRootCharacter_Override == nullptr) { ULOG(TEXT("m_pRootCharacter_Override is nullptr")); } m_pStateClass.Add(static_cast<int32>(E_StateAI_EnemyE3::E_Normal), NewObject<UStateAI_EnemyE3_Normal>()); m_pStateClass.Add(static_cast<int32>(E_StateAI_EnemyE3::E_Chase), NewObject<UState_AI_EnemyE3_Chase>()); m_pStateClass.Add(static_cast<int32>(E_StateAI_EnemyE3::E_Combat), NewObject<UStateAI_EnemyE3_Combat>()); m_pStateClass.Add(static_cast<int32>(E_StateAI_EnemyE3::E_Lost), NewObject<UStateAI_EnemyE3_Lost>()); for (TMap<int, class UStateRoot_AI*>::TIterator it = m_pStateClass.CreateIterator(); it; ++it) { it->Value->Init(this); } } void UStateMng_AI_EnemyE3::Destroy() { Super::Destroy(); m_pRootCharacter_Override = nullptr; }
26.75
106
0.7774
Bornsoul
7ea12f60bea230787f42772c870f7e48e1ea77ca
1,926
hpp
C++
headers/board.hpp
MartinKondor/WildTetris
84a8c84762b674b9b407f5122e3b35dad4d444ce
[ "MIT" ]
null
null
null
headers/board.hpp
MartinKondor/WildTetris
84a8c84762b674b9b407f5122e3b35dad4d444ce
[ "MIT" ]
1
2019-05-30T12:31:46.000Z
2019-06-04T09:40:36.000Z
headers/board.hpp
MartinKondor/WildTetris
84a8c84762b674b9b407f5122e3b35dad4d444ce
[ "MIT" ]
null
null
null
/*--------------------------------------------------------------- The Board, where each tetromino is stored, and the collusion detection takes place. ---------------------------------------------------------------*/ #ifndef _BOARD_ #define _BOARD_ #include "tetromino.hpp" #define BOARD_HEIGHT 15 #define BOARD_WIDTH 10 class Board { public: int prev_board[BOARD_HEIGHT][BOARD_WIDTH]; int board[BOARD_HEIGHT][BOARD_WIDTH]; std::vector<Tetromino> tetrominos; std::vector<Tetromino> prev_tetrominos; int tetromino_id; int score; int game_is_over; /** * The active or falling tetroino's id */ int current_tetromino_id; Board(); const void print(); /** * Throw a new playable tetromino from the top */ const void throw_new_tetromino(); /** * Place tetromino to the board from it's first filled element * * xcoord - Horizontal position in blocks * ycoord - Vertical position in blocks * * The x, y coordinate center is (0, 0) the left upper * corner of the this->board matrix * * returns the tetromino's id */ const int store_tetromino(int xcoord, int ycoord, char shape_type, int rotation); /** * Determine if the block is free from tetrominos */ const bool is_free_block(int xcoord, int ycoord); const void restore_board(); /** * Fills the board with 0s */ const void clean_up(); const int get_new_tetromino_id(); /** * This is where the current tetromnio starts to fall */ const void update(int rotation, int xmove, int ymove); const void draw_tetromino(int xcoord, int ycoord, Tetromino &t); const void save_board(); const void remove_last_line_if_possible(); /** * Checks if the player can continue or lose the game * false = losing * true = continue */ const bool is_won(); }; #endif
23.777778
85
0.607996
MartinKondor
7ea324a5d6413d9be9ad5ad01d8c1da842586b85
580
cpp
C++
example/iterable/at.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
2
2015-05-07T14:29:13.000Z
2015-07-04T10:59:46.000Z
example/iterable/at.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
example/iterable/at.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
/* @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #include <boost/hana/detail/assert.hpp> #include <boost/hana/integral.hpp> #include <boost/hana/list/instance.hpp> using namespace boost::hana; int main() { //! [main] BOOST_HANA_CONSTEXPR_ASSERT(at(int_<0>, list(0, '1', 2.0)) == 0); BOOST_HANA_CONSTEXPR_ASSERT(at(int_<1>, list(0, '1', 2.0)) == '1'); BOOST_HANA_CONSTEXPR_ASSERT(at(int_<2>, list(0, '1', 2.0)) == 2.0); //! [main] }
29
78
0.674138
rbock
7ea3e4fa4f2f94bac0ff40745f8e800c0968fb86
50,109
cc
C++
bindings/v8_opengl_es2.cc
slightlyoff/bravo
450d13427a27ac4f276ecac5bc350b81de838a6b
[ "BSD-3-Clause" ]
5
2015-12-17T19:48:38.000Z
2021-05-07T15:45:15.000Z
bindings/v8_opengl_es2.cc
slightlyoff/bravo
450d13427a27ac4f276ecac5bc350b81de838a6b
[ "BSD-3-Clause" ]
null
null
null
bindings/v8_opengl_es2.cc
slightlyoff/bravo
450d13427a27ac4f276ecac5bc350b81de838a6b
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "bravo/bindings/v8_opengl_es2.h" #include "base/strings/stringprintf.h" #include "bravo/bindings/util.h" #include "bravo/plugin/instance.h" #include "bravo/plugin/ppb.h" #include "v8/include/v8.h" #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> // See also: // https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.cpp namespace bravo { namespace { #define ARG_GLbitfield(arg) \ (arg)->Int32Value() #define ARG_GLenum(arg) \ (arg)->Int32Value() #define ARG_GLint(arg) \ (arg)->Int32Value() #define ARG_GLuint(arg) \ (arg)->Uint32Value() #define ARG_GLsizei(arg) \ (arg)->Uint32Value() #define ARG_GLfloat(arg) \ (arg)->NumberValue() #define ARG_GLclampf(arg) \ (arg)->NumberValue() #define ARG_GLboolean(arg) \ (arg)->BooleanValue() #define V8_BIND_0(interface, name) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ ppb.interface->name( \ GetPPResource(info)); \ } #define V8_BIND_1(interface, name, arg0) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 1) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0])); \ } #define V8_BIND_2(interface, name, arg0, arg1) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 2) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1])); \ } #define V8_BIND_2_V(interface, name, arg0, arg1, type) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 2) \ return; \ type v = arg1(info[1]); \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ &v); \ } #define V8_BIND_3(interface, name, arg0, arg1, arg2) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 3) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1]), \ arg2(info[2])); \ } #define V8_BIND_4(interface, name, arg0, arg1, arg2, arg3) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 4) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1]), \ arg2(info[2]), \ arg3(info[3])); \ } #define V8_BIND_4_V(interface, name, arg0, arg1, arg2, arg3, type) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 4) \ return; \ type v = arg3(info[3]); \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1]), \ arg2(info[2]), \ &v); \ } #define V8_BIND_5(interface, name, arg0, arg1, arg2, arg3, arg4) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 4) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1]), \ arg2(info[2]), \ arg3(info[3]), \ arg4(info[4])); \ } #define V8_BIND_8(interface, name, arg0, arg1, arg2, arg3, \ arg4, arg5, arg6, arg7) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 4) \ return; \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]), \ arg1(info[1]), \ arg2(info[2]), \ arg3(info[3]), \ arg4(info[4]), \ arg5(info[5]), \ arg6(info[6]), \ arg7(info[7])); \ } #define V8_BIND_HANDLE_0(interface, name) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ info.GetReturnValue().Set(v8::Uint32::New( \ ppb.interface->name( \ GetPPResource(info) \ ))); \ } #define V8_BIND_HANDLE_1(interface, name, arg0) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 1) \ return; \ info.GetReturnValue().Set(v8::Uint32::New( \ ppb.interface->name( \ GetPPResource(info), \ arg0(info[0]) \ ))); \ } #define V8_BIND_HANDLE_BUFFER(interface, name, singular) \ void singular(const v8::FunctionCallbackInfo<v8::Value>& info) { \ GLuint buffer = 0; \ ppb.interface->name(GetPPResource(info), 1, &buffer); \ info.GetReturnValue().Set(v8::Uint32::New(buffer)); \ } #define V8_BIND_DELETE_BUFFER(interface, name, singular) \ void singular(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 1) \ return; \ GLuint buffer = info[0]->Uint32Value(); \ ppb.interface->name(GetPPResource(info), 1, &buffer); \ } #define V8_BIND_1_SHADER_STRING(interface, name, getter, type, arg0) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 1) \ return; \ \ GLsizei length = 0; \ ppb.interface->getter(GetPPResource(info), \ arg0(info[0]), \ type, \ &length); \ char buffer[length]; \ GLsizei returnedLength = 0; \ ppb.interface->name(GetPPResource(info), \ arg0(info[0]), \ length, \ &returnedLength, \ buffer); \ info.GetReturnValue().Set(v8::String::New(buffer, returnedLength)); \ } #define V8_BIND_VERTEX_V(interface, name, v8type, typeTest, glType) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 2) \ return; \ \ /* TODO: handle regular arrays like WebGL does */ \ if (!info[1]->typeTest()) \ return; \ \ GLint index = ARG_GLint(info[0]); \ v8::Handle<v8::v8type> arr = v8::Handle<v8::v8type>::Cast(info[1]); \ void * data = arr->Buffer()->Externalize().Data(); \ ppb.interface->name(GetPPResource(info), \ index, \ reinterpret_cast<const glType *>(data)); \ } #define V8_BIND_UNIFORM_V(interface, name, v8type, typeTest, glType) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 2) \ return; \ \ /* TODO: handle regular arrays like WebGL does */ \ if (!info[1]->typeTest()) \ return; \ \ GLint location = ARG_GLint(info[0]); \ v8::Handle<v8::v8type> arr = v8::Handle<v8::v8type>::Cast(info[1]); \ void * data = arr->Buffer()->Externalize().Data(); \ ppb.interface->name(GetPPResource(info), \ location, \ 1, \ reinterpret_cast<const glType *>(data)); \ } #define V8_BIND_UNIFORM_MATRIX(interface, name, v8type, typeTest, glType) \ void name(const v8::FunctionCallbackInfo<v8::Value>& info) { \ if (info.Length() < 3) \ return; \ \ /* TODO: handle regular arrays like WebGL does */ \ if (!info[2]->typeTest()) \ return; \ \ GLint location = ARG_GLint(info[0]); \ GLboolean transpose = ARG_GLboolean(info[1]); \ v8::Handle<v8::v8type> arr = v8::Handle<v8::v8type>::Cast(info[2]); \ void * data = arr->Buffer()->Externalize().Data(); \ ppb.interface->name(GetPPResource(info), \ location, \ 1, \ transpose, \ reinterpret_cast<const glType *>(data)); \ } V8_BIND_1(opengl_es2, ActiveTexture, ARG_GLenum) V8_BIND_2(opengl_es2, AttachShader, ARG_GLuint, ARG_GLuint) // void (*BindAttribLocation)( // PP_Resource context, GLuint program, GLuint index, const char* name); V8_BIND_2(opengl_es2, BindBuffer, ARG_GLenum, ARG_GLuint) V8_BIND_2(opengl_es2, BindFramebuffer, ARG_GLenum, ARG_GLuint) V8_BIND_2(opengl_es2, BindRenderbuffer, ARG_GLenum, ARG_GLuint) V8_BIND_2(opengl_es2, BindTexture, ARG_GLenum, ARG_GLuint) V8_BIND_4(opengl_es2, BlendColor, ARG_GLclampf, ARG_GLclampf, ARG_GLclampf, ARG_GLclampf) V8_BIND_1(opengl_es2, BlendEquation, ARG_GLenum) V8_BIND_2(opengl_es2, BlendEquationSeparate, ARG_GLenum, ARG_GLenum) V8_BIND_2(opengl_es2, BlendFunc, ARG_GLenum, ARG_GLenum) V8_BIND_4(opengl_es2, BlendFuncSeparate, ARG_GLenum, ARG_GLenum, ARG_GLenum, ARG_GLenum) void BufferData(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 3) return; GLenum target = info[0]->Int32Value(); GLenum usage = info[2]->Int32Value(); /* void bufferData(GLenum target, GLsizeiptr size, GLenum usage) (OpenGL ES 2.0 §2.9, man page) Set the size of the currently bound WebGLBuffer object for the passed target. The buffer is initialized to 0. */ if (info[1]->IsNumber()) { ppb.opengl_es2->BufferData(GetPPResource(info), target, info[1]->Int32Value(), 0, usage); return; } /* void bufferData(GLenum target, ArrayBufferView data, GLenum usage) */ if (info[1]->IsArrayBuffer()) { v8::Handle<v8::ArrayBuffer> buffer = v8::Handle<v8::ArrayBuffer>::Cast(info[1]); // (GLsizeiptr)buffer->ByteLength(), ppb.opengl_es2->BufferData(GetPPResource(info), target, buffer->ByteLength(), buffer->Externalize().Data(), usage); } /* void bufferData(GLenum target, ArrayBuffer? data, GLenum usage) (OpenGL ES 2.0 §2.9, man page) Set the size of the currently bound WebGLBuffer object for the passed target to the size of the passed data, then write the contents of data to the buffer object. */ if (info[1]->IsArrayBufferView()) { v8::Handle<v8::ArrayBufferView> view = v8::Handle<v8::ArrayBufferView>::Cast(info[1]); void * data = view->Buffer()->Externalize().Data(); ppb.opengl_es2->BufferData(GetPPResource(info), target, view->ByteLength(), data, usage); } /* TODO(slightlyoff): If the passed data is null then an INVALID_VALUE error is generated. */ } // void (*BufferSubData)( // PP_Resource context, GLenum target, GLintptr offset, GLsizeiptr size, // const void* data); V8_BIND_1(opengl_es2, CheckFramebufferStatus, ARG_GLenum) V8_BIND_1(opengl_es2, Clear, ARG_GLbitfield) V8_BIND_4(opengl_es2, ClearColor, ARG_GLclampf, ARG_GLclampf, ARG_GLclampf, ARG_GLclampf) V8_BIND_1(opengl_es2, ClearDepthf, ARG_GLclampf) V8_BIND_1(opengl_es2, ClearStencil, ARG_GLint) V8_BIND_4(opengl_es2, ColorMask, ARG_GLboolean, ARG_GLboolean, ARG_GLboolean, ARG_GLboolean) V8_BIND_1(opengl_es2, CompileShader, ARG_GLuint) // void (*CompressedTexImage2D)( // PP_Resource context, GLenum target, GLint level, GLenum internalformat, // GLsizei width, GLsizei height, GLint border, GLsizei imageSize, // const void* data); V8_BIND_8(opengl_es2, CopyTexImage2D, ARG_GLenum, ARG_GLint, ARG_GLenum, ARG_GLint, ARG_GLint, ARG_GLsizei, ARG_GLsizei, ARG_GLint) V8_BIND_8(opengl_es2, CopyTexSubImage2D, ARG_GLenum, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLsizei, ARG_GLsizei) V8_BIND_HANDLE_BUFFER(opengl_es2, GenBuffers, CreateBuffer) V8_BIND_HANDLE_BUFFER(opengl_es2, GenFramebuffers, CreateFramebuffer) V8_BIND_HANDLE_BUFFER(opengl_es2, GenRenderbuffers, CreateRenderbuffer) V8_BIND_HANDLE_BUFFER(opengl_es2, GenTextures, CreateTexture) V8_BIND_HANDLE_0(opengl_es2, CreateProgram) V8_BIND_HANDLE_1(opengl_es2, CreateShader, ARG_GLenum) V8_BIND_1(opengl_es2, CullFace, ARG_GLenum) V8_BIND_DELETE_BUFFER(opengl_es2, DeleteBuffers, DeleteBuffer) V8_BIND_DELETE_BUFFER(opengl_es2, DeleteFramebuffers, DeleteFramebuffer) V8_BIND_1(opengl_es2, DeleteProgram, ARG_GLuint) V8_BIND_DELETE_BUFFER(opengl_es2, DeleteRenderbuffers, DeleteRenderbuffer) V8_BIND_1(opengl_es2, DeleteShader, ARG_GLuint) V8_BIND_DELETE_BUFFER(opengl_es2, DeleteTextures, DeleteTexture) V8_BIND_1(opengl_es2, DepthFunc, ARG_GLenum) V8_BIND_1(opengl_es2, DepthMask, ARG_GLboolean) V8_BIND_2(opengl_es2, DepthRangef, ARG_GLclampf, ARG_GLclampf) V8_BIND_2(opengl_es2, DetachShader, ARG_GLuint, ARG_GLuint) V8_BIND_1(opengl_es2, Disable, ARG_GLenum) V8_BIND_1(opengl_es2, DisableVertexAttribArray, ARG_GLuint) V8_BIND_3(opengl_es2, DrawArrays, ARG_GLenum, ARG_GLint, ARG_GLsizei) void DrawElements(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 4) return; GLenum mode = ARG_GLenum(info[0]); GLsizei count = ARG_GLsizei(info[1]); GLenum elementType = ARG_GLenum(info[2]); GLint indices = ARG_GLint(info[3]); ppb.opengl_es2->DrawElements(GetPPResource(info), mode, count, elementType, reinterpret_cast<void *>(indices)); } V8_BIND_1(opengl_es2, Enable, ARG_GLenum) V8_BIND_1(opengl_es2, EnableVertexAttribArray, ARG_GLuint) V8_BIND_0(opengl_es2, Finish) V8_BIND_0(opengl_es2, Flush) V8_BIND_4(opengl_es2, FramebufferRenderbuffer, ARG_GLenum, ARG_GLenum, ARG_GLenum, ARG_GLuint) V8_BIND_5(opengl_es2, FramebufferTexture2D, ARG_GLenum, ARG_GLenum, ARG_GLenum, ARG_GLuint, ARG_GLint) V8_BIND_1(opengl_es2, FrontFace, ARG_GLenum) V8_BIND_1(opengl_es2, GenerateMipmap, ARG_GLenum) // void (*GetActiveAttrib)( // PP_Resource context, GLuint program, GLuint index, GLsizei bufsize, // GLsizei* length, GLint* size, GLenum* type, char* name); // void (*GetActiveUniform)( // PP_Resource context, GLuint program, GLuint index, GLsizei bufsize, // GLsizei* length, GLint* size, GLenum* type, char* name); // void (*GetAttachedShaders)( // PP_Resource context, GLuint program, GLsizei maxcount, GLsizei* count, // GLuint* shaders); void GetAttribLocation(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) return; if (!info[0]->IsNumber()) return; if (!info[1]->IsString()) return; v8::String::Utf8Value name(info[1]); const char* str = *name; GLint value = ppb.opengl_es2->GetAttribLocation(GetPPResource(info), ARG_GLint(info[0]), str); info.GetReturnValue().Set(v8::Uint32::New(value)); } // void (*GetBooleanv)(PP_Resource context, GLenum pname, GLboolean* params); // void (*GetBufferParameteriv)( // PP_Resource context, GLenum target, GLenum pname, GLint* params); V8_BIND_HANDLE_0(opengl_es2, GetError) // void (*GetFloatv)(PP_Resource context, GLenum pname, GLfloat* params); // void (*GetFramebufferAttachmentParameteriv)( // PP_Resource context, GLenum target, GLenum attachment, GLenum pname, // GLint* params); // void (*GetIntegerv)(PP_Resource context, GLenum pname, GLint* params); void GetProgramParameter(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) return; GLenum name = ARG_GLenum(info[1]); GLint value = 0; ppb.opengl_es2->GetProgramiv(GetPPResource(info), ARG_GLuint(info[0]), name, &value); if (name == GL_DELETE_STATUS || name == GL_LINK_STATUS || name == GL_VALIDATE_STATUS) { info.GetReturnValue().Set(v8::Boolean::New(value)); return; } if (name == GL_ATTACHED_SHADERS || name == GL_ACTIVE_ATTRIBUTES || name == GL_ACTIVE_UNIFORMS) { info.GetReturnValue().Set(v8::Uint32::New(value)); return; } info.GetReturnValue().Set(v8::Null()); } V8_BIND_1_SHADER_STRING(opengl_es2, GetProgramInfoLog, GetProgramiv, GL_INFO_LOG_LENGTH, ARG_GLuint) // void (*GetRenderbufferParameteriv)( // PP_Resource context, GLenum target, GLenum pname, GLint* params); // void (*GetShaderiv)( // PP_Resource context, GLuint shader, GLenum pname, GLint* params); void GetShaderParameter(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) return; GLint shader = ARG_GLuint(info[0]); GLenum name = ARG_GLenum(info[1]); GLint value = 0; ppb.opengl_es2->GetShaderiv(GetPPResource(info), shader, name, &value); if (name == GL_DELETE_STATUS || name == GL_COMPILE_STATUS) { info.GetReturnValue().Set(v8::Boolean::New(value)); return; } if (name == GL_SHADER_TYPE) { info.GetReturnValue().Set(v8::Uint32::New(value)); return; } info.GetReturnValue().Set(v8::Null()); } V8_BIND_1_SHADER_STRING(opengl_es2, GetShaderInfoLog, GetShaderiv, GL_INFO_LOG_LENGTH, ARG_GLuint) // void (*GetShaderPrecisionFormat)( // PP_Resource context, GLenum shadertype, GLenum precisiontype, // GLint* range, GLint* precision); V8_BIND_1_SHADER_STRING(opengl_es2, GetShaderSource, GetShaderiv, GL_SHADER_SOURCE_LENGTH, ARG_GLuint) // const GLubyte* (*GetString)(PP_Resource context, GLenum name); // void (*GetTexParameterfv)( // PP_Resource context, GLenum target, GLenum pname, GLfloat* params); // void (*GetTexParameteriv)( // PP_Resource context, GLenum target, GLenum pname, GLint* params); // void (*GetUniformfv)( // PP_Resource context, GLuint program, GLint location, GLfloat* params); // void (*GetUniformiv)( // PP_Resource context, GLuint program, GLint location, GLint* params); void GetUniformLocation(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) return; if (!info[0]->IsNumber()) return; if (!info[1]->IsString()) return; v8::String::Utf8Value name(info[1]); const char* str = *name; GLint value = ppb.opengl_es2->GetUniformLocation(GetPPResource(info), ARG_GLint(info[0]), str); info.GetReturnValue().Set(v8::Uint32::New(value)); } // void (*GetVertexAttribfv)( // PP_Resource context, GLuint index, GLenum pname, GLfloat* params); // void (*GetVertexAttribiv)( // PP_Resource context, GLuint index, GLenum pname, GLint* params); // void (*GetVertexAttribPointerv)( // PP_Resource context, GLuint index, GLenum pname, void** pointer); V8_BIND_2(opengl_es2, Hint, ARG_GLenum, ARG_GLenum) // GLboolean (*IsBuffer)(PP_Resource context, GLuint buffer); // GLboolean (*IsEnabled)(PP_Resource context, GLenum cap); // GLboolean (*IsFramebuffer)(PP_Resource context, GLuint framebuffer); // GLboolean (*IsProgram)(PP_Resource context, GLuint program); // GLboolean (*IsRenderbuffer)(PP_Resource context, GLuint renderbuffer); // GLboolean (*IsShader)(PP_Resource context, GLuint shader); // GLboolean (*IsTexture)(PP_Resource context, GLuint texture); V8_BIND_1(opengl_es2, LineWidth, ARG_GLfloat) V8_BIND_1(opengl_es2, LinkProgram, ARG_GLuint) V8_BIND_2(opengl_es2, PixelStorei, ARG_GLenum, ARG_GLint) V8_BIND_2(opengl_es2, PolygonOffset, ARG_GLfloat, ARG_GLfloat) // void (*ReadPixels)( // PP_Resource context, GLint x, GLint y, GLsizei width, GLsizei height, // GLenum format, GLenum type, void* pixels); V8_BIND_0(opengl_es2, ReleaseShaderCompiler) V8_BIND_4(opengl_es2, RenderbufferStorage, ARG_GLenum, ARG_GLenum, ARG_GLsizei, ARG_GLsizei) V8_BIND_2(opengl_es2, SampleCoverage, ARG_GLclampf, ARG_GLboolean) V8_BIND_4(opengl_es2, Scissor, ARG_GLint, ARG_GLint, ARG_GLsizei, ARG_GLsizei) // void (*ShaderBinary)( // PP_Resource context, GLsizei n, const GLuint* shaders, // GLenum binaryformat, const void* binary, GLsizei length); void ShaderSource(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) return; if (!info[1]->IsString()) return; v8::String::Utf8Value shaderSource(info[1]); const char* str = *shaderSource; int length = shaderSource.length(); ppb.opengl_es2->ShaderSource( GetPPResource(info), ARG_GLint(info[0]), 1, &str, // string &length); } V8_BIND_3(opengl_es2, StencilFunc, ARG_GLenum, ARG_GLint, ARG_GLuint) V8_BIND_4(opengl_es2, StencilFuncSeparate, ARG_GLenum, ARG_GLenum, ARG_GLint, ARG_GLuint) V8_BIND_1(opengl_es2, StencilMask, ARG_GLuint) V8_BIND_2(opengl_es2, StencilMaskSeparate, ARG_GLenum, ARG_GLuint) V8_BIND_3(opengl_es2, StencilOp, ARG_GLenum, ARG_GLenum, ARG_GLenum) V8_BIND_4(opengl_es2, StencilOpSeparate, ARG_GLenum, ARG_GLenum, ARG_GLenum, ARG_GLenum) /* void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels); // void (*TexImage2D)( // PP_Resource context, GLenum target, GLint level, GLint internalformat, // GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, // const void* pixels); */ V8_BIND_3(opengl_es2, TexParameterf, ARG_GLenum, ARG_GLenum, ARG_GLfloat) // void (*TexParameterfv)( // PP_Resource context, GLenum target, GLenum pname, const GLfloat* params); V8_BIND_3(opengl_es2, TexParameteri, ARG_GLenum, ARG_GLenum, ARG_GLint) // void (*TexParameteriv)( // PP_Resource context, GLenum target, GLenum pname, const GLint* params); // void (*TexSubImage2D)( // PP_Resource context, GLenum target, GLint level, GLint xoffset, // GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, // const void* pixels); V8_BIND_2(opengl_es2, Uniform1f, ARG_GLint, ARG_GLfloat) V8_BIND_UNIFORM_V(opengl_es2, Uniform1fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_2(opengl_es2, Uniform1i, ARG_GLint, ARG_GLint) V8_BIND_UNIFORM_V(opengl_es2, Uniform1iv, Int32Array, IsInt32Array, GLint) V8_BIND_3(opengl_es2, Uniform2f, ARG_GLint, ARG_GLfloat, ARG_GLfloat) V8_BIND_UNIFORM_V(opengl_es2, Uniform2fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_3(opengl_es2, Uniform2i, ARG_GLint, ARG_GLint, ARG_GLint) V8_BIND_UNIFORM_V(opengl_es2, Uniform2iv, Int32Array, IsInt32Array, GLint) V8_BIND_4(opengl_es2, Uniform3f, ARG_GLint, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat) V8_BIND_UNIFORM_V(opengl_es2, Uniform3fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_4(opengl_es2, Uniform3i, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLint) V8_BIND_UNIFORM_V(opengl_es2, Uniform3iv, Int32Array, IsInt32Array, GLint) V8_BIND_5(opengl_es2, Uniform4f, ARG_GLint, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat) V8_BIND_UNIFORM_V(opengl_es2, Uniform4fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_5(opengl_es2, Uniform4i, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLint, ARG_GLint) V8_BIND_UNIFORM_V(opengl_es2, Uniform4iv, Int32Array, IsInt32Array, GLint) V8_BIND_UNIFORM_MATRIX(opengl_es2, UniformMatrix2fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_UNIFORM_MATRIX(opengl_es2, UniformMatrix3fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_UNIFORM_MATRIX(opengl_es2, UniformMatrix4fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_1(opengl_es2, UseProgram, ARG_GLuint) V8_BIND_1(opengl_es2, ValidateProgram, ARG_GLuint) V8_BIND_2(opengl_es2, VertexAttrib1f, ARG_GLuint, ARG_GLfloat) V8_BIND_VERTEX_V(opengl_es2, VertexAttrib1fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_3(opengl_es2, VertexAttrib2f, ARG_GLuint, ARG_GLfloat, ARG_GLfloat) V8_BIND_VERTEX_V(opengl_es2, VertexAttrib2fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_4(opengl_es2, VertexAttrib3f, ARG_GLuint, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat) V8_BIND_VERTEX_V(opengl_es2, VertexAttrib3fv, Float32Array, IsFloat32Array, GLfloat) V8_BIND_5(opengl_es2, VertexAttrib4f, ARG_GLuint, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat, ARG_GLfloat) V8_BIND_VERTEX_V(opengl_es2, VertexAttrib4fv, Float32Array, IsFloat32Array, GLfloat) void VertexAttribPointer(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 5) return; ppb.opengl_es2->VertexAttribPointer( GetPPResource(info), ARG_GLuint(info[0]), ARG_GLint(info[1]), ARG_GLenum(info[2]), ARG_GLboolean(info[3]), ARG_GLsizei(info[4]), reinterpret_cast<void*>(static_cast<intptr_t>(ARG_GLint(info[4])))); } V8_BIND_4(opengl_es2, Viewport, ARG_GLint, ARG_GLint, ARG_GLsizei, ARG_GLsizei) static const size_t kMethodCount = 107; static const MethodConfiguration g_methods[kMethodCount] = { { "activeTexture", ActiveTexture }, { "attachShader", AttachShader }, { "bindBuffer", BindBuffer }, { "bindFramebuffer", BindFramebuffer }, { "bindRenderbuffer", BindRenderbuffer }, { "bindTexture", BindTexture }, { "blendColor", BlendColor }, { "blendEquation", BlendEquation }, { "blendEquationSeparate", BlendEquationSeparate }, { "blendFunc", BlendFunc }, { "blendFuncSeparate", BlendFuncSeparate }, { "bufferData", BufferData }, { "checkFramebufferStatus", CheckFramebufferStatus }, { "clear", Clear }, { "clearColor", ClearColor }, { "clearDepth", ClearDepthf }, { "clearStencil", ClearStencil }, { "colorMask", ColorMask }, { "compileShader", CompileShader }, { "copyTexImage2D", CopyTexImage2D }, { "copyTexSubImage2D", CopyTexSubImage2D }, { "createBuffer", CreateBuffer }, { "createFramebuffer", CreateFramebuffer }, { "createProgram", CreateProgram }, { "createRenderbuffer", CreateRenderbuffer }, { "createShader", CreateShader }, { "createTexture", CreateTexture }, { "cullFace", CullFace }, { "deleteBuffer", DeleteBuffer }, { "deleteFramebuffer", DeleteFramebuffer }, { "deleteProgram", DeleteProgram }, { "deleteRenderbuffer", DeleteRenderbuffer }, { "deleteShader", DeleteShader }, { "deleteTexture", DeleteTexture }, { "depthFunc", DepthFunc }, { "depthMask", DepthMask }, { "depthRangef", DepthRangef }, { "detachShader", DetachShader }, { "disable", Disable }, { "disableVertexAttribArray", DisableVertexAttribArray }, { "drawArrays", DrawArrays }, { "drawElements", DrawElements }, { "enable", Enable }, { "enableVertexAttribArray", EnableVertexAttribArray }, { "finish", Finish }, { "flush", Flush }, { "framebufferRenderbuffer", FramebufferRenderbuffer }, { "framebufferTexture2D", FramebufferTexture2D }, { "frontFace", FrontFace }, { "generateMipmap", GenerateMipmap }, { "getAttribLocation", GetAttribLocation }, { "getError", GetError }, { "getProgramInfoLog", GetProgramInfoLog }, { "getProgramParameter", GetProgramParameter }, { "getShaderInfoLog", GetShaderInfoLog }, { "getShaderParameter", GetShaderParameter }, { "getShaderSource", GetShaderSource }, { "getUniformLocation", GetUniformLocation }, { "hint", Hint }, { "lineWidth", LineWidth }, { "linkProgram", LinkProgram }, { "pixelStorei", PixelStorei }, { "polygonOffset", PolygonOffset }, { "releaseShaderCompiler", ReleaseShaderCompiler }, { "renderbufferStorage", RenderbufferStorage }, { "sampleCoverage", SampleCoverage }, { "scissor", Scissor }, { "shaderSource", ShaderSource }, { "stencilFunc", StencilFunc }, { "stencilFuncSeparate", StencilFuncSeparate }, { "stencilMask", StencilMask }, { "stencilMaskSeparate", StencilMaskSeparate }, { "stencilOp", StencilOp }, { "stencilOpSeparate", StencilOpSeparate }, { "texParameterf", TexParameterf }, { "texParameteri", TexParameteri }, { "uniform1f", Uniform1f }, { "uniform1fv", Uniform1fv }, { "uniform1i", Uniform1i }, { "uniform1iv", Uniform1iv }, { "uniform2f", Uniform2f }, { "uniform2fv", Uniform2fv }, { "uniform2i", Uniform2i }, { "uniform2iv", Uniform2iv }, { "uniform3f", Uniform3f }, { "uniform3fv", Uniform3fv }, { "uniform3i", Uniform3i }, { "uniform3iv", Uniform3iv }, { "uniform4f", Uniform4f }, { "uniform4fv", Uniform4fv }, { "uniform4i", Uniform4i }, { "uniform4iv", Uniform4iv }, { "uniformMatrix2fv", UniformMatrix2fv }, { "uniformMatrix3fv", UniformMatrix3fv }, { "uniformMatrix4fv", UniformMatrix4fv }, { "useProgram", UseProgram }, { "validateProgram", ValidateProgram }, { "vertexAttrib1f", VertexAttrib1f }, { "vertexAttrib1fv", VertexAttrib1fv }, { "vertexAttrib2f", VertexAttrib2f }, { "vertexAttrib2fv", VertexAttrib2fv }, { "vertexAttrib3f", VertexAttrib3f }, { "vertexAttrib3fv", VertexAttrib3fv }, { "vertexAttrib4f", VertexAttrib4f }, { "vertexAttrib4fv", VertexAttrib4fv }, { "vertexAttribPointer", VertexAttribPointer }, { "viewport", Viewport }, }; static const size_t kConstantCount = 301; static const ConstantConfiguration g_constants[kConstantCount] = { { "DEPTH_BUFFER_BIT", GL_DEPTH_BUFFER_BIT }, { "STENCIL_BUFFER_BIT", GL_STENCIL_BUFFER_BIT }, { "COLOR_BUFFER_BIT", GL_COLOR_BUFFER_BIT }, { "FALSE", GL_FALSE }, { "TRUE", GL_TRUE }, { "POINTS", GL_POINTS }, { "LINES", GL_LINES }, { "LINE_LOOP", GL_LINE_LOOP }, { "LINE_STRIP", GL_LINE_STRIP }, { "TRIANGLES", GL_TRIANGLES }, { "TRIANGLE_STRIP", GL_TRIANGLE_STRIP }, { "TRIANGLE_FAN", GL_TRIANGLE_FAN }, { "ZERO", GL_ZERO }, { "ONE", GL_ONE }, { "SRC_COLOR", GL_SRC_COLOR }, { "ONE_MINUS_SRC_COLOR", GL_ONE_MINUS_SRC_COLOR }, { "SRC_ALPHA", GL_SRC_ALPHA }, { "ONE_MINUS_SRC_ALPHA", GL_ONE_MINUS_SRC_ALPHA }, { "DST_ALPHA", GL_DST_ALPHA }, { "ONE_MINUS_DST_ALPHA", GL_ONE_MINUS_DST_ALPHA }, { "DST_COLOR", GL_DST_COLOR }, { "ONE_MINUS_DST_COLOR", GL_ONE_MINUS_DST_COLOR }, { "SRC_ALPHA_SATURATE", GL_SRC_ALPHA_SATURATE }, { "FUNC_ADD", GL_FUNC_ADD }, { "BLEND_EQUATION", GL_BLEND_EQUATION }, { "BLEND_EQUATION_RGB", GL_BLEND_EQUATION_RGB }, { "BLEND_EQUATION_ALPHA", GL_BLEND_EQUATION_ALPHA }, { "FUNC_SUBTRACT", GL_FUNC_SUBTRACT }, { "FUNC_REVERSE_SUBTRACT", GL_FUNC_REVERSE_SUBTRACT }, { "BLEND_DST_RGB", GL_BLEND_DST_RGB }, { "BLEND_SRC_RGB", GL_BLEND_SRC_RGB }, { "BLEND_DST_ALPHA", GL_BLEND_DST_ALPHA }, { "BLEND_SRC_ALPHA", GL_BLEND_SRC_ALPHA }, { "CONSTANT_COLOR", GL_CONSTANT_COLOR }, { "ONE_MINUS_CONSTANT_COLOR", GL_ONE_MINUS_CONSTANT_COLOR }, { "CONSTANT_ALPHA", GL_CONSTANT_ALPHA }, { "ONE_MINUS_CONSTANT_ALPHA", GL_ONE_MINUS_CONSTANT_ALPHA }, { "BLEND_COLOR", GL_BLEND_COLOR }, { "ARRAY_BUFFER", GL_ARRAY_BUFFER }, { "ELEMENT_ARRAY_BUFFER", GL_ELEMENT_ARRAY_BUFFER }, { "ARRAY_BUFFER_BINDING", GL_ARRAY_BUFFER_BINDING }, { "ELEMENT_ARRAY_BUFFER_BINDING", GL_ELEMENT_ARRAY_BUFFER_BINDING }, { "STREAM_DRAW", GL_STREAM_DRAW }, { "STATIC_DRAW", GL_STATIC_DRAW }, { "DYNAMIC_DRAW", GL_DYNAMIC_DRAW }, { "BUFFER_SIZE", GL_BUFFER_SIZE }, { "BUFFER_USAGE", GL_BUFFER_USAGE }, { "CURRENT_VERTEX_ATTRIB", GL_CURRENT_VERTEX_ATTRIB }, { "FRONT", GL_FRONT }, { "BACK", GL_BACK }, { "FRONT_AND_BACK", GL_FRONT_AND_BACK }, { "TEXTURE_2D", GL_TEXTURE_2D }, { "CULL_FACE", GL_CULL_FACE }, { "BLEND", GL_BLEND }, { "DITHER", GL_DITHER }, { "STENCIL_TEST", GL_STENCIL_TEST }, { "DEPTH_TEST", GL_DEPTH_TEST }, { "SCISSOR_TEST", GL_SCISSOR_TEST }, { "POLYGON_OFFSET_FILL", GL_POLYGON_OFFSET_FILL }, { "SAMPLE_ALPHA_TO_COVERAGE", GL_SAMPLE_ALPHA_TO_COVERAGE }, { "SAMPLE_COVERAGE", GL_SAMPLE_COVERAGE }, { "NO_ERROR", GL_NO_ERROR }, { "INVALID_ENUM", GL_INVALID_ENUM }, { "INVALID_VALUE", GL_INVALID_VALUE }, { "INVALID_OPERATION", GL_INVALID_OPERATION }, { "OUT_OF_MEMORY", GL_OUT_OF_MEMORY }, { "CW", GL_CW }, { "CCW", GL_CCW }, { "LINE_WIDTH", GL_LINE_WIDTH }, { "ALIASED_POINT_SIZE_RANGE", GL_ALIASED_POINT_SIZE_RANGE }, { "ALIASED_LINE_WIDTH_RANGE", GL_ALIASED_LINE_WIDTH_RANGE }, { "CULL_FACE_MODE", GL_CULL_FACE_MODE }, { "FRONT_FACE", GL_FRONT_FACE }, { "DEPTH_RANGE", GL_DEPTH_RANGE }, { "DEPTH_WRITEMASK", GL_DEPTH_WRITEMASK }, { "DEPTH_CLEAR_VALUE", GL_DEPTH_CLEAR_VALUE }, { "DEPTH_FUNC", GL_DEPTH_FUNC }, { "STENCIL_CLEAR_VALUE", GL_STENCIL_CLEAR_VALUE }, { "STENCIL_FUNC", GL_STENCIL_FUNC }, { "STENCIL_FAIL", GL_STENCIL_FAIL }, { "STENCIL_PASS_DEPTH_FAIL", GL_STENCIL_PASS_DEPTH_FAIL }, { "STENCIL_PASS_DEPTH_PASS", GL_STENCIL_PASS_DEPTH_PASS }, { "STENCIL_REF", GL_STENCIL_REF }, { "STENCIL_VALUE_MASK", GL_STENCIL_VALUE_MASK }, { "STENCIL_WRITEMASK", GL_STENCIL_WRITEMASK }, { "STENCIL_BACK_FUNC", GL_STENCIL_BACK_FUNC }, { "STENCIL_BACK_FAIL", GL_STENCIL_BACK_FAIL }, { "STENCIL_BACK_PASS_DEPTH_FAIL", GL_STENCIL_BACK_PASS_DEPTH_FAIL }, { "STENCIL_BACK_PASS_DEPTH_PASS", GL_STENCIL_BACK_PASS_DEPTH_PASS }, { "STENCIL_BACK_REF", GL_STENCIL_BACK_REF }, { "STENCIL_BACK_VALUE_MASK", GL_STENCIL_BACK_VALUE_MASK }, { "STENCIL_BACK_WRITEMASK", GL_STENCIL_BACK_WRITEMASK }, { "VIEWPORT", GL_VIEWPORT }, { "SCISSOR_BOX", GL_SCISSOR_BOX }, { "COLOR_CLEAR_VALUE", GL_COLOR_CLEAR_VALUE }, { "COLOR_WRITEMASK", GL_COLOR_WRITEMASK }, { "UNPACK_ALIGNMENT", GL_UNPACK_ALIGNMENT }, { "PACK_ALIGNMENT", GL_PACK_ALIGNMENT }, { "MAX_TEXTURE_SIZE", GL_MAX_TEXTURE_SIZE }, { "MAX_VIEWPORT_DIMS", GL_MAX_VIEWPORT_DIMS }, { "SUBPIXEL_BITS", GL_SUBPIXEL_BITS }, { "RED_BITS", GL_RED_BITS }, { "GREEN_BITS", GL_GREEN_BITS }, { "BLUE_BITS", GL_BLUE_BITS }, { "ALPHA_BITS", GL_ALPHA_BITS }, { "DEPTH_BITS", GL_DEPTH_BITS }, { "STENCIL_BITS", GL_STENCIL_BITS }, { "POLYGON_OFFSET_UNITS", GL_POLYGON_OFFSET_UNITS }, { "POLYGON_OFFSET_FACTOR", GL_POLYGON_OFFSET_FACTOR }, { "TEXTURE_BINDING_2D", GL_TEXTURE_BINDING_2D }, { "SAMPLE_BUFFERS", GL_SAMPLE_BUFFERS }, { "SAMPLES", GL_SAMPLES }, { "SAMPLE_COVERAGE_VALUE", GL_SAMPLE_COVERAGE_VALUE }, { "SAMPLE_COVERAGE_INVERT", GL_SAMPLE_COVERAGE_INVERT }, { "NUM_COMPRESSED_TEXTURE_FORMATS", GL_NUM_COMPRESSED_TEXTURE_FORMATS }, { "COMPRESSED_TEXTURE_FORMATS", GL_COMPRESSED_TEXTURE_FORMATS }, { "DONT_CARE", GL_DONT_CARE }, { "FASTEST", GL_FASTEST }, { "NICEST", GL_NICEST }, { "GENERATE_MIPMAP_HINT", GL_GENERATE_MIPMAP_HINT }, { "BYTE", GL_BYTE }, { "UNSIGNED_BYTE", GL_UNSIGNED_BYTE }, { "SHORT", GL_SHORT }, { "UNSIGNED_SHORT", GL_UNSIGNED_SHORT }, { "INT", GL_INT }, { "UNSIGNED_INT", GL_UNSIGNED_INT }, { "FLOAT", GL_FLOAT }, { "FIXED", GL_FIXED }, { "DEPTH_COMPONENT", GL_DEPTH_COMPONENT }, { "ALPHA", GL_ALPHA }, { "RGB", GL_RGB }, { "RGBA", GL_RGBA }, { "LUMINANCE", GL_LUMINANCE }, { "LUMINANCE_ALPHA", GL_LUMINANCE_ALPHA }, { "UNSIGNED_SHORT_4_4_4_4", GL_UNSIGNED_SHORT_4_4_4_4 }, { "UNSIGNED_SHORT_5_5_5_1", GL_UNSIGNED_SHORT_5_5_5_1 }, { "UNSIGNED_SHORT_5_6_5", GL_UNSIGNED_SHORT_5_6_5 }, { "FRAGMENT_SHADER", GL_FRAGMENT_SHADER }, { "VERTEX_SHADER", GL_VERTEX_SHADER }, { "MAX_VERTEX_ATTRIBS", GL_MAX_VERTEX_ATTRIBS }, { "MAX_VERTEX_UNIFORM_VECTORS", GL_MAX_VERTEX_UNIFORM_VECTORS }, { "MAX_VARYING_VECTORS", GL_MAX_VARYING_VECTORS }, { "MAX_COMBINED_TEXTURE_IMAGE_UNITS", GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS }, { "MAX_VERTEX_TEXTURE_IMAGE_UNITS", GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS }, { "MAX_TEXTURE_IMAGE_UNITS", GL_MAX_TEXTURE_IMAGE_UNITS }, { "MAX_FRAGMENT_UNIFORM_VECTORS", GL_MAX_FRAGMENT_UNIFORM_VECTORS }, { "SHADER_TYPE", GL_SHADER_TYPE }, { "DELETE_STATUS", GL_DELETE_STATUS }, { "LINK_STATUS", GL_LINK_STATUS }, { "VALIDATE_STATUS", GL_VALIDATE_STATUS }, { "ATTACHED_SHADERS", GL_ATTACHED_SHADERS }, { "ACTIVE_UNIFORMS", GL_ACTIVE_UNIFORMS }, { "ACTIVE_UNIFORM_MAX_LENGTH", GL_ACTIVE_UNIFORM_MAX_LENGTH }, { "ACTIVE_ATTRIBUTES", GL_ACTIVE_ATTRIBUTES }, { "ACTIVE_ATTRIBUTE_MAX_LENGTH", GL_ACTIVE_ATTRIBUTE_MAX_LENGTH }, { "SHADING_LANGUAGE_VERSION", GL_SHADING_LANGUAGE_VERSION }, { "CURRENT_PROGRAM", GL_CURRENT_PROGRAM }, { "NEVER", GL_NEVER }, { "LESS", GL_LESS }, { "EQUAL", GL_EQUAL }, { "LEQUAL", GL_LEQUAL }, { "GREATER", GL_GREATER }, { "NOTEQUAL", GL_NOTEQUAL }, { "GEQUAL", GL_GEQUAL }, { "ALWAYS", GL_ALWAYS }, { "KEEP", GL_KEEP }, { "REPLACE", GL_REPLACE }, { "INCR", GL_INCR }, { "DECR", GL_DECR }, { "INVERT", GL_INVERT }, { "INCR_WRAP", GL_INCR_WRAP }, { "DECR_WRAP", GL_DECR_WRAP }, { "VENDOR", GL_VENDOR }, { "RENDERER", GL_RENDERER }, { "VERSION", GL_VERSION }, { "EXTENSIONS", GL_EXTENSIONS }, { "NEAREST", GL_NEAREST }, { "LINEAR", GL_LINEAR }, { "NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST }, { "LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST }, { "NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR }, { "LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR }, { "TEXTURE_MAG_FILTER", GL_TEXTURE_MAG_FILTER }, { "TEXTURE_MIN_FILTER", GL_TEXTURE_MIN_FILTER }, { "TEXTURE_WRAP_S", GL_TEXTURE_WRAP_S }, { "TEXTURE_WRAP_T", GL_TEXTURE_WRAP_T }, { "TEXTURE", GL_TEXTURE }, { "TEXTURE_CUBE_MAP", GL_TEXTURE_CUBE_MAP }, { "TEXTURE_BINDING_CUBE_MAP", GL_TEXTURE_BINDING_CUBE_MAP }, { "TEXTURE_CUBE_MAP_POSITIVE_X", GL_TEXTURE_CUBE_MAP_POSITIVE_X }, { "TEXTURE_CUBE_MAP_NEGATIVE_X", GL_TEXTURE_CUBE_MAP_NEGATIVE_X }, { "TEXTURE_CUBE_MAP_POSITIVE_Y", GL_TEXTURE_CUBE_MAP_POSITIVE_Y }, { "TEXTURE_CUBE_MAP_NEGATIVE_Y", GL_TEXTURE_CUBE_MAP_NEGATIVE_Y }, { "TEXTURE_CUBE_MAP_POSITIVE_Z", GL_TEXTURE_CUBE_MAP_POSITIVE_Z }, { "TEXTURE_CUBE_MAP_NEGATIVE_Z", GL_TEXTURE_CUBE_MAP_NEGATIVE_Z }, { "MAX_CUBE_MAP_TEXTURE_SIZE", GL_MAX_CUBE_MAP_TEXTURE_SIZE }, { "TEXTURE0", GL_TEXTURE0 }, { "TEXTURE1", GL_TEXTURE1 }, { "TEXTURE2", GL_TEXTURE2 }, { "TEXTURE3", GL_TEXTURE3 }, { "TEXTURE4", GL_TEXTURE4 }, { "TEXTURE5", GL_TEXTURE5 }, { "TEXTURE6", GL_TEXTURE6 }, { "TEXTURE7", GL_TEXTURE7 }, { "TEXTURE8", GL_TEXTURE8 }, { "TEXTURE9", GL_TEXTURE9 }, { "TEXTURE10", GL_TEXTURE10 }, { "TEXTURE11", GL_TEXTURE11 }, { "TEXTURE12", GL_TEXTURE12 }, { "TEXTURE13", GL_TEXTURE13 }, { "TEXTURE14", GL_TEXTURE14 }, { "TEXTURE15", GL_TEXTURE15 }, { "TEXTURE16", GL_TEXTURE16 }, { "TEXTURE17", GL_TEXTURE17 }, { "TEXTURE18", GL_TEXTURE18 }, { "TEXTURE19", GL_TEXTURE19 }, { "TEXTURE20", GL_TEXTURE20 }, { "TEXTURE21", GL_TEXTURE21 }, { "TEXTURE22", GL_TEXTURE22 }, { "TEXTURE23", GL_TEXTURE23 }, { "TEXTURE24", GL_TEXTURE24 }, { "TEXTURE25", GL_TEXTURE25 }, { "TEXTURE26", GL_TEXTURE26 }, { "TEXTURE27", GL_TEXTURE27 }, { "TEXTURE28", GL_TEXTURE28 }, { "TEXTURE29", GL_TEXTURE29 }, { "TEXTURE30", GL_TEXTURE30 }, { "TEXTURE31", GL_TEXTURE31 }, { "ACTIVE_TEXTURE", GL_ACTIVE_TEXTURE }, { "REPEAT", GL_REPEAT }, { "CLAMP_TO_EDGE", GL_CLAMP_TO_EDGE }, { "MIRRORED_REPEAT", GL_MIRRORED_REPEAT }, { "FLOAT_VEC2", GL_FLOAT_VEC2 }, { "FLOAT_VEC3", GL_FLOAT_VEC3 }, { "FLOAT_VEC4", GL_FLOAT_VEC4 }, { "INT_VEC2", GL_INT_VEC2 }, { "INT_VEC3", GL_INT_VEC3 }, { "INT_VEC4", GL_INT_VEC4 }, { "BOOL", GL_BOOL }, { "BOOL_VEC2", GL_BOOL_VEC2 }, { "BOOL_VEC3", GL_BOOL_VEC3 }, { "BOOL_VEC4", GL_BOOL_VEC4 }, { "FLOAT_MAT2", GL_FLOAT_MAT2 }, { "FLOAT_MAT3", GL_FLOAT_MAT3 }, { "FLOAT_MAT4", GL_FLOAT_MAT4 }, { "SAMPLER_2D", GL_SAMPLER_2D }, { "SAMPLER_CUBE", GL_SAMPLER_CUBE }, { "VERTEX_ATTRIB_ARRAY_ENABLED", GL_VERTEX_ATTRIB_ARRAY_ENABLED }, { "VERTEX_ATTRIB_ARRAY_SIZE", GL_VERTEX_ATTRIB_ARRAY_SIZE }, { "VERTEX_ATTRIB_ARRAY_STRIDE", GL_VERTEX_ATTRIB_ARRAY_STRIDE }, { "VERTEX_ATTRIB_ARRAY_TYPE", GL_VERTEX_ATTRIB_ARRAY_TYPE }, { "VERTEX_ATTRIB_ARRAY_NORMALIZED", GL_VERTEX_ATTRIB_ARRAY_NORMALIZED }, { "VERTEX_ATTRIB_ARRAY_POINTER", GL_VERTEX_ATTRIB_ARRAY_POINTER }, { "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING", GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING }, { "IMPLEMENTATION_COLOR_READ_TYPE", GL_IMPLEMENTATION_COLOR_READ_TYPE }, { "IMPLEMENTATION_COLOR_READ_FORMAT", GL_IMPLEMENTATION_COLOR_READ_FORMAT }, { "COMPILE_STATUS", GL_COMPILE_STATUS }, { "INFO_LOG_LENGTH", GL_INFO_LOG_LENGTH }, { "SHADER_SOURCE_LENGTH", GL_SHADER_SOURCE_LENGTH }, { "SHADER_COMPILER", GL_SHADER_COMPILER }, { "SHADER_BINARY_FORMATS", GL_SHADER_BINARY_FORMATS }, { "NUM_SHADER_BINARY_FORMATS", GL_NUM_SHADER_BINARY_FORMATS }, { "LOW_FLOAT", GL_LOW_FLOAT }, { "MEDIUM_FLOAT", GL_MEDIUM_FLOAT }, { "HIGH_FLOAT", GL_HIGH_FLOAT }, { "LOW_INT", GL_LOW_INT }, { "MEDIUM_INT", GL_MEDIUM_INT }, { "HIGH_INT", GL_HIGH_INT }, { "FRAMEBUFFER", GL_FRAMEBUFFER }, { "RENDERBUFFER", GL_RENDERBUFFER }, { "RGBA4", GL_RGBA4 }, { "RGB5_A1", GL_RGB5_A1 }, { "RGB565", GL_RGB565 }, { "DEPTH_COMPONENT16", GL_DEPTH_COMPONENT16 }, { "STENCIL_INDEX8", GL_STENCIL_INDEX8 }, { "RENDERBUFFER_WIDTH", GL_RENDERBUFFER_WIDTH }, { "RENDERBUFFER_HEIGHT", GL_RENDERBUFFER_HEIGHT }, { "RENDERBUFFER_INTERNAL_FORMAT", GL_RENDERBUFFER_INTERNAL_FORMAT }, { "RENDERBUFFER_RED_SIZE", GL_RENDERBUFFER_RED_SIZE }, { "RENDERBUFFER_GREEN_SIZE", GL_RENDERBUFFER_GREEN_SIZE }, { "RENDERBUFFER_BLUE_SIZE", GL_RENDERBUFFER_BLUE_SIZE }, { "RENDERBUFFER_ALPHA_SIZE", GL_RENDERBUFFER_ALPHA_SIZE }, { "RENDERBUFFER_DEPTH_SIZE", GL_RENDERBUFFER_DEPTH_SIZE }, { "RENDERBUFFER_STENCIL_SIZE", GL_RENDERBUFFER_STENCIL_SIZE }, { "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE", GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE }, { "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME", GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME }, { "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL", GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL }, { "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE", GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE }, { "COLOR_ATTACHMENT0", GL_COLOR_ATTACHMENT0 }, { "DEPTH_ATTACHMENT", GL_DEPTH_ATTACHMENT }, { "STENCIL_ATTACHMENT", GL_STENCIL_ATTACHMENT }, { "NONE", GL_NONE }, { "FRAMEBUFFER_COMPLETE", GL_FRAMEBUFFER_COMPLETE }, { "FRAMEBUFFER_INCOMPLETE_ATTACHMENT", GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT }, { "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT }, { "FRAMEBUFFER_INCOMPLETE_DIMENSIONS", GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS }, { "FRAMEBUFFER_UNSUPPORTED", GL_FRAMEBUFFER_UNSUPPORTED }, { "FRAMEBUFFER_BINDING", GL_FRAMEBUFFER_BINDING }, { "RENDERBUFFER_BINDING", GL_RENDERBUFFER_BINDING }, { "MAX_RENDERBUFFER_SIZE", GL_MAX_RENDERBUFFER_SIZE }, { "INVALID_FRAMEBUFFER_OPERATION", GL_INVALID_FRAMEBUFFER_OPERATION }, }; } v8::Handle<v8::FunctionTemplate> CreateWebGLBindings() { v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); v8::Handle<v8::FunctionTemplate> templ = v8::FunctionTemplate::New(); v8::Handle<v8::ObjectTemplate> proto = templ->PrototypeTemplate(); InstallConstants(proto, g_constants, kConstantCount); InstallMethods(proto, g_methods, kMethodCount); return handle_scope.Close(templ); } }
46.354302
166
0.585304
slightlyoff
7ea3f9a1df3bd3da6eca305d090830fb52b18294
3,503
cc
C++
chromecast/media/cma/backend/media_pipeline_backend_wrapper.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chromecast/media/cma/backend/media_pipeline_backend_wrapper.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chromecast/media/cma/backend/media_pipeline_backend_wrapper.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/media/cma/backend/media_pipeline_backend_wrapper.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "chromecast/media/cma/backend/media_pipeline_backend_manager.h" #include "chromecast/public/cast_media_shlib.h" namespace chromecast { namespace media { using DecoderType = MediaPipelineBackendManager::DecoderType; MediaPipelineBackendWrapper::MediaPipelineBackendWrapper( const media::MediaPipelineDeviceParams& params, MediaPipelineBackendManager* backend_manager) : backend_(base::WrapUnique( media::CastMediaShlib::CreateMediaPipelineBackend(params))), backend_manager_(backend_manager), sfx_backend_(params.audio_type == media::MediaPipelineDeviceParams::kAudioStreamSoundEffects), have_audio_decoder_(false), have_video_decoder_(false), playing_(false) { DCHECK(backend_); DCHECK(backend_manager_); } MediaPipelineBackendWrapper::~MediaPipelineBackendWrapper() { if (have_audio_decoder_) backend_manager_->DecrementDecoderCount( sfx_backend_ ? DecoderType::SFX_DECODER : DecoderType::AUDIO_DECODER); if (have_video_decoder_) backend_manager_->DecrementDecoderCount(DecoderType::VIDEO_DECODER); if (playing_) { LOG(WARNING) << "Destroying media backend while still in 'playing' state"; if (have_audio_decoder_ && !sfx_backend_) { backend_manager_->UpdatePlayingAudioCount(-1); } } } void MediaPipelineBackendWrapper::LogicalPause() { SetPlaying(false); } void MediaPipelineBackendWrapper::LogicalResume() { SetPlaying(true); } MediaPipelineBackend::AudioDecoder* MediaPipelineBackendWrapper::CreateAudioDecoder() { DCHECK(!have_audio_decoder_); if (!backend_manager_->IncrementDecoderCount( sfx_backend_ ? DecoderType::SFX_DECODER : DecoderType::AUDIO_DECODER)) return nullptr; have_audio_decoder_ = true; return backend_->CreateAudioDecoder(); } MediaPipelineBackend::VideoDecoder* MediaPipelineBackendWrapper::CreateVideoDecoder() { DCHECK(!have_video_decoder_); if (!backend_manager_->IncrementDecoderCount(DecoderType::VIDEO_DECODER)) return nullptr; have_video_decoder_ = true; return backend_->CreateVideoDecoder(); } bool MediaPipelineBackendWrapper::Initialize() { return backend_->Initialize(); } bool MediaPipelineBackendWrapper::Start(int64_t start_pts) { if (!backend_->Start(start_pts)) { return false; } SetPlaying(true); return true; } void MediaPipelineBackendWrapper::Stop() { backend_->Stop(); SetPlaying(false); } bool MediaPipelineBackendWrapper::Pause() { if (!backend_->Pause()) { return false; } SetPlaying(false); return true; } bool MediaPipelineBackendWrapper::Resume() { if (!backend_->Resume()) { return false; } SetPlaying(true); return true; } int64_t MediaPipelineBackendWrapper::GetCurrentPts() { return backend_->GetCurrentPts(); } bool MediaPipelineBackendWrapper::SetPlaybackRate(float rate) { return backend_->SetPlaybackRate(rate); } void MediaPipelineBackendWrapper::SetPlaying(bool playing) { if (playing == playing_) { return; } playing_ = playing; if (have_audio_decoder_ && !sfx_backend_) { backend_manager_->UpdatePlayingAudioCount(playing_ ? 1 : -1); } } } // namespace media } // namespace chromecast
26.740458
80
0.750785
metux
7ea58079b6255985d1f6beb4f64afc078e105862
1,481
cpp
C++
Curs/En/ProjectCourse5/ProjectCourse5/Source.cpp
catalinboja/cpp_examples_2017
8671fa984e3ca3e9f0d74a7e6869f6730dcf4056
[ "Apache-2.0" ]
null
null
null
Curs/En/ProjectCourse5/ProjectCourse5/Source.cpp
catalinboja/cpp_examples_2017
8671fa984e3ca3e9f0d74a7e6869f6730dcf4056
[ "Apache-2.0" ]
null
null
null
Curs/En/ProjectCourse5/ProjectCourse5/Source.cpp
catalinboja/cpp_examples_2017
8671fa984e3ca3e9f0d74a7e6869f6730dcf4056
[ "Apache-2.0" ]
4
2017-11-16T17:18:12.000Z
2018-07-14T05:43:34.000Z
#include<iostream> using namespace std; class Student { private: char* name; int age; const int id; const int personalID; static int noStudents; Student():id(1),personalID(0) { Student::noStudents += 1; this->age = 18; this->name = new char[strlen("John")+1]; strcpy(this->name, "John"); } public: Student(char*name, int age, int Id):id(Id),personalID(0) { Student::noStudents += 1; this->age = age; this->name = new char[strlen(name) + 1]; strcpy(this->name, name); } Student(char*name, int age) :id(Student::noStudents), personalID(0) { Student::noStudents += 1; this->age = age; this->name = new char[strlen(name) + 1]; strcpy(this->name, name); } void display() { cout << endl << "Name " << this->name << " age " << this->age<<" id "<<this->id; } //copy constructor Student(Student& stud):id(stud.id),personalID(0) { // } }; int Student::noStudents = 0; void main() { //Student student; Student *pStudent; //pStudent = &student; //pStudent = new Student(); //pStudent = new Student[1]; //student.id = 100; //Student list[10]; Student student2("Alice", 19, 1); Student *pStudent2 = new Student("Bob",19,2); Student *pStudent3 = new Student("Bob", 19); Student *pStudent4 = new Student("Bob", 19); Student *pStudent5 = new Student("John", 19); student2.display(); pStudent5->display(); Student student3 = student2; Student *pStudent6 = pStudent5; student3.display(); pStudent6->display(); }
18.5125
70
0.635381
catalinboja
7ea632659d78f66c799da5c115d5812060e893c0
2,942
hpp
C++
src/siili/kz/data_object_vector_list_impl.hpp
siilisolutions-pl/siili-kzutils
567e1f17160899911939d2402ee60550d6309e90
[ "Apache-2.0" ]
1
2019-10-07T15:58:29.000Z
2019-10-07T15:58:29.000Z
src/siili/kz/data_object_vector_list_impl.hpp
siilisolutions-pl/siili-kzutils
567e1f17160899911939d2402ee60550d6309e90
[ "Apache-2.0" ]
null
null
null
src/siili/kz/data_object_vector_list_impl.hpp
siilisolutions-pl/siili-kzutils
567e1f17160899911939d2402ee60550d6309e90
[ "Apache-2.0" ]
1
2019-10-07T16:38:37.000Z
2019-10-07T16:38:37.000Z
#ifndef SIILI__KZ__DATA_OBJECT_VECTOR_LIST_IMPL_HPP #define SIILI__KZ__DATA_OBJECT_VECTOR_LIST_IMPL_HPP #include <algorithm> #include <kanzi/core.ui/data/data_object.hpp> #include <kanzi/core.ui/data/data_object_list.hpp> #include <memory> #include <siili/kz/data_object_dynamic_list.hpp> #include <utility> #include <vector> namespace siili { namespace kz { namespace data_object_vector_list_impl { class DataObjectVectorList : public DataObjectDynamicList { public: DataObjectVectorList( kanzi::Domain *domain, kanzi::string_view name, kanzi::DataObjectSharedPtr itemTemplate); std::size_t itemCount() override; kanzi::DataObjectSharedPtr acquireItem(std::size_t index) override; void releaseItem(std::size_t index) override; kanzi::DataObjectSharedPtr getItemTemplate() override; void insertItems(std::size_t pos, const std::vector<kanzi::DataObjectSharedPtr> &items) override; void eraseItems(std::size_t beginPos, std::size_t endPos) override; private: std::vector<kanzi::DataObjectSharedPtr> mListItems; kanzi::DataObjectSharedPtr mItemTemplate; }; inline DataObjectVectorList::DataObjectVectorList( kanzi::Domain *domain, kanzi::string_view name, kanzi::DataObjectSharedPtr itemTemplate) : DataObjectDynamicList(domain, name), mListItems(), mItemTemplate(std::move(itemTemplate)) { } inline std::size_t DataObjectVectorList::itemCount() { return mListItems.size(); } inline kanzi::DataObjectSharedPtr DataObjectVectorList::acquireItem(std::size_t index) { return index < mListItems.size() ? mListItems[index] : std::make_shared<kanzi::DataObject>(getDomain(), ""); } inline void DataObjectVectorList::releaseItem(std::size_t) { } inline kanzi::DataObjectSharedPtr DataObjectVectorList::getItemTemplate() { return mItemTemplate ? mItemTemplate : acquireItem(0); } inline void DataObjectVectorList::insertItems(std::size_t pos, const std::vector<kanzi::DataObjectSharedPtr> &items) { const auto effPos = std::min(pos, mListItems.size()); if (!items.empty()) { mListItems.insert(mListItems.begin() + effPos, items.begin(), items.end()); notifyModified(); } } inline void DataObjectVectorList::eraseItems(std::size_t beginPos, std::size_t endPos) { if (endPos < beginPos) { return; } const auto effBeginPos = std::min(beginPos, mListItems.size()); const auto effEndPos = std::min(endPos, mListItems.size()); if (effBeginPos != effEndPos) { mListItems.erase(mListItems.begin() + effBeginPos, mListItems.begin() + effEndPos); notifyModified(); } } } inline std::shared_ptr<DataObjectDynamicList> makeDataObjectVectorList( kanzi::Domain *domain, kanzi::string_view name, kanzi::DataObjectSharedPtr itemTemplate) { using namespace data_object_vector_list_impl; return std::make_shared<DataObjectVectorList>(domain, name, itemTemplate); } } } #endif
25.807018
116
0.743372
siilisolutions-pl
7ea7b75c29ff9d489fae9263e40124805ca0fd04
15,112
cxx
C++
main/svx/source/dialog/dialcontrol.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/svx/source/dialog/dialcontrol.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/svx/source/dialog/dialcontrol.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include "svx/dialcontrol.hxx" #include "bmpmask.hrc" #include <svx/dialmgr.hxx> #include <tools/rcid.h> #include <math.h> #include <vcl/virdev.hxx> #include <vcl/svapp.hxx> #include <vcl/bitmap.hxx> #include <vcl/field.hxx> #include <svtools/colorcfg.hxx> namespace svx { // ============================================================================ const long DIAL_OUTER_WIDTH = 8; // ============================================================================ // ---------------------------------------------------------------------------- DialControlBmp::DialControlBmp( Window& rParent ) : VirtualDevice( rParent, 0, 0 ), mbEnabled( true ), mrParent( rParent ) { EnableRTL( sal_False ); } void DialControlBmp::InitBitmap( const Size& rSize, const Font& rFont ) { Init( rSize ); SetFont( rFont ); } void DialControlBmp::CopyBackground( const DialControlBmp& rSrc ) { Init( rSrc.maRect.GetSize() ); mbEnabled = rSrc.mbEnabled; Point aPos; DrawBitmapEx( aPos, rSrc.GetBitmapEx( aPos, maRect.GetSize() ) ); } void DialControlBmp::DrawBackground( const Size& rSize, bool bEnabled ) { Init( rSize ); mbEnabled = bEnabled; DrawBackground(); } void DialControlBmp::DrawElements( const String& rText, sal_Int32 nAngle ) { // *** rotated text *** Font aFont( GetFont() ); aFont.SetColor( GetTextColor() ); aFont.SetOrientation( static_cast< short >( (nAngle + 5) / 10 ) ); // Font uses 1/10 degrees aFont.SetWeight( WEIGHT_BOLD ); SetFont( aFont ); double fAngle = nAngle * F_PI180 / 100.0; double fSin = sin( fAngle ); double fCos = cos( fAngle ); double fWidth = GetTextWidth( rText ) / 2.0; double fHeight = GetTextHeight() / 2.0; long nX = static_cast< long >( mnCenterX - fWidth * fCos - fHeight * fSin ); long nY = static_cast< long >( mnCenterY + fWidth * fSin - fHeight * fCos ); Rectangle aRect( nX, nY, 2 * mnCenterX - nX, 2 * mnCenterY - nY ); DrawText( aRect, rText, mbEnabled ? 0 : TEXT_DRAW_DISABLE ); // *** drag button *** bool bMain = (nAngle % 4500) != 0; SetLineColor( GetButtonLineColor() ); SetFillColor( GetButtonFillColor( bMain ) ); nX = mnCenterX - static_cast< long >( (DIAL_OUTER_WIDTH / 2 - mnCenterX) * fCos ); nY = mnCenterY - static_cast< long >( (mnCenterY - DIAL_OUTER_WIDTH / 2) * fSin ); long nSize = bMain ? (DIAL_OUTER_WIDTH / 4) : (DIAL_OUTER_WIDTH / 2 - 1); DrawEllipse( Rectangle( nX - nSize, nY - nSize, nX + nSize, nY + nSize ) ); } // private -------------------------------------------------------------------- const Color& DialControlBmp::GetBackgroundColor() const { return GetSettings().GetStyleSettings().GetDialogColor(); } const Color& DialControlBmp::GetTextColor() const { return GetSettings().GetStyleSettings().GetLabelTextColor(); } const Color& DialControlBmp::GetScaleLineColor() const { const StyleSettings& rSett = GetSettings().GetStyleSettings(); return mbEnabled ? rSett.GetButtonTextColor() : rSett.GetDisableColor(); } const Color& DialControlBmp::GetButtonLineColor() const { const StyleSettings& rSett = GetSettings().GetStyleSettings(); return mbEnabled ? rSett.GetButtonTextColor() : rSett.GetDisableColor(); } const Color& DialControlBmp::GetButtonFillColor( bool bMain ) const { const StyleSettings& rSett = GetSettings().GetStyleSettings(); return mbEnabled ? (bMain ? rSett.GetMenuColor() : rSett.GetHighlightColor()) : rSett.GetDisableColor(); } void DialControlBmp::Init( const Size& rSize ) { SetSettings( mrParent.GetSettings() ); maRect.SetPos( Point( 0, 0 ) ); maRect.SetSize( rSize ); mnCenterX = rSize.Width() / 2; mnCenterY = rSize.Height() / 2; SetOutputSize( rSize ); SetBackground(); } void DialControlBmp::DrawBackground() { // *** background with 3D effect *** SetLineColor(); SetFillColor(); Erase(); EnableRTL( sal_True ); // #107807# draw 3D effect in correct direction sal_uInt8 nDiff = mbEnabled ? 0x18 : 0x10; Color aColor; aColor = GetBackgroundColor(); SetFillColor( aColor ); DrawPie( maRect, maRect.TopRight(), maRect.TopCenter() ); DrawPie( maRect, maRect.BottomLeft(), maRect.BottomCenter() ); aColor.DecreaseLuminance( nDiff ); SetFillColor( aColor ); DrawPie( maRect, maRect.BottomCenter(), maRect.TopRight() ); aColor.DecreaseLuminance( nDiff ); SetFillColor( aColor ); DrawPie( maRect, maRect.BottomRight(), maRect.RightCenter() ); aColor = GetBackgroundColor(); aColor.IncreaseLuminance( nDiff ); SetFillColor( aColor ); DrawPie( maRect, maRect.TopCenter(), maRect.BottomLeft() ); aColor.IncreaseLuminance( nDiff ); SetFillColor( aColor ); DrawPie( maRect, maRect.TopLeft(), maRect.LeftCenter() ); EnableRTL( sal_False ); // *** calibration *** Point aStartPos( mnCenterX, mnCenterY ); Color aFullColor( GetScaleLineColor() ); Color aLightColor( GetBackgroundColor() ); aLightColor.Merge( aFullColor, 128 ); for( int nAngle = 0; nAngle < 360; nAngle += 15 ) { SetLineColor( (nAngle % 45) ? aLightColor : aFullColor ); double fAngle = nAngle * F_PI180; long nX = static_cast< long >( -mnCenterX * cos( fAngle ) ); long nY = static_cast< long >( mnCenterY * sin( fAngle ) ); DrawLine( aStartPos, Point( mnCenterX - nX, mnCenterY - nY ) ); } // *** clear inner area *** SetLineColor(); SetFillColor( GetBackgroundColor() ); DrawEllipse( Rectangle( maRect.Left() + DIAL_OUTER_WIDTH, maRect.Top() + DIAL_OUTER_WIDTH, maRect.Right() - DIAL_OUTER_WIDTH, maRect.Bottom() - DIAL_OUTER_WIDTH ) ); } // ---------------------------------------------------------------------------- DialControl::DialControl_Impl::DialControl_Impl ( Window& rParent ) : mpBmpEnabled(new DialControlBmp(rParent)), mpBmpDisabled(new DialControlBmp(rParent)), mpBmpBuffered(new DialControlBmp(rParent)), mpLinkField( 0 ), mnAngle( 0 ), mbNoRot( false ) { } void DialControl::DialControl_Impl::Init( const Size& rWinSize, const Font& rWinFont ) { // "(x - 1) | 1" creates odd value <= x, to have a well-defined center pixel position maWinSize = Size( (rWinSize.Width() - 1) | 1, (rWinSize.Height() - 1) | 1 ); maWinFont = rWinFont; mnCenterX = maWinSize.Width() / 2; mnCenterY = maWinSize.Height() / 2; maWinFont.SetTransparent( sal_True ); mpBmpEnabled->DrawBackground( maWinSize, true ); mpBmpDisabled->DrawBackground( maWinSize, false ); mpBmpBuffered->InitBitmap( maWinSize, maWinFont ); } // ============================================================================ DialControl::DialControl( Window* pParent, const Size& rSize, const Font& rFont, WinBits nWinStyle ) : Control( pParent, nWinStyle ), mpImpl( new DialControl_Impl( *this ) ) { Init( rSize, rFont ); } DialControl::DialControl( Window* pParent, const Size& rSize, WinBits nWinStyle ) : Control( pParent, nWinStyle ), mpImpl( new DialControl_Impl( *this ) ) { if( pParent ) Init( rSize, pParent->GetFont() ); else Init( rSize ); } DialControl::DialControl( Window* pParent, const ResId& rResId ) : Control( pParent, rResId ), mpImpl( new DialControl_Impl( *this ) ) { Init( GetOutputSizePixel() ); } DialControl::~DialControl() { } void DialControl::Paint( const Rectangle& ) { Point aPos; DrawBitmapEx( aPos, mpImpl->mpBmpBuffered->GetBitmapEx( aPos, mpImpl->maWinSize ) ); } void DialControl::StateChanged( StateChangedType nStateChange ) { if( nStateChange == STATE_CHANGE_ENABLE ) InvalidateControl(); // update the linked edit field if( mpImpl->mpLinkField ) { NumericField& rField = *mpImpl->mpLinkField; switch( nStateChange ) { case STATE_CHANGE_VISIBLE: rField.Show( IsVisible() ); break; case STATE_CHANGE_ENABLE: rField.Enable( IsEnabled() ); break; } } Control::StateChanged( nStateChange ); } void DialControl::DataChanged( const DataChangedEvent& rDCEvt ) { if( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) ) { Init( mpImpl->maWinSize, mpImpl->maWinFont ); InvalidateControl(); } Control::DataChanged( rDCEvt ); } void DialControl::MouseButtonDown( const MouseEvent& rMEvt ) { if( rMEvt.IsLeft() ) { GrabFocus(); CaptureMouse(); mpImpl->mnOldAngle = mpImpl->mnAngle; HandleMouseEvent( rMEvt.GetPosPixel(), true ); } Control::MouseButtonDown( rMEvt ); } void DialControl::MouseMove( const MouseEvent& rMEvt ) { if( IsMouseCaptured() && rMEvt.IsLeft() ) HandleMouseEvent( rMEvt.GetPosPixel(), false ); Control::MouseMove(rMEvt ); } void DialControl::MouseButtonUp( const MouseEvent& rMEvt ) { if( IsMouseCaptured() ) { ReleaseMouse(); if( mpImpl->mpLinkField ) mpImpl->mpLinkField->GrabFocus(); } Control::MouseButtonUp( rMEvt ); } void DialControl::KeyInput( const KeyEvent& rKEvt ) { const KeyCode& rKCode = rKEvt.GetKeyCode(); if( !rKCode.GetModifier() && (rKCode.GetCode() == KEY_ESCAPE) ) HandleEscapeEvent(); else Control::KeyInput( rKEvt ); } void DialControl::LoseFocus() { // release captured mouse HandleEscapeEvent(); Control::LoseFocus(); } bool DialControl::HasRotation() const { return !mpImpl->mbNoRot; } void DialControl::SetNoRotation() { if( !mpImpl->mbNoRot ) { mpImpl->mbNoRot = true; InvalidateControl(); if( mpImpl->mpLinkField ) mpImpl->mpLinkField->SetText( String() ); } } sal_Int32 DialControl::GetRotation() const { return mpImpl->mnAngle; } void DialControl::SetRotation( sal_Int32 nAngle ) { SetRotation( nAngle, false ); } void DialControl::SetLinkedField( NumericField* pField ) { // remove modify handler from old linked field ImplSetFieldLink( Link() ); // remember the new linked field mpImpl->mpLinkField = pField; // set modify handler at new linked field ImplSetFieldLink( LINK( this, DialControl, LinkedFieldModifyHdl ) ); } NumericField* DialControl::GetLinkedField() const { return mpImpl->mpLinkField; } void DialControl::SetModifyHdl( const Link& rLink ) { mpImpl->maModifyHdl = rLink; } const Link& DialControl::GetModifyHdl() const { return mpImpl->maModifyHdl; } // private -------------------------------------------------------------------- void DialControl::Init( const Size& rWinSize, const Font& rWinFont ) { mpImpl->Init( rWinSize, rWinFont ); EnableRTL( sal_False ); // #107807# don't mirror mouse handling SetOutputSizePixel( mpImpl->maWinSize ); SetBackground(); } void DialControl::Init( const Size& rWinSize ) { Font aFont( OutputDevice::GetDefaultFont( DEFAULTFONT_UI_SANS, Application::GetSettings().GetUILanguage(), DEFAULTFONT_FLAGS_ONLYONE ) ); Init( rWinSize, aFont ); } void DialControl::InvalidateControl() { mpImpl->mpBmpBuffered->CopyBackground( IsEnabled() ? *mpImpl->mpBmpEnabled : *mpImpl->mpBmpDisabled ); if( !mpImpl->mbNoRot ) mpImpl->mpBmpBuffered->DrawElements( GetText(), mpImpl->mnAngle ); Invalidate(); } void DialControl::SetRotation( sal_Int32 nAngle, bool bBroadcast ) { bool bOldSel = mpImpl->mbNoRot; mpImpl->mbNoRot = false; while( nAngle < 0 ) nAngle += 36000; nAngle = (((nAngle + 50) / 100) * 100) % 36000; if( !bOldSel || (mpImpl->mnAngle != nAngle) ) { mpImpl->mnAngle = nAngle; InvalidateControl(); if( mpImpl->mpLinkField ) mpImpl->mpLinkField->SetValue( static_cast< long >( GetRotation() / 100 ) ); if( bBroadcast ) mpImpl->maModifyHdl.Call( this ); } } void DialControl::ImplSetFieldLink( const Link& rLink ) { if( mpImpl->mpLinkField ) { NumericField& rField = *mpImpl->mpLinkField; rField.SetModifyHdl( rLink ); rField.SetUpHdl( rLink ); rField.SetDownHdl( rLink ); rField.SetFirstHdl( rLink ); rField.SetLastHdl( rLink ); rField.SetLoseFocusHdl( rLink ); } } void DialControl::HandleMouseEvent( const Point& rPos, bool bInitial ) { long nX = rPos.X() - mpImpl->mnCenterX; long nY = mpImpl->mnCenterY - rPos.Y(); double fH = sqrt( static_cast< double >( nX ) * nX + static_cast< double >( nY ) * nY ); if( fH != 0.0 ) { double fAngle = acos( nX / fH ); sal_Int32 nAngle = static_cast< sal_Int32 >( fAngle / F_PI180 * 100.0 ); if( nY < 0 ) nAngle = 36000 - nAngle; if( bInitial ) // round to entire 15 degrees nAngle = ((nAngle + 750) / 1500) * 1500; SetRotation( nAngle, true ); } } void DialControl::HandleEscapeEvent() { if( IsMouseCaptured() ) { ReleaseMouse(); SetRotation( mpImpl->mnOldAngle, true ); if( mpImpl->mpLinkField ) mpImpl->mpLinkField->GrabFocus(); } } IMPL_LINK( DialControl, LinkedFieldModifyHdl, NumericField*, pField ) { if( pField ) SetRotation( static_cast< sal_Int32 >( pField->GetValue() * 100 ), false ); return 0; } // ============================================================================ DialControlWrapper::DialControlWrapper( DialControl& rDial ) : SingleControlWrapperType( rDial ) { } bool DialControlWrapper::IsControlDontKnow() const { return !GetControl().HasRotation(); } void DialControlWrapper::SetControlDontKnow( bool bSet ) { if( bSet ) GetControl().SetNoRotation(); } sal_Int32 DialControlWrapper::GetControlValue() const { return GetControl().GetRotation(); } void DialControlWrapper::SetControlValue( sal_Int32 nValue ) { GetControl().SetRotation( nValue ); } // ============================================================================ } // namespace svx
28.621212
108
0.625199
Grosskopf
7ea8ae9aaa21af63f1bcee21ef1be9fb2b852ebc
632
cpp
C++
src/Queue.cpp
dylsonowski/Producer_Consumers_Scheme
b784dc1f497f41c13d7ddee51c73e39a6daeb923
[ "Apache-2.0" ]
null
null
null
src/Queue.cpp
dylsonowski/Producer_Consumers_Scheme
b784dc1f497f41c13d7ddee51c73e39a6daeb923
[ "Apache-2.0" ]
null
null
null
src/Queue.cpp
dylsonowski/Producer_Consumers_Scheme
b784dc1f497f41c13d7ddee51c73e39a6daeb923
[ "Apache-2.0" ]
null
null
null
#include "Queue.h" std::mutex Queue::s_queueBlock; bool Queue::s_creationProcessFinished = false; void Queue::ChangeQueueStatus(bool canRead, bool canWrite) { _canRead = canRead; _canWrite = canWrite; } bool Queue::AddElement(std::array<int, 100000> newElement) { if (_canWrite) { s_queueBlock.lock(); _taskQueue.emplace_back(newElement); s_queueBlock.unlock(); return true; } else return false; } std::array<int, 100000> Queue::PopFirstElement() { if (_canRead) { s_queueBlock.lock(); std::array<int, 100000> temp = _taskQueue.front(); _taskQueue.pop_front(); s_queueBlock.unlock(); return temp; } }
20.387097
60
0.71519
dylsonowski
7ead7044df37b77e631c423666929b1980841d4c
12,726
cpp
C++
src/message_manager.cpp
klei1984/max
dc0f9108bbcfd4cb73ea101883d551c612097469
[ "MIT" ]
19
2020-02-06T17:41:39.000Z
2022-03-31T07:38:15.000Z
src/message_manager.cpp
klei1984/max
dc0f9108bbcfd4cb73ea101883d551c612097469
[ "MIT" ]
9
2020-02-14T15:46:46.000Z
2021-12-22T16:35:53.000Z
src/message_manager.cpp
klei1984/max
dc0f9108bbcfd4cb73ea101883d551c612097469
[ "MIT" ]
null
null
null
/* Copyright (c) 2021 M.A.X. Port Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "message_manager.hpp" #include <algorithm> #include "dialogmenu.hpp" #include "gui.hpp" extern "C" { #include "gnw.h" } /// \todo Fix gwin includes extern "C" { WindowInfo* gwin_get_window(unsigned char id); } static_assert(sizeof(Point) == 4, "It is expected that Point is exactly 2+2 bytes long."); static_assert(sizeof(bool) == 1, "It is expected that bool is exactly 1 byte long."); #define MESSAGE_MANAGER_TEAM_COUNT 4 #define MESSAGE_MANAGER_MAX_COUNT 50 #define MESSAGE_MANAGER_MESSAGE_BUFFER_SIZE 800 #define MESSAGE_MANAGER_TEXT_BUFFER_SIZE 300 char MessageManager_MessageBuffer[MESSAGE_MANAGER_MESSAGE_BUFFER_SIZE]; char MessageManager_TextBuffer[MESSAGE_MANAGER_TEXT_BUFFER_SIZE]; short MessageManager_Buffer1_Length; short MessageManager_MessageBox_Width; short MessageManager_MessageBox_Height; char* MessageManager_MessageBox_BgColor; bool MessageManager_MessageBox_IsActive; /// \todo Implement correct LUT char** MessageManager_MessageBox_BgColorArray[] = {0, 0, 0}; SmartList<MessageLogEntry> MessageManager_TeamMessageLog[MESSAGE_MANAGER_TEAM_COUNT]; void MessageManager_WrapText(char* text, short width) { int position = 0; short row_width = 0; char* buffer = MessageManager_MessageBuffer; do { if (text[position] == '\n') { MessageManager_MessageBox_Width = std::max(row_width, MessageManager_MessageBox_Width); MessageManager_MessageBox_Height += 10; MessageManager_MessageBuffer[MessageManager_Buffer1_Length] = ' '; ++MessageManager_Buffer1_Length; MessageManager_MessageBuffer[MessageManager_Buffer1_Length] = '\0'; ++MessageManager_Buffer1_Length; row_width = 0; buffer = &MessageManager_MessageBuffer[MessageManager_Buffer1_Length]; } else { short char_width = text_char_width(text[position]); if ((row_width + char_width) > width) { char* line_buffer = &MessageManager_MessageBuffer[MessageManager_Buffer1_Length]; *line_buffer = '\0'; --line_buffer; while (*line_buffer != ' ') { --line_buffer; } *line_buffer = '\0'; row_width = text_width(buffer); MessageManager_MessageBox_Width = std::max(row_width, MessageManager_MessageBox_Width); buffer = line_buffer + 1; row_width = text_width(buffer); MessageManager_MessageBox_Height += 10; } row_width += char_width; SDL_assert(MessageManager_Buffer1_Length < sizeof(MessageManager_MessageBuffer)); MessageManager_MessageBuffer[MessageManager_Buffer1_Length] = text[position]; ++MessageManager_Buffer1_Length; } } while (text[position++] != '\0'); MessageManager_MessageBox_Width = std::max(row_width, MessageManager_MessageBox_Width); MessageManager_MessageBox_Height += 10; } void MessageManager_DrawMessageBoxText(unsigned char* buffer, int width, int left_margin, int top_margin, char* text, int color, bool monospace) { int flags; int offset; offset = 0; text_font(5); top_margin *= width; if (monospace) { flags = 0x40000; } else { flags = 0; } color += flags + 0x10000; do { text_to_buf(&buffer[left_margin + top_margin], &text[offset], width, width, color); top_margin += 10 * width; offset += strlen(&text[offset]) + 1; } while (text[offset] != '\0'); } void MessageManager_AddMessage(char* text, ResourceID id) { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].PushBack( *dynamic_cast<MessageLogEntry*>(new (std::nothrow) MessageLogEntry(text, id))); if (MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].GetCount() > MESSAGE_MANAGER_MAX_COUNT) { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Remove( *MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Begin()); } } void MessageManager_DrawMessage(char* text, char type, UnitInfo* unit, Point point) { if (text[0] != '\0') { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].PushBack( *dynamic_cast<MessageLogEntry*>(new (std::nothrow) MessageLogEntry(text, unit, point))); if (MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].GetCount() > MESSAGE_MANAGER_MAX_COUNT) { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Remove( *MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Begin()); } MessageManager_DrawMessage(text, type, 0); } } void MessageManager_DrawMessage(char* text, char type, int mode, bool flag1, bool save_to_log) { if (*text != '\0') { if (mode) { DialogMenu dialog(text, flag1); dialog.Run(); } else { WindowInfo* window_2; WindowInfo* window_38; int width; int offset_x; int offset_y; Rect bounds; if (MessageManager_MessageBox_IsActive) { MessageManager_ClearMessageBox(); } if (save_to_log) { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].PushBack( *dynamic_cast<MessageLogEntry*>(new (std::nothrow) MessageLogEntry(text, I_CMPLX))); if (MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].GetCount() > MESSAGE_MANAGER_MAX_COUNT) { MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Remove( *MessageManager_TeamMessageLog[GUI_PlayerTeamIndex].Begin()); } } text_font(5); window_38 = gwin_get_window(38); width = window_38->window.lrx - window_38->window.ulx; MessageManager_MessageBox_Width = 0; MessageManager_Buffer1_Length = 0; MessageManager_MessageBox_Height = 20; MessageManager_WrapText(text, width - 20); MessageManager_MessageBuffer[MessageManager_Buffer1_Length] = '\0'; MessageManager_MessageBox_Width += 20; offset_x = 0; offset_y = 10; window_2 = gwin_get_window(2); window_2->window.ulx = window_38->window.ulx + offset_x; window_2->window.uly = window_38->window.uly + offset_y; window_2->window.lrx = window_2->window.ulx + MessageManager_MessageBox_Width; window_2->window.lry = window_2->window.uly + MessageManager_MessageBox_Height; window_2->buffer = &window_38->buffer[offset_x + 640 * offset_y]; MessageManager_MessageBox_BgColor = *MessageManager_MessageBox_BgColorArray[type]; MessageManager_MessageBox_IsActive = true; /// \todo Implement functions // sub_9A9FD(&bounds); // drawmap_add_dirty_zone(&bounds); } } } void MessageManager_DrawMessageBox() { WindowInfo* window; int height; int fullw; int row; window = gwin_get_window(2); for (height = MessageManager_MessageBox_Height, fullw = 0; height > 0; --height, fullw += 640) { for (row = 0; row < MessageManager_MessageBox_Width; ++row) { window->buffer[row + fullw] = MessageManager_MessageBox_BgColor[window->buffer[row + fullw]]; } } MessageManager_DrawMessageBoxText(window->buffer, 640, 10, 10, MessageManager_MessageBuffer, 0xFF, false); } void MessageManager_ClearMessageBox() { WindowInfo* window; Rect bounds; /// \todo Implement functions // sub_9A9FD(&bounds); // drawmap_add_dirty_zone(&bounds); window = gwin_get_window(2); window->window.ulx = -1; window->window.uly = -1; window->window.lrx = -1; window->window.lry = -1; MessageManager_MessageBox_IsActive = false; } void MessageManager_DrawTextMessage(WindowInfo* window, unsigned char* buffer, int width, int left_margin, int top_margin, char* text, int color, bool screen_refresh) { int text_position = 0; int buffer_position = 0; do { if (text[text_position] == '\n') { MessageManager_TextBuffer[buffer_position] = ' '; ++buffer_position; MessageManager_TextBuffer[buffer_position] = '\0'; ++buffer_position; } else { MessageManager_TextBuffer[buffer_position] = text[text_position]; ++buffer_position; } } while (text[text_position++] != '\0'); MessageManager_TextBuffer[buffer_position] = '\0'; MessageManager_DrawMessageBoxText(buffer, width, left_margin, top_margin, MessageManager_TextBuffer, color, false); if (screen_refresh) { win_draw_rect(window->id, &window->window); } } void MessageManager_LoadMessageLogs(SmartFileReader& file) { for (int i = 0; i < MESSAGE_MANAGER_TEAM_COUNT; + i) { MessageManager_TeamMessageLog[i].Clear(); for (int count = file.ReadObjectCount(); count > 0; --count) { MessageManager_TeamMessageLog[i].PushBack( *dynamic_cast<MessageLogEntry*>(new (std::nothrow) MessageLogEntry(file))); } } } void MessageManager_SaveMessageLogs(SmartFileWriter& file) { for (int i = 0; i < MESSAGE_MANAGER_TEAM_COUNT; + i) { file.WriteObjectCount(MessageManager_TeamMessageLog[i].GetCount()); for (SmartList<MessageLogEntry>::Iterator it = MessageManager_TeamMessageLog[i].Begin(); it != MessageManager_TeamMessageLog[i].End(); ++it) { (*it).FileSave(file); } } } void MessageManager_ClearMessageLogs() { for (int i = 0; i < MESSAGE_MANAGER_TEAM_COUNT; + i) { MessageManager_TeamMessageLog[i].Clear(); } } MessageLogEntry::MessageLogEntry(SmartFileReader& file) { unsigned short length; file.Read(length); text = new (std::nothrow) char[length]; file.Read(text, length); unit = dynamic_cast<UnitInfo*>(file.ReadObject()); file.Read(point); file.Read(field_20); file.Read(id); } MessageLogEntry::MessageLogEntry(char* text, ResourceID id) : id(id), text(strdup(text)), field_20(false) {} MessageLogEntry::MessageLogEntry(char* text, UnitInfo* unit, Point point) : text(strdup(text)), unit(unit), point(point), field_20(true), id(INVALID_ID) {} MessageLogEntry::~MessageLogEntry() { delete text; } void MessageLogEntry::FileSave(SmartFileWriter& file) { unsigned short length = strlen(text); file.Write(length); file.Write(text, length); file.WriteObject(&*unit); file.Write(point); file.Write(field_20); file.Write(id); } char* MessageLogEntry::GetCstr() const { return text; } void MessageLogEntry::MessageLogEntry_sub_B780B() { MessageManager_DrawMessage(text, 0, 0); if (field_20) { /// \todo Implement missing stuff if (unit != nullptr && unit->hits && unit->IsVisibleToTeam(GUI_PlayerTeamIndex)) { // sub_9F637(*unit); } else { // sub_A1620(1, point.x, point, y); } } }
35.747191
120
0.63995
klei1984
7ead720914b8f04b9d2f83f5db5bfd9789445a62
460
cpp
C++
Me.cpp
adityas129/ECE-150
0db483690ad2ce8fe1d5df4994c55bddc7a32569
[ "MIT" ]
null
null
null
Me.cpp
adityas129/ECE-150
0db483690ad2ce8fe1d5df4994c55bddc7a32569
[ "MIT" ]
null
null
null
Me.cpp
adityas129/ECE-150
0db483690ad2ce8fe1d5df4994c55bddc7a32569
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ cout << "My name is Aditya Sharma." << endl; cout << "My UserID is a273shar." << endl; cout << "I am in Electrical Engineering" << endl; cout << "I like programming because it is a very intellectually stimulating process. When you are solving a question, its like a big puzzle that has a bunch of pieces and the pieces need to match just perfectly for you to get the result." << endl; return 0; }
32.857143
248
0.708696
adityas129
7eae8153038ba986de7660142658879d2ae4ab80
2,676
cpp
C++
4/src/InterfaceFileSystem.cpp
AlinaNenasheva/operating-systems
9f04381945aa7870dff9616b45c6d07e96701bd7
[ "MIT" ]
null
null
null
4/src/InterfaceFileSystem.cpp
AlinaNenasheva/operating-systems
9f04381945aa7870dff9616b45c6d07e96701bd7
[ "MIT" ]
null
null
null
4/src/InterfaceFileSystem.cpp
AlinaNenasheva/operating-systems
9f04381945aa7870dff9616b45c6d07e96701bd7
[ "MIT" ]
null
null
null
#pragma once #include <map> #include "FileExistException.cpp" #include "FileNotFoundException.cpp" #include "OutOfMemoryException.cpp" #include "CustomFile.cpp" #define FILE_NOT_FOUND 0 #define DEFAULT_TOTAL_MEMORY 1024 using namespace std; class InterfaceFileSystem { private: map<string, CustomFile *> *nameToFile = new map<string, CustomFile *>(); unsigned long totalMemory; unsigned long capturedMemory = 0; public: InterfaceFileSystem() { InterfaceFileSystem(DEFAULT_TOTAL_MEMORY); } InterfaceFileSystem(unsigned long totalMemory) { this->totalMemory = totalMemory; } vector<CustomFile *> *findAll() { vector<CustomFile *> *files = new vector<CustomFile *>(); for (map<string, CustomFile *>::iterator it = nameToFile->begin(); it != nameToFile->end(); it++) { files->push_back(it->second); } return files; } CustomFile *findByName(const string &name) { if (nameToFile->count(name) > FILE_NOT_FOUND) { return nameToFile->find(name)->second; } else { throw FileNotFoundException(); } } CustomFile *save(const string &name, CustomFile *file) { if (nameToFile->count(name) == FILE_NOT_FOUND) { nameToFile->insert(pair<string, CustomFile *>(name, file)); decreaseFreeMemory(file->getSize()); return file; } else { throw FileIsExistException(); } } CustomFile *deleteFile(const string &name) { CustomFile *file = findByName(name); increaseFreeMemory(file->getSize()); nameToFile->erase(name); return file; } void updateFile(const string &name, CustomFile *file) { if (nameToFile->count(name) > FILE_NOT_FOUND) { const unsigned long previousSize = nameToFile->find(name)->second->getSize(); const unsigned long currentSize = file->getSize(); increaseFreeMemory(previousSize); if (currentSize <= getFreeMemory()) { nameToFile->insert(pair<string, CustomFile *>(name, file)); decreaseFreeMemory(currentSize); } else { decreaseFreeMemory(previousSize); throw OutOfMemoryException(); } } else { throw FileNotFoundException(); } } private: void increaseFreeMemory(unsigned long memory) { capturedMemory -= memory; } void decreaseFreeMemory(unsigned long memory) { capturedMemory += memory; } unsigned long getFreeMemory() { return totalMemory - capturedMemory; } };
28.168421
107
0.612855
AlinaNenasheva
7eb340e9f9ce1ad7b6adb4eec682b41d149ac8db
736
cpp
C++
lecture_code/lecture6_1/date_class7.cpp
ahurta92/ams562-notes
e66baa1e50654e125902651f388d45cb32c81f00
[ "MIT" ]
1
2021-09-01T19:09:54.000Z
2021-09-01T19:09:54.000Z
lecture_code/lecture6_1/date_class7.cpp
ahurta92/ams562-notes
e66baa1e50654e125902651f388d45cb32c81f00
[ "MIT" ]
null
null
null
lecture_code/lecture6_1/date_class7.cpp
ahurta92/ams562-notes
e66baa1e50654e125902651f388d45cb32c81f00
[ "MIT" ]
1
2021-11-30T19:26:02.000Z
2021-11-30T19:26:02.000Z
#include "Month_enum.h" // class (controls acc) class Date { public: int day() const; // const member: can't modify object Month month() const; // const member can't modify object int year() const; // const member can't modify object void add_day(int n); // non-const member: can modify void add_month(int n); // non-const member: can modify void add_year(int n); // non-const member: can modify private: // default values int y{2001}; Month m{Month::jan}; int d{1}; }; int main() { Date d; const Date cd = d; d.day(); d.add_day(2); cd.day(); cd.add_day(2); // error const } int Date::day() const { ++d; // error attempt to change object from const member function return d; }
20.444444
67
0.633152
ahurta92
9d176a9145ad7fbc6bbe4820ac5e59ab56825274
4,556
cpp
C++
Engine/source/forest/ts/tsForestCellBatch.cpp
jyaskus/Torque3D
fcac140405b2fbe7c54e7a2dc6e3b10b79c8983f
[ "Unlicense" ]
6
2015-06-01T15:44:43.000Z
2021-01-07T06:50:21.000Z
Engine/source/forest/ts/tsForestCellBatch.cpp
timmgt/Torque3D
ebc6c9cf3a2c7642b2cd30be3726810a302c3deb
[ "Unlicense" ]
null
null
null
Engine/source/forest/ts/tsForestCellBatch.cpp
timmgt/Torque3D
ebc6c9cf3a2c7642b2cd30be3726810a302c3deb
[ "Unlicense" ]
10
2015-01-05T15:58:31.000Z
2021-11-20T14:05:46.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "forest/ts/tsForestCellBatch.h" #include "forest/ts/tsForestItemData.h" #include "scene/sceneManager.h" #include "ts/tsLastDetail.h" TSForestCellBatch::TSForestCellBatch( TSLastDetail *detail ) : mDetail( detail ) { } TSForestCellBatch::~TSForestCellBatch() { } bool TSForestCellBatch::_prepBatch( const ForestItem &item ) { // Make sure it's our item type! TSForestItemData* data = dynamic_cast<TSForestItemData*>( item.getData() ); if ( !data ) return false; // TODO: Eventually we should atlas multiple details into // a single combined texture map. Till then we have to // do one batch per-detail type. // If the detail type doesn't match then // we need to start a new batch. if ( data->getLastDetail() != mDetail ) return false; return true; } void TSForestCellBatch::_rebuildBatch() { // Clean up first. mVB = NULL; if ( mItems.empty() ) return; // How big do we need to make this? U32 verts = mItems.size() * 6; mVB.set( GFX, verts, GFXBufferTypeStatic ); if ( !mVB.isValid() ) { // If we failed it is probably because we requested // a size bigger than a VB can be. Warn the user. AssertWarn( false, "TSForestCellBatch::_rebuildBatch: Batch too big... try reducing the forest cell size!" ); return; } // Fill this puppy! ImposterState *vertPtr = mVB.lock(); Vector<ForestItem>::const_iterator item = mItems.begin(); const F32 radius = mDetail->getRadius(); ImposterState state; for ( ; item != mItems.end(); item++ ) { item->getWorldBox().getCenter( &state.center ); state.halfSize = radius * item->getScale(); state.alpha = 1.0f; item->getTransform().getColumn( 2, &state.upVec ); item->getTransform().getColumn( 0, &state.rightVec ); *vertPtr = state; vertPtr->corner = 0; ++vertPtr; *vertPtr = state; vertPtr->corner = 1; ++vertPtr; *vertPtr = state; vertPtr->corner = 2; ++vertPtr; *vertPtr = state; vertPtr->corner = 2; ++vertPtr; *vertPtr = state; vertPtr->corner = 3; ++vertPtr; *vertPtr = state; vertPtr->corner = 0; ++vertPtr; } mVB.unlock(); } void TSForestCellBatch::_render( const SceneRenderState *state ) { if ( !mVB.isValid() || ( state->isShadowPass() && !TSLastDetail::smCanShadow ) ) return; // Make sure we have a material to render with. BaseMatInstance *mat = state->getOverrideMaterial( mDetail->getMatInstance() ); if ( mat == NULL ) return; // We don't really render here... we submit it to // the render manager which collects all the batches // in the scene, sorts them by texture, sets up the // shader, and then renders them all at once. ImposterBatchRenderInst *inst = state->getRenderPass()->allocInst<ImposterBatchRenderInst>(); inst->mat = mat; inst->vertBuff = &mVB; // We sort by the imposter type first so that RIT_Imposter and // RIT_ImposterBatches do not get mixed together. // // We then sort by material. // inst->defaultKey = 0; inst->defaultKey2 = mat->getStateHint(); state->getRenderPass()->addInst( inst ); }
30.373333
115
0.645303
jyaskus
9d196c5aefd16eff10981d4fc13eb7160a19db1a
147
cpp
C++
Pong/src/Paddle.cpp
tbui468/pong
ff1ade4db34ac6b329ab1628e579550f4863968c
[ "MIT" ]
null
null
null
Pong/src/Paddle.cpp
tbui468/pong
ff1ade4db34ac6b329ab1628e579550f4863968c
[ "MIT" ]
null
null
null
Pong/src/Paddle.cpp
tbui468/pong
ff1ade4db34ac6b329ab1628e579550f4863968c
[ "MIT" ]
null
null
null
#include "Paddle.h" void Paddle::move(int key, unsigned int delta_time) { update_location(m_h_velocity * key, m_v_velocity * key, delta_time); }
24.5
69
0.748299
tbui468
9d19bf9f94485656e748eb749dc0a026a2342f57
1,332
cpp
C++
src/X-GSD/ComponentSprite.cpp
iPruch/X-GSD
1f0b294e27f5aee0fb0448207cd1091c9d42ae44
[ "Zlib" ]
2
2015-01-04T22:17:23.000Z
2017-04-28T14:19:56.000Z
src/X-GSD/ComponentSprite.cpp
iPruch/X-GSD
1f0b294e27f5aee0fb0448207cd1091c9d42ae44
[ "Zlib" ]
null
null
null
src/X-GSD/ComponentSprite.cpp
iPruch/X-GSD
1f0b294e27f5aee0fb0448207cd1091c9d42ae44
[ "Zlib" ]
null
null
null
#include <X-GSD/ComponentSprite.hpp> using namespace xgsd; ComponentSprite::ComponentSprite(const sf::Texture& texture) : mSprite(texture) { // Load resources here (RAII) // If this constructor is used and no texture rect is specified it will be as big as the texture } ComponentSprite::ComponentSprite(const sf::Texture& texture, sf::IntRect textureRect) : mSprite(texture) { // Load resources here (RAII) mSprite.setTextureRect(textureRect); } void ComponentSprite::draw(sf::RenderTarget& target, sf::RenderStates states) const { // Just draw the sprite on the render target target.draw(mSprite, states); } void ComponentSprite::setColor(sf::Color color) { mSprite.setColor(color); } void ComponentSprite::setTexture(sf::Texture &texture) { mSprite.setTexture(texture); } void ComponentSprite::setTextureRect(sf::IntRect textureRect) { mSprite.setTextureRect(textureRect); } sf::FloatRect ComponentSprite::getGlobalBounds() { return mSprite.getGlobalBounds(); } sf::Color ComponentSprite::getColor() { return mSprite.getColor(); } const sf::Texture& ComponentSprite::getTexture() { return *mSprite.getTexture(); } sf::IntRect ComponentSprite::getTextureRect() { return mSprite.getTextureRect(); } ComponentSprite::~ComponentSprite() { // Cleanup }
20.181818
104
0.726727
iPruch