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
cb484272f48beefce0e678883967d121ba1e81c9
1,977
cpp
C++
depends/libyarn/src/protocolrecords/RegisterApplicationMasterRequest.cpp
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
450
2015-09-05T09:12:51.000Z
2018-08-30T01:45:36.000Z
depends/libyarn/src/protocolrecords/RegisterApplicationMasterRequest.cpp
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
1,274
2015-09-22T20:06:16.000Z
2018-08-31T22:14:00.000Z
depends/libyarn/src/protocolrecords/RegisterApplicationMasterRequest.cpp
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
278
2015-09-21T19:15:06.000Z
2018-08-31T00:36: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. */ #include "RegisterApplicationMasterRequest.h" namespace libyarn { RegisterApplicationMasterRequest::RegisterApplicationMasterRequest() { requestProto = RegisterApplicationMasterRequestProto::default_instance(); } RegisterApplicationMasterRequest::RegisterApplicationMasterRequest( const RegisterApplicationMasterRequestProto &proto) : requestProto(proto) { } RegisterApplicationMasterRequest::~RegisterApplicationMasterRequest() { } RegisterApplicationMasterRequestProto& RegisterApplicationMasterRequest::getProto(){ return requestProto; } void RegisterApplicationMasterRequest::setHost(string &host) { requestProto.set_host(host); } string RegisterApplicationMasterRequest::getHost() { return requestProto.host(); } void RegisterApplicationMasterRequest::setRpcPort(int32_t port) { requestProto.set_rpc_port(port); } int32_t RegisterApplicationMasterRequest::getRpcPort() { return requestProto.rpc_port(); } void RegisterApplicationMasterRequest::setTrackingUrl(string &url) { requestProto.set_tracking_url(url); } string RegisterApplicationMasterRequest::getTrackingUrl() { return requestProto.tracking_url(); } } /* namespace libyarn */
29.954545
84
0.794638
YangHao666666
cb4a4d1e1c306ca1bcdef8945b3e789bf8773c8a
5,461
cpp
C++
openstudiocore/src/openstudio_lib/ConstructionsController.cpp
colemat/OpenStudio
46680e95efa5ef51c7199176f366dfdede5ab706
[ "blessing" ]
null
null
null
openstudiocore/src/openstudio_lib/ConstructionsController.cpp
colemat/OpenStudio
46680e95efa5ef51c7199176f366dfdede5ab706
[ "blessing" ]
1
2019-02-04T23:30:45.000Z
2019-02-04T23:30:45.000Z
openstudiocore/src/openstudio_lib/ConstructionsController.cpp
colemat/OpenStudio
46680e95efa5ef51c7199176f366dfdede5ab706
[ "blessing" ]
null
null
null
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #include "ConstructionsController.hpp" #include "ConstructionsView.hpp" #include "../model/CFactorUndergroundWallConstruction.hpp" #include "../model/Component.hpp" #include "../model/Component_Impl.hpp" #include "../model/ComponentData.hpp" #include "../model/ComponentData_Impl.hpp" #include "../model/Construction.hpp" #include "../model/ConstructionBase.hpp" #include "../model/ConstructionBase_Impl.hpp" #include "../model/ConstructionWithInternalSource.hpp" #include "../model/DefaultConstructionSet.hpp" #include "../model/DefaultConstructionSet_Impl.hpp" #include "../model/FFactorGroundFloorConstruction.hpp" #include "../model/WindowDataFile.hpp" #include "../utilities/core/Logger.hpp" #include <utilities/idd/IddEnums.hxx> namespace openstudio { ConstructionsController::ConstructionsController(bool isIP, const model::Model& model) : ModelSubTabController(new ConstructionsView(isIP,model), model) { } ConstructionsController::~ConstructionsController() { } void ConstructionsController::onAddObject(const openstudio::IddObjectType& iddObjectType) { switch(iddObjectType.value()){ case IddObjectType::OS_Construction: openstudio::model::Construction(this->model()); break; case IddObjectType::OS_Construction_InternalSource: openstudio::model::ConstructionWithInternalSource(this->model()); break; case IddObjectType::OS_Construction_CfactorUndergroundWall: openstudio::model::CFactorUndergroundWallConstruction(this->model()); break; case IddObjectType::OS_Construction_FfactorGroundFloor: openstudio::model::FFactorGroundFloorConstruction(this->model()); break; case IddObjectType::OS_Construction_WindowDataFile: openstudio::model::WindowDataFile(this->model()); break; default: LOG_FREE_AND_THROW("ConstructionsController", "Unknown IddObjectType '" << iddObjectType.valueName() << "'"); } } void ConstructionsController::onCopyObject(const openstudio::model::ModelObject& modelObject) { modelObject.clone(this->model()); } void ConstructionsController::onRemoveObject(openstudio::model::ModelObject modelObject) { modelObject.remove(); } void ConstructionsController::onReplaceObject(openstudio::model::ModelObject modelObject, const OSItemId& replacementItemId) { // not yet implemented } void ConstructionsController::onPurgeObjects(const openstudio::IddObjectType& iddObjectType) { this->model().purgeUnusedResourceObjects(iddObjectType); } void ConstructionsController::onDrop(const OSItemId& itemId) { boost::optional<model::ModelObject> modelObject = this->getModelObject(itemId); if (modelObject){ if(modelObject->optionalCast<model::ConstructionBase>()){ if (this->fromComponentLibrary(itemId)){ modelObject = modelObject->clone(this->model()); } } }else{ boost::optional<model::Component> component = this->getComponent(itemId); if (component){ if (component->primaryObject().optionalCast<model::ModelObject>()){ this->model().insertComponent(*component); } } } } void ConstructionsController::onInspectItem(OSItem* item) { } } // openstudio
42.333333
125
0.730819
colemat
cb4ba2cb949e2aaaf6e6c36f773ed35c82df9e73
7,632
cpp
C++
sim/decoder_tb.cpp
nmoroze/lemoncore
8223f6f6fd9b3bb6dfeeae3025d1d63aceced324
[ "MIT" ]
11
2020-08-29T19:49:48.000Z
2021-05-29T17:52:12.000Z
sim/decoder_tb.cpp
nmoroze/lemoncore
8223f6f6fd9b3bb6dfeeae3025d1d63aceced324
[ "MIT" ]
null
null
null
sim/decoder_tb.cpp
nmoroze/lemoncore
8223f6f6fd9b3bb6dfeeae3025d1d63aceced324
[ "MIT" ]
null
null
null
#include <stdint.h> #include <stdlib.h> #include <gtest/gtest.h> #include "Vdecoder.h" #include "verilated.h" #include "riscv.h" #include "decoder_tb.h" const static int NUM_INSTRUCTIONS = 37; struct control_signals_t { std::string instr; uint32_t (*gen_instr)(); int alu_op; int a_src; int b_src; int b_neg; int mem_w; int reg_w; int next_pc; int wb_src; int shift_type; }; struct control_signals_t CONTROL_SIGNAL_TABLE[NUM_INSTRUCTIONS] = { // Instr ALUop Asrc Bsrc Bneg MemW RegW NextPc WBsrc ShiftType {"LUI", rv_lui, ALU_OP_ADD, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"AUIPC", rv_auipc, ALU_OP_ADD, A_SRC_PC, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"JAL", rv_jal, ALU_OP_AND, A_SRC_RS1, -1, -1, 0, 1, NEXT_PC_BR0, WB_SRC_PC, -1}, {"JALR", rv_jalr, ALU_OP_ADD, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_ALU, WB_SRC_PC, -1}, {"BEQ", rv_beq, ALU_OP_XOR, A_SRC_RS1, B_SRC_RS2, 0, 0, 0, NEXT_PC_BR0, -1, -1}, {"BNE", rv_bne, ALU_OP_XOR, A_SRC_RS1, B_SRC_RS2, 0, 0, 0, NEXT_PC_BR1, -1, -1}, {"BLT", rv_blt, ALU_OP_CMP, A_SRC_RS1, B_SRC_RS2, 0, 0, 0, NEXT_PC_BR1, -1, -1}, {"BGE", rv_bge, ALU_OP_CMP, A_SRC_RS1, B_SRC_RS2, 0, 0, 0, NEXT_PC_BR0, -1, -1}, {"BLTU", rv_bltu, ALU_OP_CMPU, A_SRC_RS1, B_SRC_RS2, 0, 0, 0, NEXT_PC_BR1, -1, -1}, {"BGEU", rv_bgeu, ALU_OP_CMPU, A_SRC_RS1, B_SRC_RS2, 0, 0, 0, NEXT_PC_BR0, -1, -1}, {"LB", rv_lb, ALU_OP_ADD, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_MEM, -1}, {"LH", rv_lh, ALU_OP_ADD, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_MEM, -1}, {"LW", rv_lw, ALU_OP_ADD, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_MEM, -1}, {"LBU", rv_lbu, ALU_OP_ADD, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_MEM, -1}, {"LHU", rv_lhu, ALU_OP_ADD, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_MEM, -1}, {"SB", rv_sb, ALU_OP_ADD, A_SRC_RS1, B_SRC_IMM, 0, 1, 0, NEXT_PC_INC, -1, -1}, {"SH", rv_sh, ALU_OP_ADD, A_SRC_RS1, B_SRC_IMM, 0, 1, 0, NEXT_PC_INC, -1, -1}, {"SW", rv_sw, ALU_OP_ADD, A_SRC_RS1, B_SRC_IMM, 0, 1, 0, NEXT_PC_INC, -1, -1}, {"ADDI", rv_addi, ALU_OP_ADD, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"SLTI", rv_slti, ALU_OP_CMP, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"SLTIU", rv_sltiu, ALU_OP_CMPU, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"XORI", rv_xori, ALU_OP_XOR, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"ORI", rv_ori, ALU_OP_OR, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"ANDI", rv_andi, ALU_OP_AND, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"SLLI", rv_slli, ALU_OP_SHL, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"SRLI", rv_srli, ALU_OP_SHR, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, 1}, {"SRAI", rv_srai, ALU_OP_SHR, A_SRC_RS1, B_SRC_IMM, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, 0}, {"ADD", rv_add, ALU_OP_ADD, A_SRC_RS1, B_SRC_RS2, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"SUB", rv_sub, ALU_OP_ADD, A_SRC_RS1, B_SRC_RS2, 1, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"SLL", rv_sll, ALU_OP_SHL, A_SRC_RS1, B_SRC_RS2, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"SLT", rv_slt, ALU_OP_CMP, A_SRC_RS1, B_SRC_RS2, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"SLTU", rv_sltu, ALU_OP_CMPU, A_SRC_RS1, B_SRC_RS2, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"XOR", rv_xor, ALU_OP_XOR, A_SRC_RS1, B_SRC_RS2, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"SRL", rv_srl, ALU_OP_SHR, A_SRC_RS1, B_SRC_RS2, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, 1}, {"SRA", rv_sra, ALU_OP_SHR, A_SRC_RS1, B_SRC_RS2, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, 0}, {"OR", rv_or, ALU_OP_OR, A_SRC_RS1, B_SRC_RS2, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, {"AND", rv_and, ALU_OP_AND, A_SRC_RS1, B_SRC_RS2, 0, 0, 1, NEXT_PC_INC, WB_SRC_ALU, -1}, }; class DecoderTest : public ::testing::Test { protected: void SetUp() override { tb = new Vdecoder; } void TearDown() override { delete tb; } Vdecoder *tb; }; TEST_F(DecoderTest, ControlSignals) { for (int i = 0; i < NUM_INSTRUCTIONS; i++) { auto ctrlsigs = CONTROL_SIGNAL_TABLE[i]; uint32_t instr = ctrlsigs.gen_instr(); auto name = ctrlsigs.instr; tb->instr_i = instr; tb->eval(); EXPECT_EQ(tb->illegal_instr_o, 0); if (ctrlsigs.alu_op != -1) EXPECT_EQ(tb->alu_op_o, ctrlsigs.alu_op) << "ALUOp incorrect for instruction " << name; if (ctrlsigs.a_src != -1) EXPECT_EQ(tb->a_src_o, ctrlsigs.a_src) << "Asrc incorrect for instruction " << name; if (ctrlsigs.b_src != -1) EXPECT_EQ(tb->b_src_o, ctrlsigs.b_src) << "Bsrc incorrect for instruction " << name; if (ctrlsigs.b_neg != -1) EXPECT_EQ(tb->negate_b_o, ctrlsigs.b_neg) << "NegateB incorrect for instruction " << name; if (ctrlsigs.mem_w != -1) EXPECT_EQ(tb->mem_w_o, ctrlsigs.mem_w) << "MemW incorrect for instruction " << name; if (ctrlsigs.reg_w != -1) EXPECT_EQ(tb->reg_w_o, ctrlsigs.reg_w) << "RegW incorrect for instruction " << name; if (ctrlsigs.next_pc != -1) EXPECT_EQ(tb->next_pc_o, ctrlsigs.next_pc) << "NextPC incorrect for instruction " << name; if (ctrlsigs.wb_src != -1) EXPECT_EQ(tb->wb_src_o, ctrlsigs.wb_src) << "WBsrc incorrect for instruction " << name; } } TEST_F(DecoderTest, IllegalInstruction) { tb->instr_i = 0x0; tb->eval(); EXPECT_EQ(tb->illegal_instr_o, 1); tb->instr_i = rv_and() | (1 << 30); // AND w/ a twist tb->eval(); EXPECT_EQ(tb->illegal_instr_o, 1); } TEST_F(DecoderTest, ExtractRs1) { // Regression test for silly bug where I mixed up jal and jalr when refactoring // decoder. Would be nice to include rs1 gating in main control signals test, // but not sure of super clean way to do it. tb->instr_i = rv_jalr(0, 1, 0); // jalr w/ rs1 = 1 tb->eval(); EXPECT_EQ(tb->rs1_o, 1); tb->instr_i = rv_jal() | (1 << 15); tb->eval(); EXPECT_EQ(tb->rs1_o, 0); } TEST_F(DecoderTest, System) { // System instructions don't really take advantage of the same control signals, // so cleanest to test them individually. tb->instr_i = rv_fence(); tb->eval(); EXPECT_EQ(tb->nop_o, 1); EXPECT_EQ(tb->ebreak_o, 0); EXPECT_EQ(tb->ecall_o, 0); EXPECT_EQ(tb->mret_o, 0); tb->instr_i = rv_fence_i(); tb->eval(); EXPECT_EQ(tb->nop_o, 1); EXPECT_EQ(tb->ebreak_o, 0); EXPECT_EQ(tb->ecall_o, 0); EXPECT_EQ(tb->mret_o, 0); tb->instr_i = rv_wfi(); tb->eval(); EXPECT_EQ(tb->nop_o, 1); EXPECT_EQ(tb->ebreak_o, 0); EXPECT_EQ(tb->ecall_o, 0); EXPECT_EQ(tb->mret_o, 0); tb->instr_i = rv_ecall(); tb->eval(); EXPECT_EQ(tb->ecall_o, 1); EXPECT_EQ(tb->ebreak_o, 0); EXPECT_EQ(tb->mret_o, 0); EXPECT_EQ(tb->nop_o, 0); tb->instr_i = rv_ebreak(); tb->eval(); EXPECT_EQ(tb->ebreak_o, 1); EXPECT_EQ(tb->ecall_o, 0); EXPECT_EQ(tb->mret_o, 0); EXPECT_EQ(tb->nop_o, 0); tb->instr_i = rv_mret(); tb->eval(); EXPECT_EQ(tb->mret_o, 1); EXPECT_EQ(tb->ecall_o, 0); EXPECT_EQ(tb->ebreak_o, 0); EXPECT_EQ(tb->nop_o, 0); }
43.363636
108
0.611242
nmoroze
cb4e3e53265ee0210bdb8c10ec8420f8ed69f681
2,261
cc
C++
Testcase4-Application-breakdown/online-compiling/examples/gtest/wrapper.cc
hunhoffe/ServerlessBench
529eb835638cad0edb5be3343166c7ade375ece2
[ "MulanPSL-1.0" ]
129
2020-08-09T12:02:30.000Z
2022-03-31T15:26:03.000Z
Testcase4-Application-breakdown/online-compiling/examples/gtest/wrapper.cc
hunhoffe/ServerlessBench
529eb835638cad0edb5be3343166c7ade375ece2
[ "MulanPSL-1.0" ]
11
2020-09-17T09:42:07.000Z
2022-03-30T19:05:38.000Z
Testcase4-Application-breakdown/online-compiling/examples/gtest/wrapper.cc
hunhoffe/ServerlessBench
529eb835638cad0edb5be3343166c7ade375ece2
[ "MulanPSL-1.0" ]
22
2020-08-20T06:59:24.000Z
2022-03-18T21:00:05.000Z
/* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ #include <string> #include <vector> #include "thunk/thunk.hh" #include "thunk/thunk_reader.hh" #include "util/exception.hh" #include "util/path.hh" #include "util/system_runner.hh" #include "util/util.hh" using namespace std; using namespace gg::thunk; void usage( const char * argv0 ) { cerr << argv0 << " TEST-BINARY TEST-NAME" << endl; } class TempSymlink { private: roost::path linkpath_; public: TempSymlink( const roost::path & target, const roost::path & linkpath ) : linkpath_( linkpath ) { roost::symlink( target, linkpath ); } ~TempSymlink() { try { roost::remove( linkpath_ ); } catch ( const exception & e ) { print_exception( "TempSymlink", e ); } } }; int main( int argc, char * argv [] ) { try { if ( argc <= 0 ) { abort(); } if ( argc != 3 ) { usage( argv[ 0 ] ); return EXIT_FAILURE; } if ( getenv( "__GG_ENABLED__" ) == nullptr ) { throw runtime_error( "gg is not enabled" ); } const roost::path thunk_path = safe_getenv( "__GG_THUNK_PATH__" ); const roost::path gg_path = safe_getenv( "__GG_DIR__" ); const Thunk thunk = ThunkReader::read( thunk_path ); vector<TempSymlink> symlinks; symlinks.reserve( thunk.values().size() ); /* (1) let's create the necessary symlinks */ for ( const auto & value : thunk.values() ) { if ( value.second.length() > 0 ) { if ( value.second.find( '/' ) != string::npos ) { throw runtime_error( "paths are not supported yet" ); } symlinks.emplace_back( gg_path / value.first, value.second ); } } /* (2) run the test */ const string test_binary { argv[ 1 ] }; const string test_name { argv[ 2 ] }; const string output_name { "output" }; vector<string> all_args { argv[ 1 ] }; all_args.push_back( "--gtest_filter=" + test_name ); all_args.push_back( "--gtest_output=json:" + output_name ); all_args.push_back( "--gtest_color=no" ); run( all_args[ 0 ], all_args, {}, true, false ); } catch ( const exception & e ) { print_exception( argv[ 0 ], e ); return EXIT_FAILURE; } return EXIT_SUCCESS; }
24.311828
77
0.603273
hunhoffe
cb4e69dd28ffffcb5e6fa2caf1d40c1e9b27c11d
4,001
cpp
C++
emulation/hel/lib/ChipObject/tInterruptManager.cpp
NWalker1208/synthesis
c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34
[ "Apache-2.0" ]
null
null
null
emulation/hel/lib/ChipObject/tInterruptManager.cpp
NWalker1208/synthesis
c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34
[ "Apache-2.0" ]
null
null
null
emulation/hel/lib/ChipObject/tInterruptManager.cpp
NWalker1208/synthesis
c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34
[ "Apache-2.0" ]
null
null
null
#include <ChipObject/tInterruptManager.h> #include <stdio.h> #ifndef __NI_CRITICAL_SECTION #define __NI_CRITICAL_SECTION #include <OSAL/Synchronized.h> class ni::dsc::osdep::CriticalSection { public: NTReentrantSemaphore sem; }; #endif #include <OSAL/Task.h> namespace nFPGA { uint32_t tInterruptManager::_globalInterruptMask = 0; ni::dsc::osdep::CriticalSection *tInterruptManager::_globalInterruptMaskSemaphore = new ni::dsc::osdep::CriticalSection(); tInterruptManager::tInterruptManager(uint32_t interruptMask, bool watcher, tRioStatusCode *status) : tSystem(status){ this->_interruptMask = interruptMask; this->_watcher = watcher; this->_enabled = false; this->_handler = NULL; *status = NiFpga_Status_Success; if (!watcher) { enable(status); } } tInterruptManager::~tInterruptManager() { } class tInterruptManager::tInterruptThread { private: friend class tInterruptManager; NTTask task; static DWORD WINAPI invokeInternal(LPVOID param){ return tInterruptManager::handlerWrapper((tInterruptManager*) param); } tInterruptThread() : task("Interruptwaiter", &tInterruptThread::invokeInternal) { } }; void tInterruptManager::registerHandler(tInterruptHandler handler, void *param, tRioStatusCode *status) { this->_handler = handler; this->_userParam = param; *status = NiFpga_Status_Success; } uint32_t tInterruptManager::watch(int32_t timeoutInMs, tRioStatusCode *status) { if (timeoutInMs == NiFpga_InfiniteTimeout) { timeoutInMs = INFINITE; } NiFpga_WaitOnIrqs(_DeviceHandle, NULL, _interruptMask, timeoutInMs, NULL, NULL); return 0;// wth guys. plz explain } void tInterruptManager::enable(tRioStatusCode *status){ *status = NiFpga_Status_Success; reserve(status); bool old = this->_enabled; this->_enabled = true; if (old) { this->_thread->task.Stop(); } this->_thread = new tInterruptThread(); this->_thread->task.Start(this); } void tInterruptManager::disable(tRioStatusCode *status){ *status = NiFpga_Status_Success; unreserve(status); bool old = this->_enabled; this->_enabled = false; if (old) { this->_thread->task.Stop(); } } bool tInterruptManager::isEnabled(tRioStatusCode *status){ *status = NiFpga_Status_Success; return this->_enabled; } void tInterruptManager::handler(){ // Don't use this. It is stupid. Doesn't provide irqsAsserted } /// Background task to wait on the IRQ signal until seen, then call the handler. int tInterruptManager::handlerWrapper(tInterruptManager *pInterrupt){ while (pInterrupt->_enabled) { NiFpga_Bool failed = false; uint32_t irqsAsserted = pInterrupt->_interruptMask; NiFpga_WaitOnIrqs(_DeviceHandle, NULL, pInterrupt->_interruptMask, INFINITE, &irqsAsserted, &failed); // Wait until interrupted if (!failed && pInterrupt->_handler!=NULL) { pInterrupt->_handler(irqsAsserted, pInterrupt->_userParam); // Notify whomever subscribed } } return 0; // No error, right? Right. } void tInterruptManager::acknowledge(tRioStatusCode *status){ // Supposed to tell the IRQ manager that this successfully processed the IRQ. But that is difficult } void tInterruptManager::reserve(tRioStatusCode *status){ tInterruptManager::_globalInterruptMaskSemaphore->sem.take(); if ((tInterruptManager::_globalInterruptMask & this->_interruptMask) > 0) { *status = NiFpga_Status_AccessDenied; // You derped printf("Interrupt already in use!\n"); tInterruptManager::_globalInterruptMaskSemaphore->sem.give(); return; } tInterruptManager::_globalInterruptMask |= this->_interruptMask; *status = NiFpga_Status_Success; tInterruptManager::_globalInterruptMaskSemaphore->sem.give(); } void tInterruptManager::unreserve(tRioStatusCode *status){ tInterruptManager::_globalInterruptMaskSemaphore->sem.take(); tInterruptManager::_globalInterruptMask &= ~this->_interruptMask; tInterruptManager::_globalInterruptMaskSemaphore->sem.give(); *status = NiFpga_Status_Success; } }
31.503937
130
0.749563
NWalker1208
cb503f82f6fdc341a6a002ed76655a823192614d
483
hpp
C++
system/sysutil.hpp
mrtryhard/mrtlib
07344c7a374ea60b494fab67c3d66d617143479e
[ "BSD-3-Clause" ]
null
null
null
system/sysutil.hpp
mrtryhard/mrtlib
07344c7a374ea60b494fab67c3d66d617143479e
[ "BSD-3-Clause" ]
null
null
null
system/sysutil.hpp
mrtryhard/mrtlib
07344c7a374ea60b494fab67c3d66d617143479e
[ "BSD-3-Clause" ]
null
null
null
#ifndef MRT_SYSTEM_SYSUTIL_HPP_ #define MRT_SYSTEM_SYSUTIL_HPP_ #include <iostream> namespace mrt { namespace system { void pause() { const auto old_flags = std::cin.flags(); char wait_char; std::cin.setf(old_flags & ~std::ios_base::skipws); std::cout << "Press any key to continue..." << std::endl; std::cin >> std::noskipws >> wait_char; std::cin.setf(old_flags); } } } #endif // MRT_SYSTEM_SYSUTIL_HPP_
23
65
0.610766
mrtryhard
cb5247f01f34da3b7c30612dbdca21cba22c0bbe
1,665
cpp
C++
rollhash.cpp
rakibulhossain/competetive-programming-library
1a1d8e18e411c6094001d56a7aca45cc106e0f09
[ "MIT" ]
1
2021-11-18T13:07:39.000Z
2021-11-18T13:07:39.000Z
rollhash.cpp
Sajjadhossaintalukder/competetive-programming-library
1a1d8e18e411c6094001d56a7aca45cc106e0f09
[ "MIT" ]
null
null
null
rollhash.cpp
Sajjadhossaintalukder/competetive-programming-library
1a1d8e18e411c6094001d56a7aca45cc106e0f09
[ "MIT" ]
2
2021-08-07T05:09:52.000Z
2021-08-23T19:41:07.000Z
#include<bits/stdc++.h> using namespace std; typedef unsigned long long ull; typedef long long ll; int gen_base(const int bef,const int aft) { auto seed = chrono::high_resolution_clock::now().time_since_epoch().count(); mt19937 mt_rand(seed); int base=uniform_int_distribution<int>(bef+1,aft)(mt_rand); return base%2==0? base-1 : base; } struct rollhash { static const int mod = (int)1e9+123; // mod vector<ll>pref1; // hash by mod vector<ull>pref2; // hash by 2^64 static vector<ll>pow1; // pow of base by mod static vector<ull>pow2; // pow of base by 2^64 static int base; // base of hash inline void init(const string& s) { pref1.push_back(0); pref2.push_back(0); int n=s.length(); while((int)pow1.size()<=n) { pow1.push_back((1ll*pow1.back()*base)%mod); pow2.push_back(pow2.back()*base); } for(int i=0; i<n; i++) { assert(base>s[i]); pref1.push_back((pref1[i]+1ll*(s[i]*pow1[i]))%mod); pref2.push_back(pref2[i]+(s[i]*pow2[i])); } } inline pair<ll,ull> operator()(const int pos,const int len,const int mxpow=0)const{ ll hash1=pref1[pos+len]-pref1[pos]; ull hash2=pref2[pos+len]-pref2[pos]; if(hash1<0) hash1+=mod; if(mxpow) { hash1=(1ll*hash1*pow1[mxpow-pos-len+1])%mod; hash2=hash2*pow2[mxpow-pos-len+1]; } return make_pair(hash1,hash2); } }; int rollhash::base((int)1e9+7); vector<ll> rollhash::pow1{1}; vector<ull> rollhash::pow2{1u}; int main() { return 0; }
21.075949
87
0.574775
rakibulhossain
cb530e61579194d839aaa97b208695672266b836
2,307
hpp
C++
test-suite/marketmodel.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
2
2021-12-12T01:27:45.000Z
2022-01-25T17:44:12.000Z
test-suite/marketmodel.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
1
2020-07-17T18:49:22.000Z
2020-07-17T18:49:22.000Z
test-suite/marketmodel.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
1
2021-07-11T08:32:27.000Z
2021-07-11T08:32:27.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2006 Ferdinando Ametrano Copyright (C) 2006 StatPro Italia srl Copyright (C) 2012 Peter Caspers This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #ifndef quantlib_test_market_model_hpp #define quantlib_test_market_model_hpp #include <ql/qldefines.hpp> #include <boost/test/unit_test.hpp> #include "speedlevel.hpp" /* remember to document new and/or updated tests in the Doxygen comment block of the corresponding class */ class MarketModelTest { public: enum MarketModelType { ExponentialCorrelationFlatVolatility, ExponentialCorrelationAbcdVolatility/*, CalibratedMM*/ }; static void testInverseFloater(); static void testPeriodAdapter(); static void testAllMultiStepProducts(); static void testOneStepForwardsAndOptionlets(); static void testOneStepNormalForwardsAndOptionlets(); static void testCallableSwapNaif(); static void testCallableSwapLS(); static void testCallableSwapAnderson( MarketModelType marketModel, unsigned testedFactor); static void testGreeks(); static void testPathwiseGreeks(); static void testPathwiseVegas(); static void testPathwiseMarketVegas(); static void testStochVolForwardsAndOptionlets(); static void testAbcdVolatilityIntegration(); static void testAbcdVolatilityCompare(); static void testAbcdVolatilityFit(); static void testDriftCalculator(); static void testIsInSubset(); static void testAbcdDegenerateCases(); static void testCovariance(); static boost::unit_test_framework::test_suite* suite(SpeedLevel); }; #endif
37.209677
79
0.763762
zhengyuzhang1
cb57507b16a829830bb93d61c699889ee7ffe63f
1,609
cpp
C++
src/OpcUaStackCore/EventType/EventHandler.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
src/OpcUaStackCore/EventType/EventHandler.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
src/OpcUaStackCore/EventType/EventHandler.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
/* Copyright 2017 Kai Huebl (kai@huebl-sgh.de) Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser Datei nur in Übereinstimmung mit der Lizenz erlaubt. Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0. Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart, erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend. Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen im Rahmen der Lizenz finden Sie in der Lizenz. Autor: Kai Huebl (kai@huebl-sgh.de) */ #include <OpcUaStackCore/EventType/EventHandler.h> #include "OpcUaStackCore/Base/Log.h" namespace OpcUaStackCore { EventHandler::EventHandler(void) : EventHandlerBase() , callback_() { } EventHandler::~EventHandler(void) { } void EventHandler::callback(Callback& callback) { callback_ = callback; } Callback& EventHandler::callback(void) { return callback_; } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // interface EventHandlerBase // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ bool EventHandler::fireEvent(OpcUaNodeId& nodeId, EventBase::SPtr& eventBase) { if (!callback_.exist()) { return false; } callback_(eventBase); return true; } }
24.753846
86
0.59913
gianricardo
cb5a4018b10c384cabca4cf983c909761d3eb6ac
9,998
cxx
C++
ParaViewCore/ServerManager/Core/vtkSMGlobalPropertiesProxy.cxx
brown-ccv/paraview-scalable
64b221a540737d2ac94a120039bd8d1e661bdc8f
[ "Apache-2.0", "BSD-3-Clause" ]
2
2019-09-27T08:04:34.000Z
2019-10-16T22:30:54.000Z
ParaViewCore/ServerManager/Core/vtkSMGlobalPropertiesProxy.cxx
sakjain92/paraview
f3af0cd9f6750e24ad038eac573b870c88d6b7dd
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
ParaViewCore/ServerManager/Core/vtkSMGlobalPropertiesProxy.cxx
sakjain92/paraview
f3af0cd9f6750e24ad038eac573b870c88d6b7dd
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: ParaView Module: vtkSMGlobalPropertiesProxy.cxx Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSMGlobalPropertiesProxy.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkPVXMLElement.h" #include "vtkSMProperty.h" #include "vtkSMProxyLocator.h" #include "vtkWeakPointer.h" #include <list> #include <map> class vtkSMGlobalPropertiesProxy::vtkInternals { public: class vtkValue { public: vtkWeakPointer<vtkSMProxy> Proxy; std::string PropertyName; unsigned long ObserverId; vtkValue() : ObserverId(0) { } void RemoveObserver() { vtkSMProperty* prop = this->Proxy ? this->Proxy->GetProperty(this->PropertyName.c_str()) : NULL; if (prop && this->ObserverId > 0) { prop->RemoveObserver(this->ObserverId); } this->ObserverId = 0; } }; typedef std::list<vtkValue> VectorOfValues; typedef std::map<std::string, VectorOfValues> LinksType; LinksType Links; bool Updating; vtkInternals() : Updating(false) { } }; vtkStandardNewMacro(vtkSMGlobalPropertiesProxy); //---------------------------------------------------------------------------- vtkSMGlobalPropertiesProxy::vtkSMGlobalPropertiesProxy() { this->Internals = new vtkSMGlobalPropertiesProxy::vtkInternals(); this->SetLocation(0); this->PrototypeOn(); } //---------------------------------------------------------------------------- vtkSMGlobalPropertiesProxy::~vtkSMGlobalPropertiesProxy() { this->RemoveAllLinks(); delete this->Internals; this->Internals = NULL; } //---------------------------------------------------------------------------- void vtkSMGlobalPropertiesProxy::RemoveAllLinks() { vtkInternals::LinksType::iterator mapIter; for (mapIter = this->Internals->Links.begin(); mapIter != this->Internals->Links.end(); ++mapIter) { vtkInternals::VectorOfValues::iterator listIter; for (listIter = mapIter->second.begin(); listIter != mapIter->second.end(); ++listIter) { listIter->RemoveObserver(); } } this->Internals->Links.clear(); } //---------------------------------------------------------------------------- bool vtkSMGlobalPropertiesProxy::Link( const char* globalPropertyName, vtkSMProxy* proxy, const char* propname) { if (!globalPropertyName || !proxy || !propname) { vtkErrorMacro("Incorrect arguments."); return false; } if (!proxy->GetProperty(propname)) { vtkErrorMacro("Incorrect target property name: " << propname); return false; } if (!this->GetProperty(globalPropertyName)) { vtkErrorMacro("Incorrect source property name:" << globalPropertyName); return false; } // avoid double linking. if (const char* oldname = this->GetLinkedPropertyName(proxy, propname)) { if (strcmp(oldname, globalPropertyName) == 0) { return true; } this->Unlink(oldname, proxy, propname); } // Copy current value. vtkSMProperty* targetProp = proxy->GetProperty(propname); vtkSMProperty* globalProperty = this->GetProperty(globalPropertyName); targetProp->Copy(globalProperty); proxy->UpdateVTKObjects(); vtkInternals::vtkValue value; value.Proxy = proxy; value.PropertyName = propname; value.ObserverId = targetProp->AddObserver( vtkCommand::ModifiedEvent, this, &vtkSMGlobalPropertiesProxy::TargetPropertyModified); this->Internals->Links[globalPropertyName].push_back(value); // FIXME: is this relevant? // if (proxy->GetObjectsCreated()) // { // // This handles the case when the proxy hasn't been created yet (which // // happens when reviving servermanager on the server side. // proxy->UpdateVTKObjects(); // } // If we ever want to bring undo-redo support back. // ModifiedInfo info; // info.AddLink = true; // info.GlobalPropertyName = globalPropertyName; // info.PropertyName = propname; // info.Proxy = proxy; // this->InvokeEvent(vtkSMGlobalPropertiesProxy::GlobalPropertyLinkModified, &info); return true; } //---------------------------------------------------------------------------- bool vtkSMGlobalPropertiesProxy::Unlink( const char* globalPropertyName, vtkSMProxy* proxy, const char* propname) { vtkInternals::VectorOfValues& values = this->Internals->Links[globalPropertyName]; vtkInternals::VectorOfValues::iterator listIter; for (listIter = values.begin(); listIter != values.end(); ++listIter) { if (listIter->Proxy == proxy && listIter->PropertyName == propname) { listIter->RemoveObserver(); values.erase(listIter); return true; } } return false; // If we ever want to bring undo-redo support back. // ModifiedInfo info; // info.AddLink = false; // info.GlobalPropertyName = globalPropertyName; // info.PropertyName = propname; // info.Proxy = proxy; // this->InvokeEvent(vtkSMGlobalPropertiesProxy::GlobalPropertyLinkModified, &info); } //---------------------------------------------------------------------------- const char* vtkSMGlobalPropertiesProxy::GetLinkedPropertyName( vtkSMProxy* proxy, const char* propname) { vtkInternals::LinksType::iterator mapIter; for (mapIter = this->Internals->Links.begin(); mapIter != this->Internals->Links.end(); ++mapIter) { vtkInternals::VectorOfValues::iterator listIter; for (listIter = mapIter->second.begin(); listIter != mapIter->second.end(); ++listIter) { if (listIter->Proxy == proxy && listIter->PropertyName == propname) { return mapIter->first.c_str(); } } } return NULL; } //---------------------------------------------------------------------------- void vtkSMGlobalPropertiesProxy::SetPropertyModifiedFlag(const char* name, int flag) { this->Superclass::SetPropertyModifiedFlag(name, flag); // Copy property value to all linked properties. bool prev = this->Internals->Updating; this->Internals->Updating = true; vtkSMProperty* globalProperty = this->GetProperty(name); vtkInternals::VectorOfValues& values = this->Internals->Links[name]; vtkInternals::VectorOfValues::iterator iter; for (iter = values.begin(); iter != values.end(); ++iter) { if (iter->Proxy.GetPointer() && iter->Proxy->GetProperty(iter->PropertyName.c_str())) { iter->Proxy->GetProperty(iter->PropertyName.c_str())->Copy(globalProperty); iter->Proxy->UpdateVTKObjects(); } } this->Internals->Updating = prev; } //---------------------------------------------------------------------------- void vtkSMGlobalPropertiesProxy::TargetPropertyModified(vtkObject* caller, unsigned long, void*) { if (this->Internals->Updating) { return; } // target property was modified on its own volition. Unlink it. vtkSMProperty* target = vtkSMProperty::SafeDownCast(caller); for (vtkInternals::LinksType::iterator mapIter = this->Internals->Links.begin(); mapIter != this->Internals->Links.end(); ++mapIter) { vtkInternals::VectorOfValues& values = mapIter->second; vtkInternals::VectorOfValues::iterator listIter; for (listIter = values.begin(); listIter != values.end(); ++listIter) { vtkInternals::vtkValue value = (*listIter); if (value.Proxy && (value.Proxy->GetProperty(value.PropertyName.c_str()) == target)) { value.RemoveObserver(); values.erase(listIter); return; } } } } //---------------------------------------------------------------------------- vtkPVXMLElement* vtkSMGlobalPropertiesProxy::SaveXMLState( vtkPVXMLElement* root, vtkSMPropertyIterator* iter) { (void)iter; if (!root) { return NULL; } vtkInternals::LinksType::iterator mapIter; for (mapIter = this->Internals->Links.begin(); mapIter != this->Internals->Links.end(); ++mapIter) { vtkInternals::VectorOfValues::iterator listIter; for (listIter = mapIter->second.begin(); listIter != mapIter->second.end(); ++listIter) { if (listIter->Proxy) { vtkPVXMLElement* linkElem = vtkPVXMLElement::New(); linkElem->SetName("GlobalPropertyLink"); linkElem->AddAttribute("global_name", mapIter->first.c_str()); linkElem->AddAttribute("proxy", listIter->Proxy->GetGlobalIDAsString()); linkElem->AddAttribute("property", listIter->PropertyName.c_str()); root->AddNestedElement(linkElem); linkElem->Delete(); } } } return root; } //---------------------------------------------------------------------------- int vtkSMGlobalPropertiesProxy::LoadXMLState(vtkPVXMLElement* element, vtkSMProxyLocator* locator) { if (!locator) { return 1; } unsigned int numElems = element->GetNumberOfNestedElements(); for (unsigned int cc = 0; cc < numElems; cc++) { vtkPVXMLElement* child = element->GetNestedElement(cc); if (!child->GetName() || strcmp(child->GetName(), "GlobalPropertyLink") != 0) { continue; } std::string global_name = child->GetAttributeOrEmpty("global_name"); std::string property = child->GetAttributeOrEmpty("property"); int proxyid = 0; child->GetScalarAttribute("proxy", &proxyid); vtkSMProxy* proxy = locator->LocateProxy(proxyid); if (!global_name.empty() && !property.empty() && proxy) { this->Link(global_name.c_str(), proxy, property.c_str()); } } return 1; } //---------------------------------------------------------------------------- void vtkSMGlobalPropertiesProxy::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
31.049689
100
0.620324
brown-ccv
cb5a8fe23001a40702e83f803cfa086d3fb07f05
742
cpp
C++
python/swig_/timepoint_to_datetime/foo.cpp
SnoopJeDi/playground
73fab4a38ceeff3da23683e3dd1cb1b3a74cf4cf
[ "MIT" ]
null
null
null
python/swig_/timepoint_to_datetime/foo.cpp
SnoopJeDi/playground
73fab4a38ceeff3da23683e3dd1cb1b3a74cf4cf
[ "MIT" ]
null
null
null
python/swig_/timepoint_to_datetime/foo.cpp
SnoopJeDi/playground
73fab4a38ceeff3da23683e3dd1cb1b3a74cf4cf
[ "MIT" ]
null
null
null
#include <iostream> #include <chrono> std::chrono::steady_clock::time_point get_time() { return std::chrono::steady_clock::now(); } int main(int argc, char** argv) { auto start = get_time(); std::cout << "Hello, I'm going to print out some stars I guess\n"; for(int i=0; i<1000; i++) { std::cout << "*"; } std::cout << "\n\n"; auto end = get_time(); auto dt = end - start; auto dtsec = std::chrono::duration_cast<std::chrono::seconds>(dt); double conv = std::chrono::steady_clock::duration::period::num*1.0 / std::chrono::steady_clock::duration::period::den; std::cout << "That took " << dt.count() << " ticks\n"; std::cout << "That took " << dt.count() * conv << " seconds\n"; }
27.481481
122
0.591644
SnoopJeDi
cb5bd046319c5b0670668f4b193a9d75638ca782
1,357
cpp
C++
apps/panel/widgets/ApplicationListing.cpp
AptRock327/skift
1c8192ab2d3b3f2688128bf7a85b46dbcdcb7cb3
[ "MIT" ]
null
null
null
apps/panel/widgets/ApplicationListing.cpp
AptRock327/skift
1c8192ab2d3b3f2688128bf7a85b46dbcdcb7cb3
[ "MIT" ]
null
null
null
apps/panel/widgets/ApplicationListing.cpp
AptRock327/skift
1c8192ab2d3b3f2688128bf7a85b46dbcdcb7cb3
[ "MIT" ]
null
null
null
#include <libsystem/process/Process.h> #include <libutils/FuzzyMatcher.h> #include <libwidget/Button.h> #include <libwidget/Label.h> #include <libwidget/Window.h> #include "panel/model/MenuEntry.h" #include "panel/widgets/ApplicationListing.h" namespace panel { ApplicationListing::ApplicationListing(Widget *parent) : VScroll(parent) { layout(VFLOW(4)); flags(Widget::FILL); insets(Insetsi(4)); render(); } void ApplicationListing::filter(const String &filter) { if (_filter == filter) { return; } _filter = filter; render(); } void ApplicationListing::render() { FuzzyMatcher matcher; host()->clear_children(); host()->layout(VFLOW(4)); bool find_any = false; MenuEntry::load().foreach ([&](auto &entry) { if (!matcher.match(_filter, entry.name)) { return Iteration::CONTINUE; } find_any = true; auto item = new Button(host(), Button::TEXT, entry.icon, entry.name); item->insets(Insetsi(8)); item->on(Event::ACTION, [this, entry](auto) { process_run(entry.command.cstring(), nullptr); window()->hide(); }); return Iteration::CONTINUE; }); if (!find_any) { new Label(host(), "No application found!", Anchor::CENTER); } } } // namespace panel
19.385714
77
0.607222
AptRock327
cb5d04dd07cb6c00ed36c2d2ea19f01019719629
1,146
cpp
C++
src/aimp_dotnet/SDK/MusicLibrary/Extension/Command/AimpDataStorageCommandUserMark.cpp
Smartoteka/aimp_dotnet
544502b8d080c9280ba11917ef0cc3e8dec44234
[ "Apache-2.0" ]
52
2015-04-14T14:39:30.000Z
2022-02-07T07:16:05.000Z
src/aimp_dotnet/SDK/MusicLibrary/Extension/Command/AimpDataStorageCommandUserMark.cpp
Smartoteka/aimp_dotnet
544502b8d080c9280ba11917ef0cc3e8dec44234
[ "Apache-2.0" ]
11
2015-04-02T10:45:55.000Z
2022-02-03T07:21:53.000Z
src/aimp_dotnet/SDK/MusicLibrary/Extension/Command/AimpDataStorageCommandUserMark.cpp
Smartoteka/aimp_dotnet
544502b8d080c9280ba11917ef0cc3e8dec44234
[ "Apache-2.0" ]
9
2015-04-05T18:25:57.000Z
2022-02-07T07:20:23.000Z
// ---------------------------------------------------- // AIMP DotNet SDK // Copyright (c) 2014 - 2020 Evgeniy Bogdan // https://github.com/martin211/aimp_dotnet // Mail: mail4evgeniy@gmail.com // ---------------------------------------------------- #include "Stdafx.h" #include "AimpDataStorageCommandUserMark.h" AimpDataStorageCommandUserMark::AimpDataStorageCommandUserMark( gcroot<MusicLibrary::Extension::Command::IAimpDataStorageCommandUserMark^> instance) { _instance = instance; } HRESULT WINAPI AimpDataStorageCommandUserMark::SetMark(VARIANT* ID, const DOUBLE Value) { return HRESULT(_instance->SetMark(AimpConverter::FromVaiant(ID), Value)->ResultType); } HRESULT WINAPI AimpDataStorageCommandUserMark::QueryInterface(REFIID riid, LPVOID* ppvObject) { *ppvObject = nullptr; if (riid == IID_IAIMPMLDataStorageCommandUserMark) { *ppvObject = this; AddRef(); return S_OK; } return E_NOINTERFACE; } ULONG WINAPI AimpDataStorageCommandUserMark::AddRef(void) { return Base::AddRef(); } ULONG WINAPI AimpDataStorageCommandUserMark::Release(void) { return Base::Release(); }
30.157895
95
0.67452
Smartoteka
cb605c273c1aeefd1fd821e29b23580d29d367d4
6,542
cc
C++
src/misc_audio.cc
bartvanerp/visqol
9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb
[ "Apache-2.0" ]
null
null
null
src/misc_audio.cc
bartvanerp/visqol
9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb
[ "Apache-2.0" ]
null
null
null
src/misc_audio.cc
bartvanerp/visqol
9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC, Andrew Hines // // 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 "misc_audio.h" #include <assert.h> #include <algorithm> #include <cmath> #include <fstream> #include <memory> #include <sstream> #include <utility> #include <vector> #include "absl/base/internal/raw_logging.h" #include "wav_reader.h" namespace Visqol { const size_t MiscAudio::kNumChanMono = 1; const double MiscAudio::kZeroSample = 0.0; const double MiscAudio::kSplReferencePoint = 0.00002; const double kNoiseFloorRelativeToPeakDb = 45.; const double kNoiseFloorAbsoluteDb = -45.; AudioSignal MiscAudio::ScaleToMatchSoundPressureLevel( const AudioSignal &reference, const AudioSignal &degraded) { const double ref_spl = MiscAudio::CalcSoundPressureLevel(reference); const double deg_spl = MiscAudio::CalcSoundPressureLevel(degraded); const double scale_factor = std::pow(10, (ref_spl - deg_spl) / 20); const auto scaled_mat = degraded.data_matrix * scale_factor; AudioSignal scaled_sig{std::move(scaled_mat), degraded.sample_rate}; return scaled_sig; } double MiscAudio::CalcSoundPressureLevel(const AudioSignal &signal) { const auto &data_matrix = signal.data_matrix; double sum = 0; std::for_each(data_matrix.cbegin(), data_matrix.cend(), [&](const double &datum) { sum += std::pow(datum, 2); }); const double sound_pressure = std::sqrt(sum / data_matrix.NumElements()); return 20 * std::log10(sound_pressure / kSplReferencePoint); } // Combines the data from all channels into a single channel. AMatrix<double> MiscAudio::ToMono(const AMatrix<double> &signal) { // If already Mono, nothing to do. if (signal.NumCols() > kNumChanMono) { auto mono_mat = AMatrix<double>::Filled(signal.NumRows(), kNumChanMono, kZeroSample); for (size_t chan_i = 0; chan_i < signal.NumCols(); chan_i++) { for (size_t sample_i = 0; sample_i < signal.NumRows(); sample_i++) { mono_mat(sample_i, 0) += signal(sample_i, chan_i); } } return mono_mat / signal.NumCols(); } else { return signal; } } // Combines the data from all channels into a single channel. AudioSignal MiscAudio::ToMono(const AudioSignal &signal) { // If already Mono, nothing to do. if (signal.data_matrix.NumCols() > kNumChanMono) { const AMatrix<double> sig_mid_mat(MiscAudio::ToMono(signal.data_matrix)); AudioSignal sig_mid; sig_mid.data_matrix = std::move(sig_mid_mat); sig_mid.sample_rate = signal.sample_rate; return sig_mid; } else { return signal; } } AudioSignal MiscAudio::LoadAsMono(const FilePath &path) { AudioSignal sig; std::ifstream wav_file(path.Path().c_str(), std::ios::binary); if (wav_file) { std::stringstream wav_string_stream; wav_string_stream << wav_file.rdbuf(); wav_file.close(); WavReader wav_reader(&wav_string_stream); const size_t num_total_samples = wav_reader.GetNumTotalSamples(); if (wav_reader.IsHeaderValid() && num_total_samples != 0) { std::vector<int16_t> interleaved_samples(num_total_samples); const auto num_samp_read = wav_reader.ReadSamples(num_total_samples, &interleaved_samples[0]); // Certain wav files are 'mostly valid' and have a slight difference with // the reported file length. Warn for these. if (num_samp_read != num_total_samples) { ABSL_RAW_LOG(WARNING, "Number of samples read (%lu) was less than the expected" " number (%lu).", num_samp_read, num_total_samples); } if (num_samp_read > 0) { const auto interleaved_norm_vec = MiscMath::NormalizeInt16ToDouble( interleaved_samples); const auto multi_chan_norm_vec = ExtractMultiChannel( wav_reader.GetNumChannels(), interleaved_norm_vec); const AMatrix<double> outMat(multi_chan_norm_vec); sig.data_matrix = outMat; sig.sample_rate = wav_reader.GetSampleRateHz(); sig = MiscAudio::ToMono(sig); } else { ABSL_RAW_LOG(ERROR, "Error reading data for file %s.", path.Path().c_str()); } } else { ABSL_RAW_LOG(ERROR, "Error reading header for file %s.", path.Path().c_str()); } } else { ABSL_RAW_LOG(ERROR, "Could not find file %s.", path.Path().c_str()); } return sig; } std::vector<std::vector<double>> MiscAudio::ExtractMultiChannel( const int num_channels, const std::vector<double> &interleaved_vector) { assert(interleaved_vector.size() % num_channels == 0); const size_t sub_vector_size = interleaved_vector.size() / num_channels; std::vector<std::vector<double>> multi_channel_vec( num_channels, std::vector<double>(sub_vector_size)); auto itr = interleaved_vector.cbegin(); for (size_t sample = 0; sample < sub_vector_size; sample++) { for (int channel = 0; channel < num_channels; channel++) { multi_channel_vec[channel][sample] = *itr; itr++; } } return multi_channel_vec; } void MiscAudio::PrepareSpectrogramsForComparison( Spectrogram &reference, Spectrogram &degraded) { reference.ConvertToDb(); degraded.ConvertToDb(); // An absolute threshold is also applied. reference.RaiseFloor(kNoiseFloorAbsoluteDb); degraded.RaiseFloor(kNoiseFloorAbsoluteDb); // Apply a per-frame relative threshold. // Note that this is not an STFT spectrogram, the spectrogram bins // here are each the RMS of a band filter output on the time domain signal. reference.RaiseFloorPerFrame(kNoiseFloorRelativeToPeakDb, degraded); // Normalize to a 0dB global floor (which is probably kNoiseFloorAbsoluteDb). double ref_floor = reference.Minimum(); double deg_floor = degraded.Minimum(); double lowest_floor = std::min(ref_floor, deg_floor); reference.SubtractFloor(lowest_floor); degraded.SubtractFloor(lowest_floor); } } // namespace Visqol
35.945055
79
0.693366
bartvanerp
cb62f0e1b2ba7516ed1b49dfe0e0061f35a11105
1,218
cpp
C++
tests/syscall/epoll/host/host.cpp
oe-ci-test/openenclave
966ef04f623aba54720fa95996c1ff9e0585c22b
[ "MIT" ]
null
null
null
tests/syscall/epoll/host/host.cpp
oe-ci-test/openenclave
966ef04f623aba54720fa95996c1ff9e0585c22b
[ "MIT" ]
3
2021-04-07T20:56:28.000Z
2021-09-23T23:31:47.000Z
tests/syscall/epoll/host/host.cpp
oe-ci-test/openenclave
966ef04f623aba54720fa95996c1ff9e0585c22b
[ "MIT" ]
1
2019-11-16T08:21:33.000Z
2019-11-16T08:21:33.000Z
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include <openenclave/host.h> #include <openenclave/internal/tests.h> #include <cstdio> #include <thread> #include "epoll_u.h" using namespace std; int main(int argc, const char* argv[]) { oe_result_t r; const uint32_t flags = oe_get_create_flags(); const oe_enclave_type_t type = OE_ENCLAVE_TYPE_SGX; if (argc != 2) { fprintf(stderr, "Usage: %s ENCLAVE_PATH\n", argv[0]); return 1; } oe_enclave_t* enclave; r = oe_create_epoll_enclave(argv[1], type, flags, NULL, 0, &enclave); OE_TEST(r == OE_OK); set_up(enclave); thread wait_thread( [enclave] { OE_TEST(wait_for_events(enclave) == OE_OK); }); this_thread::sleep_for(100ms); // give wait_thread time to initialize for (int i = 0; i < 100; ++i) { OE_TEST(trigger_and_add_event(enclave) == OE_OK); OE_TEST(trigger_and_delete_event(enclave) == OE_OK); } cancel_wait(enclave); wait_thread.join(); tear_down(enclave); r = oe_terminate_enclave(enclave); OE_TEST(r == OE_OK); printf("=== passed all tests (epoll)\n"); fflush(stdout); return 0; }
23.423077
73
0.646141
oe-ci-test
cb64800ebc8deabf49e40a3a9886fe7a8da352a5
6,819
cpp
C++
dev/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/Transitions/RemoveTransitionCondition.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/Transitions/RemoveTransitionCondition.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/Transitions/RemoveTransitionCondition.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <gtest/gtest.h> #include <Tests/UI/UIFixture.h> #include <EMotionFX/CommandSystem/Source/CommandManager.h> #include <EMotionFX/Source/AnimGraphManager.h> #include <EMotionFX/Source/AnimGraphMotionNode.h> #include <EMotionFX/Source/AnimGraphStateMachine.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.h> #include <QApplication> #include <QtTest> #include "qtestsystem.h" #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AttributesWindow.h> #include <Source/Editor/ObjectEditor.h> #include <AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx> #include <EMotionFX/Source/AnimGraphPlayTimeCondition.h> #include <AzQtComponents/Components/Widgets/CardHeader.h> namespace EMotionFX { class RemoveTransitionConditionFixture : public UIFixture { public: void SetUp() override { UIFixture::SetUp(); AZStd::string commandResult; MCore::CommandGroup group; // Create empty anim graph, add a motion node and a blend tree. group.AddCommandString(AZStd::string::format("CreateAnimGraph -animGraphID %d", m_animGraphId)); group.AddCommandString(AZStd::string::format("AnimGraphCreateNode -animGraphID %d -type %s -parentName Root -xPos 100 -yPos 100 -name testMotion", m_animGraphId, azrtti_typeid<AnimGraphMotionNode>().ToString<AZStd::string>().c_str())); group.AddCommandString(AZStd::string::format("AnimGraphCreateNode -animGraphID %d -type %s -parentName Root -xPos 200 -yPos 100 -name testBlendTree", m_animGraphId, azrtti_typeid<BlendTree>().ToString<AZStd::string>().c_str())); group.AddCommandString(AZStd::string::format("AnimGraphCreateConnection -animGraphID %d -transitionType %s -sourceNode testMotion -targetNode testBlendTree", m_animGraphId, azrtti_typeid<AnimGraphStateTransition>().ToString<AZStd::string>().c_str())); EXPECT_TRUE(CommandSystem::GetCommandManager()->ExecuteCommandGroup(group, commandResult)) << commandResult.c_str(); m_animGraph = GetAnimGraphManager().FindAnimGraphByID(m_animGraphId); EXPECT_NE(m_animGraph, nullptr) << "Cannot find newly created anim graph."; } void TearDown() override { QApplication::processEvents(QEventLoop::ExcludeUserInputEvents); delete m_animGraph; UIFixture::TearDown(); } public: const AZ::u32 m_animGraphId = 64; AnimGraph* m_animGraph = nullptr; }; TEST_F(RemoveTransitionConditionFixture, RemoveTransitionConditions) { RecordProperty("test_case_id", "C15031141"); auto animGraphPlugin = static_cast<EMStudio::AnimGraphPlugin*>(EMStudio::GetPluginManager()->FindActivePlugin(EMStudio::AnimGraphPlugin::CLASS_ID)); ASSERT_TRUE(animGraphPlugin) << "Anim graph plugin not found."; EMStudio::AnimGraphModel& animGraphModel = animGraphPlugin->GetAnimGraphModel(); // Find the transition between the motion node and the blend tree. AnimGraphStateTransition* transition = m_animGraph->GetRootStateMachine()->GetTransition(0); ASSERT_TRUE(transition) << "Anim graph transition not found."; // Select the transition in the anim graph model. const QModelIndex& modelIndex = animGraphModel.FindFirstModelIndex(transition); const EMStudio::AnimGraphModel::ModelItemType itemType = modelIndex.data(EMStudio::AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value<EMStudio::AnimGraphModel::ModelItemType>(); ASSERT_TRUE(modelIndex.isValid()) << "Anim graph transition has an invalid model index."; animGraphModel.GetSelectionModel().select(QItemSelection(modelIndex, modelIndex), QItemSelectionModel::Current | QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); // Ensure Theere is no initial condition ASSERT_EQ(0, transition->GetNumConditions()) << " Anim Graph Should not have a condition"; // Create Condition // Find and "click" on Add Condition button EMStudio::AddConditionButton* addConditionButton = m_animGraphPlugin->GetAttributesWindow()->GetAddConditionButton(); ASSERT_TRUE(addConditionButton) << "Add Condition button was not found"; addConditionButton->OnCreateContextMenu(); // Add a specific condition QAction* addPlayTimeConditionButton = RemoveTransitionConditionFixture::GetNamedAction(m_animGraphPlugin->GetAttributesWindow(), "Play Time Condition"); ASSERT_TRUE(addPlayTimeConditionButton) << "'Play Time Condition' button was not found"; addPlayTimeConditionButton->trigger(); // Ensure Condition is created ASSERT_EQ(1, transition->GetNumConditions()) << " Anim Graph transition condition should have been made removed"; // Find the created Condition auto transitionCondition = transition->GetCondition(0); auto objectEditor = animGraphPlugin->GetAttributesWindow()->findChild<QWidget*>("EMFX.AttributesWindowWidget.NodeTransition.ConditionsWidget"); ASSERT_TRUE(objectEditor); const AzQtComponents::CardHeader* cardHeader = objectEditor->findChild<AzQtComponents::CardHeader*>(); ASSERT_TRUE(cardHeader) << "Transition Condition CardHeader not found."; const QFrame* frame = cardHeader->findChild<QFrame*>("Background"); ASSERT_TRUE(frame) << "Transtion Condition CardHeader Background Frame not found."; QPushButton* contextMenubutton = frame->findChild< QPushButton*>("ContextMenu"); ASSERT_TRUE(contextMenubutton) << "Transition Condition ContextMenu not found."; // Pop up the context menu. QTest::mouseClick(contextMenubutton, Qt::LeftButton); QAction* deleteAction = RemoveTransitionConditionFixture::GetNamedAction(animGraphPlugin->GetAttributesWindow(), "Delete condition"); ASSERT_TRUE(deleteAction) << "Delete Condition Action not found"; deleteAction->trigger(); // Check if the Condition get deleted. ASSERT_EQ(0, transition->GetNumConditions()) << " Anim Graph transition condition should be removed"; } } // namespace EMotionFX
52.860465
186
0.72078
brianherrera
cb6515063d85df722a2f25fdfcb40563f6d94796
4,869
cpp
C++
inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/convolution/convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3.cpp
cwzrad/openvino
ae4bd370eac7c695bd797a31e62317d328dbe742
[ "Apache-2.0" ]
1
2020-10-13T22:49:18.000Z
2020-10-13T22:49:18.000Z
inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/convolution/convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3.cpp
cwzrad/openvino
ae4bd370eac7c695bd797a31e62317d328dbe742
[ "Apache-2.0" ]
1
2021-07-24T15:22:27.000Z
2021-07-24T15:22:27.000Z
inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/convolution/convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3.cpp
cwzrad/openvino
ae4bd370eac7c695bd797a31e62317d328dbe742
[ "Apache-2.0" ]
1
2020-08-13T08:33:55.000Z
2020-08-13T08:33:55.000Z
// Copyright (c) 2020 Intel Corporation // // 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 "convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3.h" #include "kernel_selector_utils.h" #include "common_tools.h" #include <vector> #include <iostream> // // Kernel specific constants // #define SIMD_SIZE 16 namespace kernel_selector { ParamsKey Convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3::GetSupportedKey() const { ParamsKey k; k.EnableInputDataType(Datatype::INT8); k.EnableInputDataType(Datatype::UINT8); k.EnableOutputDataType(Datatype::INT8); k.EnableOutputDataType(Datatype::UINT8); k.EnableOutputDataType(Datatype::F32); k.EnableInputWeightsType(WeightsType::INT8); k.EnableInputLayout(DataLayout::bs_fs_yx_bsv16_fsv16); k.EnableOutputLayout(DataLayout::bs_fs_yx_bsv16_fsv16); k.EnableDifferentTypes(); k.EnableDifferentInputWeightsTypes(); k.EnableTensorOffset(); k.EnableTensorPitches(); k.EnableBiasPerFeature(); k.EnableNonBiasTerm(); k.EnableBatching(); k.EnableQuantization(QuantizationType::SYMMETRIC); k.DisableTuning(); return k; } KernelsData Convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3::GetKernelsData(const Params& params, const optional_params& options) const { return GetCommonKernelsData(params, options); } JitConstants Convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3::GetJitConstants(const convolution_params& params, const DispatchData& kd) const { auto mem_consts = Parent::GetJitConstants(params, kd); if (!params.fused_ops.empty()) { auto input_dt = GetActivationType(params); FusedOpsConfiguration conf_scalar = {"", {"out_b", "out_f + get_sub_group_local_id()", "out_y", "out_x"}, "dequantized", input_dt, 1, LoadType::FEATURE_SHUFFLE}; conf_scalar.SetLoopAxes({ Tensor::DataChannelName::BATCH }, true); conf_scalar.SetShuffleVarName("i"); mem_consts.Merge(MakeFusedOpsJitConstants(params, {conf_scalar})); } return mem_consts; } // GetJitConstants ConvolutionKernelBase::DispatchData Convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3::SetDefault(const convolution_params& params, int) const { DispatchData kd; const auto& output = params.output; std::vector<size_t> global = {output.X().v, output.Y().v, output.Feature().v / 16 * output.Batch().v}; std::vector<size_t> local = {1, 1, SIMD_SIZE}; kd.gws0 = global[0]; kd.gws1 = global[1]; kd.gws2 = global[2]; kd.lws0 = local[0]; kd.lws1 = local[1]; kd.lws2 = local[2]; kd.cldnnStyle = {0, 0, 0, 0, 0}; kd.gemmStyle = {0, 0, 0, 0, 0, 0}; kd.efficiency = FORCE_PRIORITY_2; return kd; } // SetDefault bool Convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3::Validate(const Params& params, const optional_params& options) const { if (!Parent::Validate(params, options)) { return false; } KernelData kd = KernelData::Default<convolution_params>(params); convolution_params& newParams = *static_cast<convolution_params*>(kd.params.get()); if ((newParams.filterSize.x != newParams.filterSize.y) || newParams.filterSize.x != 3) { // Fitler size needs to be 3x3 return false; } if (newParams.stride.x != newParams.stride.y) { // Strides must be equal return false; } if (newParams.output.X().v != newParams.output.Y().v) { // W and H must be equal return false; } if (newParams.output.Feature().v % 16 != 0) { // output feature size must be divided by 16 return false; } if (newParams.output.Batch().v % 16 != 0) { // batch size must be divided by 16 return false; } // check that all fused ops except eltwise have only feature or scalar inputs for (auto& fo : newParams.fused_ops) { if (fo.GetType() == FusedOpType::ELTWISE) continue; for (auto& input : fo.tensors) { if (input.X().v != 1 || input.Y().v != 1 || input.Batch().v != 1) return false; } } return true; } } // namespace kernel_selector
33.122449
144
0.653933
cwzrad
cb674231b80c63b7bbdd86e527291ea4cbe9b33d
27,792
cpp
C++
src/gpu/ganesh/d3d/GrD3DPipelineStateBuilder.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
src/gpu/ganesh/d3d/GrD3DPipelineStateBuilder.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
src/gpu/ganesh/d3d/GrD3DPipelineStateBuilder.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2020 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ //#include <d3dcompiler.h> #include "src/gpu/ganesh/d3d/GrD3DPipelineStateBuilder.h" #include "include/gpu/GrDirectContext.h" #include "include/gpu/d3d/GrD3DTypes.h" #include "src/core/SkReadBuffer.h" #include "src/core/SkTraceEvent.h" #include "src/gpu/ganesh/GrAutoLocaleSetter.h" #include "src/gpu/ganesh/GrDirectContextPriv.h" #include "src/gpu/ganesh/GrPersistentCacheUtils.h" #include "src/gpu/ganesh/GrShaderCaps.h" #include "src/gpu/ganesh/GrStencilSettings.h" #include "src/gpu/ganesh/d3d/GrD3DGpu.h" #include "src/gpu/ganesh/d3d/GrD3DPipeline.h" #include "src/gpu/ganesh/d3d/GrD3DRenderTarget.h" #include "src/gpu/ganesh/d3d/GrD3DRootSignature.h" #include "src/gpu/ganesh/d3d/GrD3DUtil.h" #include "src/sksl/SkSLCompiler.h" #include "src/utils/SkShaderUtils.h" #include <d3dcompiler.h> std::unique_ptr<GrD3DPipelineState> GrD3DPipelineStateBuilder::MakePipelineState( GrD3DGpu* gpu, GrD3DRenderTarget* renderTarget, const GrProgramDesc& desc, const GrProgramInfo& programInfo) { // ensure that we use "." as a decimal separator when creating SkSL code GrAutoLocaleSetter als("C"); // create a builder. This will be handed off to effects so they can use it to add // uniforms, varyings, textures, etc GrD3DPipelineStateBuilder builder(gpu, renderTarget, desc, programInfo); if (!builder.emitAndInstallProcs()) { return nullptr; } return builder.finalize(); } GrD3DPipelineStateBuilder::GrD3DPipelineStateBuilder(GrD3DGpu* gpu, GrD3DRenderTarget* renderTarget, const GrProgramDesc& desc, const GrProgramInfo& programInfo) : INHERITED(desc, programInfo) , fGpu(gpu) , fVaryingHandler(this) , fUniformHandler(this) , fRenderTarget(renderTarget) {} const GrCaps* GrD3DPipelineStateBuilder::caps() const { return fGpu->caps(); } SkSL::Compiler* GrD3DPipelineStateBuilder::shaderCompiler() const { return fGpu->shaderCompiler(); } void GrD3DPipelineStateBuilder::finalizeFragmentOutputColor(GrShaderVar& outputColor) { outputColor.addLayoutQualifier("location = 0, index = 0"); } void GrD3DPipelineStateBuilder::finalizeFragmentSecondaryColor(GrShaderVar& outputColor) { outputColor.addLayoutQualifier("location = 0, index = 1"); } // Print the source code for all shaders generated. static const bool gPrintSKSL = false; static const bool gPrintHLSL = false; static gr_cp<ID3DBlob> GrCompileHLSLShader(GrD3DGpu* gpu, const std::string& hlsl, SkSL::ProgramKind kind) { TRACE_EVENT0("skia.shaders", "driver_compile_shader"); const char* compileTarget = nullptr; switch (kind) { case SkSL::ProgramKind::kVertex: compileTarget = "vs_5_1"; break; case SkSL::ProgramKind::kFragment: compileTarget = "ps_5_1"; break; default: SkUNREACHABLE; } uint32_t compileFlags = 0; #ifdef SK_DEBUG // Enable better shader debugging with the graphics debugging tools. compileFlags |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION; #endif // SPRIV-cross does matrix multiplication expecting row major matrices compileFlags |= D3DCOMPILE_PACK_MATRIX_ROW_MAJOR; gr_cp<ID3DBlob> shader; gr_cp<ID3DBlob> errors; HRESULT hr = D3DCompile(hlsl.c_str(), hlsl.length(), nullptr, nullptr, nullptr, "main", compileTarget, compileFlags, 0, &shader, &errors); if (!SUCCEEDED(hr)) { gpu->getContext()->priv().getShaderErrorHandler()->compileError( hlsl.c_str(), reinterpret_cast<char*>(errors->GetBufferPointer())); } return shader; } bool GrD3DPipelineStateBuilder::loadHLSLFromCache(SkReadBuffer* reader, gr_cp<ID3DBlob> shaders[]) { std::string hlsl[kGrShaderTypeCount]; SkSL::Program::Inputs inputs[kGrShaderTypeCount]; if (!GrPersistentCacheUtils::UnpackCachedShaders(reader, hlsl, inputs, kGrShaderTypeCount)) { return false; } auto compile = [&](SkSL::ProgramKind kind, GrShaderType shaderType) { if (inputs[shaderType].fUseFlipRTUniform) { this->addRTFlipUniform(SKSL_RTFLIP_NAME); } shaders[shaderType] = GrCompileHLSLShader(fGpu, hlsl[shaderType], kind); return shaders[shaderType].get(); }; return compile(SkSL::ProgramKind::kVertex, kVertex_GrShaderType) && compile(SkSL::ProgramKind::kFragment, kFragment_GrShaderType); } gr_cp<ID3DBlob> GrD3DPipelineStateBuilder::compileD3DProgram( SkSL::ProgramKind kind, const std::string& sksl, const SkSL::Program::Settings& settings, SkSL::Program::Inputs* outInputs, std::string* outHLSL) { #ifdef SK_DEBUG std::string src = SkShaderUtils::PrettyPrint(sksl); #else const std::string& src = sksl; #endif std::unique_ptr<SkSL::Program> program = fGpu->shaderCompiler()->convertProgram( kind, src, settings); if (!program || !fGpu->shaderCompiler()->toHLSL(*program, outHLSL)) { auto errorHandler = fGpu->getContext()->priv().getShaderErrorHandler(); errorHandler->compileError(src.c_str(), fGpu->shaderCompiler()->errorText().c_str()); return gr_cp<ID3DBlob>(); } *outInputs = program->fInputs; if (gPrintSKSL || gPrintHLSL) { SkShaderUtils::PrintShaderBanner(kind); if (gPrintSKSL) { SkDebugf("SKSL:\n"); SkShaderUtils::PrintLineByLine(SkShaderUtils::PrettyPrint(sksl)); } if (gPrintHLSL) { SkDebugf("HLSL:\n"); SkShaderUtils::PrintLineByLine(SkShaderUtils::PrettyPrint(*outHLSL)); } } if (program->fInputs.fUseFlipRTUniform) { this->addRTFlipUniform(SKSL_RTFLIP_NAME); } return GrCompileHLSLShader(fGpu, *outHLSL, kind); } static DXGI_FORMAT attrib_type_to_format(GrVertexAttribType type) { switch (type) { case kFloat_GrVertexAttribType: return DXGI_FORMAT_R32_FLOAT; case kFloat2_GrVertexAttribType: return DXGI_FORMAT_R32G32_FLOAT; case kFloat3_GrVertexAttribType: return DXGI_FORMAT_R32G32B32_FLOAT; case kFloat4_GrVertexAttribType: return DXGI_FORMAT_R32G32B32A32_FLOAT; case kHalf_GrVertexAttribType: return DXGI_FORMAT_R16_FLOAT; case kHalf2_GrVertexAttribType: return DXGI_FORMAT_R16G16_FLOAT; case kHalf4_GrVertexAttribType: return DXGI_FORMAT_R16G16B16A16_FLOAT; case kInt2_GrVertexAttribType: return DXGI_FORMAT_R32G32_SINT; case kInt3_GrVertexAttribType: return DXGI_FORMAT_R32G32B32_SINT; case kInt4_GrVertexAttribType: return DXGI_FORMAT_R32G32B32A32_SINT; case kByte_GrVertexAttribType: return DXGI_FORMAT_R8_SINT; case kByte2_GrVertexAttribType: return DXGI_FORMAT_R8G8_SINT; case kByte4_GrVertexAttribType: return DXGI_FORMAT_R8G8B8A8_SINT; case kUByte_GrVertexAttribType: return DXGI_FORMAT_R8_UINT; case kUByte2_GrVertexAttribType: return DXGI_FORMAT_R8G8_UINT; case kUByte4_GrVertexAttribType: return DXGI_FORMAT_R8G8B8A8_UINT; case kUByte_norm_GrVertexAttribType: return DXGI_FORMAT_R8_UNORM; case kUByte4_norm_GrVertexAttribType: return DXGI_FORMAT_R8G8B8A8_UNORM; case kShort2_GrVertexAttribType: return DXGI_FORMAT_R16G16_SINT; case kShort4_GrVertexAttribType: return DXGI_FORMAT_R16G16B16A16_SINT; case kUShort2_GrVertexAttribType: return DXGI_FORMAT_R16G16_UINT; case kUShort2_norm_GrVertexAttribType: return DXGI_FORMAT_R16G16_UNORM; case kInt_GrVertexAttribType: return DXGI_FORMAT_R32_SINT; case kUInt_GrVertexAttribType: return DXGI_FORMAT_R32_UINT; case kUShort_norm_GrVertexAttribType: return DXGI_FORMAT_R16_UNORM; case kUShort4_norm_GrVertexAttribType: return DXGI_FORMAT_R16G16B16A16_UNORM; } SK_ABORT("Unknown vertex attrib type"); } static void setup_vertex_input_layout(const GrGeometryProcessor& geomProc, D3D12_INPUT_ELEMENT_DESC* inputElements) { unsigned int slotNumber = 0; unsigned int vertexSlot = 0; unsigned int instanceSlot = 0; if (geomProc.hasVertexAttributes()) { vertexSlot = slotNumber++; } if (geomProc.hasInstanceAttributes()) { instanceSlot = slotNumber++; } unsigned int currentAttrib = 0; for (auto attrib : geomProc.vertexAttributes()) { // When using SPIRV-Cross it converts the location modifier in SPIRV to be // TEXCOORD<N> where N is the location value for eveery vertext attribute inputElements[currentAttrib] = { "TEXCOORD", currentAttrib, attrib_type_to_format(attrib.cpuType()), vertexSlot, SkToU32(*attrib.offset()), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }; currentAttrib++; } for (auto attrib : geomProc.instanceAttributes()) { // When using SPIRV-Cross it converts the location modifier in SPIRV to be // TEXCOORD<N> where N is the location value for eveery vertext attribute inputElements[currentAttrib] = { "TEXCOORD", currentAttrib, attrib_type_to_format(attrib.cpuType()), instanceSlot, SkToU32(*attrib.offset()), D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 }; currentAttrib++; } } static D3D12_BLEND blend_coeff_to_d3d_blend(skgpu::BlendCoeff coeff) { switch (coeff) { case skgpu::BlendCoeff::kZero: return D3D12_BLEND_ZERO; case skgpu::BlendCoeff::kOne: return D3D12_BLEND_ONE; case skgpu::BlendCoeff::kSC: return D3D12_BLEND_SRC_COLOR; case skgpu::BlendCoeff::kISC: return D3D12_BLEND_INV_SRC_COLOR; case skgpu::BlendCoeff::kDC: return D3D12_BLEND_DEST_COLOR; case skgpu::BlendCoeff::kIDC: return D3D12_BLEND_INV_DEST_COLOR; case skgpu::BlendCoeff::kSA: return D3D12_BLEND_SRC_ALPHA; case skgpu::BlendCoeff::kISA: return D3D12_BLEND_INV_SRC_ALPHA; case skgpu::BlendCoeff::kDA: return D3D12_BLEND_DEST_ALPHA; case skgpu::BlendCoeff::kIDA: return D3D12_BLEND_INV_DEST_ALPHA; case skgpu::BlendCoeff::kConstC: return D3D12_BLEND_BLEND_FACTOR; case skgpu::BlendCoeff::kIConstC: return D3D12_BLEND_INV_BLEND_FACTOR; case skgpu::BlendCoeff::kS2C: return D3D12_BLEND_SRC1_COLOR; case skgpu::BlendCoeff::kIS2C: return D3D12_BLEND_INV_SRC1_COLOR; case skgpu::BlendCoeff::kS2A: return D3D12_BLEND_SRC1_ALPHA; case skgpu::BlendCoeff::kIS2A: return D3D12_BLEND_INV_SRC1_ALPHA; case skgpu::BlendCoeff::kIllegal: return D3D12_BLEND_ZERO; } SkUNREACHABLE; } static D3D12_BLEND blend_coeff_to_d3d_blend_for_alpha(skgpu::BlendCoeff coeff) { switch (coeff) { // Force all srcColor used in alpha slot to alpha version. case skgpu::BlendCoeff::kSC: return D3D12_BLEND_SRC_ALPHA; case skgpu::BlendCoeff::kISC: return D3D12_BLEND_INV_SRC_ALPHA; case skgpu::BlendCoeff::kDC: return D3D12_BLEND_DEST_ALPHA; case skgpu::BlendCoeff::kIDC: return D3D12_BLEND_INV_DEST_ALPHA; case skgpu::BlendCoeff::kS2C: return D3D12_BLEND_SRC1_ALPHA; case skgpu::BlendCoeff::kIS2C: return D3D12_BLEND_INV_SRC1_ALPHA; default: return blend_coeff_to_d3d_blend(coeff); } } static D3D12_BLEND_OP blend_equation_to_d3d_op(skgpu::BlendEquation equation) { switch (equation) { case skgpu::BlendEquation::kAdd: return D3D12_BLEND_OP_ADD; case skgpu::BlendEquation::kSubtract: return D3D12_BLEND_OP_SUBTRACT; case skgpu::BlendEquation::kReverseSubtract: return D3D12_BLEND_OP_REV_SUBTRACT; default: SkUNREACHABLE; } } static void fill_in_blend_state(const GrPipeline& pipeline, D3D12_BLEND_DESC* blendDesc) { blendDesc->AlphaToCoverageEnable = false; blendDesc->IndependentBlendEnable = false; const GrXferProcessor::BlendInfo& blendInfo = pipeline.getXferProcessor().getBlendInfo(); skgpu::BlendEquation equation = blendInfo.fEquation; skgpu::BlendCoeff srcCoeff = blendInfo.fSrcBlend; skgpu::BlendCoeff dstCoeff = blendInfo.fDstBlend; bool blendOff = skgpu::BlendShouldDisable(equation, srcCoeff, dstCoeff); auto& rtBlend = blendDesc->RenderTarget[0]; rtBlend.BlendEnable = !blendOff; if (!blendOff) { rtBlend.SrcBlend = blend_coeff_to_d3d_blend(srcCoeff); rtBlend.DestBlend = blend_coeff_to_d3d_blend(dstCoeff); rtBlend.BlendOp = blend_equation_to_d3d_op(equation); rtBlend.SrcBlendAlpha = blend_coeff_to_d3d_blend_for_alpha(srcCoeff); rtBlend.DestBlendAlpha = blend_coeff_to_d3d_blend_for_alpha(dstCoeff); rtBlend.BlendOpAlpha = blend_equation_to_d3d_op(equation); } if (!blendInfo.fWriteColor) { rtBlend.RenderTargetWriteMask = 0; } else { rtBlend.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; } } static void fill_in_rasterizer_state(const GrPipeline& pipeline, bool multisampleEnable, const GrCaps* caps, D3D12_RASTERIZER_DESC* rasterizer) { rasterizer->FillMode = (caps->wireframeMode() || pipeline.isWireframe()) ? D3D12_FILL_MODE_WIREFRAME : D3D12_FILL_MODE_SOLID; rasterizer->CullMode = D3D12_CULL_MODE_NONE; rasterizer->FrontCounterClockwise = true; rasterizer->DepthBias = 0; rasterizer->DepthBiasClamp = 0.0f; rasterizer->SlopeScaledDepthBias = 0.0f; rasterizer->DepthClipEnable = false; rasterizer->MultisampleEnable = multisampleEnable; rasterizer->AntialiasedLineEnable = false; rasterizer->ForcedSampleCount = 0; rasterizer->ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; } static D3D12_STENCIL_OP stencil_op_to_d3d_op(GrStencilOp op) { switch (op) { case GrStencilOp::kKeep: return D3D12_STENCIL_OP_KEEP; case GrStencilOp::kZero: return D3D12_STENCIL_OP_ZERO; case GrStencilOp::kReplace: return D3D12_STENCIL_OP_REPLACE; case GrStencilOp::kInvert: return D3D12_STENCIL_OP_INVERT; case GrStencilOp::kIncWrap: return D3D12_STENCIL_OP_INCR; case GrStencilOp::kDecWrap: return D3D12_STENCIL_OP_DECR; case GrStencilOp::kIncClamp: return D3D12_STENCIL_OP_INCR_SAT; case GrStencilOp::kDecClamp: return D3D12_STENCIL_OP_DECR_SAT; } SkUNREACHABLE; } static D3D12_COMPARISON_FUNC stencil_test_to_d3d_func(GrStencilTest test) { switch (test) { case GrStencilTest::kAlways: return D3D12_COMPARISON_FUNC_ALWAYS; case GrStencilTest::kNever: return D3D12_COMPARISON_FUNC_NEVER; case GrStencilTest::kGreater: return D3D12_COMPARISON_FUNC_GREATER; case GrStencilTest::kGEqual: return D3D12_COMPARISON_FUNC_GREATER_EQUAL; case GrStencilTest::kLess: return D3D12_COMPARISON_FUNC_LESS; case GrStencilTest::kLEqual: return D3D12_COMPARISON_FUNC_LESS_EQUAL; case GrStencilTest::kEqual: return D3D12_COMPARISON_FUNC_EQUAL; case GrStencilTest::kNotEqual: return D3D12_COMPARISON_FUNC_NOT_EQUAL; } SkUNREACHABLE; } static void setup_stencilop_desc(D3D12_DEPTH_STENCILOP_DESC* desc, const GrStencilSettings::Face& stencilFace) { desc->StencilFailOp = stencil_op_to_d3d_op(stencilFace.fFailOp); desc->StencilDepthFailOp = desc->StencilFailOp; desc->StencilPassOp = stencil_op_to_d3d_op(stencilFace.fPassOp); desc->StencilFunc = stencil_test_to_d3d_func(stencilFace.fTest); } static void fill_in_depth_stencil_state(const GrProgramInfo& programInfo, D3D12_DEPTH_STENCIL_DESC* dsDesc) { GrStencilSettings stencilSettings = programInfo.nonGLStencilSettings(); GrSurfaceOrigin origin = programInfo.origin(); dsDesc->DepthEnable = false; dsDesc->DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; dsDesc->DepthFunc = D3D12_COMPARISON_FUNC_NEVER; dsDesc->StencilEnable = !stencilSettings.isDisabled(); if (!stencilSettings.isDisabled()) { if (stencilSettings.isTwoSided()) { const auto& frontFace = stencilSettings.postOriginCCWFace(origin); const auto& backFace = stencilSettings.postOriginCWFace(origin); SkASSERT(frontFace.fTestMask == backFace.fTestMask); SkASSERT(frontFace.fWriteMask == backFace.fWriteMask); dsDesc->StencilReadMask = frontFace.fTestMask; dsDesc->StencilWriteMask = frontFace.fWriteMask; setup_stencilop_desc(&dsDesc->FrontFace, frontFace); setup_stencilop_desc(&dsDesc->BackFace, backFace); } else { dsDesc->StencilReadMask = stencilSettings.singleSidedFace().fTestMask; dsDesc->StencilWriteMask = stencilSettings.singleSidedFace().fWriteMask; setup_stencilop_desc(&dsDesc->FrontFace, stencilSettings.singleSidedFace()); dsDesc->BackFace = dsDesc->FrontFace; } } } static D3D12_PRIMITIVE_TOPOLOGY_TYPE gr_primitive_type_to_d3d(GrPrimitiveType primitiveType) { switch (primitiveType) { case GrPrimitiveType::kTriangles: case GrPrimitiveType::kTriangleStrip: //fall through return D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; case GrPrimitiveType::kPoints: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT; case GrPrimitiveType::kLines: // fall through case GrPrimitiveType::kLineStrip: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; case GrPrimitiveType::kPatches: // fall through, unsupported case GrPrimitiveType::kPath: // fall through, unsupported default: SkUNREACHABLE; } } gr_cp<ID3D12PipelineState> create_pipeline_state( GrD3DGpu* gpu, const GrProgramInfo& programInfo, const sk_sp<GrD3DRootSignature>& rootSig, gr_cp<ID3DBlob> vertexShader, gr_cp<ID3DBlob> pixelShader, DXGI_FORMAT renderTargetFormat, DXGI_FORMAT depthStencilFormat, unsigned int sampleQualityPattern) { D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.pRootSignature = rootSig->rootSignature(); psoDesc.VS = { reinterpret_cast<UINT8*>(vertexShader->GetBufferPointer()), vertexShader->GetBufferSize() }; psoDesc.PS = { reinterpret_cast<UINT8*>(pixelShader->GetBufferPointer()), pixelShader->GetBufferSize() }; psoDesc.StreamOutput = { nullptr, 0, nullptr, 0, 0 }; fill_in_blend_state(programInfo.pipeline(), &psoDesc.BlendState); psoDesc.SampleMask = UINT_MAX; fill_in_rasterizer_state(programInfo.pipeline(), programInfo.numSamples() > 1, gpu->caps(), &psoDesc.RasterizerState); fill_in_depth_stencil_state(programInfo, &psoDesc.DepthStencilState); unsigned int totalAttributeCnt = programInfo.geomProc().numVertexAttributes() + programInfo.geomProc().numInstanceAttributes(); SkAutoSTArray<4, D3D12_INPUT_ELEMENT_DESC> inputElements(totalAttributeCnt); setup_vertex_input_layout(programInfo.geomProc(), inputElements.get()); psoDesc.InputLayout = { inputElements.get(), totalAttributeCnt }; psoDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; // This is for geometry or hull shader primitives psoDesc.PrimitiveTopologyType = gr_primitive_type_to_d3d(programInfo.primitiveType()); psoDesc.NumRenderTargets = 1; psoDesc.RTVFormats[0] = renderTargetFormat; psoDesc.DSVFormat = depthStencilFormat; unsigned int numSamples = programInfo.numSamples(); psoDesc.SampleDesc = { numSamples, sampleQualityPattern }; // Only used for multi-adapter systems. psoDesc.NodeMask = 0; psoDesc.CachedPSO = { nullptr, 0 }; psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; gr_cp<ID3D12PipelineState> pipelineState; { TRACE_EVENT0("skia.shaders", "CreateGraphicsPipelineState"); GR_D3D_CALL_ERRCHECK( gpu->device()->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pipelineState))); } return pipelineState; } static constexpr SkFourByteTag kHLSL_Tag = SkSetFourByteTag('H', 'L', 'S', 'L'); static constexpr SkFourByteTag kSKSL_Tag = SkSetFourByteTag('S', 'K', 'S', 'L'); std::unique_ptr<GrD3DPipelineState> GrD3DPipelineStateBuilder::finalize() { TRACE_EVENT0("skia.shaders", TRACE_FUNC); this->finalizeShaders(); SkSL::Program::Settings settings; settings.fSharpenTextures = true; settings.fRTFlipOffset = fUniformHandler.getRTFlipOffset(); settings.fRTFlipBinding = 0; settings.fRTFlipSet = 0; sk_sp<SkData> cached; SkReadBuffer reader; SkFourByteTag shaderType = 0; auto persistentCache = fGpu->getContext()->priv().getPersistentCache(); if (persistentCache) { // Shear off the D3D-specific portion of the Desc to get the persistent key. We only cache // shader code, not entire pipelines. sk_sp<SkData> key = SkData::MakeWithoutCopy(this->desc().asKey(), this->desc().initialKeyLength()); cached = persistentCache->load(*key); if (cached) { reader.setMemory(cached->data(), cached->size()); shaderType = GrPersistentCacheUtils::GetType(&reader); } } const GrGeometryProcessor& geomProc = this->geometryProcessor(); gr_cp<ID3DBlob> shaders[kGrShaderTypeCount]; if (kHLSL_Tag == shaderType && this->loadHLSLFromCache(&reader, shaders)) { // We successfully loaded and compiled HLSL } else { SkSL::Program::Inputs inputs[kGrShaderTypeCount]; std::string* sksl[kGrShaderTypeCount] = { &fVS.fCompilerString, &fFS.fCompilerString, }; std::string cached_sksl[kGrShaderTypeCount]; std::string hlsl[kGrShaderTypeCount]; if (kSKSL_Tag == shaderType) { if (GrPersistentCacheUtils::UnpackCachedShaders(&reader, cached_sksl, inputs, kGrShaderTypeCount)) { for (int i = 0; i < kGrShaderTypeCount; ++i) { sksl[i] = &cached_sksl[i]; } } } auto compile = [&](SkSL::ProgramKind kind, GrShaderType shaderType) { shaders[shaderType] = this->compileD3DProgram(kind, *sksl[shaderType], settings, &inputs[shaderType], &hlsl[shaderType]); return shaders[shaderType].get(); }; if (!compile(SkSL::ProgramKind::kVertex, kVertex_GrShaderType) || !compile(SkSL::ProgramKind::kFragment, kFragment_GrShaderType)) { return nullptr; } if (persistentCache && !cached) { const bool cacheSkSL = fGpu->getContext()->priv().options().fShaderCacheStrategy == GrContextOptions::ShaderCacheStrategy::kSkSL; if (cacheSkSL) { // Replace the HLSL with formatted SkSL to be cached. This looks odd, but this is // the last time we're going to use these strings, so it's safe. for (int i = 0; i < kGrShaderTypeCount; ++i) { hlsl[i] = SkShaderUtils::PrettyPrint(*sksl[i]); } } sk_sp<SkData> key = SkData::MakeWithoutCopy(this->desc().asKey(), this->desc().initialKeyLength()); SkString description = GrProgramDesc::Describe(fProgramInfo, *this->caps()); sk_sp<SkData> data = GrPersistentCacheUtils::PackCachedShaders( cacheSkSL ? kSKSL_Tag : kHLSL_Tag, hlsl, inputs, kGrShaderTypeCount); persistentCache->store(*key, *data, description); } } sk_sp<GrD3DRootSignature> rootSig = fGpu->resourceProvider().findOrCreateRootSignature(fUniformHandler.fTextures.count()); if (!rootSig) { return nullptr; } const GrD3DRenderTarget* rt = static_cast<const GrD3DRenderTarget*>(fRenderTarget); gr_cp<ID3D12PipelineState> pipelineState = create_pipeline_state( fGpu, fProgramInfo, rootSig, std::move(shaders[kVertex_GrShaderType]), std::move(shaders[kFragment_GrShaderType]), rt->dxgiFormat(), rt->stencilDxgiFormat(), rt->sampleQualityPattern()); sk_sp<GrD3DPipeline> pipeline = GrD3DPipeline::Make(std::move(pipelineState)); return std::unique_ptr<GrD3DPipelineState>( new GrD3DPipelineState(std::move(pipeline), std::move(rootSig), fUniformHandles, fUniformHandler.fUniforms, fUniformHandler.fCurrentUBOOffset, fUniformHandler.fSamplers.count(), std::move(fGPImpl), std::move(fXPImpl), std::move(fFPImpls), geomProc.vertexStride(), geomProc.instanceStride())); } sk_sp<GrD3DPipeline> GrD3DPipelineStateBuilder::MakeComputePipeline(GrD3DGpu* gpu, GrD3DRootSignature* rootSig, const char* shader) { D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.pRootSignature = rootSig->rootSignature(); // compile shader gr_cp<ID3DBlob> shaderBlob; { TRACE_EVENT0("skia.shaders", "driver_compile_shader"); uint32_t compileFlags = 0; #ifdef SK_DEBUG // Enable better shader debugging with the graphics debugging tools. compileFlags |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION; #endif gr_cp<ID3DBlob> errors; HRESULT hr = D3DCompile(shader, strlen(shader), nullptr, nullptr, nullptr, "main", "cs_5_1", compileFlags, 0, &shaderBlob, &errors); if (!SUCCEEDED(hr)) { gpu->getContext()->priv().getShaderErrorHandler()->compileError( shader, reinterpret_cast<char*>(errors->GetBufferPointer())); return nullptr; } psoDesc.CS = { reinterpret_cast<UINT8*>(shaderBlob->GetBufferPointer()), shaderBlob->GetBufferSize() }; } // Only used for multi-adapter systems. psoDesc.NodeMask = 0; psoDesc.CachedPSO = { nullptr, 0 }; psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; gr_cp<ID3D12PipelineState> pipelineState; { TRACE_EVENT0("skia.shaders", "CreateComputePipelineState"); GR_D3D_CALL_ERRCHECK( gpu->device()->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&pipelineState))); } return GrD3DPipeline::Make(std::move(pipelineState)); }
39.365439
100
0.667098
JimmySoftware
cb680c2a4f44b30f8779f92f9997901e875fa3c6
6,605
cpp
C++
tag/src/v20180813/model/ResourcesTag.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
tag/src/v20180813/model/ResourcesTag.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
tag/src/v20180813/model/ResourcesTag.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tag/v20180813/model/ResourcesTag.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tag::V20180813::Model; using namespace rapidjson; using namespace std; ResourcesTag::ResourcesTag() : m_resourceRegionHasBeenSet(false), m_serviceTypeHasBeenSet(false), m_resourcePrefixHasBeenSet(false), m_resourceIdHasBeenSet(false), m_tagsHasBeenSet(false) { } CoreInternalOutcome ResourcesTag::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("ResourceRegion") && !value["ResourceRegion"].IsNull()) { if (!value["ResourceRegion"].IsString()) { return CoreInternalOutcome(Error("response `ResourcesTag.ResourceRegion` IsString=false incorrectly").SetRequestId(requestId)); } m_resourceRegion = string(value["ResourceRegion"].GetString()); m_resourceRegionHasBeenSet = true; } if (value.HasMember("ServiceType") && !value["ServiceType"].IsNull()) { if (!value["ServiceType"].IsString()) { return CoreInternalOutcome(Error("response `ResourcesTag.ServiceType` IsString=false incorrectly").SetRequestId(requestId)); } m_serviceType = string(value["ServiceType"].GetString()); m_serviceTypeHasBeenSet = true; } if (value.HasMember("ResourcePrefix") && !value["ResourcePrefix"].IsNull()) { if (!value["ResourcePrefix"].IsString()) { return CoreInternalOutcome(Error("response `ResourcesTag.ResourcePrefix` IsString=false incorrectly").SetRequestId(requestId)); } m_resourcePrefix = string(value["ResourcePrefix"].GetString()); m_resourcePrefixHasBeenSet = true; } if (value.HasMember("ResourceId") && !value["ResourceId"].IsNull()) { if (!value["ResourceId"].IsString()) { return CoreInternalOutcome(Error("response `ResourcesTag.ResourceId` IsString=false incorrectly").SetRequestId(requestId)); } m_resourceId = string(value["ResourceId"].GetString()); m_resourceIdHasBeenSet = true; } if (value.HasMember("Tags") && !value["Tags"].IsNull()) { if (!value["Tags"].IsArray()) return CoreInternalOutcome(Error("response `ResourcesTag.Tags` is not array type")); const Value &tmpValue = value["Tags"]; for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { Tag item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_tags.push_back(item); } m_tagsHasBeenSet = true; } return CoreInternalOutcome(true); } void ResourcesTag::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_resourceRegionHasBeenSet) { Value iKey(kStringType); string key = "ResourceRegion"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_resourceRegion.c_str(), allocator).Move(), allocator); } if (m_serviceTypeHasBeenSet) { Value iKey(kStringType); string key = "ServiceType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_serviceType.c_str(), allocator).Move(), allocator); } if (m_resourcePrefixHasBeenSet) { Value iKey(kStringType); string key = "ResourcePrefix"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_resourcePrefix.c_str(), allocator).Move(), allocator); } if (m_resourceIdHasBeenSet) { Value iKey(kStringType); string key = "ResourceId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_resourceId.c_str(), allocator).Move(), allocator); } if (m_tagsHasBeenSet) { Value iKey(kStringType); string key = "Tags"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kArrayType).Move(), allocator); int i=0; for (auto itr = m_tags.begin(); itr != m_tags.end(); ++itr, ++i) { value[key.c_str()].PushBack(Value(kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } } string ResourcesTag::GetResourceRegion() const { return m_resourceRegion; } void ResourcesTag::SetResourceRegion(const string& _resourceRegion) { m_resourceRegion = _resourceRegion; m_resourceRegionHasBeenSet = true; } bool ResourcesTag::ResourceRegionHasBeenSet() const { return m_resourceRegionHasBeenSet; } string ResourcesTag::GetServiceType() const { return m_serviceType; } void ResourcesTag::SetServiceType(const string& _serviceType) { m_serviceType = _serviceType; m_serviceTypeHasBeenSet = true; } bool ResourcesTag::ServiceTypeHasBeenSet() const { return m_serviceTypeHasBeenSet; } string ResourcesTag::GetResourcePrefix() const { return m_resourcePrefix; } void ResourcesTag::SetResourcePrefix(const string& _resourcePrefix) { m_resourcePrefix = _resourcePrefix; m_resourcePrefixHasBeenSet = true; } bool ResourcesTag::ResourcePrefixHasBeenSet() const { return m_resourcePrefixHasBeenSet; } string ResourcesTag::GetResourceId() const { return m_resourceId; } void ResourcesTag::SetResourceId(const string& _resourceId) { m_resourceId = _resourceId; m_resourceIdHasBeenSet = true; } bool ResourcesTag::ResourceIdHasBeenSet() const { return m_resourceIdHasBeenSet; } vector<Tag> ResourcesTag::GetTags() const { return m_tags; } void ResourcesTag::SetTags(const vector<Tag>& _tags) { m_tags = _tags; m_tagsHasBeenSet = true; } bool ResourcesTag::TagsHasBeenSet() const { return m_tagsHasBeenSet; }
28.106383
139
0.672521
datalliance88
cb691e6d92f3a9a20d483cbfad738dfa15f23b4a
16,699
cpp
C++
src/apps/sequencer/python/sequencer.cpp
forestcaver/performer
17750bc8e6fa23cd806d58a9c519fac25a52473f
[ "MIT" ]
1
2019-04-19T01:34:03.000Z
2019-04-19T01:34:03.000Z
src/apps/sequencer/python/sequencer.cpp
forestcaver/performer
17750bc8e6fa23cd806d58a9c519fac25a52473f
[ "MIT" ]
null
null
null
src/apps/sequencer/python/sequencer.cpp
forestcaver/performer
17750bc8e6fa23cd806d58a9c519fac25a52473f
[ "MIT" ]
null
null
null
#include "SequencerApp.h" #include "model/Model.h" #include <pybind11/pybind11.h> namespace py = pybind11; void register_sequencer(py::module &m) { // ------------------------------------------------------------------------ // Sequencer // ------------------------------------------------------------------------ py::class_<SequencerApp> sequencer(m, "Sequencer"); sequencer .def_property_readonly("model", [] (SequencerApp &app) { return &app.model; }) ; // ------------------------------------------------------------------------ // Model // ------------------------------------------------------------------------ py::class_<Model> model(m, "Model"); model .def_property_readonly("project", [] (Model &model) { return &model.project(); }) ; // ------------------------------------------------------------------------ // Project // ------------------------------------------------------------------------ py::class_<Project> project(m, "Project"); project .def_property("name", &Project::name, &Project::setName) .def_property("slot", &Project::slot, &Project::setSlot) .def_property("tempo", &Project::tempo, &Project::setTempo) .def_property("swing", &Project::swing, &Project::setSwing) .def_property("syncMeasure", &Project::syncMeasure, &Project::setSyncMeasure) .def_property("scale", &Project::scale, &Project::setScale) .def_property("rootNote", &Project::rootNote, &Project::setRootNote) .def_property("recordMode", &Project::recordMode, &Project::setRecordMode) .def_property_readonly("clockSetup", [] (Project &project) { return &project.clockSetup(); }) .def_property_readonly("tracks", [] (Project &project) { py::list result; for (int i = 0; i < CONFIG_TRACK_COUNT; ++i) { result.append(&project.track(i)); } return result; }) .def("cvOutputTrack", &Project::cvOutputTrack) .def("setCvOutputTrack", &Project::setCvOutputTrack) .def("gateOutputTrack", &Project::gateOutputTrack) .def("setGateOutputTrack", &Project::setGateOutputTrack) .def_property_readonly("song", [] (Project &project) { return &project.song(); }) .def_property_readonly("playState", [] (Project &project) { return &project.playState(); }) // TODO userScales .def_property_readonly("routing", [] (Project &project) { return &project.routing(); }) .def_property_readonly("midiOutput", [] (Project &project) { return &project.midiOutput(); }) .def_property("selectedTrackIndex", &Project::selectedTrackIndex, &Project::setSelectedTrackIndex) .def_property("selectedPatternIndex", &Project::selectedPatternIndex, &Project::setSelectedPatternIndex) .def("clear", &Project::clear) .def("clearPattern", &Project::clearPattern) .def("setTrackMode", &Project::setTrackMode) ; // ------------------------------------------------------------------------ // Types // ------------------------------------------------------------------------ py::class_<Types> types(m, "Types"); py::enum_<Types::RecordMode>(types, "RecordMode") .value("Overdub", Types::RecordMode::Overdub) .value("Overwrite", Types::RecordMode::Overwrite) .export_values() ; py::enum_<Types::PlayMode>(types, "PlayMode") .value("Aligned", Types::PlayMode::Aligned) .value("Free", Types::PlayMode::Free) .export_values() ; py::enum_<Types::FillMode>(types, "FillMode") .value("None", Types::FillMode::None) .value("Gates", Types::FillMode::Gates) .value("NextPattern", Types::FillMode::NextPattern) .export_values() ; py::enum_<Types::RunMode>(types, "RunMode") .value("Forward", Types::RunMode::Forward) .value("Backward", Types::RunMode::Backward) .value("Pendulum", Types::RunMode::Pendulum) .value("PingPong", Types::RunMode::PingPong) .value("Random", Types::RunMode::Random) .value("RandomWalk", Types::RunMode::RandomWalk) .export_values() ; py::enum_<Types::VoltageRange>(types, "VoltageRange") .value("Unipolar1V", Types::VoltageRange::Unipolar1V) .value("Unipolar2V", Types::VoltageRange::Unipolar2V) .value("Unipolar3V", Types::VoltageRange::Unipolar3V) .value("Unipolar4V", Types::VoltageRange::Unipolar4V) .value("Unipolar5V", Types::VoltageRange::Unipolar5V) .value("Bipolar1V", Types::VoltageRange::Bipolar1V) .value("Bipolar2V", Types::VoltageRange::Bipolar2V) .value("Bipolar3V", Types::VoltageRange::Bipolar3V) .value("Bipolar4V", Types::VoltageRange::Bipolar4V) .value("Bipolar5V", Types::VoltageRange::Bipolar5V) .export_values() ; // ------------------------------------------------------------------------ // ClockSetup // ------------------------------------------------------------------------ py::class_<ClockSetup> clockSetup(m, "ClockSetup"); clockSetup .def_property("mode", &ClockSetup::mode, &ClockSetup::setMode) .def_property("shiftMode", &ClockSetup::shiftMode, &ClockSetup::setShiftMode) .def_property("clockInputDivisor", &ClockSetup::clockInputDivisor, &ClockSetup::setClockInputDivisor) .def_property("clockInputMode", &ClockSetup::clockInputMode, &ClockSetup::setClockInputMode) .def_property("clockOutputDivisor", &ClockSetup::clockOutputDivisor, &ClockSetup::setClockOutputDivisor) .def_property("clockOutputPulse", &ClockSetup::clockOutputPulse, &ClockSetup::setClockOutputPulse) .def_property("clockOutputMode", &ClockSetup::clockOutputMode, &ClockSetup::setClockOutputMode) .def_property("midiRx", &ClockSetup::midiRx, &ClockSetup::setMidiRx) .def_property("midiTx", &ClockSetup::midiTx, &ClockSetup::setMidiTx) .def_property("usbRx", &ClockSetup::usbRx, &ClockSetup::setUsbRx) .def_property("usbTx", &ClockSetup::usbTx, &ClockSetup::setUsbTx) .def("clear", &ClockSetup::clear) ; py::enum_<ClockSetup::Mode>(clockSetup, "Mode") .value("Auto", ClockSetup::Mode::Auto) .value("Master", ClockSetup::Mode::Master) .value("Slave", ClockSetup::Mode::Slave) .export_values() ; py::enum_<ClockSetup::ShiftMode>(clockSetup, "ShiftMode") .value("Restart", ClockSetup::ShiftMode::Restart) .value("Pause", ClockSetup::ShiftMode::Pause) .export_values() ; py::enum_<ClockSetup::ClockInputMode>(clockSetup, "ClockInputMode") .value("Reset", ClockSetup::ClockInputMode::Reset) .value("Run", ClockSetup::ClockInputMode::Run) .value("StartStop", ClockSetup::ClockInputMode::StartStop) .export_values() ; py::enum_<ClockSetup::ClockOutputMode>(clockSetup, "ClockOutputMode") .value("Reset", ClockSetup::ClockOutputMode::Reset) .value("Run", ClockSetup::ClockOutputMode::Run) .export_values() ; // ------------------------------------------------------------------------ // Track // ------------------------------------------------------------------------ py::class_<Track> track(m, "Track"); track .def_property_readonly("trackIndex", &Track::trackIndex) .def_property_readonly("trackMode", &Track::trackMode) .def_property("linkTrack", &Track::linkTrack, &Track::setLinkTrack) .def_property_readonly("noteTrack", [] (Track &track) { return &track.noteTrack(); }) .def_property_readonly("curveTrack", [] (Track &track) { return &track.curveTrack(); }) .def_property_readonly("midiCvTrack", [] (Track &track) { return &track.midiCvTrack(); }) .def("clear", &Track::clear) .def("clearPattern", &Track::clearPattern) ; py::enum_<Track::TrackMode>(track, "TrackMode") .value("Note", Track::TrackMode::Note) .value("Curve", Track::TrackMode::Curve) .value("MidiCv", Track::TrackMode::MidiCv) .export_values() ; // ------------------------------------------------------------------------ // NoteTrack // ------------------------------------------------------------------------ py::class_<NoteTrack> noteTrack(m, "NoteTrack"); noteTrack .def_property("playMode", &NoteTrack::playMode, &NoteTrack::setPlayMode) .def_property("fillMode", &NoteTrack::fillMode, &NoteTrack::setFillMode) .def_property("slideTime", &NoteTrack::slideTime, &NoteTrack::setSlideTime) .def_property("octave", &NoteTrack::octave, &NoteTrack::setOctave) .def_property("transpose", &NoteTrack::transpose, &NoteTrack::setTranspose) .def_property("rotate", &NoteTrack::rotate, &NoteTrack::setRotate) .def_property("gateProbabilityBias", &NoteTrack::gateProbabilityBias, &NoteTrack::setGateProbabilityBias) .def_property("retriggerProbabilityBias", &NoteTrack::retriggerProbabilityBias, &NoteTrack::setRetriggerProbabilityBias) .def_property("lengthBias", &NoteTrack::lengthBias, &NoteTrack::setLengthBias) .def_property("noteProbabilityBias", &NoteTrack::noteProbabilityBias, &NoteTrack::setNoteProbabilityBias) .def_property_readonly("sequences", [] (NoteTrack &noteTrack) { py::list result; for (int i = 0; i < CONFIG_PATTERN_COUNT; ++i) { result.append(&noteTrack.sequence(i)); } return result; }) .def("clear", &NoteTrack::clear) ; // ------------------------------------------------------------------------ // CurveTrack // ------------------------------------------------------------------------ py::class_<CurveTrack> curveTrack(m, "CurveTrack"); curveTrack .def_property("playMode", &CurveTrack::playMode, &CurveTrack::setPlayMode) .def_property("fillMode", &CurveTrack::fillMode, &CurveTrack::setFillMode) .def_property("rotate", &CurveTrack::rotate, &CurveTrack::setRotate) .def_property_readonly("sequences", [] (CurveTrack &curveTrack) { py::list result; for (int i = 0; i < CONFIG_PATTERN_COUNT; ++i) { result.append(&curveTrack.sequence(i)); } return result; }) .def("clear", &CurveTrack::clear) ; // ------------------------------------------------------------------------ // MidiCvTrack // ------------------------------------------------------------------------ py::class_<MidiCvTrack> midiCvTrack(m, "MidiCvTrack"); midiCvTrack .def_property_readonly("source", [] (MidiCvTrack &midiCvTrack) { return &midiCvTrack.source(); }) .def_property("voices", &MidiCvTrack::voices, &MidiCvTrack::setVoices) .def_property("voiceConfig", &MidiCvTrack::voiceConfig, &MidiCvTrack::setVoiceConfig) .def_property("pitchBendRange", &MidiCvTrack::pitchBendRange, &MidiCvTrack::setPitchBendRange) .def_property("modulationRange", &MidiCvTrack::modulationRange, &MidiCvTrack::setModulationRange) .def_property("retrigger", &MidiCvTrack::retrigger, &MidiCvTrack::setRetrigger) .def("clear", &MidiCvTrack::clear) ; py::enum_<MidiCvTrack::VoiceConfig>(midiCvTrack, "VoiceConfig") .value("Pitch", MidiCvTrack::VoiceConfig::Pitch) .value("PitchVelocity", MidiCvTrack::VoiceConfig::PitchVelocity) .value("PitchVelocityPressure", MidiCvTrack::VoiceConfig::PitchVelocityPressure) .export_values() ; // ------------------------------------------------------------------------ // NoteSequence // ------------------------------------------------------------------------ py::class_<NoteSequence> noteSequence(m, "NoteSequence"); noteSequence .def_property("scale", &NoteSequence::scale, &NoteSequence::setScale) .def_property("rootNote", &NoteSequence::rootNote, &NoteSequence::setRootNote) .def_property("divisor", &NoteSequence::divisor, &NoteSequence::setDivisor) .def_property("resetMeasure", &NoteSequence::resetMeasure, &NoteSequence::setResetMeasure) .def_property("runMode", &NoteSequence::runMode, &NoteSequence::setRunMode) .def_property("firstStep", &NoteSequence::firstStep, &NoteSequence::setFirstStep) .def_property("lastStep", &NoteSequence::lastStep, &NoteSequence::setLastStep) .def_property_readonly("steps", [] (NoteSequence &noteSequence) { py::list result; for (int i = 0; i < CONFIG_STEP_COUNT; ++i) { result.append(&noteSequence.step(i)); } return result; }) .def("clear", &NoteSequence::clear) .def("clearSteps", &NoteSequence::clearSteps) ; py::class_<NoteSequence::Step> noteSequenceStep(noteSequence, "Step"); noteSequenceStep .def_property("gate", &NoteSequence::Step::gate, &NoteSequence::Step::setGate) .def_property("gateProbability", &NoteSequence::Step::gateProbability, &NoteSequence::Step::setGateProbability) .def_property("slide", &NoteSequence::Step::slide, &NoteSequence::Step::setSlide) .def_property("retrigger", &NoteSequence::Step::retrigger, &NoteSequence::Step::setRetrigger) .def_property("retriggerProbability", &NoteSequence::Step::retriggerProbability, &NoteSequence::Step::setRetriggerProbability) .def_property("length", &NoteSequence::Step::length, &NoteSequence::Step::setLength) .def_property("lengthVariationRange", &NoteSequence::Step::lengthVariationRange, &NoteSequence::Step::setLengthVariationRange) .def_property("lengthVariationProbability", &NoteSequence::Step::lengthVariationProbability, &NoteSequence::Step::setLengthVariationProbability) .def_property("note", &NoteSequence::Step::note, &NoteSequence::Step::setNote) .def_property("noteVariationRange", &NoteSequence::Step::noteVariationRange, &NoteSequence::Step::setNoteVariationRange) .def_property("noteVariationProbability", &NoteSequence::Step::noteVariationProbability, &NoteSequence::Step::setNoteVariationProbability) .def("clear", &NoteSequence::Step::clear) ; // ------------------------------------------------------------------------ // CurveSequence // ------------------------------------------------------------------------ py::class_<CurveSequence> curveSequence(m, "CurveSequence"); curveSequence .def_property("range", &CurveSequence::range, &CurveSequence::setRange) .def_property("divisor", &CurveSequence::divisor, &CurveSequence::setDivisor) .def_property("resetMeasure", &CurveSequence::resetMeasure, &CurveSequence::setResetMeasure) .def_property("runMode", &CurveSequence::runMode, &CurveSequence::setRunMode) .def_property("firstStep", &CurveSequence::firstStep, &CurveSequence::setFirstStep) .def_property("lastStep", &CurveSequence::lastStep, &CurveSequence::setLastStep) .def_property_readonly("steps", [] (CurveSequence &curveSequence) { py::list result; for (int i = 0; i < CONFIG_STEP_COUNT; ++i) { result.append(&curveSequence.step(i)); } return result; }) .def("clear", &CurveSequence::clear) .def("clearSteps", &CurveSequence::clearSteps) ; py::class_<CurveSequence::Step> curveSequenceStep(curveSequence, "Step"); curveSequenceStep .def_property("shape", &CurveSequence::Step::shape, &CurveSequence::Step::setShape) .def_property("min", &CurveSequence::Step::min, &CurveSequence::Step::setMin) .def_property("max", &CurveSequence::Step::max, &CurveSequence::Step::setMax) .def("clear", &CurveSequence::Step::clear) ; // ------------------------------------------------------------------------ // Song // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // PlayState // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Routing // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // MidiOutput // ------------------------------------------------------------------------ }
49.259587
152
0.565243
forestcaver
cb697c77faa2819c8e8d38ca4485f7ea793d8b14
5,064
cpp
C++
libs/variant/test/rvalue_test.cpp
juslee/boost-svn
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
[ "BSL-1.0" ]
null
null
null
libs/variant/test/rvalue_test.cpp
juslee/boost-svn
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
[ "BSL-1.0" ]
null
null
null
libs/variant/test/rvalue_test.cpp
juslee/boost-svn
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
[ "BSL-1.0" ]
null
null
null
//----------------------------------------------------------------------------- // boost-libs variant/test/rvalue_test.cpp source file // See http://www.boost.org for updates, documentation, and revision history. //----------------------------------------------------------------------------- // // Copyright (c) 2012 // Antony Polukhin // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "boost/config.hpp" #include "boost/test/minimal.hpp" #include "boost/variant.hpp" // This test requires BOOST_HAS_RVALUE_REFS #ifndef BOOST_HAS_RVALUE_REFS void run() { BOOST_CHECK(true); } #else class move_copy_conting_class { public: static unsigned int moves_count; static unsigned int copy_count; move_copy_conting_class(){} move_copy_conting_class(move_copy_conting_class&&) { ++ moves_count; } move_copy_conting_class& operator=(move_copy_conting_class&&) { ++ moves_count; return *this; } move_copy_conting_class(const move_copy_conting_class&) { ++ copy_count; } move_copy_conting_class& operator=(const move_copy_conting_class&) { ++ copy_count; return *this; } }; unsigned int move_copy_conting_class::moves_count = 0; unsigned int move_copy_conting_class::copy_count = 0; void run() { typedef boost::variant<int, move_copy_conting_class> variant_I_type; variant_I_type v1, v2; // Assuring that `move_copy_conting_class` was not created BOOST_CHECK(move_copy_conting_class::copy_count == 0); BOOST_CHECK(move_copy_conting_class::moves_count == 0); v1 = move_copy_conting_class(); // Assuring that `move_copy_conting_class` was moved at least once BOOST_CHECK(move_copy_conting_class::moves_count != 0); unsigned int total_count = move_copy_conting_class::moves_count + move_copy_conting_class::copy_count; move_copy_conting_class var; v1 = 0; move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v1 = var; // Assuring that move assignment operator moves/copyes value not more times than copy assignment operator BOOST_CHECK(total_count <= move_copy_conting_class::moves_count + move_copy_conting_class::copy_count); move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v2 = static_cast<variant_I_type&&>(v1); // Assuring that `move_copy_conting_class` in v1 was moved at least once and was not copied BOOST_CHECK(move_copy_conting_class::moves_count != 0); BOOST_CHECK(move_copy_conting_class::copy_count == 0); v1 = move_copy_conting_class(); move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v2 = static_cast<variant_I_type&&>(v1); // Assuring that `move_copy_conting_class` in v1 was moved at least once and was not copied BOOST_CHECK(move_copy_conting_class::moves_count != 0); BOOST_CHECK(move_copy_conting_class::copy_count == 0); total_count = move_copy_conting_class::moves_count + move_copy_conting_class::copy_count; move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v1 = v2; // Assuring that move assignment operator moves/copyes value not more times than copy assignment operator BOOST_CHECK(total_count <= move_copy_conting_class::moves_count + move_copy_conting_class::copy_count); typedef boost::variant<move_copy_conting_class, int> variant_II_type; variant_II_type v3; move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v1 = static_cast<variant_II_type&&>(v3); // Assuring that `move_copy_conting_class` in v3 was moved at least once (v1 and v3 have different types) BOOST_CHECK(move_copy_conting_class::moves_count != 0); move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v2 = static_cast<variant_I_type&&>(v1); // Assuring that `move_copy_conting_class` in v1 was moved at least once (v1 and v3 have different types) BOOST_CHECK(move_copy_conting_class::moves_count != 0); move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; variant_I_type v5(static_cast<variant_I_type&&>(v1)); // Assuring that `move_copy_conting_class` in v1 was moved at least once and was not copied BOOST_CHECK(move_copy_conting_class::moves_count != 0); BOOST_CHECK(move_copy_conting_class::copy_count == 0); total_count = move_copy_conting_class::moves_count + move_copy_conting_class::copy_count; move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; variant_I_type v6(v1); // Assuring that move constructor moves/copyes value not more times than copy constructor BOOST_CHECK(total_count <= move_copy_conting_class::moves_count + move_copy_conting_class::copy_count); } #endif int test_main(int , char* []) { run(); return 0; }
36.963504
109
0.720182
juslee
cb6a19f9d53d524703bf6ff2cd44ea4655a5d8d4
696
cpp
C++
#1059 Prime Factors.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
1
2021-12-26T08:34:47.000Z
2021-12-26T08:34:47.000Z
#1059 Prime Factors.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
null
null
null
#1059 Prime Factors.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> int main() { size_t num; if(!scanf("%zu", &num)) return 0; std::vector<bool> isPrime(50000, true); isPrime[0] = isPrime[1] = false; for(size_t i = 2; i < 50000; ++i) { if(!isPrime[i]) continue; for(size_t j = 2 * i; j < 50000; j *= 2) isPrime[j] = false; } printf("%zu=", num); if(num == 1) putchar('1'); for(size_t i = 2, n = num, exp; i < 50000 && n != 1; ++i) { if(!isPrime[i] || n % i != 0) continue; if(n != num) putchar('*'); for(exp = 0; n % i == 0; ++exp) n /= i; printf("%zu", i); if(exp != 1) printf("^%zu", exp); } putchar('\n'); return 0; }
27.84
68
0.465517
ZachVec
cb6a6e0d94bd252250f45486b117b886d3441738
3,651
hpp
C++
ThirdParty/pegtl/vtkpegtl/include/tao/pegtl/contrib/parse_tree_to_dot.hpp
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
1,755
2015-01-03T06:55:00.000Z
2022-03-29T05:23:26.000Z
ThirdParty/pegtl/vtkpegtl/include/tao/pegtl/contrib/parse_tree_to_dot.hpp
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
1,110
2015-04-20T19:30:34.000Z
2020-06-01T08:13:52.000Z
ThirdParty/pegtl/vtkpegtl/include/tao/pegtl/contrib/parse_tree_to_dot.hpp
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
1,044
2015-01-05T22:48:27.000Z
2022-03-31T02:38:26.000Z
// Copyright (c) 2019-2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_CONTRIB_PARSE_TREE_TO_DOT_HPP #define TAO_PEGTL_CONTRIB_PARSE_TREE_TO_DOT_HPP #include <cassert> #include <ostream> #include <string> #include "parse_tree.hpp" namespace tao { namespace TAO_PEGTL_NAMESPACE { namespace parse_tree { namespace internal { inline void escape( std::ostream& os, const char* p, const std::size_t s ) { static const char* h = "0123456789abcdef"; const char* l = p; const char* const e = p + s; while( p != e ) { const unsigned char c = *p; if( c == '\\' ) { os.write( l, p - l ); l = ++p; os << "\\\\"; } else if( c == '"' ) { os.write( l, p - l ); l = ++p; os << "\\\""; } else if( c < 32 ) { os.write( l, p - l ); l = ++p; switch( c ) { case '\b': os << "\\b"; break; case '\f': os << "\\f"; break; case '\n': os << "\\n"; break; case '\r': os << "\\r"; break; case '\t': os << "\\t"; break; default: os << "\\u00" << h[ ( c & 0xf0 ) >> 4 ] << h[ c & 0x0f ]; } } else if( c == 127 ) { os.write( l, p - l ); l = ++p; os << "\\u007f"; } else { ++p; } } os.write( l, p - l ); } inline void escape( std::ostream& os, const std::string& s ) { escape( os, s.data(), s.size() ); } template< typename Node > void print_dot_node( std::ostream& os, const Node& n, const std::string& s ) { os << " x" << &n << " [ label=\""; escape( os, s ); if( n.has_content() ) { os << "\\n"; escape( os, n.m_begin.data, n.m_end.data - n.m_begin.data ); } os << "\" ]\n"; if( !n.children.empty() ) { os << " x" << &n << " -> { "; for( auto& up : n.children ) { os << "x" << up.get() << ( ( up == n.children.back() ) ? " }\n" : ", " ); } for( auto& up : n.children ) { print_dot_node( os, *up, up->name() ); } } } } // namespace internal template< typename Node > void print_dot( std::ostream& os, const Node& n ) { os << "digraph parse_tree\n{\n"; internal::print_dot_node( os, n, n.is_root() ? "ROOT" : n.name() ); os << "}\n"; } } // namespace parse_tree } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #endif
31.205128
94
0.325938
cclauss
cb6af83f1807b38ebb0333de2396014c2f838543
21,064
cpp
C++
library/property/test/src/test_tetengo.property.property_set.cpp
kaorut/tetengo
3360cce3e3f4c92b18154927685986c1fa7b4e8e
[ "MIT" ]
null
null
null
library/property/test/src/test_tetengo.property.property_set.cpp
kaorut/tetengo
3360cce3e3f4c92b18154927685986c1fa7b4e8e
[ "MIT" ]
153
2019-08-11T05:26:36.000Z
2021-06-23T17:24:04.000Z
library/property/test/src/test_tetengo.property.property_set.cpp
kaorut/tetengo
3360cce3e3f4c92b18154927685986c1fa7b4e8e
[ "MIT" ]
null
null
null
/*! \file \brief A property set. Copyright (C) 2019-2021 kaoru https://www.tetengo.org/ */ #include <cstdint> #include <filesystem> #include <iterator> #include <memory> #include <optional> #include <string> #include <string_view> #include <utility> #include <vector> #include <stddef.h> #include <boost/preprocessor.hpp> #include <boost/scope_exit.hpp> #include <boost/test/unit_test.hpp> #include <tetengo/property/memory_storage.hpp> #include <tetengo/property/propertySet.h> #include <tetengo/property/property_set.hpp> #include <tetengo/property/storage.h> #include <tetengo/property/storage.hpp> namespace { const std::filesystem::path& property_set_path() { static const std::filesystem::path singleton{ "test_tetengo.property.property_set" }; return singleton; } } BOOST_AUTO_TEST_SUITE(test_tetengo) BOOST_AUTO_TEST_SUITE(property) BOOST_AUTO_TEST_SUITE(property_set) BOOST_AUTO_TEST_CASE(construction) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); const tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST(p_property_set); } } BOOST_AUTO_TEST_CASE(get_bool) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); const tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; const auto o_value = property_set_.get_bool("alpha"); BOOST_CHECK(!o_value); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); auto value = static_cast<int>(0); const auto result = tetengo_property_propertySet_getBool(p_property_set, "alpha", &value); BOOST_TEST(!result); } { auto value = static_cast<int>(0); const auto result = tetengo_property_propertySet_getBool(nullptr, "alpha", &value); BOOST_TEST(!result); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); auto value = static_cast<int>(0); const auto result = tetengo_property_propertySet_getBool(p_property_set, nullptr, &value); BOOST_TEST(!result); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); const auto result = tetengo_property_propertySet_getBool(p_property_set, "alpha", nullptr); BOOST_TEST(!result); } } BOOST_AUTO_TEST_CASE(set_bool) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; property_set_.set_bool("alpha", false); const auto o_value = property_set_.get_bool("alpha"); BOOST_REQUIRE(o_value); BOOST_TEST(!*o_value); } { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; property_set_.set_bool("alpha", true); const auto o_value = property_set_.get_bool("alpha"); BOOST_REQUIRE(o_value); BOOST_TEST(*o_value); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setBool(p_property_set, "alpha", 0); auto value = static_cast<int>(0); const auto result = tetengo_property_propertySet_getBool(p_property_set, "alpha", &value); BOOST_TEST_REQUIRE(result); BOOST_TEST(!value); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setBool(p_property_set, "alpha", 1); auto value = static_cast<int>(0); const auto result = tetengo_property_propertySet_getBool(p_property_set, "alpha", &value); BOOST_TEST_REQUIRE(result); BOOST_TEST(value); } { tetengo_property_propertySet_setBool(nullptr, "alpha", 0); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setBool(p_property_set, nullptr, 0); } } BOOST_AUTO_TEST_CASE(get_uint32) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); const tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; const auto o_value = property_set_.get_uint32("bravo"); BOOST_CHECK(!o_value); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set, "alpha", &value); BOOST_TEST(!result); } { auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(nullptr, "alpha", &value); BOOST_TEST(!result); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set, nullptr, &value); BOOST_TEST(!result); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); const auto result = tetengo_property_propertySet_getUint32(p_property_set, "alpha", nullptr); BOOST_TEST(!result); } } BOOST_AUTO_TEST_CASE(set_uint32) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; property_set_.set_uint32("bravo", 42); const auto o_value = property_set_.get_uint32("bravo"); BOOST_REQUIRE(o_value); BOOST_TEST(*o_value == 42U); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setUint32(p_property_set, "bravo", 42); auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set, "bravo", &value); BOOST_TEST_REQUIRE(result); BOOST_TEST(value == 42U); } { tetengo_property_propertySet_setUint32(nullptr, "bravo", 0); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setUint32(p_property_set, nullptr, 0); } } BOOST_AUTO_TEST_CASE(get_string) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); const tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; const auto o_value = property_set_.get_string("charlie"); BOOST_CHECK(!o_value); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); const auto length = tetengo_property_propertySet_getString(p_property_set, "charlie", nullptr, 0); BOOST_TEST(length == static_cast<size_t>(-1)); } { const auto length = tetengo_property_propertySet_getString(nullptr, "charlie", nullptr, 0); BOOST_TEST(length == static_cast<size_t>(-1)); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); const auto length = tetengo_property_propertySet_getString(p_property_set, nullptr, nullptr, 0); BOOST_TEST(length == static_cast<size_t>(-1)); } } BOOST_AUTO_TEST_CASE(set_string) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; property_set_.set_string("charlie", "hoge"); const auto o_value = property_set_.get_string("charlie"); BOOST_REQUIRE(o_value); BOOST_TEST(*o_value == "hoge"); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setString(p_property_set, "charlie", "hoge"); const auto length = tetengo_property_propertySet_getString(p_property_set, "charlie", nullptr, 0); BOOST_TEST_REQUIRE(length == 4U); std::vector<char> value(length + 1, '\0'); const auto length_again = tetengo_property_propertySet_getString(p_property_set, "charlie", std::data(value), std::size(value)); BOOST_TEST_REQUIRE(length_again == length); BOOST_TEST((std::string_view{ std::data(value), length } == "hoge")); } { tetengo_property_propertySet_setString(nullptr, "charlie", "hoge"); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setString(p_property_set, nullptr, "hoge"); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setString(p_property_set, "charlie", nullptr); } } BOOST_AUTO_TEST_CASE(update) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader1 = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set1{ std::move(p_storage_loader1), property_set_path() }; auto p_storage_loader2 = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set2{ std::move(p_storage_loader2), property_set_path() }; property_set1.set_uint32("hoge.cpp", 42); property_set1.commit(); { const auto o_value = property_set2.get_uint32("hoge.cpp"); BOOST_CHECK(!o_value); } property_set2.update(); { const auto o_value = property_set2.get_uint32("hoge.cpp"); BOOST_REQUIRE(o_value); BOOST_TEST(*o_value == 42U); } } { auto* const p_storage_loader1 = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set1 = tetengo_property_propertySet_create(p_storage_loader1, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set1) { tetengo_property_propertySet_destroy(p_property_set1); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set1); auto* const p_storage_loader2 = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set2 = tetengo_property_propertySet_create(p_storage_loader2, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set2) { tetengo_property_propertySet_destroy(p_property_set2); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set2); tetengo_property_propertySet_setUint32(p_property_set1, "hoge", 42); tetengo_property_propertySet_commit(p_property_set1); { auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set2, "hoge", &value); BOOST_TEST(!result); } tetengo_property_propertySet_update(p_property_set2); { auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set2, "hoge", &value); BOOST_TEST_REQUIRE(result); BOOST_TEST(value == 42U); } } } BOOST_AUTO_TEST_CASE(commit) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; property_set_.set_uint32("hoge.cpp", 42); property_set_.commit(); } { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); const tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; const auto o_value = property_set_.get_uint32("hoge.cpp"); BOOST_REQUIRE(o_value); BOOST_TEST(*o_value == 42U); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setUint32(p_property_set, "hoge", 42); tetengo_property_propertySet_commit(p_property_set); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set, "hoge", &value); BOOST_TEST_REQUIRE(result); BOOST_TEST(value == 42U); } } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
38.437956
121
0.664214
kaorut
cb6c2f31090c6ea33cabe18bf1054a7f947f9895
1,054
inl
C++
src/ComponentWrapper.inl
vis4rd/ecs
ef32770d93ef5a24dcf056032fc75a40077dcddc
[ "MIT" ]
null
null
null
src/ComponentWrapper.inl
vis4rd/ecs
ef32770d93ef5a24dcf056032fc75a40077dcddc
[ "MIT" ]
null
null
null
src/ComponentWrapper.inl
vis4rd/ecs
ef32770d93ef5a24dcf056032fc75a40077dcddc
[ "MIT" ]
null
null
null
namespace ecs { template <typename ComponentT> ComponentWrapper<ComponentT>::ComponentWrapper(const uint64 &entity_id) : m_component(), m_entityID(entity_id) { } template <typename ComponentT> ComponentWrapper<ComponentT>::ComponentWrapper(const ComponentT &comp) : m_component(comp), m_entityID(0) { } template <typename ComponentT> const ComponentT &ComponentWrapper<ComponentT>::operator()() const { return m_component; } template <typename ComponentT> ComponentT &ComponentWrapper<ComponentT>::operator()() { return m_component; } template <typename ComponentT> const uint64 &ComponentWrapper<ComponentT>::eID() const { return m_entityID; } template <typename ComponentT> const ComponentT &ComponentWrapper<ComponentT>::eComponent() const { return m_component; } template <typename ComponentT> ComponentT &ComponentWrapper<ComponentT>::eComponent() { return m_component; } template <typename ComponentT> void ComponentWrapper<ComponentT>::printType() const { std::cout << util::type_name_to_string<ComponentT>(); } } // namespace ecs
20.666667
71
0.781784
vis4rd
cb6c3806ae14398a4db0b47f3d8235ed4db43c00
7,313
cpp
C++
Current/773_Sliding_Puzzle/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
3
2019-09-21T16:25:44.000Z
2021-08-29T20:43:57.000Z
Current/773_Sliding_Puzzle/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
null
null
null
Current/773_Sliding_Puzzle/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <map> #include <queue> #include <string> #include <unordered_map> #include <unordered_set> using namespace std; //// 83.56% , 100.00% class Solution { public: int slidingPuzzle(vector<vector<int>>& board) { string final_state = "123450"; unordered_set<string> visited; vector<vector<int>> possible_step = { {1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4} }; string myboard; for (auto &row : board) { for (auto & x : row) myboard+=to_string(x); } int position_0 = 0; for (int i = 0; i < myboard.length(); ++i) { if (myboard[i] == '0') { position_0 = i; break; } } queue<tuple<int, string, int>> bas; // <position_0, board, level> bas.emplace(make_tuple(position_0, myboard, 0)); visited.insert(myboard); int tmp_position_0; string tmp_board; int cur_level; while (!bas.empty()) { tie(tmp_position_0, tmp_board, cur_level) = bas.front(); bas.pop(); if (tmp_board == final_state) return cur_level; for (auto & possible_position : possible_step[tmp_position_0]) { swap(tmp_board[possible_position], tmp_board[tmp_position_0]); if (visited.find(tmp_board) == visited.end()) { bas.emplace(make_tuple(possible_position, tmp_board, cur_level+1)); visited.insert(tmp_board); } swap(tmp_board[possible_position], tmp_board[tmp_position_0]); } } return -1; } }; //// 27.45%, 16.67% //// convert to 1-d vector //class Solution { //private: // vector<int> final_state{1,2,3,4,5,0}; // map<vector<int>, int> visited; // <board, level> // map<int, vector<int>> possible_step; // //public: // int slidingPuzzle(vector<vector<int>>& board) { // possible_step[0] = vector<int>{1,3}; // possible_step[1] = vector<int>{0,2,4}; // possible_step[2] = vector<int>{1,5}; // possible_step[3] = vector<int>{0,4}; // possible_step[4] = vector<int>{1,3,5}; // possible_step[5] = vector<int>{2,4}; // // vector<int> myboard; // for (auto &row : board) // { // for (auto & x : row) // { // myboard.emplace_back(x); // } // } // int position_0 = 0; // for (int i = 0; i < 6; ++i) // { // if (myboard[i] == 0) // { // position_0 = i; break; // } // } // // queue<pair<int, vector<int>>> bas; // bas.push(make_pair(position_0, myboard)); // visited[myboard] = 0; // while (!bas.empty()) // { // pair<int, vector<int>> cur = bas.front(); // bas.pop(); // if (cur.second == final_state) return visited[cur.second]; // vector<pair<int, vector<int>>> next_states; // for (auto & possible_position : possible_step[cur.first]) // { // vector<int> tmp = cur.second; // swap(tmp[possible_position], tmp[cur.first]); // next_states.emplace_back(make_pair(possible_position, tmp)); // } // // for (auto &next_state : next_states) // { // if (visited.find(next_state.second) == visited.end()) // { // bas.emplace(next_state); // visited[next_state.second] = visited[cur.second]+1; // } // } // } // return -1; // } //}; //// 7.2%, 16.67% //// bfs, can optimize by turning vector<vector<int>> board into string (or just one-dimensional vector) //class Solution { //private: // vector<vector<int>> move_step{{0,1},{1,0},{0,-1},{-1,0}}; // vector<vector<int>> final_state{{1,2,3},{4,5,0}}; // map<vector<vector<int>>, int> visited; // <board, level> // map<vector<int>, vector<vector<int>>> possible_step; // // vector<pair<vector<int>, vector<vector<int>>>> find_next_states(pair<vector<int>, vector<vector<int>>> &val) // { // vector<pair<vector<int>, vector<vector<int>>>> res; // for (auto & next_position : possible_step[val.first]) // { // vector<vector<int>> tmp_state = val.second; // int tmp = val.second[next_position[0]][next_position[1]]; // tmp_state[next_position[0]][next_position[1]] = 0; // tmp_state[val.first[0]][val.first[1]] = tmp; // res.emplace_back(make_pair(next_position, tmp_state)); // } // return res; // } // // static void print_board(vector<vector<int>> &board) // { // cout << board[0][0] << " " << board[0][1] << " " << board[0][2] << '\n'; // cout << board[1][0] << " " << board[1][1] << " " << board[1][2] << "\n\n"; // } // //public: // int slidingPuzzle(vector<vector<int>>& board) { // vector<int> position_0 = vector<int>(2,0); // for (int i = 0; i < board.size(); ++i) // { // for (int j = 0; j < board[0].size(); ++j) // { // if (board[i][j] == 0) // { // position_0[0] = i; position_0[1] = j; // } // } // } // // cout << "initial position at " << position_0[0] << " " << position_0[1] << '\n'; // // possible_step[{0,0}] = vector<vector<int>>{{0,1}, {1,0}}; // possible_step[{0,1}] = vector<vector<int>>{{0,0}, {0,2}, {1,1}}; // possible_step[{0,2}] = vector<vector<int>>{{0,1}, {1,2}}; // possible_step[{1,0}] = vector<vector<int>>{{0,0}, {1,1}}; // possible_step[{1,1}] = vector<vector<int>>{{0,1}, {1,0}, {1,2}}; // possible_step[{1,2}] = vector<vector<int>>{{0,2}, {1,1}}; // // queue<pair<vector<int>, vector<vector<int>>>> bas; // bas.push(make_pair(position_0, board)); // visited[board] = 0; // while (!bas.empty()) // { // pair<vector<int>, vector<vector<int>>> cur = bas.front(); // bas.pop(); //// print_board(cur.second); // if (cur.second == final_state) return visited[cur.second]; // if (visited[cur.second] > 18) return -1; // vector<pair<vector<int>, vector<vector<int>>>> next_states = find_next_states(cur); // for (auto &next_state : next_states) // { // if (visited.find(next_state.second) == visited.end()) // { // bas.emplace(next_state); // visited[next_state.second] = visited[cur.second]+1; // } // } // } // return -1; // } //}; int main() { vector<vector<int>> test_board = {{1,2,3},{4,0,5}}; // vector<vector<int>> test_board = {{3,2,4},{1,5,0}}; // vector<vector<int>> test_board = {{4,1,2},{5,0,3}}; // vector<vector<int>> test_board = {{1,2,3},{5,4,0}}; Solution test; cout << test.slidingPuzzle(test_board); return 0; }
34.013953
114
0.484069
camelboat
cb6cba189bc797f73a004a5045c8242f5be2ae05
2,661
hpp
C++
api/mraa/common.hpp
rwaldron/mraa
df05dc58caf3985ef2c3b86a635f4579150e984f
[ "MIT" ]
null
null
null
api/mraa/common.hpp
rwaldron/mraa
df05dc58caf3985ef2c3b86a635f4579150e984f
[ "MIT" ]
null
null
null
api/mraa/common.hpp
rwaldron/mraa
df05dc58caf3985ef2c3b86a635f4579150e984f
[ "MIT" ]
2
2015-03-29T23:20:44.000Z
2021-03-29T17:22:43.000Z
/* * Author: Thomas Ingleby <thomas.c.ingleby@intel.com> * Copyright (c) 2014 Intel Corporation. * * 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. */ #pragma once #include "common.h" #include <string> namespace mraa { /** * @file * @brief C++ API to common functions of MRAA * * This file defines the C++ interface for libmraa common functions */ /** * Get libmraa version. * * @return libmraa version (e.g. v0.4.0-20-gb408207) */ std::string getVersion() { std::string ret = mraa_get_version(); return ret; } /** * This function attempts to set the mraa process to a given priority and the * scheduler to SCHED_RR. Highest * priority is typically 99 and minimum is 0. * This function * will set to MAX if * priority is > MAX. Function will return * -1 on failure. * * @param priority Value from typically 0 to 99 * @return The priority value set */ int setPriority(const unsigned int priority) { return mraa_set_priority(priority); } /** * Get platform type, board must be initialised. * * @return mraa_platform_t Platform type enum */ mraa_platform_t getPlatformType() { return mraa_get_platform_type(); } /** * Print a textual representation of the mraa_result_t * * @param result the result to print */ void printError(mraa_result_t result) { mraa_result_print(result); } /** * Checks if a pin is able to use the passed in mode. * * @param pin Physical Pin to be checked. * @param mode the mode to be tested. * @return boolean if the mode is supported, 0=false. */ bool pinModeTest(int pin, mraa_pinmodes_t mode) { return (bool) mraa_pin_mode_test(pin,mode); } }
27.43299
79
0.725667
rwaldron
cb6ef70105e91a1081e5eb9f7d6764262921806a
5,114
cpp
C++
messageprovider.cpp
dhdhxji/SBP_client
64ec057bd73c9320b7aa38b55eaaec3740a5e9ca
[ "MIT" ]
null
null
null
messageprovider.cpp
dhdhxji/SBP_client
64ec057bd73c9320b7aa38b55eaaec3740a5e9ca
[ "MIT" ]
null
null
null
messageprovider.cpp
dhdhxji/SBP_client
64ec057bd73c9320b7aa38b55eaaec3740a5e9ca
[ "MIT" ]
null
null
null
#include "messageprovider.h" MessageProvider::MessageProvider(QObject *parent) : QObject(parent) { _socket = new QTcpSocket(this); connect(_socket, &QIODevice::readyRead, this, &MessageProvider::processMessage); connect(_socket, &QAbstractSocket::disconnected, [=](){emit this->disconnected();}); connect(_socket, &QAbstractSocket::connected, [=](){emit this->connected();}); connect(_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &MessageProvider::socketError); //_stream.setDevice(_socket); //_stream.setVersion(QDataStream::Qt_5_12); } void MessageProvider::connectToSrv(QString addr, qint16 port) { _socket->connectToHost(addr, port); } void MessageProvider::disconnectFromSrv() { _socket->disconnectFromHost(); } void MessageProvider::setShip(QPoint point) { char cmd[3]; cmd[0] = SIG_SETUP_CELL; cmd[1] = point.x(); cmd[2] = point.y(); write(cmd, 3); } void MessageProvider::ready() { char cmd[1]; cmd[0] = SIG_READY; write(cmd, 1); } void MessageProvider::shot(QPoint point) { char cmd[3]; cmd[0] = SIG_SHOT; cmd[1] = point.x(); cmd[2] = point.y(); write(cmd, 3); } void MessageProvider::nameResponse(QString name) { char cmdbuf[128]; cmdbuf[0] = SIG_RESPONSE_NAME; cmdbuf[1] = char(name.length()); for(int i = 0; i < name.length(); ++i) { cmdbuf[i+2] = name.toStdString()[i]; } write(cmdbuf, 2+name.length()); } void MessageProvider::processMessage() { const int maxBufSize = 5*100*2; //5 bytes per cell repeated 100 times(full area) char buf[maxBufSize]; int size = read(buf); char* command = buf; qDebug() << "received msg size: " << size; while(command < (buf+size)) switch(*(command)) { case SIG_REQUEST_NAME: { qDebug() << "DEBUG: name request"; emit sigNameRequest(); command+=1; break; } case SIG_SHARE_NAME: { qDebug() << "DEBUG: name share" << buf+2; int nameLen = command[1]; int temp = command[2 + nameLen]; command[2 + nameLen] = '\0'; QString name(command+2); command[2 + nameLen] = temp; emit sigShareName(name); command += (2+nameLen); break; } case SIG_SET_CELL: { qDebug() << "DEBUG: set cell"; GameArea::CellType t; qDebug() << "DEBUG: received cell type is : " << "X: " << static_cast<int>(command[1]) << " y: " << static_cast<int>(command[2]) << " wnemy: " << static_cast<int>(command[3]) << static_cast<int>(command[4]); switch(command[4]) { case CELL_SEA: t = GameArea::Sea; break; case CELL_SHIP: t = GameArea::Ship; break; case CELL_SEA_SHOTED: t = GameArea::ShotSea; break; case CELL_SHIP_WOUNDED: t = GameArea::ShotShip; break; case CELL_SHIP_KILLED: t = GameArea::KilledShip; break; } if(command[3] == OWN) emit sigOwnCellUpdate(QPoint(command[1], command[2]), t); else if(command[3] == ENEMY) emit sigEnemyCellUpdate(QPoint(command[1], command[2]), t); command += 5; break; } case SIG_GAME_STARTED: { qDebug() << "DEBUG: game started"; command += 1; break; } case SIG_FIRE: { qDebug() << "DEBUG: fire"; emit sigYouTurn(); command += 1; break; } case SIG_ERR_SHIPS_INCORRECT: { emit sigShipPlacementIncorrect(); emit externalMsg(tr("Ship placement incorrect")); command += 1; break; } case SIG_SHIP_PLACEMENT_OK: { emit sigShipPlacementOk(); command += 1; break; } case SIG_NOT_READY: { emit sigNotReady(); command+=1; break; } case SIG_WIN: { emit sigWin(); emit externalMsg("You win!"); command += 1; break; } case SIG_LOSE: { emit sigLose(); emit externalMsg("You lose =("); command += 1; break; } default: qDebug() << "DEBUG: Unknown command"; return; } } void MessageProvider::socketError(QAbstractSocket::SocketError err) { switch (err) { case QAbstractSocket::HostNotFoundError: emit externalMsg(tr("The host was not found")); break; case QAbstractSocket::ConnectionRefusedError: emit externalMsg(tr("Connection was refused by destination host")); break; case QAbstractSocket::RemoteHostClosedError: emit externalMsg(tr("Host closed")); //emit disconnected(); break; } } void MessageProvider::write(char* msg, int len) { _socket->write(msg, len); } int MessageProvider::read(char* msgPtr) { int len = _socket->bytesAvailable(); _socket->read(msgPtr, 128); return len; }
20.873469
90
0.56316
dhdhxji
cb6fc702e9b73092ec3977740d469c67965ed898
21,223
cpp
C++
Source/Modio/Private/ModioSubsystem.cpp
modio/modio-ue4
f7c16749def7a33a0e3ca77f1dc077d57d0b972e
[ "MIT" ]
19
2020-10-21T16:55:52.000Z
2022-03-27T10:21:23.000Z
Source/Modio/Private/ModioSubsystem.cpp
modio/modio-ue4
f7c16749def7a33a0e3ca77f1dc077d57d0b972e
[ "MIT" ]
6
2020-10-16T09:38:30.000Z
2021-11-15T23:43:59.000Z
Source/Modio/Private/ModioSubsystem.cpp
modio/modio-ue4
f7c16749def7a33a0e3ca77f1dc077d57d0b972e
[ "MIT" ]
1
2021-02-21T15:02:24.000Z
2021-02-21T15:02:24.000Z
/* * Copyright (C) 2021 mod.io Pty Ltd. <https://mod.io> * * This file is part of the mod.io UE4 Plugin. * * Distributed under the MIT License. (See accompanying file LICENSE or * view online at <https://github.com/modio/modio-ue4/blob/main/LICENSE>) * */ #include "ModioSubsystem.h" #include "Engine/Engine.h" #include "Internal/Convert/AuthParams.h" #include "Internal/Convert/ErrorCode.h" #include "Internal/Convert/FilterParams.h" #include "Internal/Convert/InitializeOptions.h" #include "Internal/Convert/List.h" #include "Internal/Convert/ModCollectionEntry.h" #include "Internal/Convert/ModDependency.h" #include "Internal/Convert/ModInfo.h" #include "Internal/Convert/ModInfoList.h" #include "Internal/Convert/ModManagementEvent.h" #include "Internal/Convert/ModProgressInfo.h" #include "Internal/Convert/ModTagInfo.h" #include "Internal/Convert/ModTagOptions.h" #include "Internal/Convert/Rating.h" #include "Internal/Convert/ReportParams.h" #include "Internal/Convert/Terms.h" #include "Internal/Convert/User.h" #include "Internal/ModioConvert.h" #include "ModioSettings.h" #include <map> template<typename DestKey, typename DestValue, typename SourceKey, typename SourceValue> TMap<DestKey, DestValue> ToUnreal(std::map<SourceKey, SourceValue>&& OriginalMap); template<typename Dest, typename Source> TOptional<Dest> ToUnrealOptional(Source Original); template<typename Dest, typename Source> Dest ToBP(Source Original); void UModioSubsystem::Initialize(FSubsystemCollectionBase& Collection) { Super::Initialize(Collection); if (const UModioSettings* Settings = GetDefault<UModioSettings>()) { SetLogLevel(Settings->LogLevel); } ImageCache = MakeUnique<FModioImageCache>(); } void UModioSubsystem::Deinitialize() { ImageCache.Release(); Super::Deinitialize(); } bool UModioSubsystem::ShouldCreateSubsystem(UObject* Outer) const { // @todo: Add hooks here where the user can decide where the subsystem is valid return true; } void UModioSubsystem::InitializeAsync(const FModioInitializeOptions& Options, FOnErrorOnlyDelegateFast OnInitComplete) { Modio::InitializeAsync(ToModio(Options), [this, OnInitComplete](Modio::ErrorCode ec) { InvalidateUserSubscriptionCache(); OnInitComplete.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::K2_InitializeAsync(const FModioInitializeOptions& InitializeOptions, FOnErrorOnlyDelegate InitCallback) { InitializeAsync(InitializeOptions, FOnErrorOnlyDelegateFast::CreateLambda( [InitCallback](FModioErrorCode ec) { InitCallback.ExecuteIfBound(ec); })); } void UModioSubsystem::ListAllModsAsync(const FModioFilterParams& Filter, FOnListAllModsDelegateFast Callback) { Modio::ListAllModsAsync(ToModio(Filter), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModInfoList> Result) { Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioModInfoList>(Result)); }); } void UModioSubsystem::SubscribeToModAsync(FModioModID ModToSubscribeTo, FOnErrorOnlyDelegateFast OnSubscribeComplete) { Modio::SubscribeToModAsync(ToModio(ModToSubscribeTo), [this, OnSubscribeComplete](Modio::ErrorCode ec) { InvalidateUserSubscriptionCache(); OnSubscribeComplete.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::UnsubscribeFromModAsync(FModioModID ModToUnsubscribeFrom, FOnErrorOnlyDelegateFast OnUnsubscribeComplete) { Modio::UnsubscribeFromModAsync(ToModio(ModToUnsubscribeFrom), [this, OnUnsubscribeComplete](Modio::ErrorCode ec) { InvalidateUserSubscriptionCache(); OnUnsubscribeComplete.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::FetchExternalUpdatesAsync(FOnErrorOnlyDelegateFast OnFetchDone) { Modio::FetchExternalUpdatesAsync([this, OnFetchDone](Modio::ErrorCode ec) { InvalidateUserSubscriptionCache(); OnFetchDone.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::EnableModManagement(FOnModManagementDelegateFast Callback) { Modio::EnableModManagement([this, Callback](Modio::ModManagementEvent Event) { // @todo: For some smarter caching, look at the event and see if we should invalidate the cache InvalidateUserInstallationCache(); Callback.ExecuteIfBound(ToUnreal(Event)); }); } void UModioSubsystem::K2_ListAllModsAsync(const FModioFilterParams& Filter, FOnListAllModsDelegate Callback) { ListAllModsAsync(Filter, FOnListAllModsDelegateFast::CreateLambda( [Callback](FModioErrorCode ec, TOptional<FModioModInfoList> ModList) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalModInfoList>(ModList)); })); } void UModioSubsystem::K2_SubscribeToModAsync(FModioModID ModToSubscribeTo, FOnErrorOnlyDelegate OnSubscribeComplete) { SubscribeToModAsync(ModToSubscribeTo, FOnErrorOnlyDelegateFast::CreateLambda( [OnSubscribeComplete](FModioErrorCode ec) { OnSubscribeComplete.ExecuteIfBound(ec); })); } void UModioSubsystem::K2_UnsubscribeFromModAsync(FModioModID ModToUnsubscribeFrom, FOnErrorOnlyDelegate OnUnsubscribeComplete) { UnsubscribeFromModAsync(ModToUnsubscribeFrom, FOnErrorOnlyDelegateFast::CreateLambda([OnUnsubscribeComplete](FModioErrorCode ec) { OnUnsubscribeComplete.ExecuteIfBound(ec); })); } void UModioSubsystem::K2_FetchExternalUpdatesAsync(FOnErrorOnlyDelegate OnFetchDone) { FetchExternalUpdatesAsync( FOnErrorOnlyDelegateFast::CreateLambda([OnFetchDone](FModioErrorCode ec) { OnFetchDone.ExecuteIfBound(ec); })); } void UModioSubsystem::K2_EnableModManagement(FOnModManagementDelegate Callback) { EnableModManagement(FOnModManagementDelegateFast::CreateLambda( [Callback](FModioModManagementEvent Event) { Callback.ExecuteIfBound(Event); })); } void UModioSubsystem::DisableModManagement() { Modio::DisableModManagement(); } void UModioSubsystem::ShutdownAsync(FOnErrorOnlyDelegateFast OnShutdownComplete) { Modio::ShutdownAsync([this, OnShutdownComplete](Modio::ErrorCode ec) { InvalidateUserSubscriptionCache(); OnShutdownComplete.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::K2_ShutdownAsync(FOnErrorOnlyDelegate OnShutdownComplete) { ShutdownAsync(FOnErrorOnlyDelegateFast::CreateLambda( [OnShutdownComplete](FModioErrorCode ec) { OnShutdownComplete.ExecuteIfBound(ec); })); } void UModioSubsystem::RunPendingHandlers() { InvalidateUserSubscriptionCache(); Modio::RunPendingHandlers(); } void UModioSubsystem::SetLogLevel(EModioLogLevel UnrealLogLevel) { Modio::SetLogLevel(ToModio(UnrealLogLevel)); } bool UModioSubsystem::IsModManagementBusy() { return Modio::IsModManagementBusy(); } TOptional<FModioModProgressInfo> UModioSubsystem::QueryCurrentModUpdate() { return ToUnrealOptional<FModioModProgressInfo>(Modio::QueryCurrentModUpdate()); } FModioOptionalModProgressInfo UModioSubsystem::K2_QueryCurrentModUpdate() { return ToBP<FModioOptionalModProgressInfo>(QueryCurrentModUpdate()); } const TMap<FModioModID, FModioModCollectionEntry>& UModioSubsystem::QueryUserSubscriptions() { if (!CachedUserSubscriptions) { CachedUserSubscriptions = ToUnreal<FModioModID, FModioModCollectionEntry>(Modio::QueryUserSubscriptions()); } return CachedUserSubscriptions.GetValue(); } const TMap<FModioModID, FModioModCollectionEntry>& UModioSubsystem::QueryUserInstallations(bool bIncludeOutdatedMods) { TOptional<TMap<FModioModID, FModioModCollectionEntry>>& UserInstallation = bIncludeOutdatedMods ? CachedUserInstallationWithOutdatedMods : CachedUserInstallationWithoutOutdatedMods; if (!UserInstallation) { UserInstallation = ToUnreal<FModioModID, FModioModCollectionEntry>(Modio::QueryUserInstallations(bIncludeOutdatedMods)); } return UserInstallation.GetValue(); } TOptional<FModioUser> UModioSubsystem::QueryUserProfile() { return ToUnrealOptional<FModioUser>(Modio::QueryUserProfile()); } FModioOptionalUser UModioSubsystem::K2_QueryUserProfile() { return ToBP<FModioOptionalUser>(QueryUserProfile()); } void UModioSubsystem::GetModInfoAsync(FModioModID ModId, FOnGetModInfoDelegateFast Callback) { Modio::GetModInfoAsync(ToModio(ModId), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModInfo> ModInfo) { Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioModInfo>(ModInfo)); }); } void UModioSubsystem::K2_GetModInfoAsync(FModioModID ModId, FOnGetModInfoDelegate Callback) { GetModInfoAsync(ModId, FOnGetModInfoDelegateFast::CreateLambda( [Callback](FModioErrorCode ec, TOptional<FModioModInfo> ModInfo) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalModInfo>(ModInfo)); })); } void UModioSubsystem::GetModMediaAsync(FModioModID ModId, EModioAvatarSize AvatarSize, FOnGetMediaDelegateFast Callback) { Modio::GetModMediaAsync(ToModio(ModId), ToModio(AvatarSize), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Path) { // Manually calling ToUnreal on the path and assigning to the member of FModioImage // because we already have a Modio::filesystem::path -> FString overload of ToUnreal // TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a template // function returning type T so we can be explicit about the expected type if (Path) { FModioImage Out; Out.ImagePath = ToUnreal(Path.value()); Callback.ExecuteIfBound(ec, Out); } else { Callback.ExecuteIfBound(ec, {}); } }); } void UModioSubsystem::GetModMediaAsync(FModioModID ModId, EModioGallerySize GallerySize, int32 Index, FOnGetMediaDelegateFast Callback) { Modio::GetModMediaAsync(ToModio(ModId), ToModio(GallerySize), Index, [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Path) { // Manually calling ToUnreal on the path and assigning to the member of FModioImage // because we already have a Modio::filesystem::path -> FString overload of ToUnreal // TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a template // function returning type T so we can be explicit about the expected type if (Path) { FModioImage Out; Out.ImagePath = ToUnreal(Path.value()); Callback.ExecuteIfBound(ec, Out); } else { Callback.ExecuteIfBound(ec, {}); } }); } void UModioSubsystem::GetModMediaAsync(FModioModID ModId, EModioLogoSize LogoSize, FOnGetMediaDelegateFast Callback) { Modio::GetModMediaAsync(ToModio(ModId), ToModio(LogoSize), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Path) { // Manually calling ToUnreal on the path and assigning to the member of FModioImage // because we already have a Modio::filesystem::path -> FString overload of ToUnreal // TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a template // function returning type T so we can be explicit about the expected type if (Path) { FModioImage Out; Out.ImagePath = ToUnreal(Path.value()); Callback.ExecuteIfBound(ec, Out); } else { Callback.ExecuteIfBound(ec, {}); } }); } void UModioSubsystem::K2_GetModMediaAvatarAsync(FModioModID ModId, EModioAvatarSize AvatarSize, FOnGetMediaDelegate Callback) { GetModMediaAsync( ModId, AvatarSize, FOnGetMediaDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioImage> Media) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(Media)); })); } void UModioSubsystem::K2_GetModMediaGalleryImageAsync(FModioModID ModId, EModioGallerySize GallerySize, int32 Index, FOnGetMediaDelegate Callback) { GetModMediaAsync( ModId, GallerySize, Index, FOnGetMediaDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioImage> Media) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(Media)); })); } void UModioSubsystem::K2_GetModMediaLogoAsync(FModioModID ModId, EModioLogoSize LogoSize, FOnGetMediaDelegate Callback) { GetModMediaAsync( ModId, LogoSize, FOnGetMediaDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioImage> Media) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(Media)); })); } void UModioSubsystem::GetModTagOptionsAsync(FOnGetModTagOptionsDelegateFast Callback) { if (CachedModTags) { Callback.ExecuteIfBound({}, CachedModTags); return; } Modio::GetModTagOptionsAsync( [this, Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModTagOptions> ModTagOptions) { CachedModTags = ToUnrealOptional<FModioModTagOptions>(ModTagOptions); Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioModTagOptions>(ModTagOptions)); }); } void UModioSubsystem::K2_GetModTagOptionsAsync(FOnGetModTagOptionsDelegate Callback) { GetModTagOptionsAsync(FOnGetModTagOptionsDelegateFast::CreateLambda( [Callback](FModioErrorCode ec, TOptional<FModioModTagOptions> ModTagOptions) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalModTagOptions>(ModTagOptions)); })); } void UModioSubsystem::RequestEmailAuthCodeAsync(const FModioEmailAddress& EmailAddress, FOnErrorOnlyDelegateFast Callback) { Modio::RequestEmailAuthCodeAsync(ToModio(EmailAddress), [Callback](Modio::ErrorCode ec) { Callback.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::K2_RequestEmailAuthCodeAsync(const FModioEmailAddress& EmailAddress, FOnErrorOnlyDelegate Callback) { RequestEmailAuthCodeAsync(EmailAddress, FOnErrorOnlyDelegateFast::CreateLambda( [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::AuthenticateUserEmailAsync(const FModioEmailAuthCode& AuthenticationCode, FOnErrorOnlyDelegateFast Callback) { Modio::AuthenticateUserEmailAsync(ToModio(AuthenticationCode), [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }); } void UModioSubsystem::K2_AuthenticateUserEmailAsync(const FModioEmailAuthCode& AuthenticationCode, FOnErrorOnlyDelegate Callback) { AuthenticateUserEmailAsync( AuthenticationCode, FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::AuthenticateUserExternalAsync(const FModioAuthenticationParams& User, EModioAuthenticationProvider Provider, FOnErrorOnlyDelegateFast Callback) { Modio::AuthenticateUserExternalAsync(ToModio(User), ToModio(Provider), [Callback](Modio::ErrorCode ec) { Callback.ExecuteIfBound(ec); }); } void UModioSubsystem::K2_AuthenticateUserExternalAsync(const FModioAuthenticationParams& User, EModioAuthenticationProvider Provider, FOnErrorOnlyDelegate Callback) { AuthenticateUserExternalAsync( User, Provider, FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::GetTermsOfUseAsync(EModioAuthenticationProvider Provider, EModioLanguage Locale, FOnGetTermsOfUseDelegateFast Callback) { Modio::GetTermsOfUseAsync(ToModio(Provider), ToModio(Locale), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::Terms> Terms) { Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioTerms>(Terms)); }); } void UModioSubsystem::K2_GetTermsOfUseAsync(EModioAuthenticationProvider Provider, EModioLanguage Locale, FOnGetTermsOfUseDelegate Callback) { GetTermsOfUseAsync( Provider, Locale, FOnGetTermsOfUseDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioTerms> Terms) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalTerms>(Terms)); })); } void UModioSubsystem::ClearUserDataAsync(FOnErrorOnlyDelegateFast Callback) { Modio::ClearUserDataAsync([Callback](Modio::ErrorCode ec) { Callback.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::K2_ClearUserDataAsync(FOnErrorOnlyDelegate Callback) { ClearUserDataAsync( FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::GetUserMediaAsync(EModioAvatarSize AvatarSize, FOnGetMediaDelegateFast Callback) { Modio::GetUserMediaAsync(ToModio(AvatarSize), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Media) { // Manually calling ToUnreal on the path and assigning to the member of FModioImage // because we already have a Modio::filesystem::path -> FString overload of ToUnreal // TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a // template function returning type T so we can be explicit about the expected type if (Media) { FModioImage Out; Out.ImagePath = ToUnreal(Media.value()); Callback.ExecuteIfBound(ec, Out); } else { Callback.ExecuteIfBound(ec, {}); } }); } void UModioSubsystem::K2_GetUserMediaAvatarAsync(EModioAvatarSize AvatarSize, FOnGetMediaDelegate Callback) { GetUserMediaAsync(AvatarSize, FOnGetMediaDelegateFast::CreateLambda( [Callback](FModioErrorCode ec, TOptional<FModioImage> ModioMedia) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(ModioMedia)); })); } void UModioSubsystem::InvalidateUserSubscriptionCache() { CachedUserSubscriptions.Reset(); } void UModioSubsystem::InvalidateUserInstallationCache() { CachedUserInstallationWithOutdatedMods.Reset(); CachedUserInstallationWithoutOutdatedMods.Reset(); } FModioImageCache& UModioSubsystem::GetImageCache() const { return *ImageCache; } TArray<FModioValidationError> UModioSubsystem::GetLastValidationError() { TArray<FModioValidationError> Errors; for (const auto& Error : Modio::GetLastValidationError()) { Errors.Add(FModioValidationError {ToUnreal(Error.Field), ToUnreal(Error.Error)}); } return Errors; } TMap<FModioModID, FModioModCollectionEntry> UModioSubsystem::QuerySystemInstallations() { return ToUnreal<FModioModID, FModioModCollectionEntry>(Modio::QuerySystemInstallations()); } void UModioSubsystem::ForceUninstallModAsync(FModioModID ModToRemove, FOnErrorOnlyDelegate Callback) { Modio::ForceUninstallModAsync(ToModio(ModToRemove), [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }); } void UModioSubsystem::SubmitModRatingAsync(FModioModID Mod, EModioRating Rating, FOnErrorOnlyDelegateFast Callback) { Modio::SubmitModRatingAsync(ToModio(Mod), ToModio(Rating), [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }); } void UModioSubsystem::K2_SubmitModRatingAsync(FModioModID Mod, EModioRating Rating, FOnErrorOnlyDelegate Callback) { SubmitModRatingAsync(Mod, Rating, FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::ReportContentAsync(FModioReportParams Report, FOnErrorOnlyDelegateFast Callback) { Modio::ReportContentAsync(ToModio(Report), [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }); } void UModioSubsystem::K2_ReportContentAsync(FModioReportParams Report, FOnErrorOnlyDelegate Callback) { ReportContentAsync(Report, FOnErrorOnlyDelegateFast::CreateLambda( [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::GetModDependenciesAsync(FModioModID ModID, FOnGetModDependenciesDelegateFast Callback) { Modio::GetModDependenciesAsync( ToModio(ModID), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModDependencyList> Dependencies) { if (Dependencies) { FModioModDependencyList Out; Out.InternalList = ToUnreal<FModioModDependency>(Dependencies->GetRawList()); Out.PagedResult = FModioPagedResult(Dependencies.value()); Callback.ExecuteIfBound(ec, Out); } else { Callback.ExecuteIfBound(ec, {}); } }); } MODIO_API void UModioSubsystem::K2_GetModDependenciesAsync(FModioModID ModID, FOnGetModDependenciesDelegate Callback) { GetModDependenciesAsync(ModID, FOnGetModDependenciesDelegateFast::CreateLambda( [Callback](FModioErrorCode ec, TOptional<FModioModDependencyList> Dependencies) { Callback.ExecuteIfBound( ec, FModioOptionalModDependencyList(MoveTempIfPossible(Dependencies))); })); } /// File scope implementations #pragma region Implementation template<typename DestKey, typename DestValue, typename SourceKey, typename SourceValue> TMap<DestKey, DestValue> ToUnreal(std::map<SourceKey, SourceValue>&& OriginalMap) { TMap<DestKey, DestValue> Result; Result.Reserve(OriginalMap.size()); for (auto& It : OriginalMap) { Result.Add(ToUnreal(It.first), ToUnreal(It.second)); } return Result; } template<typename Dest, typename Source> TOptional<Dest> ToUnrealOptional(Source Original) { TOptional<Dest> DestinationOptional = {}; if (Original) { DestinationOptional = ToUnreal(Original.value()); } return DestinationOptional; } template<typename Dest, typename Source> Dest ToBP(Source Original) { Dest Result = {MoveTempIfPossible(Original)}; return Result; } #pragma endregion
35.195688
120
0.766433
modio
cb6fdd5a0491cc8422de48d74f399a9c03b6a21c
10,021
hpp
C++
fon9/Subr.hpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
21
2019-01-29T14:41:46.000Z
2022-03-11T00:22:56.000Z
fon9/Subr.hpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
null
null
null
fon9/Subr.hpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
9
2019-01-27T14:19:33.000Z
2022-03-11T06:18:24.000Z
/// \file fon9/Subr.hpp /// \author fonwinz@gmail.com #ifndef __fon9_Subr_hpp__ #define __fon9_Subr_hpp__ #include "fon9/DummyMutex.hpp" #include "fon9/MustLock.hpp" #include "fon9/SortedVector.hpp" namespace fon9 { /// Subject/Subscriber 註冊取得的 ID, 用來取消註冊時使用. /// - 此ID的編碼方式為: 在新的訂閱者註冊時, 為目前最後一個ID+1, 如果現在沒有任何訂閱者則使用1. /// - 所以如果最後一個訂閱者為 0xffffffff... 則無法再註冊新的訂閱者, 此時註冊就會失敗傳回 nullptr using SubConn = struct SubId*; fon9_WARN_DISABLE_PADDING; /// 提供給 Subject 儲存訂閱者的容器. template <class SubscriberT> class SubrMap : private SortedVector<SubConn, SubscriberT> { using base = SortedVector<SubConn, SubscriberT>; unsigned FirstReserve_; public: using typename base::size_type; using typename base::iterator; using typename base::difference_type; using typename base::value_type; /// \param firstReserve 當加入第一個元素時的預分配資料量,0表示使用預設值. /// - 第一個 subr 註冊時, 表示此 Subject 是讓人感興趣的. /// - 可以預期, 接下來可能還會有別人訂閱. /// - 預先分配 **一小塊** 可能的空間, 可大幅改進後續訂閱者的處理速度. /// - 在 x64 系統裡: 如果 SubscriberT=Object*; 加上 SubId; 每個 T 占用 sizeof(void*)*2 = 16; /// - 所以如果 firstReserve=64, 則加入第一個 subr 時大約占用 16 bytes * 64 items = 1024 bytes. SubrMap(unsigned firstReserve) : FirstReserve_{firstReserve} { } using base::begin; using base::end; using base::erase; using base::size; using base::empty; using base::sindex; using base::clear; /// 使用 SortedVector::find(SubConn id) 進行二元搜尋. iterator find(SubConn id) { return base::find(id); } /// 使用 std::find(subr) 線性搜尋, subr 必須提供 `==` 操作. template <class SubscriberT2> iterator find(const SubscriberT2& subr) { return std::find_if(this->begin(), this->end(), [&subr](const value_type& i) { return(i.second == subr); }); } /// 移除全部相同的 subr, 傳回移除的數量. template <class SubscriberT2> size_type remove(const SubscriberT2& subr, size_type ibegin, size_type iend) { return this->remove_if(ibegin, iend, [&subr](const value_type& i) -> bool { return(i.second == subr); }); } /// 在尾端建立一個 Subscriber. /// \return 傳回nullptr表示失敗, 請參閱 \ref SubConn template <class... ArgsT> SubConn emplace_back(ArgsT&&... args) { SubConn id; if (fon9_LIKELY(!this->empty())) { SubConn lastid = this->back().first; id = reinterpret_cast<SubConn>(reinterpret_cast<uintptr_t>(lastid) + 1); if (fon9_UNLIKELY(id < lastid)) return nullptr; } else { id = reinterpret_cast<SubConn>(1); if (this->FirstReserve_) this->reserve(this->FirstReserve_); } base::emplace_back(id, std::forward<ArgsT>(args)...); return id; } }; /// 事件訂閱機制: 訂閱事件的主題. /// \tparam SubscriberT 訂閱者型別, 必須配合 Publish(args...) 的參數, 提供 SubscriberT(args...) 呼叫. /// 針對 thread safe 的議題, 可考慮 std::function + shared_ptr + weak_ptr. /// \tparam MutexT 預設使用 std::recursive_mutex: 允許在收到訊息的時候, 在同一個 thread 直接取消訂閱! /// \tparam ContainerT 儲存訂閱者的容器: 預設使用 SubrMap; 請參考 SubrMap 的介面. template < class SubscriberT , class MutexT = std::recursive_mutex , template <class T/*SubscriberT*/> class ContainerT = SubrMap > class Subject { fon9_NON_COPY_NON_MOVE(Subject); using ContainerImpl = ContainerT<SubscriberT>; using Container = MustLock<ContainerImpl, MutexT>; using Locker = typename Container::Locker; using ConstLocker = typename Container::ConstLocker; using iterator = typename ContainerImpl::iterator; using size_type = typename ContainerImpl::size_type; using difference_type = typename ContainerImpl::difference_type; Container Subrs_; size_type NextEmitIdx_{}; size_type EraseIterator(Locker& subrs, iterator ifind) { if (ifind == subrs->end()) return 0; size_type idx = static_cast<size_type>(ifind - subrs->begin()); if (idx < this->NextEmitIdx_) --this->NextEmitIdx_; subrs->erase(ifind); return 1; } public: using Subscriber = SubscriberT; /// \copydoc SubrMap::SubrMap explicit Subject(unsigned firstReserve = 32) : Subrs_{firstReserve} { } /// 直接在尾端註冊一個新的訂閱者. /// - 註冊時不會檢查是否已經有相同訂閱者, 也就是: 同一個訂閱者, 可以註冊多次, 此時同一次發行流程, 會收到多次訂閱的事件. /// - 使用 SubscriberT{args...} 直接在尾端建立訂閱者. /// - 如果 SubscriberT 不支援 `operator==(const SubscriberT& subr)`, 則傳回值是唯一可以取消訂閱的依據. /// /// \return 傳回值是取消訂閱時的依據, 傳回 nullptr 表示無法註冊, 原因請參閱 \ref SubConn 的說明. template <class... ArgsT> SubConn Subscribe(ArgsT&&... args) { Locker subrs(this->Subrs_); return subrs->emplace_back(std::forward<ArgsT>(args)...); } /// 訂閱時, 在返回前就先設定好 conn, 避免底下情況: /// - conn = subj.Subscribe(...); 在返回後, 設定 conn 之前, /// 就在其他 thread 觸發了 subj.Publish(); /// 而在訂閱者處理時用到了 conn, 此時的 conn 不正確. template <class... ArgsT> void Subscribe(SubConn* conn, ArgsT&&... args) { Locker subrs(this->Subrs_); *conn = subrs->emplace_back(std::forward<ArgsT>(args)...); } /// 取消訂閱. /// - 若 MutexT = std::recursive_mutex 則: 可以在收到訊息的時候, 在同一個 thread 之中取消訂閱! /// - 若 MutexT = std::mutex 則: 在收到訊息的時候, 在同一個 thread 之中取消訂閱: 會死結! /// /// \param connection 是 Subscribe() 的傳回值. /// \return 傳回實際移除的數量: 0 or 1 size_type Unsubscribe(SubConn connection) { if (!connection) return 0; Locker subrs(this->Subrs_); return this->EraseIterator(subrs, subrs->find(connection)); } /// 取消訂閱, 並清除 *connection; size_type Unsubscribe(SubConn* connection) { if (SubConn c = *connection) { *connection = SubConn{}; return this->Unsubscribe(c); } return 0; } /// 取消訂閱, 並將 Subscriber 取出. bool MoveOutSubscriber(SubConn connection, SubscriberT& subr) { return this->MoveOutSubscriber(&connection, subr); } bool MoveOutSubscriber(SubConn* pConnection, SubscriberT& subr) { Locker subrs(this->Subrs_); auto ifind = subrs->find(*pConnection); *pConnection = SubConn{}; if (ifind == subrs->end()) return false; subr = std::move(ifind->second); this->EraseIterator(subrs, ifind); return true; } /// 取消訂閱. /// \param subr SubscriberT 必須支援: bool operator==(const SubscriberT&) const; /// \return 傳回實際移除的數量: 0 or 1 size_type Unsubscribe(const SubscriberT& subr) { Locker subrs(this->Subrs_); return this->EraseIterator(subrs, subrs->find(subr)); } size_type UnsubscribeAll(const SubscriberT& subr) { Locker subrs(this->Subrs_); size_type count = subrs->remove(subr, this->NextEmitIdx_, subrs->size()); if (this->NextEmitIdx_ > 0) { if (size_type count2 = subrs->remove(subr, 0, this->NextEmitIdx_)) { this->NextEmitIdx_ -= count2; count += count2; } } return count; } /// - 在發行訊息的過程, 會 **全程鎖住容器**. /// - 這裡會呼叫 subr(std::forward<ArgsT>(args)...); /// - 在收到發行訊息時: /// - 若 MutexT = std::mutex; 則禁止在同一個 thread: 重複發行 or 取消註冊 or 新增註冊. 如果您這樣做, 會立即進入鎖死狀態! /// - 若 MutexT = std::recursive_mutex: /// - 可允許: 重複發行 or 取消註冊 or 新增註冊. /// - 請避免: 在重複發行時, 又取消註冊. 因為原本的發行流程, 可能會有訂閱者遺漏訊息, 例: /// - Pub(msgA): Subr1(idx=0), Subr2(idx=1), Subr3(idx=2), Subr4(idx=3) /// - 在 Subr2 收到 msgA 時(msgA.NextIdx=2), Pub(msgB), 當 Subr1 收到 msgB 時, 取消註冊 Subr1. /// - 此時剩下 Subr2(idx=0), Subr3(idx=1), Subr4(idx=2) /// - 接下來 msgB 的流程: Subr2, Subr3, Subr4; msgB 發行結束. /// - 返回 msgA(msgA.NextIdx=2) 繼續流程: Subr4; **此時遺漏了 Subr3** template <class... ArgsT> void Publish(ArgsT&&... args) { struct Combiner { bool operator()(SubscriberT& subr, ArgsT&&... args) { subr(std::forward<ArgsT>(args)...); return true; } } combiner; Combine(combiner, std::forward<ArgsT>(args)...); } /// 透過 combiner 合併訊息發行結果. /// 若 combiner(SubscriberT& subr, ArgsT&&... args) 傳回 false 則中斷發行. template <class CombinerT, class... ArgsT> void Combine(CombinerT& combiner, ArgsT&&... args) { Locker subrs(this->Subrs_); struct ResetIdx { size_type prv; size_type* idx; ResetIdx(size_type* i) : prv{*i}, idx{i} { *i = 0; } ~ResetIdx() { *idx = prv; } } resetIdx{&this->NextEmitIdx_}; while (this->NextEmitIdx_ < subrs->size()) { if (!combiner(subrs->sindex(this->NextEmitIdx_++).second, std::forward<ArgsT>(args)...)) break; } } /// 是否沒有訂閱者? /// 若 MutexT = std::mutex 則: 在收到訊息的時候, 在同一個 thread 之中呼叫: 會死結! bool IsEmpty() const { ConstLocker subrs(this->Subrs_); return subrs->empty(); } /// 訂閱者數量. size_type GetSubscriberCount() const { ConstLocker subrs(this->Subrs_); return subrs->size(); } void Clear() { Locker subrs(this->Subrs_); return subrs->clear(); } /// 鎖定後就暫時不會發行訊息. ConstLocker Lock() const { return ConstLocker{this->Subrs_}; } }; /// 不支援 thread safe 的 Subject: 使用 fon9::DummyMutex. template <class SubscriberT, template <class T> class SubrContainerT = SubrMap> using UnsafeSubject = Subject<SubscriberT, DummyMutex, SubrContainerT>; /// - 輔助 Subject 提供 Obj* 當作 Subscriber 使用. /// \code /// struct CbObj { /// virtual void operator()() = 0; /// }; /// using Subr = fon9::ObjCallback<CbObj>; /// using Subj = fon9::Subject<Subr>; /// \endcode /// - 提供 Obj* 呼叫 Obj::operator() 的包裝. /// - 提供 operator==(); operator!=() 判斷是否指向同一個 Obj template <class Obj> struct ObjCallback { Obj* Obj_; ObjCallback(Obj* obj) : Obj_{obj} { } bool operator==(const ObjCallback& r) const { return this->Obj_ == r.Obj_; } bool operator!=(const ObjCallback& r) const { return this->Obj_ == r.Obj_; } template <class... ArgsT> auto operator()(ArgsT&&... args) const -> decltype((*this->Obj_)(std::forward<ArgsT>(args)...)) { return (*this->Obj_)(std::forward<ArgsT>(args)...); } }; fon9_WARN_POP; } // namespaces #endif//__fon9_Subr_hpp__
34.67474
100
0.621295
fonwin
cb701cc068ff1606fe3df41a4d1d1c11b984bb29
5,141
hpp
C++
misc/avisynth-reader/avisynth/distrib/include/SoftWire/RegisterAllocator.hpp
trondkr/tools
ffd1c812b63229e4d5048192488b72d34e5f2901
[ "MIT" ]
null
null
null
misc/avisynth-reader/avisynth/distrib/include/SoftWire/RegisterAllocator.hpp
trondkr/tools
ffd1c812b63229e4d5048192488b72d34e5f2901
[ "MIT" ]
null
null
null
misc/avisynth-reader/avisynth/distrib/include/SoftWire/RegisterAllocator.hpp
trondkr/tools
ffd1c812b63229e4d5048192488b72d34e5f2901
[ "MIT" ]
1
2022-03-31T01:49:42.000Z
2022-03-31T01:49:42.000Z
#ifndef SoftWire_RegisterAllocator_hpp #define SoftWire_RegisterAllocator_hpp #include "Assembler.hpp" namespace SoftWire { class RegisterAllocator : public Assembler { protected: struct AllocationData { AllocationData() { free(); } void free() { reference = 0; priority = 0; partial = 0; copyInstruction = 0; loadInstruction = 0; spillInstruction = 0; } OperandREF reference; unsigned int priority; int partial; // Number of bytes used, 0/1/2 for general-purpose, 0/4 for SSE, 0 means all Encoding *copyInstruction; Encoding *loadInstruction; Encoding *spillInstruction; }; struct Allocation : AllocationData { Allocation() { free(); } void free() { AllocationData::free(); spill.free(); modified = false; } AllocationData spill; bool modified; }; struct State { Allocation ERX[8]; Allocation MM[8]; Allocation XMM[8]; }; public: RegisterAllocator(); virtual ~RegisterAllocator(); // Register allocation const OperandREG8 r8(const OperandREF &ref, bool copy = true); const OperandR_M8 m8(const OperandREF &ref); const OperandREG16 r16(const OperandREF &ref, bool copy = true); const OperandR_M16 m16(const OperandREF &ref); OperandREG32 r32(const OperandREF &ref, bool copy = true, int partial = 0); OperandR_M32 m32(const OperandREF &ref, int partial = 0); void free(const OperandREG32 &r32); void spill(const OperandREG32 &r32); OperandMMREG r64(const OperandREF &ref, bool copy = true); OperandR_M64 m64(const OperandREF &ref); void free(const OperandMMREG &r64); void spill(const OperandMMREG &r64); OperandXMMREG r128(const OperandREF &ref, bool copy = true, bool ss = false); OperandR_M128 m128(const OperandREF &ref, bool ss = false); void free(const OperandXMMREG &r128); void spill(const OperandXMMREG &r128); OperandXMMREG rSS(const OperandREF &ref, bool copy = true, bool ss = true); OperandXMM32 mSS(const OperandREF &ref, bool ss = true); void free(const OperandREF &ref); void spill(const OperandREF &ref); void freeAll(); void spillAll(); void spillMMX(); // Specifically for using FPU after MMX void spillMMXcept(const OperandMMREG &r64); // Empty MMX state but leave one associated const State capture(); // Capture register allocation state void restore(const State &state); // Restore state to minimize spills // Temporarily exclude register from allocation (spill, then prioritize) void exclude(const OperandREG32 &r32); using Assembler::mov; Encoding *mov(OperandREG32 r32i, OperandREG32 r32j); Encoding *mov(OperandREG32 r32, OperandMEM32 m32); Encoding *mov(OperandREG32 r32, OperandR_M32 r_m32); using Assembler::movq; Encoding *movq(OperandMMREG r64i, OperandMMREG r64j); Encoding *movq(OperandMMREG r64, OperandMEM64 m64); Encoding *movq(OperandMMREG r64, OperandR_M64 r_m64); using Assembler::movaps; Encoding *movaps(OperandXMMREG r128i, OperandXMMREG r128j); Encoding *movaps(OperandXMMREG r128, OperandMEM128 m128); Encoding *movaps(OperandXMMREG r128, OperandR_M128 r_m128); // Automatically emit emms when all MMX registers freed void enableAutoEMMS(); // Default off void disableAutoEMMS(); // Optimization flags static void enableCopyPropagation(); // Default on static void disableCopyPropagation(); static void enableLoadElimination(); // Default on static void disableLoadElimination(); static void enableSpillElimination(); // Default on static void disableSpillElimination(); static void enableMinimalRestore(); // Default on static void disableMinimalRestore(); static void enableDropUnmodified(); // Default on static void disableDropUnmodified(); protected: Encoding *x86(int instructionID, const Operand &firstOperand, const Operand &secondOperand, const Operand &thirdOperand); // Current allocation data static Allocation ERX[8]; static Allocation MM[8]; static Allocation XMM[8]; private: void markModified(const Operand &op); void markReferenced(const Operand &op); OperandREG32 allocate32(int i, const OperandREF &ref, bool copy, int partial); OperandREG32 prioritize32(int i); void free32(int i); Encoding *spill32(int i); void swap32(int i, int j); OperandMMREG allocate64(int i, const OperandREF &ref, bool copy); OperandMMREG prioritize64(int i); void free64(int i); Encoding *spill64(int i); void swap64(int i, int j); OperandXMMREG allocate128(int i, const OperandREF &ref, bool copy, bool ss); OperandXMMREG prioritize128(int i); void free128(int i); Encoding *spill128(int i); void swap128(int i, int j); static bool autoEMMS; static bool copyPropagation; static bool loadElimination; static bool spillElimination; static bool minimalRestore; static bool dropUnmodified; }; } #endif // SoftWire_RegisterAllocator_hpp
28.247253
124
0.695195
trondkr
cb709ede5c4fee21b5074dd10ff4cdcc55641c39
707
cpp
C++
src/core/EConfigure.cpp
boselor/slc
a1fd53da3f180c4062cac7083b444b438d777d26
[ "Apache-2.0" ]
null
null
null
src/core/EConfigure.cpp
boselor/slc
a1fd53da3f180c4062cac7083b444b438d777d26
[ "Apache-2.0" ]
null
null
null
src/core/EConfigure.cpp
boselor/slc
a1fd53da3f180c4062cac7083b444b438d777d26
[ "Apache-2.0" ]
null
null
null
#include <core/EConfigure.hpp> #include <fstream> namespace slc { EConfigure::EConfigure() {} EConfigure::~EConfigure() {} bool EConfigure::loadFile(EString file) { if(file.isEmpty()) return false; std::ifstream reader; reader.open(file.toStdChars(),std::ios::ate); if(!reader.is_open()) return false; std::string s; while(getline(reader,s)) { EString::format("%s",s.c_str()); } reader.close(); return true; } EString EConfigure::readString(EString path, const EString val) { if(path.isEmpty()) return val; EString res; return res; } }
20.794118
69
0.547383
boselor
cb71b2f3622af2e857a15c70e7ecc586accdfb5b
8,360
cpp
C++
SNCPython/SNCPythonLib/SNCPythonGlue.cpp
rt-ispace/SNC
890acbbe336bb0429f47fa7bed499a46215aac64
[ "MIT" ]
1
2021-08-08T05:40:52.000Z
2021-08-08T05:40:52.000Z
SNCPython/SNCPythonLib/SNCPythonGlue.cpp
rt-ispace/SNC
890acbbe336bb0429f47fa7bed499a46215aac64
[ "MIT" ]
null
null
null
SNCPython/SNCPythonLib/SNCPythonGlue.cpp
rt-ispace/SNC
890acbbe336bb0429f47fa7bed499a46215aac64
[ "MIT" ]
1
2021-08-08T05:40:56.000Z
2021-08-08T05:40:56.000Z
//////////////////////////////////////////////////////////////////////////// // // This file is part of SNC // // Copyright (c) 2014-2021, Richard Barnett // // 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 "SNCPythonGlue.h" #include "SNCPythonMainConsole.h" #include "SNCPythonMainWindow.h" #include "SNCPythonClient.h" #include "SNCUtils.h" #include <qmutex.h> QMutex lockSNCPython; SNCPythonGlue::SNCPythonGlue() { m_main = NULL; m_connected = false; m_directoryRequested = false; } SNCPythonGlue::~SNCPythonGlue() { if (m_main != NULL) stopLib(); } void SNCPythonGlue::startLib(const char *productType, int& argc, char **argv, bool showWindow) { m_argc = argc; m_argv = argv; m_daemonMode = SNCUtils::checkDaemonModeFlag(m_argc, m_argv); if (SNCUtils::checkConsoleModeFlag(m_argc, m_argv)) { QCoreApplication a(m_argc, m_argv); SNCUtils::loadStandardSettings(productType, a.arguments()); m_main = new SNCPythonMainConsole(&a, this); a.exec(); } else { QApplication a(m_argc, m_argv); SNCUtils::loadStandardSettings(productType, a.arguments()); m_main = new SNCPythonMainWindow(this); if (showWindow) ((SNCPythonMainWindow *)m_main)->show(); a.exec(); } } void SNCPythonGlue::stopLib() { m_main->stopRunning(); m_main = NULL; } void SNCPythonGlue::setWindowTitle(char *title) { m_main->setWindowTitle(title); } void SNCPythonGlue::displayImage(unsigned char *image, int length, int width, int height, char *timestamp) { m_main->displayImage(QByteArray((const char *)image, length), width, height, timestamp); } void SNCPythonGlue::displayJpegImage(unsigned char *image, int length, char *timestamp) { m_main->displayJpegImage(QByteArray((const char *)image, length), timestamp); } char *SNCPythonGlue::getAppName() { static char name[256]; strcpy(name, qPrintable(SNCUtils::getAppName())); return name; } void SNCPythonGlue::setConnected(bool state) { QMutexLocker lock(&lockSNCPython); m_connected = state; } bool SNCPythonGlue::isConnected() { QMutexLocker lock(&lockSNCPython); return m_connected; } bool SNCPythonGlue::requestDirectory() { QMutexLocker lock(&lockSNCPython); if (!m_connected) return false; m_directoryRequested = true; return true; } bool SNCPythonGlue::isDirectoryRequested() { QMutexLocker lock(&lockSNCPython); bool ret = m_directoryRequested; m_directoryRequested = false; return ret; } char *SNCPythonGlue::lookupMulticastSources(const char *sourceName) { return m_main->getClient()->lookupSources(sourceName, SERVICETYPE_MULTICAST); } int SNCPythonGlue::addMulticastSourceService(const char *servicePath) { return m_main->getClient()->clientAddService(servicePath, SERVICETYPE_MULTICAST, true); } int SNCPythonGlue::addMulticastSinkService(const char *servicePath) { return m_main->getClient()->clientAddService(servicePath, SERVICETYPE_MULTICAST, false); } char *SNCPythonGlue::lookupE2ESources(const char *sourceType) { return m_main->getClient()->lookupSources(sourceType, SERVICETYPE_E2E); } int SNCPythonGlue::addE2ESourceService(const char *servicePath) { return m_main->getClient()->clientAddService(servicePath, SERVICETYPE_E2E, true); } int SNCPythonGlue::addE2ESinkService(const char *servicePath) { return m_main->getClient()->clientAddService(servicePath, SERVICETYPE_E2E, false); } bool SNCPythonGlue::removeService(int servicePort) { return m_main->getClient()->clientRemoveService(servicePort); } bool SNCPythonGlue::isClearToSend(int servicePort) { return m_main->getClient()->clientClearToSend(servicePort); } bool SNCPythonGlue::isServiceActive(int servicePort) { return m_main->getClient()->clientIsServiceActive(servicePort); } bool SNCPythonGlue::sendAVData(int servicePort, unsigned char *videoData, int videoLength, unsigned char *audioData, int audioLength) { return m_main->sendAVData(servicePort, videoData, videoLength, audioData, audioLength); } bool SNCPythonGlue::sendJpegAVData(int servicePort, unsigned char *videoData, int videoLength, unsigned char *audioData, int audioLength) { return m_main->sendJpegAVData(servicePort, videoData, videoLength, audioData, audioLength); } bool SNCPythonGlue::getAVData(int servicePort, long long *timestamp, unsigned char **videoData, int *videoLength, unsigned char **audioData, int *audioLength) { return m_main->getClient()->getAVData(servicePort, timestamp, videoData, videoLength, audioData, audioLength); } bool SNCPythonGlue::getVideoData(int servicePort, long long *timestamp, unsigned char **videoData, int *videoLength, int *width, int *height, int *rate) { return m_main->getClient()->getVideoData(servicePort, timestamp, videoData, videoLength, width, height, rate); } bool SNCPythonGlue::sendVideoData(int servicePort, long long timestamp, unsigned char *videoData, int videoLength, int width, int height, int rate) { return m_main->sendVideoData(servicePort, timestamp, videoData, videoLength, width, height, rate); } void SNCPythonGlue::setVideoParams(int width, int height, int rate) { m_main->getClient()->setVideoParams(width, height, rate); } void SNCPythonGlue::setAudioParams(int rate, int size, int channels) { m_main->getClient()->setVideoParams(rate, size, channels); } bool SNCPythonGlue::getSensorData(int servicePort, long long *timestamp, unsigned char **jsonData, int *jsonLength) { return m_main->getClient()->getSensorData(servicePort, timestamp, jsonData, jsonLength); } bool SNCPythonGlue::sendSensorData(int servicePort, unsigned char *data, int dataLength) { return m_main->sendSensorData(servicePort, data, dataLength); } bool SNCPythonGlue::sendMulticastData(int servicePort, unsigned char *data, int dataLength) { return m_main->sendMulticastData(servicePort, data, dataLength); } bool SNCPythonGlue::sendE2EData(int servicePort, unsigned char *data, int dataLength) { return m_main->sendE2EData(servicePort, data, dataLength); } bool SNCPythonGlue::getMulticastData(int servicePort, unsigned char **data, int *dataLength) { return m_main->getClient()->getGenericData(servicePort, data, dataLength); } bool SNCPythonGlue::getE2EData(int servicePort, unsigned char **data, int *dataLength) { return m_main->getClient()->getGenericData(servicePort, data, dataLength); } bool SNCPythonGlue::vidCapOpen(int cameraNum, int width, int height, int rate) { return m_main->vidCapOpen(cameraNum, width, height, rate); } bool SNCPythonGlue::vidCapClose(int cameraNum) { return m_main->vidCapClose(cameraNum); } bool SNCPythonGlue::vidCapGetFrame(int cameraNum, unsigned char** frame, int& length, bool& jpeg, int& width, int& height, int& rate) { QByteArray qframe; *frame = NULL; if (!m_main->vidCapGetFrame(cameraNum, qframe, jpeg, width, height, rate)) return false; *frame = (unsigned char *)malloc(qframe.length()); memcpy(*frame, qframe.data(), qframe.length()); length = qframe.length(); return true; }
30.848708
116
0.719258
rt-ispace
cb7387dd133ddffef34bbbea41704914c7b5e8e0
11,059
hpp
C++
ios/Pods/boost-for-react-native/boost/interprocess/detail/windows_intermodule_singleton.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
8,805
2015-11-03T00:52:29.000Z
2022-03-29T22:30:03.000Z
ios/Pods/boost-for-react-native/boost/interprocess/detail/windows_intermodule_singleton.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
14,694
2015-02-24T15:13:42.000Z
2022-03-31T13:16:45.000Z
ios/Pods/boost-for-react-native/boost/interprocess/detail/windows_intermodule_singleton.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
1,329
2015-11-03T20:25:51.000Z
2022-03-31T18:10:38.000Z
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTERPROCESS_WINDOWS_INTERMODULE_SINGLETON_HPP #define BOOST_INTERPROCESS_WINDOWS_INTERMODULE_SINGLETON_HPP #ifndef BOOST_CONFIG_HPP # include <boost/config.hpp> #endif # #if defined(BOOST_HAS_PRAGMA_ONCE) #pragma once #endif #include <boost/interprocess/detail/config_begin.hpp> #include <boost/interprocess/detail/workaround.hpp> #include <boost/container/string.hpp> #if !defined(BOOST_INTERPROCESS_WINDOWS) #error "This header can't be included from non-windows operating systems" #endif #include <boost/assert.hpp> #include <boost/interprocess/detail/intermodule_singleton_common.hpp> #include <boost/interprocess/sync/windows/winapi_semaphore_wrapper.hpp> #include <boost/interprocess/sync/windows/winapi_mutex_wrapper.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <boost/cstdint.hpp> #include <string> #include <boost/container/map.hpp> namespace boost{ namespace interprocess{ namespace ipcdetail{ namespace intermodule_singleton_helpers { //This global map will be implemented using 3 sync primitives: // //1) A named mutex that will implement global mutual exclusion between // threads from different modules/dlls // //2) A semaphore that will act as a global counter for modules attached to the global map // so that the global map can be destroyed when the last module is detached. // //3) A semaphore that will be hacked to hold the address of a heap-allocated map in the // max and current semaphore count. class windows_semaphore_based_map { typedef boost::container::map<boost::container::string, ref_count_ptr> map_type; public: windows_semaphore_based_map() { map_type *m = new map_type; boost::uint32_t initial_count = 0; boost::uint32_t max_count = 0; //Windows user address space sizes: //32 bit windows: [32 bit processes] 2GB or 3GB (31/32 bits) //64 bit windows: [32 bit processes] 2GB or 4GB (31/32 bits) // [64 bit processes] 2GB or 8TB (31/43 bits) // //Windows semaphores use 'long' parameters (32 bits in LLP64 data model) and //those values can't be negative, so we have 31 bits to store something //in max_count and initial count parameters. //Also, max count must be bigger than 0 and bigger or equal than initial count. if(sizeof(void*) == sizeof(boost::uint32_t)){ //This means that for 32 bit processes, a semaphore count (31 usable bits) is //enough to store 4 byte aligned memory (4GB -> 32 bits - 2 bits = 30 bits). //The max count will hold the pointer value and current semaphore count //will be zero. // //Relying in UB with a cast through union, but all known windows compilers //accept this (C11 also accepts this). union caster_union { void *addr; boost::uint32_t addr_uint32; } caster; caster.addr = m; //memory is at least 4 byte aligned in windows BOOST_ASSERT((caster.addr_uint32 & boost::uint32_t(3)) == 0); max_count = caster.addr_uint32 >> 2; } else if(sizeof(void*) == sizeof(boost::uint64_t)){ //Relying in UB with a cast through union, but all known windows compilers //accept this (C11 accepts this). union caster_union { void *addr; boost::uint64_t addr_uint64; } caster; caster.addr = m; //We'll encode the address using 30 bits in each 32 bit high and low parts. //High part will be the sem max count, low part will be the sem initial count. //(restrictions: max count > 0, initial count >= 0 and max count >= initial count): // // - Low part will be shifted two times (4 byte alignment) so that top // two bits are cleared (the top one for sign, the next one to // assure low part value is always less than the high part value. // - The top bit of the high part will be cleared and the next bit will be 1 // (so high part is always bigger than low part due to the quasi-top bit). // // This means that the addresses we can store must be 4 byte aligned // and less than 1 ExbiBytes ( 2^60 bytes, ~1 ExaByte). User-level address space in Windows 64 // is much less than this (8TB, 2^43 bytes): "1 EByte (or it was 640K?) ought to be enough for anybody" ;-). caster.addr = m; BOOST_ASSERT((caster.addr_uint64 & boost::uint64_t(3)) == 0); max_count = boost::uint32_t(caster.addr_uint64 >> 32); initial_count = boost::uint32_t(caster.addr_uint64); initial_count = initial_count/4; //Make sure top two bits are zero BOOST_ASSERT((max_count & boost::uint32_t(0xC0000000)) == 0); //Set quasi-top bit max_count |= boost::uint32_t(0x40000000); } bool created = false; const permissions & perm = permissions(); std::string pid_creation_time, name; get_pid_creation_time_str(pid_creation_time); name = "bipc_gmap_sem_lock_"; name += pid_creation_time; bool success = m_mtx_lock.open_or_create(name.c_str(), perm); name = "bipc_gmap_sem_count_"; name += pid_creation_time; scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock); { success = success && m_sem_count.open_or_create ( name.c_str(), static_cast<long>(0), winapi_semaphore_wrapper::MaxCount, perm, created); name = "bipc_gmap_sem_map_"; name += pid_creation_time; success = success && m_sem_map.open_or_create (name.c_str(), initial_count, max_count, perm, created); if(!success){ delete m; //winapi_xxx wrappers do the cleanup... throw int(0); } if(!created){ delete m; } else{ BOOST_ASSERT(&get_map_unlocked() == m); } m_sem_count.post(); } } map_type &get_map_unlocked() { if(sizeof(void*) == sizeof(boost::uint32_t)){ union caster_union { void *addr; boost::uint32_t addr_uint32; } caster; caster.addr = 0; caster.addr_uint32 = m_sem_map.limit(); caster.addr_uint32 = caster.addr_uint32 << 2; return *static_cast<map_type*>(caster.addr); } else{ union caster_union { void *addr; boost::uint64_t addr_uint64; } caster; boost::uint32_t max_count(m_sem_map.limit()), initial_count(m_sem_map.value()); //Clear quasi-top bit max_count &= boost::uint32_t(0xBFFFFFFF); caster.addr_uint64 = max_count; caster.addr_uint64 = caster.addr_uint64 << 32; caster.addr_uint64 |= boost::uint64_t(initial_count) << 2; return *static_cast<map_type*>(caster.addr); } } ref_count_ptr *find(const char *name) { scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock); map_type &map = this->get_map_unlocked(); map_type::iterator it = map.find(boost::container::string(name)); if(it != map.end()){ return &it->second; } else{ return 0; } } ref_count_ptr * insert(const char *name, const ref_count_ptr &ref) { scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock); map_type &map = this->get_map_unlocked(); map_type::iterator it = map.insert(map_type::value_type(boost::container::string(name), ref)).first; return &it->second; } bool erase(const char *name) { scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock); map_type &map = this->get_map_unlocked(); return map.erase(boost::container::string(name)) != 0; } template<class F> void atomic_func(F &f) { scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock); f(); } ~windows_semaphore_based_map() { scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock); m_sem_count.wait(); if(0 == m_sem_count.value()){ map_type &map = this->get_map_unlocked(); BOOST_ASSERT(map.empty()); delete &map; } //First close sems to protect this with the external mutex m_sem_map.close(); m_sem_count.close(); //Once scoped_lock unlocks the mutex, the destructor will close the handle... } private: winapi_mutex_wrapper m_mtx_lock; winapi_semaphore_wrapper m_sem_map; winapi_semaphore_wrapper m_sem_count; }; template<> struct thread_safe_global_map_dependant<windows_semaphore_based_map> { static void apply_gmem_erase_logic(const char *, const char *){} static bool remove_old_gmem() { return true; } struct lock_file_logic { lock_file_logic(windows_semaphore_based_map &) : retry_with_new_map(false) {} void operator()(void){} bool retry() const { return retry_with_new_map; } private: const bool retry_with_new_map; }; static void construct_map(void *addr) { ::new (addr)windows_semaphore_based_map; } struct unlink_map_logic { unlink_map_logic(windows_semaphore_based_map &) {} void operator()(){} }; static ref_count_ptr *find(windows_semaphore_based_map &map, const char *name) { return map.find(name); } static ref_count_ptr * insert(windows_semaphore_based_map &map, const char *name, const ref_count_ptr &ref) { return map.insert(name, ref); } static bool erase(windows_semaphore_based_map &map, const char *name) { return map.erase(name); } template<class F> static void atomic_func(windows_semaphore_based_map &map, F &f) { map.atomic_func(f); } }; } //namespace intermodule_singleton_helpers { template<typename C, bool LazyInit = true, bool Phoenix = false> class windows_intermodule_singleton : public intermodule_singleton_impl < C , LazyInit , Phoenix , intermodule_singleton_helpers::windows_semaphore_based_map > {}; } //namespace ipcdetail{ } //namespace interprocess{ } //namespace boost{ #include <boost/interprocess/detail/config_end.hpp> #endif //#ifndef BOOST_INTERPROCESS_WINDOWS_INTERMODULE_SINGLETON_HPP
35.107937
120
0.62483
rudylee
cb7474f409efed8c54baa72c51160368af647b44
6,301
hpp
C++
src/hotspot/share/jvmci/jvmci.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
src/hotspot/share/jvmci/jvmci.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
src/hotspot/share/jvmci/jvmci.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #ifndef SHARE_JVMCI_JVMCI_HPP #define SHARE_JVMCI_JVMCI_HPP #include "compiler/compiler_globals.hpp" #include "compiler/compilerDefinitions.hpp" #include "utilities/exceptions.hpp" class BoolObjectClosure; class constantPoolHandle; class JavaThread; class JVMCIEnv; class JVMCIRuntime; class Metadata; class MetadataHandleBlock; class OopClosure; class OopStorage; template <size_t> class FormatStringEventLog; typedef FormatStringEventLog<256> StringEventLog; struct _jmetadata; typedef struct _jmetadata *jmetadata; class JVMCI : public AllStatic { friend class JVMCIRuntime; friend class JVMCIEnv; private: // Access to the HotSpotJVMCIRuntime used by the CompileBroker. static JVMCIRuntime* _compiler_runtime; // True when at least one JVMCIRuntime::initialize_HotSpotJVMCIRuntime() // execution has completed successfully. static volatile bool _is_initialized; // True once boxing cache classes are guaranteed to be initialized. static bool _box_caches_initialized; // Handle created when loading the JVMCI shared library with os::dll_load. // Must hold JVMCI_lock when initializing. static void* _shared_library_handle; // Argument to os::dll_load when loading JVMCI shared library static char* _shared_library_path; // Records whether JVMCI::shutdown has been called. static volatile bool _in_shutdown; // Access to the HotSpot heap based JVMCIRuntime static JVMCIRuntime* _java_runtime; // The file descriptor to which fatal_log() writes. Initialized on // first call to fatal_log(). static volatile int _fatal_log_fd; // The path of the file underlying _fatal_log_fd if it is a normal file. static const char* _fatal_log_filename; // Native thread id of thread that will initialize _fatal_log_fd. static volatile intx _fatal_log_init_thread; // JVMCI event log (shows up in hs_err crash logs). static StringEventLog* _events; static StringEventLog* _verbose_events; enum { max_EventLog_level = 4 }; // Gets the Thread* value for the current thread or NULL if it's not available. static Thread* current_thread_or_null(); public: enum CodeInstallResult { ok, dependencies_failed, cache_full, nmethod_reclaimed, // code cache sweeper reclaimed nmethod in between its creation and being marked "in_use" code_too_large, first_permanent_bailout = code_too_large }; // Gets the handle to the loaded JVMCI shared library, loading it // first if not yet loaded and `load` is true. The path from // which the library is loaded is returned in `path`. If // `load` is true then JVMCI_lock must be locked. static void* get_shared_library(char*& path, bool load); // Logs the fatal crash data in `buf` to the appropriate stream. static void fatal_log(const char* buf, size_t count); // Gets the name of the opened JVMCI shared library crash data file or NULL // if this file has not been created. static const char* fatal_log_filename() { return _fatal_log_filename; } static void do_unloading(bool unloading_occurred); static void metadata_do(void f(Metadata*)); static void shutdown(); // Returns whether JVMCI::shutdown has been called. static bool in_shutdown(); static bool is_compiler_initialized(); /** * Determines if the VM is sufficiently booted to initialize JVMCI. */ static bool can_initialize_JVMCI(); static void initialize_globals(); static void initialize_compiler(TRAPS); // Ensures the boxing cache classes (e.g., java.lang.Integer.IntegerCache) are initialized. static void ensure_box_caches_initialized(TRAPS); // Increments a value indicating some JVMCI compilation activity // happened on `thread` if it is a CompilerThread. // Returns `thread`. static JavaThread* compilation_tick(JavaThread* thread); static JVMCIRuntime* compiler_runtime() { return _compiler_runtime; } // Gets the single runtime for JVMCI on the Java heap. This is the only // JVMCI runtime available when !UseJVMCINativeLibrary. static JVMCIRuntime* java_runtime() { return _java_runtime; } // Appends an event to the JVMCI event log if JVMCIEventLogLevel >= `level` static void vlog(int level, const char* format, va_list ap) ATTRIBUTE_PRINTF(2, 0); // Traces an event to tty if JVMCITraceLevel >= `level` static void vtrace(int level, const char* format, va_list ap) ATTRIBUTE_PRINTF(2, 0); public: // Log/trace a JVMCI event static void event(int level, const char* format, ...) ATTRIBUTE_PRINTF(2, 3); static void event1(const char* format, ...) ATTRIBUTE_PRINTF(1, 2); static void event2(const char* format, ...) ATTRIBUTE_PRINTF(1, 2); static void event3(const char* format, ...) ATTRIBUTE_PRINTF(1, 2); static void event4(const char* format, ...) ATTRIBUTE_PRINTF(1, 2); }; // JVMCI event macros. #define JVMCI_event_1 if (JVMCITraceLevel < 1 && JVMCIEventLogLevel < 1) ; else ::JVMCI::event1 #define JVMCI_event_2 if (JVMCITraceLevel < 2 && JVMCIEventLogLevel < 2) ; else ::JVMCI::event2 #define JVMCI_event_3 if (JVMCITraceLevel < 3 && JVMCIEventLogLevel < 3) ; else ::JVMCI::event3 #define JVMCI_event_4 if (JVMCITraceLevel < 4 && JVMCIEventLogLevel < 4) ; else ::JVMCI::event4 #endif // SHARE_JVMCI_JVMCI_HPP
36.005714
113
0.751944
1690296356
cb76d73b47b2234f5b46a03adc5215885c7b0e5a
3,659
hpp
C++
src/modules/socket/dgram_channel.hpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
20
2019-12-04T01:28:52.000Z
2022-03-17T14:09:34.000Z
src/modules/socket/dgram_channel.hpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
115
2020-02-04T21:29:54.000Z
2022-02-17T13:33:51.000Z
src/modules/socket/dgram_channel.hpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
16
2019-12-03T16:41:18.000Z
2021-11-06T04:44:11.000Z
#ifndef _OP_SOCKET_DGRAM_CHANNEL_HPP_ #define _OP_SOCKET_DGRAM_CHANNEL_HPP_ #include <atomic> #include <netinet/in.h> #include "framework/memory/offset_ptr.hpp" #include "socket/api.hpp" namespace openperf::socket { struct dgram_ipv4_addr { uint32_t addr; }; struct dgram_ipv6_addr { uint32_t addr[4]; /* LWIP_IPV6_SCOPES adds zone field in lwpip ip6_addr_t */ uint8_t zone; }; /* Congruent to lwIP ip_addr_t; otherwise we'd use a variant */ struct dgram_ip_addr { enum class type : uint8_t { IPv4 = 0, IPv6 = 6 }; union { dgram_ipv6_addr ip6; dgram_ipv4_addr ip4; } u_addr; type type; }; /* Congruent to struct sockaddr_ll */ struct dgram_sockaddr_ll { uint16_t family; uint16_t protocol; int ifindex; uint16_t hatype; uint8_t pkttype; uint8_t halen; std::array<uint8_t, 8> addr; }; using dgram_channel_addr = std::variant<sockaddr_in, sockaddr_in6, dgram_sockaddr_ll>; /* * Static tag for sanity checking random pointers are actually descriptors. * Can be removed once we're sure this works :) */ static constexpr uint64_t descriptor_tag = 0xABCCDDDEEEEE; /* Each datagram in the buffer is pre-pended with the following descriptor */ struct dgram_channel_descriptor { uint64_t tag = descriptor_tag; std::optional<dgram_channel_addr> address; uint16_t length; }; /* * The datagram channel uses the same approach as the stream * channel. But because we're dealing with packets of data, * we pre-pend each write to the buffer with a fixed size header. * This header allows the reader to determine the address for the * payload and the actual size of the data which follows. * * Additionally, just like the stream channel, we maintain two * individual buffers, one for transmit and one for receive, * and we used eventfd's to signal between client and server * when necessary. */ #define DGRAM_CHANNEL_MEMBERS \ struct alignas(cache_line_size) \ { \ buffer tx_buffer; \ api::socket_fd_pair client_fds; \ std::atomic_uint64_t tx_q_write_idx; \ std::atomic_uint64_t rx_q_read_idx; \ std::atomic_uint64_t tx_fd_write_idx; \ std::atomic_uint64_t rx_fd_read_idx; \ std::atomic_int socket_flags; \ }; \ struct alignas(cache_line_size) \ { \ buffer rx_buffer; \ api::socket_fd_pair server_fds; \ std::atomic_uint64_t tx_q_read_idx; \ std::atomic_uint64_t rx_q_write_idx; \ std::atomic_uint64_t tx_fd_read_idx; \ std::atomic_uint64_t rx_fd_write_idx; \ void* allocator; \ }; struct dgram_channel { DGRAM_CHANNEL_MEMBERS }; } // namespace openperf::socket #endif /* _OP_SOCKET_DGRAM_CHANNEL_HPP_ */
33.568807
80
0.529926
gchagnotSpt
cb79164058ae1e901e422738d4969ef4eef5b3d9
3,170
hpp
C++
Contrib-Intel/RSD-PSME-RMM/application/include/app.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Intel/RSD-PSME-RMM/application/include/app.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Intel/RSD-PSME-RMM/application/include/app.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
/*! * @copyright * Copyright (c) 2015-2019 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * @file app.hpp * * @brief Declares App class wrapping main program logic. * */ #pragma once #include "psme/eventing/eventing_server.hpp" #include "psme/registration/registration_server.hpp" #include "psme/rest/rest_server.hpp" #include "psme/rest/model/watcher.hpp" #include "psme/rest/eventing/event_service.hpp" #include "psme/rest/security/session/session_service.hpp" #include "net/network_change_notifier.hpp" #include <memory> namespace jsonrpc { class HttpServer; } namespace ssdp { class SsdpService; } /*! Psme namespace */ namespace psme { /*! Application namespace */ namespace app { /*! * @brief Application class wrapping main program logic. * * Responsible for application initialization and execution. */ class App final { public: /*! * @brief Constructor * @param argc number of arguments passed to program * @param argv array with program arguments */ App(int argc, const char** argv); /*! * @brief Destructor * * Responsible for resource cleanup. Stops any running servers. */ ~App(); /*! * @brief Starts servers initialized in init method * and waits for interrupt signal. */ void run(); private: /*! * @brief Initialization method * * Responsible for initialization of loggers, registration server, * eventing server and rest server. Does not start the mentioned servers. */ void init(); void init_database(); void init_logger(); void init_network_change_notifier(); void init_ssdp_service(); void init_registration_server(); void init_eventing_server(); void init_rest_event_service(); void init_rest_session_service(); void init_rest_server(); void init_registries(); void cleanup(); void statics_cleanup(); void wait_for_termination(); const json::Json& m_configuration; std::unique_ptr<psme::app::eventing::EventingServer> m_eventing_server{}; std::unique_ptr<psme::app::registration::RegistrationServer> m_registration_server{}; std::unique_ptr<psme::rest::server::RestServer> m_rest_server{}; std::unique_ptr<psme::rest::eventing::EventService> m_rest_event_service{}; std::unique_ptr<psme::rest::security::session::SessionService> m_rest_session_service{}; std::unique_ptr<net::NetworkChangeNotifier> m_network_change_notifier{}; std::shared_ptr<ssdp::SsdpService> m_ssdp_service{}; std::unique_ptr<rest::model::Watcher> m_model_watcher{}; }; } }
28.303571
92
0.708517
opencomputeproject
cb7bbcbf7ca44ffee5ac08be4646feeebe0ba463
6,725
cpp
C++
lib/AFE-I2C-Scanner/AFE-I2C-Scanner.cpp
tschaban/AFE-Firmware
b2c7c76e0f2efb6d8e02b81a5d08e39e30016502
[ "MIT" ]
36
2017-06-05T21:27:44.000Z
2022-02-13T21:04:04.000Z
lib/AFE-I2C-Scanner/AFE-I2C-Scanner.cpp
tschaban/AFE-Firmware
b2c7c76e0f2efb6d8e02b81a5d08e39e30016502
[ "MIT" ]
661
2017-05-28T12:01:53.000Z
2022-02-13T08:51:25.000Z
lib/AFE-I2C-Scanner/AFE-I2C-Scanner.cpp
tschaban/AFE-Firmware
b2c7c76e0f2efb6d8e02b81a5d08e39e30016502
[ "MIT" ]
46
2017-12-12T21:11:32.000Z
2022-02-10T21:52:26.000Z
/* AFE Firmware for smarthome devices, More info: https://afe.smartnydom.pl/ */ #include "AFE-I2C-Scanner.h" #ifdef AFE_CONFIG_HARDWARE_I2C AFEI2CScanner::AFEI2CScanner() {}; void AFEI2CScanner::begin(TwoWire *_WirePort) { AFEDataAccess Data; WirePort = _WirePort; } #ifdef DEBUG void AFEI2CScanner::scanAll() { uint8_t numberOfDeficesFound = 0; boolean searchStatus; Serial << endl << endl << F("------------------ I2C Scanner ------------------"); for (uint8_t address = 1; address < 127; address++) { searchStatus = scan(address); if (searchStatus) numberOfDeficesFound++; } if (numberOfDeficesFound == 0) { Serial << endl << F("No I2C devices found"); } else { Serial << endl << F("Scanning completed"); } Serial << endl << F("---------------------------------------------------") << endl; } #endif boolean AFEI2CScanner::scan(byte address) { byte status; WirePort->beginTransmission(address); status = WirePort->endTransmission(); if (status == 0) { #ifdef DEBUG Serial << endl << F(" - Sensor Found [0x"); if (address < 16) { Serial << F("0"); } Serial << _HEX(address) << F("] : ") << getName(address); #endif return true; } else { return false; } } const char *AFEI2CScanner::getName(byte deviceAddress) { /* WARN: Description can't be longer than 70chars, used by addDeviceI2CAddressSelectionItem in AFE-Site-Gnerator.h */ if (deviceAddress == 0x00) return "AS3935"; else if (deviceAddress == 0x01) return "AS3935"; else if (deviceAddress == 0x02) return "AS3935"; else if (deviceAddress == 0x03) return "AS3935"; else if (deviceAddress == 0x0A) return "SGTL5000"; else if (deviceAddress == 0x0B) return "SMBusBattery?"; else if (deviceAddress == 0x0C) return "AK8963"; else if (deviceAddress == 0x10) return "CS4272"; else if (deviceAddress == 0x11) return "Si4713"; else if (deviceAddress == 0x13) return "VCNL4000,AK4558"; else if (deviceAddress == 0x18) return "LIS331DLH"; else if (deviceAddress == 0x19) return "LSM303,LIS331DLH"; else if (deviceAddress == 0x1A) return "WM8731"; else if (deviceAddress == 0x1C) return "LIS3MDL"; else if (deviceAddress == 0x1D) return "LSM303D,LSM9DS0,ADXL345,MMA7455L,LSM9DS1,LIS3DSH"; else if (deviceAddress == 0x1E) return "LSM303D,HMC5883L,FXOS8700,LIS3DSH"; else if (deviceAddress == 0x20) //return "MCP23017,MCP23008,PCF8574,FXAS21002,SoilMoisture"; return "MCP23017"; else if (deviceAddress == 0x21) //return "MCP23017,MCP23008,PCF8574"; return "MCP23017"; else if (deviceAddress == 0x22) //return "MCP23017,MCP23008,PCF8574"; return "MCP23017"; else if (deviceAddress == 0x23) return "BH1750, MCP23017"; //return "BH1750,MCP23017,MCP23008,PCF8574"; else if (deviceAddress == 0x24) //return "MCP23017,MCP23008,PCF8574"; return "MCP23017,PN532"; else if (deviceAddress == 0x25) //return "MCP23017,MCP23008,PCF8574"; return "MCP23017"; else if (deviceAddress == 0x26) //return "MCP23017,MCP23008,PCF8574"; return "MCP23017"; else if (deviceAddress == 0x27) //return "MCP23017,MCP23008,PCF8574,LCD16x2,DigoleDisplay"; return "MCP23017"; else if (deviceAddress == 0x28) return "BNO055,EM7180,CAP1188"; else if (deviceAddress == 0x29) return "TSL2561,VL6180,TSL2561,TSL2591,BNO055,CAP1188"; else if (deviceAddress == 0x2A) return "SGTL5000,CAP1188"; else if (deviceAddress == 0x2B) return "CAP1188"; else if (deviceAddress == 0x2C) return "MCP44XX ePot"; else if (deviceAddress == 0x2D) return "MCP44XX ePot"; else if (deviceAddress == 0x2E) return "MCP44XX ePot"; else if (deviceAddress == 0x2F) return "MCP44XX ePot"; else if (deviceAddress == 0x38) return "RA8875,FT6206"; else if (deviceAddress == 0x39) return "TSL2561"; else if (deviceAddress == 0x3C) return "SSD1306,DigisparkOLED"; else if (deviceAddress == 0x3D) return "SSD1306"; else if (deviceAddress == 0x40) return "PCA9685,Si7021"; else if (deviceAddress == 0x41) return "STMPE610,PCA9685"; else if (deviceAddress == 0x42) return "PCA9685"; else if (deviceAddress == 0x43) return "PCA9685"; else if (deviceAddress == 0x44) return "PCA9685"; else if (deviceAddress == 0x45) return "PCA9685"; else if (deviceAddress == 0x46) return "PCA9685"; else if (deviceAddress == 0x47) return "PCA9685"; else if (deviceAddress == 0x48) return "ADS1115,PN532,TMP102,PCF8591"; else if (deviceAddress == 0x49) return "ADS1115,TSL2561,PCF8591"; else if (deviceAddress == 0x4A) return "ADS1115"; else if (deviceAddress == 0x4B) return "ADS1115,TMP102"; else if (deviceAddress == 0x50) return "EEPROM"; else if (deviceAddress == 0x51) return "EEPROM"; else if (deviceAddress == 0x52) return "Nunchuk,EEPROM"; else if (deviceAddress == 0x53) return "ADXL345,EEPROM"; else if (deviceAddress == 0x54) return "EEPROM"; else if (deviceAddress == 0x55) return "EEPROM"; else if (deviceAddress == 0x56) return "EEPROM"; else if (deviceAddress == 0x57) return "EEPROM"; else if (deviceAddress == 0x58) return "TPA2016,MAX21100"; else if (deviceAddress == 0x5A) return "MPR121"; else if (deviceAddress == 0x5C) return "BH1750"; else if (deviceAddress == 0x60) return "MPL3115,MCP4725,MCP4728,TEA5767,Si5351"; else if (deviceAddress == 0x61) return "MCP4725,AtlasEzoDO"; else if (deviceAddress == 0x62) return "LidarLite,MCP4725,AtlasEzoORP"; else if (deviceAddress == 0x63) return "MCP4725,AtlasEzoPH"; else if (deviceAddress == 0x64) return "AtlasEzoEC"; else if (deviceAddress == 0x66) return "AtlasEzoRTD"; else if (deviceAddress == 0x68) return "DS1307,DS3231,MPU6050,MPU9050,MPU9250,ITG3200,ITG3701," "LSM9DS0,L3G4200D"; else if (deviceAddress == 0x69) return "MPU6050,MPU9050,MPU9250,ITG3701,L3G4200D"; else if (deviceAddress == 0x6A) return "LSM9DS1"; else if (deviceAddress == 0x6B) return "LSM9DS0"; else if (deviceAddress == 0x70) return "AdafruitLED"; else if (deviceAddress == 0x71) return "SFE7SEG,AdafruitLED"; else if (deviceAddress == 0x72) return "AdafruitLED"; else if (deviceAddress == 0x73) return "AdafruitLED"; else if (deviceAddress == 0x76) return "BMx280"; //return "BMx280,MS5607,MS5611,MS5637"; else if (deviceAddress == 0x77) //return "BMx085,BMx180,BMx280,BMx680,MS5611"; return "BMx085,BMx180,BMx280,BMx680"; else return "UNKNOWN"; } #endif // AFE_CONFIG_HARDWARE_I2C
29.495614
119
0.654721
tschaban
cb7ddfe4bf29d5d26542d1d41a5db5f63229ffe2
6,712
cc
C++
src/mem/page_table.cc
yb-kim/gemV
02e00bb8ac0cb4aacad2fc4a8cb4eeb1cf176233
[ "BSD-3-Clause" ]
14
2015-06-25T03:00:17.000Z
2021-09-26T16:33:43.000Z
src/mem/page_table.cc
yb-kim/gemV
02e00bb8ac0cb4aacad2fc4a8cb4eeb1cf176233
[ "BSD-3-Clause" ]
1
2019-04-28T05:23:32.000Z
2019-04-28T05:23:32.000Z
src/mem/page_table.cc
yb-kim/gemV
02e00bb8ac0cb4aacad2fc4a8cb4eeb1cf176233
[ "BSD-3-Clause" ]
5
2016-10-19T07:25:58.000Z
2020-12-12T18:35:37.000Z
/* * Copyright (c) 2003 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Steve Reinhardt * Ron Dreslinski * Ali Saidi */ /** * @file * Definitions of page table. */ #include <fstream> #include <map> #include <string> #include "base/bitfield.hh" #include "base/intmath.hh" #include "base/trace.hh" #include "config/the_isa.hh" #include "debug/MMU.hh" #include "mem/page_table.hh" #include "sim/faults.hh" #include "sim/sim_object.hh" using namespace std; using namespace TheISA; PageTable::PageTable(const std::string &__name, uint64_t _pid, Addr _pageSize) : pageSize(_pageSize), offsetMask(mask(floorLog2(_pageSize))), pid(_pid), _name(__name) { assert(isPowerOf2(pageSize)); pTableCache[0].valid = false; pTableCache[1].valid = false; pTableCache[2].valid = false; } PageTable::~PageTable() { } void PageTable::map(Addr vaddr, Addr paddr, int64_t size, bool clobber) { // starting address must be page aligned assert(pageOffset(vaddr) == 0); DPRINTF(MMU, "Allocating Page: %#x-%#x\n", vaddr, vaddr+ size); for (; size > 0; size -= pageSize, vaddr += pageSize, paddr += pageSize) { if (!clobber && (pTable.find(vaddr) != pTable.end())) { // already mapped fatal("PageTable::allocate: address 0x%x already mapped", vaddr); } pTable[vaddr] = TheISA::TlbEntry(pid, vaddr, paddr); eraseCacheEntry(vaddr); updateCache(vaddr, pTable[vaddr]); } } void PageTable::remap(Addr vaddr, int64_t size, Addr new_vaddr) { assert(pageOffset(vaddr) == 0); assert(pageOffset(new_vaddr) == 0); DPRINTF(MMU, "moving pages from vaddr %08p to %08p, size = %d\n", vaddr, new_vaddr, size); for (; size > 0; size -= pageSize, vaddr += pageSize, new_vaddr += pageSize) { assert(pTable.find(vaddr) != pTable.end()); pTable[new_vaddr] = pTable[vaddr]; pTable.erase(vaddr); eraseCacheEntry(vaddr); pTable[new_vaddr].updateVaddr(new_vaddr); updateCache(new_vaddr, pTable[new_vaddr]); } } void PageTable::unmap(Addr vaddr, int64_t size) { assert(pageOffset(vaddr) == 0); DPRINTF(MMU, "Unmapping page: %#x-%#x\n", vaddr, vaddr+ size); for (; size > 0; size -= pageSize, vaddr += pageSize) { assert(pTable.find(vaddr) != pTable.end()); pTable.erase(vaddr); eraseCacheEntry(vaddr); } } bool PageTable::isUnmapped(Addr vaddr, int64_t size) { // starting address must be page aligned assert(pageOffset(vaddr) == 0); for (; size > 0; size -= pageSize, vaddr += pageSize) { if (pTable.find(vaddr) != pTable.end()) { return false; } } return true; } bool PageTable::lookup(Addr vaddr, TheISA::TlbEntry &entry) { Addr page_addr = pageAlign(vaddr); if (pTableCache[0].valid && pTableCache[0].vaddr == page_addr) { entry = pTableCache[0].entry; return true; } if (pTableCache[1].valid && pTableCache[1].vaddr == page_addr) { entry = pTableCache[1].entry; return true; } if (pTableCache[2].valid && pTableCache[2].vaddr == page_addr) { entry = pTableCache[2].entry; return true; } PTableItr iter = pTable.find(page_addr); if (iter == pTable.end()) { return false; } updateCache(page_addr, iter->second); entry = iter->second; return true; } bool PageTable::translate(Addr vaddr, Addr &paddr) { TheISA::TlbEntry entry; if (!lookup(vaddr, entry)) { DPRINTF(MMU, "Couldn't Translate: %#x\n", vaddr); return false; } paddr = pageOffset(vaddr) + entry.pageStart(); DPRINTF(MMU, "Translating: %#x->%#x\n", vaddr, paddr); return true; } Fault PageTable::translate(RequestPtr req) { Addr paddr; assert(pageAlign(req->getVaddr() + req->getSize() - 1) == pageAlign(req->getVaddr())); if (!translate(req->getVaddr(), paddr)) { return Fault(new GenericPageTableFault(req->getVaddr())); } req->setPaddr(paddr); if ((paddr & (pageSize - 1)) + req->getSize() > pageSize) { panic("Request spans page boundaries!\n"); return NoFault; } return NoFault; } void PageTable::serialize(std::ostream &os) { paramOut(os, "ptable.size", pTable.size()); PTable::size_type count = 0; PTableItr iter = pTable.begin(); PTableItr end = pTable.end(); while (iter != end) { os << "\n[" << csprintf("%s.Entry%d", name(), count) << "]\n"; paramOut(os, "vaddr", iter->first); iter->second.serialize(os); ++iter; ++count; } assert(count == pTable.size()); } void PageTable::unserialize(Checkpoint *cp, const std::string &section) { int i = 0, count; paramIn(cp, section, "ptable.size", count); pTable.clear(); while (i < count) { TheISA::TlbEntry *entry; Addr vaddr; paramIn(cp, csprintf("%s.Entry%d", name(), i), "vaddr", vaddr); entry = new TheISA::TlbEntry(); entry->unserialize(cp, csprintf("%s.Entry%d", name(), i)); pTable[vaddr] = *entry; delete entry; ++i; } }
28.201681
82
0.643623
yb-kim
cb7e0bff626080ccb1317f2bd4e4d77bd52f6ff0
8,323
cpp
C++
tests/kernel_concatenation_test/concatenation_test.cpp
pschatzmann/pico-tflmicro
c18a5081b2d5b62b1d4d74f7c7e33d543a3b75de
[ "Apache-2.0" ]
278
2021-01-21T07:25:35.000Z
2022-03-26T18:24:10.000Z
tensorflow/lite/micro/kernels/concatenation_test.cc
sseung0703/tensorflow
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
[ "Apache-2.0" ]
88
2020-11-24T08:18:10.000Z
2022-03-25T20:28:30.000Z
tensorflow/lite/micro/kernels/concatenation_test.cc
sseung0703/tensorflow
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
[ "Apache-2.0" ]
38
2021-01-21T07:25:45.000Z
2022-03-31T08:48:15.000Z
/* Copyright 2019 The TensorFlow 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 <initializer_list> #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/micro/kernels/kernel_runner.h" #include "tensorflow/lite/micro/test_helpers.h" #include "tensorflow/lite/micro/testing/micro_test.h" namespace tflite { namespace testing { namespace { void TestConcatenateTwoInputs(const int* input1_dims_data, const float* input1_data, const int* input2_dims_data, const float* input2_data, int axis, const int* output_dims_data, const float* expected_output_data, float* output_data) { TfLiteIntArray* input1_dims = IntArrayFromInts(input1_dims_data); TfLiteIntArray* input2_dims = IntArrayFromInts(input2_dims_data); TfLiteIntArray* output_dims = IntArrayFromInts(output_dims_data); constexpr int input_size = 2; constexpr int output_size = 1; constexpr int tensors_size = input_size + output_size; TfLiteTensor tensors[tensors_size] = {CreateTensor(input1_data, input1_dims), CreateTensor(input2_data, input2_dims), CreateTensor(output_data, output_dims)}; int inputs_array_data[] = {2, 0, 1}; TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data); int outputs_array_data[] = {1, 2}; TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data); TfLiteConcatenationParams builtin_data = { .axis = axis, .activation = kTfLiteActNone // Only activation supported in this impl }; const TfLiteRegistration registration = tflite::ops::micro::Register_CONCATENATION(); micro::KernelRunner runner( registration, tensors, tensors_size, inputs_array, outputs_array, reinterpret_cast<void*>(&builtin_data), micro_test::reporter); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.InitAndPrepare()); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.Invoke()); const int output_dims_count = ElementCount(*output_dims); for (int i = 0; i < output_dims_count; ++i) { TF_LITE_MICRO_EXPECT_NEAR(expected_output_data[i], output_data[i], 1e-5f); } } void TestConcatenateQuantizedTwoInputs( const int* input1_dims_data, const uint8_t* input1_data, const int* input2_dims_data, const uint8_t* input2_data, const float input_scale, const int input_zero_point, int axis, const int* output_dims_data, const uint8_t* expected_output_data, const float output_scale, const int output_zero_point, uint8_t* output_data) { TfLiteIntArray* input1_dims = IntArrayFromInts(input1_dims_data); TfLiteIntArray* input2_dims = IntArrayFromInts(input2_dims_data); TfLiteIntArray* output_dims = IntArrayFromInts(output_dims_data); constexpr int input_size = 2; constexpr int output_size = 1; constexpr int tensors_size = input_size + output_size; TfLiteTensor tensors[tensors_size] = { CreateQuantizedTensor(input1_data, input1_dims, input_scale, input_zero_point), CreateQuantizedTensor(input2_data, input2_dims, input_scale, input_zero_point), CreateQuantizedTensor(output_data, output_dims, output_scale, output_zero_point)}; int inputs_array_data[] = {2, 0, 1}; TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data); int outputs_array_data[] = {1, 2}; TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data); TfLiteConcatenationParams builtin_data = { .axis = axis, .activation = kTfLiteActNone // Only activation supported in this impl }; const TfLiteRegistration registration = tflite::ops::micro::Register_CONCATENATION(); micro::KernelRunner runner( registration, tensors, tensors_size, inputs_array, outputs_array, reinterpret_cast<void*>(&builtin_data), micro_test::reporter); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.InitAndPrepare()); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.Invoke()); const int output_dims_count = ElementCount(*output_dims); for (int i = 0; i < output_dims_count; ++i) { TF_LITE_MICRO_EXPECT_EQ(expected_output_data[i], output_data[i]); } } } // namespace } // namespace testing } // namespace tflite TF_LITE_MICRO_TESTS_BEGIN TF_LITE_MICRO_TEST(TwoInputsAllAxesCombinations) { // Concatenate the same two input tensors along all possible axes. const int input_shape[] = {2, 2, 3}; const float input1_value[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; const float input2_value[] = {7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f}; // expected output when concatenating on axis 0 const int output_shape_axis0[] = {2, 4, 3}; const float output_value_axis0[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f}; // expected output when concatenating on axis 1 const int output_shape_axis1[] = {2, 2, 6}; const float output_value_axis1[] = {1.0f, 2.0f, 3.0f, 7.0f, 8.0f, 9.0f, 4.0f, 5.0f, 6.0f, 10.0f, 11.0f, 12.0f}; float output_data[12]; // Axis = 0 tflite::testing::TestConcatenateTwoInputs( input_shape, input1_value, input_shape, input2_value, /* axis */ 0, output_shape_axis0, output_value_axis0, output_data); // Axis = -2 (equivalent to axis = 0) tflite::testing::TestConcatenateTwoInputs( input_shape, input1_value, input_shape, input2_value, /* axis */ -2, output_shape_axis0, output_value_axis0, output_data); // Axis = 1 tflite::testing::TestConcatenateTwoInputs( input_shape, input1_value, input_shape, input2_value, /* axis */ 1, output_shape_axis1, output_value_axis1, output_data); // Axis = -1 (equivalent to axis = 1) tflite::testing::TestConcatenateTwoInputs( input_shape, input1_value, input_shape, input2_value, /* axis */ -1, output_shape_axis1, output_value_axis1, output_data); } TF_LITE_MICRO_TEST(TwoInputsQuantizedUint8) { const int axis = 2; const int input_shape[] = {3, 2, 1, 2}; const int output_shape[] = {3, 2, 1, 4}; const float input_scale = 0.1f; const int input_zero_point = 127; const float output_scale = 0.1f; const int output_zero_point = 127; const uint8_t input1_values[] = {137, 157, 167, 197}; const uint8_t input2_values[] = {138, 158, 168, 198}; const uint8_t output_value[] = { 137, 157, 138, 158, 167, 197, 168, 198, }; uint8_t output_data[8]; tflite::testing::TestConcatenateQuantizedTwoInputs( input_shape, input1_values, input_shape, input2_values, input_scale, input_zero_point, axis, output_shape, output_value, output_scale, output_zero_point, output_data); } TF_LITE_MICRO_TEST(ThreeDimensionalTwoInputsDifferentShapes) { const int axis = 1; const int input1_shape[] = {3, 2, 1, 2}; const int input2_shape[] = {3, 2, 3, 2}; const int output_shape[] = {3, 2, 4, 2}; const float input1_values[] = {1.0f, 3.0f, 4.0f, 7.0f}; const float input2_values[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f}; const float output_values[] = {1.0f, 3.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 4.0f, 7.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f}; float output_data[16]; tflite::testing::TestConcatenateTwoInputs( input1_shape, input1_values, input2_shape, input2_values, axis, output_shape, output_values, output_data); } TF_LITE_MICRO_TESTS_END
39.822967
80
0.683528
pschatzmann
cb7f063423874a220d372378682c40d152c175dd
20,626
cc
C++
ash/assistant/assistant_alarm_timer_controller_impl.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
ash/assistant/assistant_alarm_timer_controller_impl.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
ash/assistant/assistant_alarm_timer_controller_impl.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 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 "ash/assistant/assistant_alarm_timer_controller_impl.h" #include <cmath> #include <utility> #include "ash/assistant/assistant_controller_impl.h" #include "ash/assistant/assistant_notification_controller_impl.h" #include "ash/assistant/util/deep_link_util.h" #include "ash/strings/grit/ash_strings.h" #include "base/bind.h" #include "base/i18n/message_formatter.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "chromeos/services/assistant/public/cpp/assistant_service.h" #include "chromeos/services/assistant/public/cpp/features.h" #include "chromeos/services/libassistant/public/cpp/assistant_notification.h" #include "chromeos/services/libassistant/public/cpp/assistant_timer.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" #include "third_party/icu/source/common/unicode/utypes.h" #include "third_party/icu/source/i18n/unicode/measfmt.h" #include "third_party/icu/source/i18n/unicode/measunit.h" #include "third_party/icu/source/i18n/unicode/measure.h" #include "ui/base/l10n/l10n_util.h" namespace ash { namespace { using assistant::util::AlarmTimerAction; using chromeos::assistant::AssistantNotification; using chromeos::assistant::AssistantNotificationButton; using chromeos::assistant::AssistantNotificationPriority; using chromeos::assistant::AssistantTimer; using chromeos::assistant::AssistantTimerState; // Grouping key and ID prefix for timer notifications. constexpr char kTimerNotificationGroupingKey[] = "assistant/timer"; constexpr char kTimerNotificationIdPrefix[] = "assistant/timer"; // Helpers --------------------------------------------------------------------- std::string ToFormattedTimeString(base::TimeDelta time, UMeasureFormatWidth width) { DCHECK(width == UMEASFMT_WIDTH_NARROW || width == UMEASFMT_WIDTH_NUMERIC); // Method aliases to prevent line-wrapping below. const auto createHour = icu::MeasureUnit::createHour; const auto createMinute = icu::MeasureUnit::createMinute; const auto createSecond = icu::MeasureUnit::createSecond; // We round |total_seconds| to the nearest full second since we don't display // our time string w/ millisecond granularity and because this method is // called very near to full second boundaries. Otherwise, values like 4.99 sec // would be displayed to the user as "0:04" instead of the expected "0:05". const int64_t total_seconds = std::abs(std::round(time.InSecondsF())); // Calculate time in hours/minutes/seconds. const int32_t hours = total_seconds / 3600; const int32_t minutes = (total_seconds - hours * 3600) / 60; const int32_t seconds = total_seconds % 60; // Success of the ICU APIs is tracked by |status|. UErrorCode status = U_ZERO_ERROR; // Create our distinct |measures| to be formatted. std::vector<icu::Measure> measures; // We only show |hours| if necessary. if (hours) measures.emplace_back(hours, createHour(status), status); // We only show |minutes| if necessary or if using numeric format |width|. if (minutes || width == UMEASFMT_WIDTH_NUMERIC) measures.emplace_back(minutes, createMinute(status), status); // We only show |seconds| if necessary or if using numeric format |width|. if (seconds || width == UMEASFMT_WIDTH_NUMERIC) measures.emplace_back(seconds, createSecond(status), status); // Format our |measures| into a |unicode_message|. icu::UnicodeString unicode_message; icu::FieldPosition field_position = icu::FieldPosition::DONT_CARE; icu::MeasureFormat measure_format(icu::Locale::getDefault(), width, status); measure_format.formatMeasures(measures.data(), measures.size(), unicode_message, field_position, status); std::string formatted_time; if (U_SUCCESS(status)) { // If formatting was successful, convert our |unicode_message| into UTF-8. unicode_message.toUTF8String(formatted_time); } else { // If something went wrong formatting w/ ICU, fall back to I18N messages. LOG(ERROR) << "Error formatting time string: " << status; formatted_time = base::UTF16ToUTF8(base::i18n::MessageFormatter::FormatWithNumberedArgs( l10n_util::GetStringUTF16( width == UMEASFMT_WIDTH_NARROW ? IDS_ASSISTANT_TIMER_NOTIFICATION_FORMATTED_TIME_NARROW_FALLBACK : IDS_ASSISTANT_TIMER_NOTIFICATION_FORMATTED_TIME_NUMERIC_FALLBACK), hours, minutes, seconds)); } // If necessary, negate the amount of time remaining. if (time.InSeconds() < 0) { formatted_time = base::UTF16ToUTF8(base::i18n::MessageFormatter::FormatWithNumberedArgs( l10n_util::GetStringUTF16( IDS_ASSISTANT_TIMER_NOTIFICATION_FORMATTED_TIME_NEGATE), formatted_time)); } return formatted_time; } // Returns a string representation of the original duration for a given |timer|. std::string ToOriginalDurationString(const AssistantTimer& timer) { return ToFormattedTimeString(timer.original_duration, UMEASFMT_WIDTH_NARROW); } // Returns a string representation of the remaining time for the given |timer|. std::string ToRemainingTimeString(const AssistantTimer& timer) { return ToFormattedTimeString(timer.remaining_time, UMEASFMT_WIDTH_NUMERIC); } // Creates a notification ID for the given |timer|. It is guaranteed that this // method will always return the same notification ID given the same timer. std::string CreateTimerNotificationId(const AssistantTimer& timer) { return std::string(kTimerNotificationIdPrefix) + timer.id; } // Creates a notification title for the given |timer|. std::string CreateTimerNotificationTitle(const AssistantTimer& timer) { return ToRemainingTimeString(timer); } // Creates a notification message for the given |timer|. std::string CreateTimerNotificationMessage(const AssistantTimer& timer) { if (timer.label.empty()) { return base::UTF16ToUTF8( base::i18n::MessageFormatter::FormatWithNumberedArgs( l10n_util::GetStringUTF16( timer.state == AssistantTimerState::kFired ? IDS_ASSISTANT_TIMER_NOTIFICATION_MESSAGE_WHEN_FIRED : IDS_ASSISTANT_TIMER_NOTIFICATION_MESSAGE), ToOriginalDurationString(timer))); } return base::UTF16ToUTF8(base::i18n::MessageFormatter::FormatWithNumberedArgs( l10n_util::GetStringUTF16( timer.state == AssistantTimerState::kFired ? IDS_ASSISTANT_TIMER_NOTIFICATION_MESSAGE_WHEN_FIRED_WITH_LABEL : IDS_ASSISTANT_TIMER_NOTIFICATION_MESSAGE_WITH_LABEL), ToOriginalDurationString(timer), timer.label)); } // Creates notification buttons for the given |timer|. std::vector<AssistantNotificationButton> CreateTimerNotificationButtons( const AssistantTimer& timer) { std::vector<AssistantNotificationButton> buttons; if (timer.state != AssistantTimerState::kFired) { if (timer.state == AssistantTimerState::kPaused) { // "RESUME" button. buttons.push_back({l10n_util::GetStringUTF8( IDS_ASSISTANT_TIMER_NOTIFICATION_RESUME_BUTTON), assistant::util::CreateAlarmTimerDeepLink( AlarmTimerAction::kResumeTimer, timer.id) .value(), /*remove_notification_on_click=*/false}); } else { // "PAUSE" button. buttons.push_back({l10n_util::GetStringUTF8( IDS_ASSISTANT_TIMER_NOTIFICATION_PAUSE_BUTTON), assistant::util::CreateAlarmTimerDeepLink( AlarmTimerAction::kPauseTimer, timer.id) .value(), /*remove_notification_on_click=*/false}); } } if (timer.state == AssistantTimerState::kFired) { // "STOP" button. buttons.push_back( {l10n_util::GetStringUTF8(IDS_ASSISTANT_TIMER_NOTIFICATION_STOP_BUTTON), assistant::util::CreateAlarmTimerDeepLink( AlarmTimerAction::kRemoveAlarmOrTimer, timer.id) .value(), /*remove_notification_on_click=*/true}); // "ADD 1 MIN" button. buttons.push_back( {l10n_util::GetStringUTF8( IDS_ASSISTANT_TIMER_NOTIFICATION_ADD_1_MIN_BUTTON), assistant::util::CreateAlarmTimerDeepLink( AlarmTimerAction::kAddTimeToTimer, timer.id, base::Minutes(1)) .value(), /*remove_notification_on_click=*/false}); } else { // "CANCEL" button. buttons.push_back({l10n_util::GetStringUTF8( IDS_ASSISTANT_TIMER_NOTIFICATION_CANCEL_BUTTON), assistant::util::CreateAlarmTimerDeepLink( AlarmTimerAction::kRemoveAlarmOrTimer, timer.id) .value(), /*remove_notification_on_click=*/true}); } return buttons; } // Creates a timer notification priority for the given |timer|. AssistantNotificationPriority CreateTimerNotificationPriority( const AssistantTimer& timer) { // In timers v2, a notification for a |kFired| timer is |kHigh| priority. // This will cause the notification to pop up to the user. if (timer.state == AssistantTimerState::kFired) return AssistantNotificationPriority::kHigh; // If the notification has lived for at least |kPopupThreshold|, drop the // priority to |kLow| so that the notification will not pop up to the user. constexpr base::TimeDelta kPopupThreshold = base::Seconds(6); const base::TimeDelta lifetime = base::Time::Now() - timer.creation_time.value_or(base::Time::Now()); if (lifetime >= kPopupThreshold) return AssistantNotificationPriority::kLow; // Otherwise, the notification is |kDefault| priority. This means that it // may or may not pop up to the user, depending on the presence of other // notifications. return AssistantNotificationPriority::kDefault; } // Creates a notification for the given |timer|. AssistantNotification CreateTimerNotification( const AssistantTimer& timer, const AssistantNotification* existing_notification = nullptr) { AssistantNotification notification; notification.title = CreateTimerNotificationTitle(timer); notification.message = CreateTimerNotificationMessage(timer); notification.buttons = CreateTimerNotificationButtons(timer); notification.client_id = CreateTimerNotificationId(timer); notification.grouping_key = kTimerNotificationGroupingKey; notification.priority = CreateTimerNotificationPriority(timer); notification.remove_on_click = false; notification.is_pinned = true; // If we are creating a notification to replace an |existing_notification| and // our new notification has higher priority, we want the system to "renotify" // the user of the notification change. This will cause the new notification // to popup to the user even if it was previously marked as read. if (existing_notification && notification.priority > existing_notification->priority) { notification.renotify = true; } return notification; } // Returns whether an |update| from LibAssistant to the specified |original| // timer is allowed. Updates are always allowed in v1, only conditionally in v2. bool ShouldAllowUpdateFromLibAssistant(const AssistantTimer& original, const AssistantTimer& update) { // If |id| is not equal, then |update| does refer to the |original| timer. DCHECK_EQ(original.id, update.id); // In v2, updates are only allowed from LibAssistant if they are significant. // We may receive an update due to a state change in another timer, and we'd // want to discard the update to this timer to avoid introducing UI jank by // updating its notification outside of its regular tick interval. In v2, we // also update timer state from |kScheduled| to |kFired| ourselves to work // around latency in receiving the event from LibAssistant. When we do so, we // expect to later receive the state change from LibAssistant but discard it. return !original.IsEqualInLibAssistantTo(update); } } // namespace // AssistantAlarmTimerControllerImpl ------------------------------------------ AssistantAlarmTimerControllerImpl::AssistantAlarmTimerControllerImpl( AssistantControllerImpl* assistant_controller) : assistant_controller_(assistant_controller) { model_.AddObserver(this); assistant_controller_observation_.Observe(AssistantController::Get()); } AssistantAlarmTimerControllerImpl::~AssistantAlarmTimerControllerImpl() { model_.RemoveObserver(this); } void AssistantAlarmTimerControllerImpl::SetAssistant( chromeos::assistant::Assistant* assistant) { assistant_ = assistant; } const AssistantAlarmTimerModel* AssistantAlarmTimerControllerImpl::GetModel() const { return &model_; } void AssistantAlarmTimerControllerImpl::OnTimerStateChanged( const std::vector<AssistantTimer>& new_or_updated_timers) { // First we remove all old timers that no longer exist. for (const auto* old_timer : model_.GetAllTimers()) { if (std::none_of(new_or_updated_timers.begin(), new_or_updated_timers.end(), [&old_timer](const auto& new_or_updated_timer) { return old_timer->id == new_or_updated_timer.id; })) { model_.RemoveTimer(old_timer->id); } } // Then we add any new timers and update existing ones (if allowed). for (const auto& new_or_updated_timer : new_or_updated_timers) { const auto* original_timer = model_.GetTimerById(new_or_updated_timer.id); const bool is_new_timer = original_timer == nullptr; if (is_new_timer || ShouldAllowUpdateFromLibAssistant( *original_timer, new_or_updated_timer)) { model_.AddOrUpdateTimer(std::move(new_or_updated_timer)); } } } void AssistantAlarmTimerControllerImpl::OnAssistantControllerConstructed() { AssistantState::Get()->AddObserver(this); } void AssistantAlarmTimerControllerImpl::OnAssistantControllerDestroying() { AssistantState::Get()->RemoveObserver(this); } void AssistantAlarmTimerControllerImpl::OnDeepLinkReceived( assistant::util::DeepLinkType type, const std::map<std::string, std::string>& params) { using assistant::util::DeepLinkParam; using assistant::util::DeepLinkType; if (type != DeepLinkType::kAlarmTimer) return; const absl::optional<AlarmTimerAction>& action = assistant::util::GetDeepLinkParamAsAlarmTimerAction(params); if (!action.has_value()) return; const absl::optional<std::string>& alarm_timer_id = assistant::util::GetDeepLinkParam(params, DeepLinkParam::kId); if (!alarm_timer_id.has_value()) return; // Duration is optional. Only used for adding time to timer. const absl::optional<base::TimeDelta>& duration = assistant::util::GetDeepLinkParamAsTimeDelta(params, DeepLinkParam::kDurationMs); PerformAlarmTimerAction(action.value(), alarm_timer_id.value(), duration); } void AssistantAlarmTimerControllerImpl::OnAssistantStatusChanged( chromeos::assistant::AssistantStatus status) { // If LibAssistant is no longer running we need to clear our cache to // accurately reflect LibAssistant alarm/timer state. if (status == chromeos::assistant::AssistantStatus::NOT_READY) model_.RemoveAllTimers(); } void AssistantAlarmTimerControllerImpl::OnTimerAdded( const AssistantTimer& timer) { // Schedule the next tick of |timer|. ScheduleNextTick(timer); // Create a notification for the added alarm/timer. assistant_controller_->notification_controller()->AddOrUpdateNotification( CreateTimerNotification(timer)); } void AssistantAlarmTimerControllerImpl::OnTimerUpdated( const AssistantTimer& timer) { // Schedule the next tick of |timer|. ScheduleNextTick(timer); auto* notification_controller = assistant_controller_->notification_controller(); const auto* existing_notification = notification_controller->model()->GetNotificationById( CreateTimerNotificationId(timer)); // When a |timer| is updated we need to update the corresponding notification // unless it has already been dismissed by the user. if (existing_notification) { notification_controller->AddOrUpdateNotification( CreateTimerNotification(timer, existing_notification)); } } void AssistantAlarmTimerControllerImpl::OnTimerRemoved( const AssistantTimer& timer) { // Clean up the ticker for |timer|, if one exists. tickers_.erase(timer.id); // Remove any notification associated w/ |timer|. assistant_controller_->notification_controller()->RemoveNotificationById( CreateTimerNotificationId(timer), /*from_server=*/false); } void AssistantAlarmTimerControllerImpl::PerformAlarmTimerAction( const AlarmTimerAction& action, const std::string& alarm_timer_id, const absl::optional<base::TimeDelta>& duration) { DCHECK(assistant_); switch (action) { case AlarmTimerAction::kAddTimeToTimer: if (!duration.has_value()) { LOG(ERROR) << "Ignoring add time to timer action duration."; return; } assistant_->AddTimeToTimer(alarm_timer_id, duration.value()); break; case AlarmTimerAction::kPauseTimer: DCHECK(!duration.has_value()); assistant_->PauseTimer(alarm_timer_id); break; case AlarmTimerAction::kRemoveAlarmOrTimer: DCHECK(!duration.has_value()); assistant_->RemoveAlarmOrTimer(alarm_timer_id); break; case AlarmTimerAction::kResumeTimer: DCHECK(!duration.has_value()); assistant_->ResumeTimer(alarm_timer_id); break; } } void AssistantAlarmTimerControllerImpl::ScheduleNextTick( const AssistantTimer& timer) { auto& ticker = tickers_[timer.id]; if (ticker.IsRunning()) return; // The next tick of |timer| should occur at its next full second of remaining // time. Here we are calculating the number of milliseconds to that next full // second. int millis_to_next_full_sec = timer.remaining_time.InMilliseconds() % 1000; // If |timer| has already fired, |millis_to_next_full_sec| will be negative. // In this case, we take the inverse of the value to get the correct number of // milliseconds to the next full second of remaining time. if (millis_to_next_full_sec < 0) millis_to_next_full_sec = 1000 + millis_to_next_full_sec; // If we are exactly at the boundary of a full second, we want to make sure // we wait until the next second to perform the next tick. Otherwise we'll end // up w/ a superfluous tick that is unnecessary. if (millis_to_next_full_sec == 0) millis_to_next_full_sec = 1000; // NOTE: We pass a copy of |timer.id| here as |timer| may no longer exist // when Tick() is called due to the possibility of the |model_| being updated // via a call to OnTimerStateChanged(), such as might happen if a timer is // created, paused, resumed, or removed by LibAssistant. ticker.Start(FROM_HERE, base::Milliseconds(millis_to_next_full_sec), base::BindOnce(&AssistantAlarmTimerControllerImpl::Tick, base::Unretained(this), timer.id)); } void AssistantAlarmTimerControllerImpl::Tick(const std::string& timer_id) { const auto* timer = model_.GetTimerById(timer_id); DCHECK(timer); // We don't tick paused timers. Once the |timer| resumes, ticking will resume. if (timer->state == AssistantTimerState::kPaused) return; // Update |timer| to reflect the new amount of |remaining_time|. AssistantTimer updated_timer(*timer); updated_timer.remaining_time = updated_timer.fire_time - base::Time::Now(); // If there is no remaining time left on the timer, we ensure that our timer // is marked as |kFired|. Since LibAssistant may be a bit slow to notify us of // the change in state, we set the value ourselves to eliminate UI jank. // NOTE: We use the rounded value of |remaining_time| since that's what we are // displaying to the user and otherwise would be out of sync for ticks // occurring at full second boundary values. if (std::round(updated_timer.remaining_time.InSecondsF()) <= 0.f) updated_timer.state = AssistantTimerState::kFired; model_.AddOrUpdateTimer(std::move(updated_timer)); } } // namespace ash
41.584677
88
0.721468
zealoussnow
cb7f46d2660af5fd64bf8c35c812b4481e56a7d3
34,615
cc
C++
source/scale_mips.cc
herocodemaster/libyuv-chromium
83f460be3324ccd546ca45e6c282e8f201853e54
[ "BSD-3-Clause" ]
36
2016-06-10T02:42:37.000Z
2021-12-09T04:57:25.000Z
source/scale_mips.cc
herocodemaster/libyuv-chromium
83f460be3324ccd546ca45e6c282e8f201853e54
[ "BSD-3-Clause" ]
2
2017-01-03T12:37:35.000Z
2017-01-11T12:49:53.000Z
source/scale_mips.cc
herocodemaster/libyuv-chromium
83f460be3324ccd546ca45e6c282e8f201853e54
[ "BSD-3-Clause" ]
15
2016-11-16T02:30:42.000Z
2021-08-10T09:01:26.000Z
/* * Copyright 2012 The LibYuv Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "libyuv/basic_types.h" #include "libyuv/row.h" #ifdef __cplusplus namespace libyuv { extern "C" { #endif // This module is for GCC MIPS DSPR2 #if !defined(LIBYUV_DISABLE_MIPS) && defined(__mips_dsp) && \ (__mips_dsp_rev >= 2) && (_MIPS_SIM == _MIPS_SIM_ABI32) void ScaleRowDown2_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "srl $t9, %[dst_width], 4 \n" // iterations -> by 16 "beqz $t9, 2f \n" " nop \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t1, 4(%[src_ptr]) \n" // |7|6|5|4| "lw $t2, 8(%[src_ptr]) \n" // |11|10|9|8| "lw $t3, 12(%[src_ptr]) \n" // |15|14|13|12| "lw $t4, 16(%[src_ptr]) \n" // |19|18|17|16| "lw $t5, 20(%[src_ptr]) \n" // |23|22|21|20| "lw $t6, 24(%[src_ptr]) \n" // |27|26|25|24| "lw $t7, 28(%[src_ptr]) \n" // |31|30|29|28| // TODO(fbarchard): Use odd pixels instead of even. "precr.qb.ph $t8, $t1, $t0 \n" // |6|4|2|0| "precr.qb.ph $t0, $t3, $t2 \n" // |14|12|10|8| "precr.qb.ph $t1, $t5, $t4 \n" // |22|20|18|16| "precr.qb.ph $t2, $t7, $t6 \n" // |30|28|26|24| "addiu %[src_ptr], %[src_ptr], 32 \n" "addiu $t9, $t9, -1 \n" "sw $t8, 0(%[dst]) \n" "sw $t0, 4(%[dst]) \n" "sw $t1, 8(%[dst]) \n" "sw $t2, 12(%[dst]) \n" "bgtz $t9, 1b \n" " addiu %[dst], %[dst], 16 \n" "2: \n" "andi $t9, %[dst_width], 0xf \n" // residue "beqz $t9, 3f \n" " nop \n" "21: \n" "lbu $t0, 0(%[src_ptr]) \n" "addiu %[src_ptr], %[src_ptr], 2 \n" "addiu $t9, $t9, -1 \n" "sb $t0, 0(%[dst]) \n" "bgtz $t9, 21b \n" " addiu %[dst], %[dst], 1 \n" "3: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst) : [dst_width] "r"(dst_width) : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9"); } void ScaleRowDown2Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { const uint8* t = src_ptr + src_stride; __asm__ __volatile__( ".set push \n" ".set noreorder \n" "srl $t9, %[dst_width], 3 \n" // iterations -> step 8 "bltz $t9, 2f \n" " nop \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t1, 4(%[src_ptr]) \n" // |7|6|5|4| "lw $t2, 8(%[src_ptr]) \n" // |11|10|9|8| "lw $t3, 12(%[src_ptr]) \n" // |15|14|13|12| "lw $t4, 0(%[t]) \n" // |19|18|17|16| "lw $t5, 4(%[t]) \n" // |23|22|21|20| "lw $t6, 8(%[t]) \n" // |27|26|25|24| "lw $t7, 12(%[t]) \n" // |31|30|29|28| "addiu $t9, $t9, -1 \n" "srl $t8, $t0, 16 \n" // |X|X|3|2| "ins $t0, $t4, 16, 16 \n" // |17|16|1|0| "ins $t4, $t8, 0, 16 \n" // |19|18|3|2| "raddu.w.qb $t0, $t0 \n" // |17+16+1+0| "raddu.w.qb $t4, $t4 \n" // |19+18+3+2| "shra_r.w $t0, $t0, 2 \n" // |t0+2|>>2 "shra_r.w $t4, $t4, 2 \n" // |t4+2|>>2 "srl $t8, $t1, 16 \n" // |X|X|7|6| "ins $t1, $t5, 16, 16 \n" // |21|20|5|4| "ins $t5, $t8, 0, 16 \n" // |22|23|7|6| "raddu.w.qb $t1, $t1 \n" // |21+20+5+4| "raddu.w.qb $t5, $t5 \n" // |23+22+7+6| "shra_r.w $t1, $t1, 2 \n" // |t1+2|>>2 "shra_r.w $t5, $t5, 2 \n" // |t5+2|>>2 "srl $t8, $t2, 16 \n" // |X|X|11|10| "ins $t2, $t6, 16, 16 \n" // |25|24|9|8| "ins $t6, $t8, 0, 16 \n" // |27|26|11|10| "raddu.w.qb $t2, $t2 \n" // |25+24+9+8| "raddu.w.qb $t6, $t6 \n" // |27+26+11+10| "shra_r.w $t2, $t2, 2 \n" // |t2+2|>>2 "shra_r.w $t6, $t6, 2 \n" // |t5+2|>>2 "srl $t8, $t3, 16 \n" // |X|X|15|14| "ins $t3, $t7, 16, 16 \n" // |29|28|13|12| "ins $t7, $t8, 0, 16 \n" // |31|30|15|14| "raddu.w.qb $t3, $t3 \n" // |29+28+13+12| "raddu.w.qb $t7, $t7 \n" // |31+30+15+14| "shra_r.w $t3, $t3, 2 \n" // |t3+2|>>2 "shra_r.w $t7, $t7, 2 \n" // |t7+2|>>2 "addiu %[src_ptr], %[src_ptr], 16 \n" "addiu %[t], %[t], 16 \n" "sb $t0, 0(%[dst]) \n" "sb $t4, 1(%[dst]) \n" "sb $t1, 2(%[dst]) \n" "sb $t5, 3(%[dst]) \n" "sb $t2, 4(%[dst]) \n" "sb $t6, 5(%[dst]) \n" "sb $t3, 6(%[dst]) \n" "sb $t7, 7(%[dst]) \n" "bgtz $t9, 1b \n" " addiu %[dst], %[dst], 8 \n" "2: \n" "andi $t9, %[dst_width], 0x7 \n" // x = residue "beqz $t9, 3f \n" " nop \n" "21: \n" "lwr $t1, 0(%[src_ptr]) \n" "lwl $t1, 3(%[src_ptr]) \n" "lwr $t2, 0(%[t]) \n" "lwl $t2, 3(%[t]) \n" "srl $t8, $t1, 16 \n" "ins $t1, $t2, 16, 16 \n" "ins $t2, $t8, 0, 16 \n" "raddu.w.qb $t1, $t1 \n" "raddu.w.qb $t2, $t2 \n" "shra_r.w $t1, $t1, 2 \n" "shra_r.w $t2, $t2, 2 \n" "sb $t1, 0(%[dst]) \n" "sb $t2, 1(%[dst]) \n" "addiu %[src_ptr], %[src_ptr], 4 \n" "addiu $t9, $t9, -2 \n" "addiu %[t], %[t], 4 \n" "bgtz $t9, 21b \n" " addiu %[dst], %[dst], 2 \n" "3: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [t] "+r"(t) : [dst_width] "r"(dst_width) : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9"); } void ScaleRowDown4_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "srl $t9, %[dst_width], 3 \n" "beqz $t9, 2f \n" " nop \n" "1: \n" "lw $t1, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t2, 4(%[src_ptr]) \n" // |7|6|5|4| "lw $t3, 8(%[src_ptr]) \n" // |11|10|9|8| "lw $t4, 12(%[src_ptr]) \n" // |15|14|13|12| "lw $t5, 16(%[src_ptr]) \n" // |19|18|17|16| "lw $t6, 20(%[src_ptr]) \n" // |23|22|21|20| "lw $t7, 24(%[src_ptr]) \n" // |27|26|25|24| "lw $t8, 28(%[src_ptr]) \n" // |31|30|29|28| "precr.qb.ph $t1, $t2, $t1 \n" // |6|4|2|0| "precr.qb.ph $t2, $t4, $t3 \n" // |14|12|10|8| "precr.qb.ph $t5, $t6, $t5 \n" // |22|20|18|16| "precr.qb.ph $t6, $t8, $t7 \n" // |30|28|26|24| "precr.qb.ph $t1, $t2, $t1 \n" // |12|8|4|0| "precr.qb.ph $t5, $t6, $t5 \n" // |28|24|20|16| "addiu %[src_ptr], %[src_ptr], 32 \n" "addiu $t9, $t9, -1 \n" "sw $t1, 0(%[dst]) \n" "sw $t5, 4(%[dst]) \n" "bgtz $t9, 1b \n" " addiu %[dst], %[dst], 8 \n" "2: \n" "andi $t9, %[dst_width], 7 \n" // residue "beqz $t9, 3f \n" " nop \n" "21: \n" "lbu $t1, 0(%[src_ptr]) \n" "addiu %[src_ptr], %[src_ptr], 4 \n" "addiu $t9, $t9, -1 \n" "sb $t1, 0(%[dst]) \n" "bgtz $t9, 21b \n" " addiu %[dst], %[dst], 1 \n" "3: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst) : [dst_width] "r"(dst_width) : "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9"); } void ScaleRowDown4Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { intptr_t stride = src_stride; const uint8* s1 = src_ptr + stride; const uint8* s2 = s1 + stride; const uint8* s3 = s2 + stride; __asm__ __volatile__( ".set push \n" ".set noreorder \n" "srl $t9, %[dst_width], 1 \n" "andi $t8, %[dst_width], 1 \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t1, 0(%[s1]) \n" // |7|6|5|4| "lw $t2, 0(%[s2]) \n" // |11|10|9|8| "lw $t3, 0(%[s3]) \n" // |15|14|13|12| "lw $t4, 4(%[src_ptr]) \n" // |19|18|17|16| "lw $t5, 4(%[s1]) \n" // |23|22|21|20| "lw $t6, 4(%[s2]) \n" // |27|26|25|24| "lw $t7, 4(%[s3]) \n" // |31|30|29|28| "raddu.w.qb $t0, $t0 \n" // |3 + 2 + 1 + 0| "raddu.w.qb $t1, $t1 \n" // |7 + 6 + 5 + 4| "raddu.w.qb $t2, $t2 \n" // |11 + 10 + 9 + 8| "raddu.w.qb $t3, $t3 \n" // |15 + 14 + 13 + 12| "raddu.w.qb $t4, $t4 \n" // |19 + 18 + 17 + 16| "raddu.w.qb $t5, $t5 \n" // |23 + 22 + 21 + 20| "raddu.w.qb $t6, $t6 \n" // |27 + 26 + 25 + 24| "raddu.w.qb $t7, $t7 \n" // |31 + 30 + 29 + 28| "add $t0, $t0, $t1 \n" "add $t1, $t2, $t3 \n" "add $t0, $t0, $t1 \n" "add $t4, $t4, $t5 \n" "add $t6, $t6, $t7 \n" "add $t4, $t4, $t6 \n" "shra_r.w $t0, $t0, 4 \n" "shra_r.w $t4, $t4, 4 \n" "sb $t0, 0(%[dst]) \n" "sb $t4, 1(%[dst]) \n" "addiu %[src_ptr], %[src_ptr], 8 \n" "addiu %[s1], %[s1], 8 \n" "addiu %[s2], %[s2], 8 \n" "addiu %[s3], %[s3], 8 \n" "addiu $t9, $t9, -1 \n" "bgtz $t9, 1b \n" " addiu %[dst], %[dst], 2 \n" "beqz $t8, 2f \n" " nop \n" "lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t1, 0(%[s1]) \n" // |7|6|5|4| "lw $t2, 0(%[s2]) \n" // |11|10|9|8| "lw $t3, 0(%[s3]) \n" // |15|14|13|12| "raddu.w.qb $t0, $t0 \n" // |3 + 2 + 1 + 0| "raddu.w.qb $t1, $t1 \n" // |7 + 6 + 5 + 4| "raddu.w.qb $t2, $t2 \n" // |11 + 10 + 9 + 8| "raddu.w.qb $t3, $t3 \n" // |15 + 14 + 13 + 12| "add $t0, $t0, $t1 \n" "add $t1, $t2, $t3 \n" "add $t0, $t0, $t1 \n" "shra_r.w $t0, $t0, 4 \n" "sb $t0, 0(%[dst]) \n" "2: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [s1] "+r"(s1), [s2] "+r"(s2), [s3] "+r"(s3) : [dst_width] "r"(dst_width) : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9"); } void ScaleRowDown34_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "1: \n" "lw $t1, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t2, 4(%[src_ptr]) \n" // |7|6|5|4| "lw $t3, 8(%[src_ptr]) \n" // |11|10|9|8| "lw $t4, 12(%[src_ptr]) \n" // |15|14|13|12| "lw $t5, 16(%[src_ptr]) \n" // |19|18|17|16| "lw $t6, 20(%[src_ptr]) \n" // |23|22|21|20| "lw $t7, 24(%[src_ptr]) \n" // |27|26|25|24| "lw $t8, 28(%[src_ptr]) \n" // |31|30|29|28| "precrq.qb.ph $t0, $t2, $t4 \n" // |7|5|15|13| "precrq.qb.ph $t9, $t6, $t8 \n" // |23|21|31|30| "addiu %[dst_width], %[dst_width], -24 \n" "ins $t1, $t1, 8, 16 \n" // |3|1|0|X| "ins $t4, $t0, 8, 16 \n" // |X|15|13|12| "ins $t5, $t5, 8, 16 \n" // |19|17|16|X| "ins $t8, $t9, 8, 16 \n" // |X|31|29|28| "addiu %[src_ptr], %[src_ptr], 32 \n" "packrl.ph $t0, $t3, $t0 \n" // |9|8|7|5| "packrl.ph $t9, $t7, $t9 \n" // |25|24|23|21| "prepend $t1, $t2, 8 \n" // |4|3|1|0| "prepend $t3, $t4, 24 \n" // |15|13|12|11| "prepend $t5, $t6, 8 \n" // |20|19|17|16| "prepend $t7, $t8, 24 \n" // |31|29|28|27| "sw $t1, 0(%[dst]) \n" "sw $t0, 4(%[dst]) \n" "sw $t3, 8(%[dst]) \n" "sw $t5, 12(%[dst]) \n" "sw $t9, 16(%[dst]) \n" "sw $t7, 20(%[dst]) \n" "bnez %[dst_width], 1b \n" " addiu %[dst], %[dst], 24 \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [dst_width] "+r"(dst_width) : : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9"); } void ScaleRowDown34_0_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* d, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "repl.ph $t3, 3 \n" // 0x00030003 "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0| "lwx $t1, %[src_stride](%[src_ptr]) \n" // |T3|T2|T1|T0| "rotr $t2, $t0, 8 \n" // |S0|S3|S2|S1| "rotr $t6, $t1, 8 \n" // |T0|T3|T2|T1| "muleu_s.ph.qbl $t4, $t2, $t3 \n" // |S0*3|S3*3| "muleu_s.ph.qbl $t5, $t6, $t3 \n" // |T0*3|T3*3| "andi $t0, $t2, 0xFFFF \n" // |0|0|S2|S1| "andi $t1, $t6, 0xFFFF \n" // |0|0|T2|T1| "raddu.w.qb $t0, $t0 \n" "raddu.w.qb $t1, $t1 \n" "shra_r.w $t0, $t0, 1 \n" "shra_r.w $t1, $t1, 1 \n" "preceu.ph.qbr $t2, $t2 \n" // |0|S2|0|S1| "preceu.ph.qbr $t6, $t6 \n" // |0|T2|0|T1| "rotr $t2, $t2, 16 \n" // |0|S1|0|S2| "rotr $t6, $t6, 16 \n" // |0|T1|0|T2| "addu.ph $t2, $t2, $t4 \n" "addu.ph $t6, $t6, $t5 \n" "sll $t5, $t0, 1 \n" "add $t0, $t5, $t0 \n" "shra_r.ph $t2, $t2, 2 \n" "shra_r.ph $t6, $t6, 2 \n" "shll.ph $t4, $t2, 1 \n" "addq.ph $t4, $t4, $t2 \n" "addu $t0, $t0, $t1 \n" "addiu %[src_ptr], %[src_ptr], 4 \n" "shra_r.w $t0, $t0, 2 \n" "addu.ph $t6, $t6, $t4 \n" "shra_r.ph $t6, $t6, 2 \n" "srl $t1, $t6, 16 \n" "addiu %[dst_width], %[dst_width], -3 \n" "sb $t1, 0(%[d]) \n" "sb $t0, 1(%[d]) \n" "sb $t6, 2(%[d]) \n" "bgtz %[dst_width], 1b \n" " addiu %[d], %[d], 3 \n" "3: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [src_stride] "+r"(src_stride), [d] "+r"(d), [dst_width] "+r"(dst_width) : : "t0", "t1", "t2", "t3", "t4", "t5", "t6"); } void ScaleRowDown34_1_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* d, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "repl.ph $t2, 3 \n" // 0x00030003 "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0| "lwx $t1, %[src_stride](%[src_ptr]) \n" // |T3|T2|T1|T0| "rotr $t4, $t0, 8 \n" // |S0|S3|S2|S1| "rotr $t6, $t1, 8 \n" // |T0|T3|T2|T1| "muleu_s.ph.qbl $t3, $t4, $t2 \n" // |S0*3|S3*3| "muleu_s.ph.qbl $t5, $t6, $t2 \n" // |T0*3|T3*3| "andi $t0, $t4, 0xFFFF \n" // |0|0|S2|S1| "andi $t1, $t6, 0xFFFF \n" // |0|0|T2|T1| "raddu.w.qb $t0, $t0 \n" "raddu.w.qb $t1, $t1 \n" "shra_r.w $t0, $t0, 1 \n" "shra_r.w $t1, $t1, 1 \n" "preceu.ph.qbr $t4, $t4 \n" // |0|S2|0|S1| "preceu.ph.qbr $t6, $t6 \n" // |0|T2|0|T1| "rotr $t4, $t4, 16 \n" // |0|S1|0|S2| "rotr $t6, $t6, 16 \n" // |0|T1|0|T2| "addu.ph $t4, $t4, $t3 \n" "addu.ph $t6, $t6, $t5 \n" "shra_r.ph $t6, $t6, 2 \n" "shra_r.ph $t4, $t4, 2 \n" "addu.ph $t6, $t6, $t4 \n" "addiu %[src_ptr], %[src_ptr], 4 \n" "shra_r.ph $t6, $t6, 1 \n" "addu $t0, $t0, $t1 \n" "addiu %[dst_width], %[dst_width], -3 \n" "shra_r.w $t0, $t0, 1 \n" "srl $t1, $t6, 16 \n" "sb $t1, 0(%[d]) \n" "sb $t0, 1(%[d]) \n" "sb $t6, 2(%[d]) \n" "bgtz %[dst_width], 1b \n" " addiu %[d], %[d], 3 \n" "3: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [src_stride] "+r"(src_stride), [d] "+r"(d), [dst_width] "+r"(dst_width) : : "t0", "t1", "t2", "t3", "t4", "t5", "t6"); } void ScaleRowDown38_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t1, 4(%[src_ptr]) \n" // |7|6|5|4| "lw $t2, 8(%[src_ptr]) \n" // |11|10|9|8| "lw $t3, 12(%[src_ptr]) \n" // |15|14|13|12| "lw $t4, 16(%[src_ptr]) \n" // |19|18|17|16| "lw $t5, 20(%[src_ptr]) \n" // |23|22|21|20| "lw $t6, 24(%[src_ptr]) \n" // |27|26|25|24| "lw $t7, 28(%[src_ptr]) \n" // |31|30|29|28| "wsbh $t0, $t0 \n" // |2|3|0|1| "wsbh $t6, $t6 \n" // |26|27|24|25| "srl $t0, $t0, 8 \n" // |X|2|3|0| "srl $t3, $t3, 16 \n" // |X|X|15|14| "srl $t5, $t5, 16 \n" // |X|X|23|22| "srl $t7, $t7, 16 \n" // |X|X|31|30| "ins $t1, $t2, 24, 8 \n" // |8|6|5|4| "ins $t6, $t5, 0, 8 \n" // |26|27|24|22| "ins $t1, $t0, 0, 16 \n" // |8|6|3|0| "ins $t6, $t7, 24, 8 \n" // |30|27|24|22| "prepend $t2, $t3, 24 \n" // |X|15|14|11| "ins $t4, $t4, 16, 8 \n" // |19|16|17|X| "ins $t4, $t2, 0, 16 \n" // |19|16|14|11| "addiu %[src_ptr], %[src_ptr], 32 \n" "addiu %[dst_width], %[dst_width], -12 \n" "addiu $t8,%[dst_width], -12 \n" "sw $t1, 0(%[dst]) \n" "sw $t4, 4(%[dst]) \n" "sw $t6, 8(%[dst]) \n" "bgez $t8, 1b \n" " addiu %[dst], %[dst], 12 \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [dst_width] "+r"(dst_width) : : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8"); } void ScaleRowDown38_2_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst_ptr, int dst_width) { intptr_t stride = src_stride; const uint8* t = src_ptr + stride; const int c = 0x2AAA; __asm__ __volatile__( ".set push \n" ".set noreorder \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0| "lw $t1, 4(%[src_ptr]) \n" // |S7|S6|S5|S4| "lw $t2, 0(%[t]) \n" // |T3|T2|T1|T0| "lw $t3, 4(%[t]) \n" // |T7|T6|T5|T4| "rotr $t1, $t1, 16 \n" // |S5|S4|S7|S6| "packrl.ph $t4, $t1, $t3 \n" // |S7|S6|T7|T6| "packrl.ph $t5, $t3, $t1 \n" // |T5|T4|S5|S4| "raddu.w.qb $t4, $t4 \n" // S7+S6+T7+T6 "raddu.w.qb $t5, $t5 \n" // T5+T4+S5+S4 "precrq.qb.ph $t6, $t0, $t2 \n" // |S3|S1|T3|T1| "precrq.qb.ph $t6, $t6, $t6 \n" // |S3|T3|S3|T3| "srl $t4, $t4, 2 \n" // t4 / 4 "srl $t6, $t6, 16 \n" // |0|0|S3|T3| "raddu.w.qb $t6, $t6 \n" // 0+0+S3+T3 "addu $t6, $t5, $t6 \n" "mul $t6, $t6, %[c] \n" // t6 * 0x2AAA "sll $t0, $t0, 8 \n" // |S2|S1|S0|0| "sll $t2, $t2, 8 \n" // |T2|T1|T0|0| "raddu.w.qb $t0, $t0 \n" // S2+S1+S0+0 "raddu.w.qb $t2, $t2 \n" // T2+T1+T0+0 "addu $t0, $t0, $t2 \n" "mul $t0, $t0, %[c] \n" // t0 * 0x2AAA "addiu %[src_ptr], %[src_ptr], 8 \n" "addiu %[t], %[t], 8 \n" "addiu %[dst_width], %[dst_width], -3 \n" "addiu %[dst_ptr], %[dst_ptr], 3 \n" "srl $t6, $t6, 16 \n" "srl $t0, $t0, 16 \n" "sb $t4, -1(%[dst_ptr]) \n" "sb $t6, -2(%[dst_ptr]) \n" "bgtz %[dst_width], 1b \n" " sb $t0, -3(%[dst_ptr]) \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst_ptr] "+r"(dst_ptr), [t] "+r"(t), [dst_width] "+r"(dst_width) : [c] "r"(c) : "t0", "t1", "t2", "t3", "t4", "t5", "t6"); } void ScaleRowDown38_3_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst_ptr, int dst_width) { intptr_t stride = src_stride; const uint8* s1 = src_ptr + stride; stride += stride; const uint8* s2 = src_ptr + stride; const int c1 = 0x1C71; const int c2 = 0x2AAA; __asm__ __volatile__( ".set push \n" ".set noreorder \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0| "lw $t1, 4(%[src_ptr]) \n" // |S7|S6|S5|S4| "lw $t2, 0(%[s1]) \n" // |T3|T2|T1|T0| "lw $t3, 4(%[s1]) \n" // |T7|T6|T5|T4| "lw $t4, 0(%[s2]) \n" // |R3|R2|R1|R0| "lw $t5, 4(%[s2]) \n" // |R7|R6|R5|R4| "rotr $t1, $t1, 16 \n" // |S5|S4|S7|S6| "packrl.ph $t6, $t1, $t3 \n" // |S7|S6|T7|T6| "raddu.w.qb $t6, $t6 \n" // S7+S6+T7+T6 "packrl.ph $t7, $t3, $t1 \n" // |T5|T4|S5|S4| "raddu.w.qb $t7, $t7 \n" // T5+T4+S5+S4 "sll $t8, $t5, 16 \n" // |R5|R4|0|0| "raddu.w.qb $t8, $t8 \n" // R5+R4 "addu $t7, $t7, $t8 \n" "srl $t8, $t5, 16 \n" // |0|0|R7|R6| "raddu.w.qb $t8, $t8 \n" // R7 + R6 "addu $t6, $t6, $t8 \n" "mul $t6, $t6, %[c2] \n" // t6 * 0x2AAA "precrq.qb.ph $t8, $t0, $t2 \n" // |S3|S1|T3|T1| "precrq.qb.ph $t8, $t8, $t4 \n" // |S3|T3|R3|R1| "srl $t8, $t8, 8 \n" // |0|S3|T3|R3| "raddu.w.qb $t8, $t8 \n" // S3 + T3 + R3 "addu $t7, $t7, $t8 \n" "mul $t7, $t7, %[c1] \n" // t7 * 0x1C71 "sll $t0, $t0, 8 \n" // |S2|S1|S0|0| "sll $t2, $t2, 8 \n" // |T2|T1|T0|0| "sll $t4, $t4, 8 \n" // |R2|R1|R0|0| "raddu.w.qb $t0, $t0 \n" "raddu.w.qb $t2, $t2 \n" "raddu.w.qb $t4, $t4 \n" "addu $t0, $t0, $t2 \n" "addu $t0, $t0, $t4 \n" "mul $t0, $t0, %[c1] \n" // t0 * 0x1C71 "addiu %[src_ptr], %[src_ptr], 8 \n" "addiu %[s1], %[s1], 8 \n" "addiu %[s2], %[s2], 8 \n" "addiu %[dst_width], %[dst_width], -3 \n" "addiu %[dst_ptr], %[dst_ptr], 3 \n" "srl $t6, $t6, 16 \n" "srl $t7, $t7, 16 \n" "srl $t0, $t0, 16 \n" "sb $t6, -1(%[dst_ptr]) \n" "sb $t7, -2(%[dst_ptr]) \n" "bgtz %[dst_width], 1b \n" " sb $t0, -3(%[dst_ptr]) \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst_ptr] "+r"(dst_ptr), [s1] "+r"(s1), [s2] "+r"(s2), [dst_width] "+r"(dst_width) : [c1] "r"(c1), [c2] "r"(c2) : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8"); } #endif // defined(__mips_dsp) && (__mips_dsp_rev >= 2) #ifdef __cplusplus } // extern "C" } // namespace libyuv #endif
55.472756
80
0.265261
herocodemaster
cb80b49bee22db688ad98ffe6917e344d3a15ec7
1,600
hpp
C++
src/core/models/mutation/indel_mutation_model.hpp
alimanfoo/octopus
f3cc3f567f02fafe33f5a06e5be693d6ea985ee3
[ "MIT" ]
1
2018-08-21T23:34:28.000Z
2018-08-21T23:34:28.000Z
src/core/models/mutation/indel_mutation_model.hpp
alimanfoo/octopus
f3cc3f567f02fafe33f5a06e5be693d6ea985ee3
[ "MIT" ]
null
null
null
src/core/models/mutation/indel_mutation_model.hpp
alimanfoo/octopus
f3cc3f567f02fafe33f5a06e5be693d6ea985ee3
[ "MIT" ]
null
null
null
// Copyright (c) 2015-2018 Daniel Cooke // Use of this source code is governed by the MIT license that can be found in the LICENSE file. #ifndef indel_mutation_model_hpp #define indel_mutation_model_hpp #include <vector> #include <cstdint> #include "core/types/haplotype.hpp" #include "core/types/variant.hpp" namespace octopus { class IndelMutationModel { public: struct Parameters { double indel_mutation_rate; unsigned max_period = 10, max_periodicity = 20; double max_open_probability = 1.0, max_extend_probability = 1.0; }; struct ContextIndelModel { using Probability = double; using ProbabilityVector = std::vector<Probability>; ProbabilityVector gap_open, gap_extend; }; IndelMutationModel() = delete; IndelMutationModel(Parameters params); IndelMutationModel(const IndelMutationModel&) = default; IndelMutationModel& operator=(const IndelMutationModel&) = default; IndelMutationModel(IndelMutationModel&&) = default; IndelMutationModel& operator=(IndelMutationModel&&) = default; ~IndelMutationModel() = default; ContextIndelModel evaluate(const Haplotype& haplotype) const; private: struct ModelCell { double open, extend; }; using RepeatModel = std::vector<std::vector<ModelCell>>; Parameters params_; RepeatModel indel_repeat_model_; }; IndelMutationModel::ContextIndelModel make_indel_model(const Haplotype& context, IndelMutationModel::Parameters params); } // namespace octopus #endif
27.586207
120
0.70625
alimanfoo
cb81d920def2080d9c5ac7baa8e1d1eacb79a56d
10,357
cc
C++
media/filters/audio_file_reader.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/filters/audio_file_reader.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/filters/audio_file_reader.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright (c) 2012 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 "media/filters/audio_file_reader.h" #include <stddef.h> #include <cmath> #include <vector> #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" #include "base/numerics/safe_math.h" #include "base/time/time.h" #include "media/base/audio_bus.h" #include "media/base/audio_sample_types.h" #include "media/ffmpeg/ffmpeg_common.h" #include "media/ffmpeg/ffmpeg_decoding_loop.h" namespace media { // AAC(M4A) decoding specific constants. static const int kAACPrimingFrameCount = 2112; static const int kAACRemainderFrameCount = 519; AudioFileReader::AudioFileReader(FFmpegURLProtocol* protocol) : stream_index_(0), protocol_(protocol), audio_codec_(kUnknownAudioCodec), channels_(0), sample_rate_(0), av_sample_format_(0) {} AudioFileReader::~AudioFileReader() { Close(); } bool AudioFileReader::Open() { return OpenDemuxer() && OpenDecoder(); } bool AudioFileReader::OpenDemuxer() { glue_.reset(new FFmpegGlue(protocol_)); AVFormatContext* format_context = glue_->format_context(); // Open FFmpeg AVFormatContext. if (!glue_->OpenContext()) { DLOG(WARNING) << "AudioFileReader::Open() : error in avformat_open_input()"; return false; } const int result = avformat_find_stream_info(format_context, NULL); if (result < 0) { DLOG(WARNING) << "AudioFileReader::Open() : error in avformat_find_stream_info()"; return false; } // Calling avformat_find_stream_info can uncover new streams. We wait till now // to find the first audio stream, if any. codec_context_.reset(); bool found_stream = false; for (size_t i = 0; i < format_context->nb_streams; ++i) { if (format_context->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { stream_index_ = i; found_stream = true; break; } } if (!found_stream) return false; // Get the codec context. codec_context_ = AVStreamToAVCodecContext(format_context->streams[stream_index_]); if (!codec_context_) return false; DCHECK_EQ(codec_context_->codec_type, AVMEDIA_TYPE_AUDIO); return true; } bool AudioFileReader::OpenDecoder() { AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id); if (codec) { // MP3 decodes to S16P which we don't support, tell it to use S16 instead. if (codec_context_->sample_fmt == AV_SAMPLE_FMT_S16P) codec_context_->request_sample_fmt = AV_SAMPLE_FMT_S16; const int result = avcodec_open2(codec_context_.get(), codec, nullptr); if (result < 0) { DLOG(WARNING) << "AudioFileReader::Open() : could not open codec -" << " result: " << result; return false; } // Ensure avcodec_open2() respected our format request. if (codec_context_->sample_fmt == AV_SAMPLE_FMT_S16P) { DLOG(ERROR) << "AudioFileReader::Open() : unable to configure a" << " supported sample format - " << codec_context_->sample_fmt; return false; } } else { DLOG(WARNING) << "AudioFileReader::Open() : could not find codec."; return false; } // Verify the channel layout is supported by Chrome. Acts as a sanity check // against invalid files. See http://crbug.com/171962 if (ChannelLayoutToChromeChannelLayout(codec_context_->channel_layout, codec_context_->channels) == CHANNEL_LAYOUT_UNSUPPORTED) { return false; } // Store initial values to guard against midstream configuration changes. channels_ = codec_context_->channels; audio_codec_ = CodecIDToAudioCodec(codec_context_->codec_id); sample_rate_ = codec_context_->sample_rate; av_sample_format_ = codec_context_->sample_fmt; return true; } bool AudioFileReader::HasKnownDuration() const { return glue_->format_context()->duration != AV_NOPTS_VALUE; } void AudioFileReader::Close() { codec_context_.reset(); glue_.reset(); } int AudioFileReader::Read( std::vector<std::unique_ptr<AudioBus>>* decoded_audio_packets, int packets_to_read) { DCHECK(glue_ && codec_context_) << "AudioFileReader::Read() : reader is not opened!"; FFmpegDecodingLoop decode_loop(codec_context_.get()); int total_frames = 0; auto frame_ready_cb = base::BindRepeating(&AudioFileReader::OnNewFrame, base::Unretained(this), &total_frames, decoded_audio_packets); AVPacket packet; int packets_read = 0; while (packets_read++ < packets_to_read && ReadPacket(&packet)) { const auto status = decode_loop.DecodePacket(&packet, frame_ready_cb); av_packet_unref(&packet); if (status != FFmpegDecodingLoop::DecodeStatus::kOkay) break; } return total_frames; } base::TimeDelta AudioFileReader::GetDuration() const { const AVRational av_time_base = {1, AV_TIME_BASE}; DCHECK_NE(glue_->format_context()->duration, AV_NOPTS_VALUE); base::CheckedNumeric<int64_t> estimated_duration_us = glue_->format_context()->duration; if (audio_codec_ == kCodecAAC) { // For certain AAC-encoded files, FFMPEG's estimated frame count might not // be sufficient to capture the entire audio content that we want. This is // especially noticeable for short files (< 10ms) resulting in silence // throughout the decoded buffer. Thus we add the priming frames and the // remainder frames to the estimation. // (See: crbug.com/513178) estimated_duration_us += ceil( 1000000.0 * static_cast<double>(kAACPrimingFrameCount + kAACRemainderFrameCount) / sample_rate()); } else { // Add one microsecond to avoid rounding-down errors which can occur when // |duration| has been calculated from an exact number of sample-frames. // One microsecond is much less than the time of a single sample-frame // at any real-world sample-rate. estimated_duration_us += 1; } return ConvertFromTimeBase(av_time_base, estimated_duration_us.ValueOrDie()); } int AudioFileReader::GetNumberOfFrames() const { return base::ClampCeil(GetDuration().InSecondsF() * sample_rate()); } bool AudioFileReader::OpenDemuxerForTesting() { return OpenDemuxer(); } bool AudioFileReader::ReadPacketForTesting(AVPacket* output_packet) { return ReadPacket(output_packet); } bool AudioFileReader::ReadPacket(AVPacket* output_packet) { while (av_read_frame(glue_->format_context(), output_packet) >= 0) { // Skip packets from other streams. if (output_packet->stream_index != stream_index_) { av_packet_unref(output_packet); continue; } return true; } return false; } bool AudioFileReader::OnNewFrame( int* total_frames, std::vector<std::unique_ptr<AudioBus>>* decoded_audio_packets, AVFrame* frame) { int frames_read = frame->nb_samples; if (frames_read < 0) return false; const int channels = frame->channels; if (frame->sample_rate != sample_rate_ || channels != channels_ || frame->format != av_sample_format_) { DLOG(ERROR) << "Unsupported midstream configuration change!" << " Sample Rate: " << frame->sample_rate << " vs " << sample_rate_ << ", Channels: " << channels << " vs " << channels_ << ", Sample Format: " << frame->format << " vs " << av_sample_format_; // This is an unrecoverable error, so bail out. We'll return // whatever we've decoded up to this point. return false; } // AAC decoding doesn't properly trim the last packet in a stream, so if we // have duration information, use it to set the correct length to avoid extra // silence from being output. In the case where we are also discarding some // portion of the packet (as indicated by a negative pts), we further want to // adjust the duration downward by however much exists before zero. if (audio_codec_ == kCodecAAC && frame->pkt_duration) { const base::TimeDelta pkt_duration = ConvertFromTimeBase( glue_->format_context()->streams[stream_index_]->time_base, frame->pkt_duration + std::min(static_cast<int64_t>(0), frame->pts)); const base::TimeDelta frame_duration = base::TimeDelta::FromSecondsD( frames_read / static_cast<double>(sample_rate_)); if (pkt_duration < frame_duration && pkt_duration > base::TimeDelta()) { const int new_frames_read = base::ClampFloor(frames_read * (pkt_duration / frame_duration)); DVLOG(2) << "Shrinking AAC frame from " << frames_read << " to " << new_frames_read << " based on packet duration."; frames_read = new_frames_read; // The above process may delete the entire packet. if (!frames_read) return true; } } // Deinterleave each channel and convert to 32bit floating-point with // nominal range -1.0 -> +1.0. If the output is already in float planar // format, just copy it into the AudioBus. decoded_audio_packets->emplace_back(AudioBus::Create(channels, frames_read)); AudioBus* audio_bus = decoded_audio_packets->back().get(); if (codec_context_->sample_fmt == AV_SAMPLE_FMT_FLT) { audio_bus->FromInterleaved<Float32SampleTypeTraits>( reinterpret_cast<float*>(frame->data[0]), frames_read); } else if (codec_context_->sample_fmt == AV_SAMPLE_FMT_FLTP) { for (int ch = 0; ch < audio_bus->channels(); ++ch) { memcpy(audio_bus->channel(ch), frame->extended_data[ch], sizeof(float) * frames_read); } } else { audio_bus->FromInterleaved( frame->data[0], frames_read, av_get_bytes_per_sample(codec_context_->sample_fmt)); } (*total_frames) += frames_read; return true; } bool AudioFileReader::SeekForTesting(base::TimeDelta seek_time) { // Use the AVStream's time_base, since |codec_context_| does not have // time_base populated until after OpenDecoder(). return av_seek_frame( glue_->format_context(), stream_index_, ConvertToTimeBase(GetAVStreamForTesting()->time_base, seek_time), AVSEEK_FLAG_BACKWARD) >= 0; } const AVStream* AudioFileReader::GetAVStreamForTesting() const { return glue_->format_context()->streams[stream_index_]; } } // namespace media
34.294702
80
0.693251
mghgroup
cb83514bbfb5f1668dd3063a6e451fc9556841f9
261
cpp
C++
imageEditorApp/src/view/main.cpp
Ecquus/imageEditor
bcecd7434e806b29b935dec58122ece4fd36f727
[ "MIT" ]
null
null
null
imageEditorApp/src/view/main.cpp
Ecquus/imageEditor
bcecd7434e806b29b935dec58122ece4fd36f727
[ "MIT" ]
null
null
null
imageEditorApp/src/view/main.cpp
Ecquus/imageEditor
bcecd7434e806b29b935dec58122ece4fd36f727
[ "MIT" ]
null
null
null
#include <mainwindow.h> #include <QApplication> #include <cstring> int main(int argc, char *argv[]) { QApplication a(argc, argv); bool debug = argc > 1 && strcmp(argv[1], "-d") == 0; MainWindow w(debug); w.show(); return a.exec(); }
16.3125
56
0.586207
Ecquus
cb86a134595e66d8180a1dccf1409e9631a5f103
1,088
cpp
C++
Week04/Fraction.cpp
mdnam2410/hcmus-oop-lab
2eb2bc781ed652b8f44396a5460a0422fda00c5b
[ "MIT" ]
null
null
null
Week04/Fraction.cpp
mdnam2410/hcmus-oop-lab
2eb2bc781ed652b8f44396a5460a0422fda00c5b
[ "MIT" ]
null
null
null
Week04/Fraction.cpp
mdnam2410/hcmus-oop-lab
2eb2bc781ed652b8f44396a5460a0422fda00c5b
[ "MIT" ]
null
null
null
#include "Fraction.h" #include <sstream> Fraction::Fraction() { m_nom = new int(0); m_denom = new int(1); } Fraction::Fraction(int value) { m_nom = new int(value); m_denom = new int(1); } Fraction::Fraction(int nom, int denom) { m_nom = new int(nom); m_denom = new int(denom); makeDenominatorPositive(); } Fraction::Fraction(const Fraction& f) { m_nom = new int(*f.m_nom); m_denom = new int(*f.m_denom); } Fraction::~Fraction() { delete m_nom; delete m_denom; } void Fraction::makeDenominatorPositive() { if (*m_denom < 0) { *m_nom = -*m_nom; *m_denom = -*m_denom; } } int Fraction::getNom() const { return *m_nom; } int Fraction::getDenom() const { return *m_denom; } void Fraction::setNom(int nom) { *m_nom = nom; } bool Fraction::setDenom(int denom) { if (denom == 0) return false; *m_denom = denom; makeDenominatorPositive(); return true; } std::string Fraction::ToString() const { std::stringstream ss; ss << *m_nom << '/' << *m_denom; return ss.str(); }
14.90411
40
0.601103
mdnam2410
cb86c9857936f21d9d2ac6bc22c725b89cca6482
16,042
cc
C++
tensorflow/compiler/xla/service/gather_expander.cc
Zwysilence/tensorflow
b55001be83da044bb21d539d433dec6231eaec55
[ "Apache-2.0" ]
4
2021-06-15T17:26:07.000Z
2021-11-17T10:58:08.000Z
tensorflow/compiler/xla/service/gather_expander.cc
Zwysilence/tensorflow
b55001be83da044bb21d539d433dec6231eaec55
[ "Apache-2.0" ]
1
2019-08-22T20:29:33.000Z
2019-12-19T10:16:21.000Z
tensorflow/compiler/xla/service/gather_expander.cc
Zwysilence/tensorflow
b55001be83da044bb21d539d433dec6231eaec55
[ "Apache-2.0" ]
6
2018-12-20T01:35:20.000Z
2020-07-10T17:29:57.000Z
/* Copyright 2018 The TensorFlow 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 <utility> #include "absl/algorithm/container.h" #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/compiler/xla/service/gather_expander.h" #include "tensorflow/compiler/xla/service/hlo_creation_utils.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/while_util.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/util.h" namespace xla { static StatusOr<HloInstruction*> TransposeIndexVectorDimToLast( HloInstruction* start_indices, int64 index_vector_dim) { const Shape& start_indices_shape = start_indices->shape(); if (start_indices_shape.dimensions_size() == index_vector_dim) { return start_indices; } if (index_vector_dim == (start_indices_shape.dimensions_size() - 1)) { return start_indices; } std::vector<int64> permutation; permutation.reserve(start_indices_shape.dimensions_size()); for (int64 i = 0, e = start_indices_shape.dimensions_size(); i < e; i++) { if (i != index_vector_dim) { permutation.push_back(i); } } permutation.push_back(index_vector_dim); return MakeTransposeHlo(start_indices, permutation); } // Canonicalizes the start_indices tensors so that we only have deal with some // specific cases in the while loop that does the heavy lifting. // // See the "High Level Algorithm" section for a broader picture. static StatusOr<HloInstruction*> CanonicalizeGatherIndices( HloInstruction* start_indices, int64 index_vector_dim) { // Transpose the non-index-vector dimensions to the front. TF_ASSIGN_OR_RETURN( HloInstruction * transposed_start_indices, TransposeIndexVectorDimToLast(start_indices, index_vector_dim)); bool indices_are_scalar = index_vector_dim == start_indices->shape().dimensions_size(); // The number of dimensions in start_indices that are index dimensions. const int64 index_dims_in_start_indices = indices_are_scalar ? 0 : 1; // If there is only one index (i.e. start_indices has rank 1 and this gather // is really just a dynamic slice) add a leading degenerate dimension for // uniformity. Otherwise create a "collapsed" leading dimension that subsumes // all of the non-index-vector dimensions. const Shape& shape = transposed_start_indices->shape(); if (shape.dimensions_size() == index_dims_in_start_indices) { return PrependDegenerateDims(transposed_start_indices, 1); } else { // Collapse all but the dimensions (0 or 1) in start_indices containing the // index vectors. return CollapseFirstNDims( transposed_start_indices, shape.dimensions_size() - index_dims_in_start_indices); } } // Expands out or contracts away the gather dimensions in the accumulator // produced by the while loop. static StatusOr<HloInstruction*> AdjustBatchDimsInAccumulator( const Shape& start_indices_shape, HloInstruction* accumulator, int64 index_vector_dim) { std::vector<int64> batch_dim_bounds; batch_dim_bounds.reserve(start_indices_shape.dimensions_size()); for (int64 i = 0, e = start_indices_shape.dimensions_size(); i < e; i++) { if (i != index_vector_dim) { batch_dim_bounds.push_back(start_indices_shape.dimensions(i)); } } if (batch_dim_bounds.empty()) { // If batch_dim_bounds is empty we must be lowering a (effectively) // dynamic-slice. In that case, there is a leading degenerate gather // dimension that we added to make this special case play well with the // general while loop which we need to remove now. return ElideDegenerateDims(accumulator, {0}); } return ExpandFirstDimIntoNDims(accumulator, batch_dim_bounds); } // Expand an index vector from the start_indices tensor into a vector that can // be used to dynamic-slice out of the gather operand. static StatusOr<HloInstruction*> ExpandIndexVectorIntoOperandSpace( HloInstruction* index_vector, const GatherDimensionNumbers& dim_numbers, int64 operand_rank) { HloComputation* computation = index_vector->parent(); const Shape& index_shape = index_vector->shape(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateFromDimensions(index_shape.element_type(), {1}))); // We extract out individual components from the smaller index and concatenate // them (interspersing zeros as needed) into the larger index. std::vector<HloInstruction*> expanded_index_components; for (int i = 0; i < operand_rank; i++) { int64 index_vector_dim_index = FindIndex(dim_numbers.start_index_map(), i); if (index_vector_dim_index != dim_numbers.start_index_map_size()) { TF_ASSIGN_OR_RETURN( HloInstruction * component_to_concat, MakeSliceHlo(index_vector, /*start_indices=*/{index_vector_dim_index}, /*limit_indices=*/{index_vector_dim_index + 1}, /*strides=*/{1})); expanded_index_components.push_back(component_to_concat); } else { expanded_index_components.push_back(zero); } } return MakeConcatHlo(expanded_index_components, /*dimension=*/0); } // This generates the body of the while that implements the main data movement // behavior of gather using dynamic-slice and dynamic-update-slice. static StatusOr<std::vector<HloInstruction*>> GatherLoopBody( const HloInstruction& gather, HloInstruction* induction_var, const std::vector<HloInstruction*>& incoming_loop_state) { const GatherDimensionNumbers& dim_numbers = gather.gather_dimension_numbers(); CHECK_EQ(incoming_loop_state.size(), 3); HloInstruction* const operand = incoming_loop_state[0]; HloInstruction* const start_indices = incoming_loop_state[1]; HloInstruction* const output_accumulator = incoming_loop_state[2]; bool has_scalar_indices = start_indices->shape().dimensions_size() == 1; CHECK_EQ(has_scalar_indices, dim_numbers.index_vector_dim() == gather.operand(1)->shape().dimensions_size()); TF_ASSIGN_OR_RETURN( HloInstruction * induction_var_as_vector, MakeBroadcastHlo(induction_var, /*broadcast_dimensions=*/{}, /*result_shape_bounds=*/{1})); HloInstruction* index_vector; if (has_scalar_indices) { // In this case start_indices has rank 1 and induction_var_as_vector (of // shape {1}) is an index into this rank 1 tensor. TF_ASSIGN_OR_RETURN( index_vector, MakeDynamicSliceHlo(start_indices, induction_var_as_vector, {1})); } else { // In this case start_indices has rank 2 and induction_var_as_vector (of // shape {1}) is an index into just the first dimension of this rank 2 // tensor. TF_ASSIGN_OR_RETURN( HloInstruction * index_into_start_indices, PadVectorWithZeros(induction_var_as_vector, /*zeros_to_prepend=*/0, /*zeros_to_append=*/1)); int64 index_vector_size = start_indices->shape().dimensions(1); TF_ASSIGN_OR_RETURN( HloInstruction * index_vector_2d, MakeDynamicSliceHlo(start_indices, index_into_start_indices, {1, index_vector_size})); TF_ASSIGN_OR_RETURN(index_vector, ElideDegenerateDims(index_vector_2d, {0})); } TF_ASSIGN_OR_RETURN( HloInstruction * gathered_slice_start, ExpandIndexVectorIntoOperandSpace(index_vector, dim_numbers, operand->shape().dimensions_size())); TF_ASSIGN_OR_RETURN(HloInstruction * gathered_slice, MakeDynamicSliceHlo(operand, gathered_slice_start, gather.gather_slice_sizes())); TF_ASSIGN_OR_RETURN( HloInstruction* const gathered_slice_with_dims_collapsed, ElideDegenerateDims(gathered_slice, AsInt64Slice(dim_numbers.collapsed_slice_dims()))); TF_ASSIGN_OR_RETURN( HloInstruction* const gathered_slice_for_update, PrependDegenerateDims(gathered_slice_with_dims_collapsed, 1)); TF_ASSIGN_OR_RETURN( HloInstruction* const index_vector_into_accumulator, PadVectorWithZeros( induction_var_as_vector, /*zeros_to_prepend=*/0, /*zeros_to_append=*/ gathered_slice_with_dims_collapsed->shape().dimensions_size())); TF_ASSIGN_OR_RETURN( HloInstruction* const updated_accumulator, MakeDynamicUpdateSliceHlo(output_accumulator, gathered_slice_for_update, index_vector_into_accumulator)); // New loop state -- only the accumulator has changed. The // WhileUtil::MakeCountedLoop functions takes care of the induction variable // and the while loop exit condition. return StatusOr<std::vector<HloInstruction*>>{ {operand, start_indices, updated_accumulator}}; } static StatusOr<HloInstruction*> CreateGatherLoopAccumulatorInitValue( HloComputation* computation, PrimitiveType element_type, absl::Span<const int64> slice_sizes, int64 gather_loop_trip_count, const GatherDimensionNumbers& dim_numbers) { std::vector<int64> accumulator_state_shape_dims; accumulator_state_shape_dims.reserve(1 + slice_sizes.size()); accumulator_state_shape_dims.push_back(gather_loop_trip_count); for (int64 i = 0; i < slice_sizes.size(); i++) { if (!absl::c_binary_search(dim_numbers.collapsed_slice_dims(), i)) { accumulator_state_shape_dims.push_back(slice_sizes[i]); } } return BroadcastZeros(computation, element_type, accumulator_state_shape_dims); } // `accumulator` is almost the tensor the gather operation would have produced, // except that it has the dimensions in the wrong order -- the batch dimensions // are the major dimensions and the offset dimensions are the minor dimensions. // Fix this up with a transpose. static StatusOr<HloInstruction*> PermuteBatchAndOffsetDims( HloInstruction* accumulator, absl::Span<const int64> offset_dims, int64 output_rank) { std::vector<int64> permutation; permutation.reserve(output_rank); int64 batch_idx_counter = 0; int64 offset_idx_counter = output_rank - offset_dims.size(); for (int64 i = 0; i < output_rank; i++) { bool is_offset_dim = absl::c_binary_search(offset_dims, i); if (is_offset_dim) { permutation.push_back(offset_idx_counter++); } else { permutation.push_back(batch_idx_counter++); } } return MakeTransposeHlo(accumulator, permutation); } // High Level Algorithm // // We follow the following steps in sequence: // // 1. We canonicalize the start_indices tensor such that it has rank // 2 (i.e. is a matrix) where each row is an index vector into the // operand. // 2. We iterate over the set of indices in the canonicalized // start_indices tensor using a while loop, accumulating slices // of the operand tensor into an accumulator using // DynamicUpdateSlice. // 3. The accumulator result from the while loop from (2) is then // reshaped to split out all the individual gather dimensions and // then transposed to give the final result. // // As an example, if we started with the following operation: // // HloModule TensorFlowGatherMultipleBatchDims // // ENTRY main { // operand = s32[3,3] parameter(0) // indices = s32[2,2] parameter(1) // ROOT gather = s32[2,3,2] gather(operand, indices), // offset_dims={1}, // collapsed_slice_dims={1}, // start_index_map={1}, // index_vector_dim=2, // slice_sizes={3, 1} // } // // We'd first reshape indices to s32[4,1], where each row is an index // into operand. We'd then run a loop to slice out 4 tensors of shape // [3,1] out of operand into an accumulator of shape [4,3,1]. We then // reshape this result to [2,2,3] and finally transpose it to [2,3,2]. StatusOr<HloInstruction*> GatherExpander::ExpandGather( HloInstruction* gather_instr) { CHECK(!ShapeUtil::IsZeroElementArray(gather_instr->shape())); HloComputation* computation = gather_instr->parent(); HloInstruction* operand = gather_instr->mutable_operand(0); HloInstruction* start_indices = gather_instr->mutable_operand(1); const Shape& start_indices_shape = start_indices->shape(); const Shape& output_shape = gather_instr->shape(); int64 output_rank = output_shape.dimensions_size(); const GatherDimensionNumbers& dim_numbers = gather_instr->gather_dimension_numbers(); int64 gather_loop_trip_count = 1; for (int64 i = 0, e = start_indices_shape.dimensions_size(); i < e; i++) { if (i != dim_numbers.index_vector_dim()) { gather_loop_trip_count *= start_indices_shape.dimensions(i); } } if (!IsInt32(gather_loop_trip_count)) { return Unimplemented( "Gather operations with more than 2147483647 gather indices are not " "supported. This error occurred for %s.", gather_instr->ToString()); } TF_ASSIGN_OR_RETURN( HloInstruction * canonical_start_indices, CanonicalizeGatherIndices(start_indices, dim_numbers.index_vector_dim())); CHECK_EQ(gather_loop_trip_count, canonical_start_indices->shape().dimensions(0)); TF_ASSIGN_OR_RETURN( HloInstruction * accumulator_init, CreateGatherLoopAccumulatorInitValue( computation, output_shape.element_type(), gather_instr->gather_slice_sizes(), gather_loop_trip_count, gather_instr->gather_dimension_numbers())); StatusOr<std::vector<HloInstruction*>> gather_loop_result_or_error = WhileUtil::MakeCountedLoop( computation, gather_loop_trip_count, {operand, canonical_start_indices, accumulator_init}, [&](HloInstruction* indvar, const std::vector<HloInstruction*>& loop_state) { return GatherLoopBody(*gather_instr, indvar, loop_state); }); TF_ASSIGN_OR_RETURN(std::vector<HloInstruction*> gather_loop_result, gather_loop_result_or_error); HloInstruction* accumulator_result = gather_loop_result.back(); TF_ASSIGN_OR_RETURN( HloInstruction* const accumulator_with_batch_dims_decanonicalized, AdjustBatchDimsInAccumulator(start_indices->shape(), accumulator_result, dim_numbers.index_vector_dim())); return PermuteBatchAndOffsetDims(accumulator_with_batch_dims_decanonicalized, AsInt64Slice(dim_numbers.offset_dims()), output_rank); } StatusOr<bool> GatherExpander::Run(HloModule* module) { auto is_nontrivial_gather = [](HloInstruction* inst) { return inst->opcode() == HloOpcode::kGather && // Avoid expanding gather ops that produce zero sized tensors, // instead punt these to ZeroSizedHloElimination. !ShapeUtil::IsZeroElementArray(inst->shape()); }; std::vector<HloInstruction*> gather_instrs; for (HloComputation* computation : module->MakeNonfusionComputations()) { absl::c_copy_if(computation->instructions(), std::back_inserter(gather_instrs), is_nontrivial_gather); } for (HloInstruction* inst : gather_instrs) { TF_ASSIGN_OR_RETURN(HloInstruction * expanded_root, ExpandGather(inst)); TF_RETURN_IF_ERROR(inst->parent()->ReplaceInstruction(inst, expanded_root)); } return !gather_instrs.empty(); } } // namespace xla
41.345361
80
0.718925
Zwysilence
cb885d1796cb98d33169e9a3dc604f20318424a5
4,696
cpp
C++
opencl/test/unit_test/os_interface/linux/local_memory_helper_tests_dg1.cpp
Panquesito7/compute-runtime
3357b8b916885a336174ab0e7bbfc7652be4fb88
[ "Intel", "MIT" ]
778
2017-09-29T20:02:43.000Z
2022-03-31T15:35:28.000Z
opencl/test/unit_test/os_interface/linux/local_memory_helper_tests_dg1.cpp
Panquesito7/compute-runtime
3357b8b916885a336174ab0e7bbfc7652be4fb88
[ "Intel", "MIT" ]
478
2018-01-26T16:06:45.000Z
2022-03-30T10:19:10.000Z
opencl/test/unit_test/os_interface/linux/local_memory_helper_tests_dg1.cpp
Panquesito7/compute-runtime
3357b8b916885a336174ab0e7bbfc7652be4fb88
[ "Intel", "MIT" ]
215
2018-01-30T08:39:32.000Z
2022-03-29T11:08:51.000Z
/* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/execution_environment/execution_environment.h" #include "shared/source/os_interface/linux/local_memory_helper.h" #include "shared/source/os_interface/linux/memory_info_impl.h" #include "shared/test/common/helpers/debug_manager_state_restore.h" #include "shared/test/common/helpers/default_hw_info.h" #include "opencl/test/unit_test/os_interface/linux/drm_mock_exp.h" #include "opencl/test/unit_test/os_interface/linux/drm_mock_prod_dg1.h" #include "test.h" using namespace NEO; using LocalMemoryHelperTestsDg1 = ::testing::Test; DG1TEST_F(LocalMemoryHelperTestsDg1, givenDg1WhenCreateGemExtThenReturnCorrectValue) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); auto drm = std::make_unique<DrmMockExp>(*executionEnvironment->rootDeviceEnvironments[0]); drm_i915_memory_region_info regionInfo[2] = {}; regionInfo[0].region = {I915_MEMORY_CLASS_SYSTEM, 0}; regionInfo[0].probed_size = 8 * GB; regionInfo[1].region = {I915_MEMORY_CLASS_DEVICE, 0}; regionInfo[1].probed_size = 16 * GB; auto localMemHelper = LocalMemoryHelper::get(defaultHwInfo->platform.eProductFamily); uint32_t handle = 0; auto ret = localMemHelper->createGemExt(drm.get(), &regionInfo[1], 1, 1024, handle); EXPECT_EQ(0u, ret); EXPECT_EQ(1u, handle); EXPECT_EQ(1u, drm->numRegions); EXPECT_EQ(1024u, drm->createExt.size); EXPECT_EQ(I915_MEMORY_CLASS_DEVICE, drm->memRegions.memory_class); } DG1TEST_F(LocalMemoryHelperTestsDg1, givenDg1WithDrmTipWhenCreateGemExtWithDebugFlagThenPrintDebugInfo) { DebugManagerStateRestore stateRestore; DebugManager.flags.PrintBOCreateDestroyResult.set(true); auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); auto drm = std::make_unique<DrmMockExp>(*executionEnvironment->rootDeviceEnvironments[0]); drm_i915_memory_region_info regionInfo[2] = {}; regionInfo[0].region = {I915_MEMORY_CLASS_SYSTEM, 0}; regionInfo[1].region = {I915_MEMORY_CLASS_DEVICE, 0}; testing::internal::CaptureStdout(); auto localMemHelper = LocalMemoryHelper::get(defaultHwInfo->platform.eProductFamily); uint32_t handle = 0; auto ret = localMemHelper->createGemExt(drm.get(), &regionInfo[1], 1, 1024, handle); std::string output = testing::internal::GetCapturedStdout(); std::string expectedOutput("Performing GEM_CREATE_EXT with { size: 1024, memory class: 1, memory instance: 0 }\nGEM_CREATE_EXT with EXT_MEMORY_REGIONS has returned: 0 BO-1 with size: 1024\n"); EXPECT_EQ(expectedOutput, output); EXPECT_EQ(1u, drm->ioctlCallsCount); EXPECT_EQ(0u, ret); } DG1TEST_F(LocalMemoryHelperTestsDg1, givenDg1WhenCreateGemExtWithDebugFlagThenPrintDebugInfo) { DebugManagerStateRestore stateRestore; DebugManager.flags.PrintBOCreateDestroyResult.set(true); auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); auto drm = std::make_unique<DrmMockProdDg1>(*executionEnvironment->rootDeviceEnvironments[0]); drm_i915_memory_region_info regionInfo[2] = {}; regionInfo[0].region = {I915_MEMORY_CLASS_SYSTEM, 0}; regionInfo[1].region = {I915_MEMORY_CLASS_DEVICE, 0}; testing::internal::CaptureStdout(); auto localMemHelper = LocalMemoryHelper::get(defaultHwInfo->platform.eProductFamily); uint32_t handle = 0; auto ret = localMemHelper->createGemExt(drm.get(), &regionInfo[1], 1, 1024, handle); std::string output = testing::internal::GetCapturedStdout(); std::string expectedOutput("Performing GEM_CREATE_EXT with { size: 1024, memory class: 1, memory instance: 0 }\nGEM_CREATE_EXT with EXT_SETPARAM has returned: 0 BO-1 with size: 1024\n"); EXPECT_EQ(expectedOutput, output); EXPECT_EQ(2u, drm->ioctlCallsCount); EXPECT_EQ(0u, ret); } DG1TEST_F(LocalMemoryHelperTestsDg1, givenDg1AndMemoryRegionQuerySupportedWhenQueryingMemoryInfoThenMemoryInfoIsCreatedWithRegions) { auto executionEnvironment = std::make_unique<ExecutionEnvironment>(); executionEnvironment->prepareRootDeviceEnvironments(1); auto drm = std::make_unique<DrmMockProdDg1>(*executionEnvironment->rootDeviceEnvironments[0]); ASSERT_NE(nullptr, drm); drm->queryMemoryInfo(); EXPECT_EQ(2u, drm->ioctlCallsCount); auto memoryInfo = static_cast<MemoryInfoImpl *>(drm->getMemoryInfo()); ASSERT_NE(nullptr, memoryInfo); EXPECT_EQ(2u, memoryInfo->getDrmRegionInfos().size()); }
43.88785
196
0.767675
Panquesito7
cb89a7a6a17b18d2dbda29ab619cb87648b427ee
2,166
cpp
C++
libRocketWrapper/Src/ManagedFileInterface.cpp
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
libRocketWrapper/Src/ManagedFileInterface.cpp
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
libRocketWrapper/Src/ManagedFileInterface.cpp
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
#include "StdAfx.h" class ManagedFileInterface : public Rocket::Core::FileInterface { public: typedef size_t (*OpenCb)(String path HANDLE_ARG); typedef void(*CloseCb)(Rocket::Core::FileHandle file HANDLE_ARG); typedef size_t(*ReadCb)(void* buffer, size_t size, Rocket::Core::FileHandle file HANDLE_ARG); typedef bool(*SeekCb)(Rocket::Core::FileHandle file, long offset, int origin HANDLE_ARG); typedef size_t(*TellCb)(Rocket::Core::FileHandle file HANDLE_ARG); typedef void (*ReleaseCb)(HANDLE_FIRST_ARG); ManagedFileInterface(OpenCb open, CloseCb close, ReadCb read, SeekCb seek, TellCb tell, ReleaseCb release HANDLE_ARG) :open(open), close(close), read(read), seek(seek), tell(tell), release(release) ASSIGN_HANDLE_INITIALIZER { } virtual ~ManagedFileInterface() { } virtual Rocket::Core::FileHandle Open(const Rocket::Core::String& path) { return open(path.CString() PASS_HANDLE_ARG); } virtual void Close(Rocket::Core::FileHandle file) { close(file PASS_HANDLE_ARG); } virtual size_t Read(void* buffer, size_t size, Rocket::Core::FileHandle file) { return read(buffer, size, file PASS_HANDLE_ARG); } virtual bool Seek(Rocket::Core::FileHandle file, long offset, int origin) { return seek(file, offset, origin PASS_HANDLE_ARG); } virtual size_t Tell(Rocket::Core::FileHandle file) { return tell(file PASS_HANDLE_ARG); } virtual void Release() { release(PASS_HANDLE); } private: OpenCb open; CloseCb close; ReadCb read; SeekCb seek; TellCb tell; ReleaseCb release; HANDLE_INSTANCE }; extern "C" _AnomalousExport ManagedFileInterface* ManagedFileInterface_Create(ManagedFileInterface::OpenCb open, ManagedFileInterface::CloseCb close, ManagedFileInterface::ReadCb read, ManagedFileInterface::SeekCb seek, ManagedFileInterface::TellCb tell, ManagedFileInterface::ReleaseCb release HANDLE_ARG) { return new ManagedFileInterface(open, close, read, seek, tell, release PASS_HANDLE_ARG); } extern "C" _AnomalousExport void ManagedFileInterface_Delete(ManagedFileInterface* fileInterface) { delete fileInterface; }
27.769231
307
0.738689
AnomalousMedical
cb8a131f111a539853047ee8850a667519923063
24,833
cpp
C++
windows/src/engine/keyman32/K32_load.cpp
ermshiperete/keyman
0eeef1b5794fd698447584e531e2a6c1ef4c05aa
[ "MIT" ]
1
2021-03-08T09:31:47.000Z
2021-03-08T09:31:47.000Z
windows/src/engine/keyman32/K32_load.cpp
ermshiperete/keyman
0eeef1b5794fd698447584e531e2a6c1ef4c05aa
[ "MIT" ]
null
null
null
windows/src/engine/keyman32/K32_load.cpp
ermshiperete/keyman
0eeef1b5794fd698447584e531e2a6c1ef4c05aa
[ "MIT" ]
null
null
null
/* Name: K32_load Copyright: Copyright (C) SIL International. Documentation: Description: Create Date: 14 Sep 2006 Modified Date: 25 Oct 2016 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 14 Sep 2006 - mcdurdin - Support unencrypted keyboards for any internal Keyman product 19 Jun 2007 - mcdurdin - Load ICO files and convert to BMP (for TIP) 11 Mar 2009 - mcdurdin - I1894 - Fix threading bugs introduced in I1888 11 Dec 2009 - mcdurdin - I934 - x64 - Initial version 12 Mar 2010 - mcdurdin - I934 - x64 - Complete 12 Mar 2010 - mcdurdin - I2229 - Remove hints and warnings 04 May 2010 - mcdurdin - I2351 - Robustness - verify _td return value 25 May 2010 - mcdurdin - I1632 - Keyboard Options 02 Dec 2011 - mcdurdin - I3160 - Hotkeys can fail to activate keyboards when multiple OEM products are running 04 Nov 2012 - mcdurdin - I3522 - V9.0 - Merge of I3160 - Hotkeys can fail to activate keyboards when multiple OEM products are running 16 Apr 2014 - mcdurdin - I4169 - V9.0 - Mnemonic layouts should be recompiled to positional based on user-selected base keyboard 06 Feb 2015 - mcdurdin - I4552 - V9.0 - Add mnemonic recompile option to ignore deadkeys 25 Oct 2016 - mcdurdin - I5136 - Remove additional product references from Keyman Engine */ #include "pch.h" HBITMAP LoadBitmapFile(LPBYTE data, DWORD sz); BOOL VerifyKeyboard(LPBYTE filebase, DWORD sz); #ifdef _WIN64 LPKEYBOARD CopyKeyboard(PBYTE bufp, PBYTE base, DWORD dwFileSize); #else LPKEYBOARD FixupKeyboard(PBYTE bufp, PBYTE base, DWORD dwFileSize); #endif HBITMAP LoadBitmapFileEx(PBYTE filebase); BOOL GetKeyboardFileName(LPSTR kbname, LPSTR buf, int nbuf) { PKEYMAN64THREADDATA _td = ThreadGlobals(); if(!_td) return FALSE; if(_td->ForceFileName[0]) { strncpy_s(buf, nbuf, _td->ForceFileName, nbuf); buf[nbuf-1] = 0; return TRUE; } int n = 0; RegistryReadOnly *reg = Reg_GetKeymanInstalledKeyboard(kbname); if(!reg) return FALSE; __try { // We need to test if the user is in deadkey conversion mode // I4552 if(Globals::get_MnemonicDeadkeyConversionMode() && reg->ValueExists(REGSZ_KeymanFile_MnemonicOverride_Deadkey)) { n = reg->ReadString(REGSZ_KeymanFile_MnemonicOverride_Deadkey, buf, nbuf); } else if(reg->ValueExists(REGSZ_KeymanFile_MnemonicOverride)) { // I4169 n = reg->ReadString(REGSZ_KeymanFile_MnemonicOverride, buf, nbuf); } else { n = reg->ReadString(REGSZ_KeymanFile, buf, nbuf); } } __finally { delete reg; } return n; } BOOL LoadlpKeyboard(int i) { PKEYMAN64THREADDATA _td = ThreadGlobals(); if(!_td) return FALSE; if(_td->lpKeyboards[i].Keyboard) return TRUE; if(_td->lpActiveKeyboard == &_td->lpKeyboards[i]) _td->lpActiveKeyboard = NULL; // I822 TSF not working char buf[256]; if(!GetKeyboardFileName(_td->lpKeyboards[i].Name, buf, 256)) return FALSE; if(!LoadKeyboard(buf, &_td->lpKeyboards[i].Keyboard)) return FALSE; // I5136 LoadDLLs(&_td->lpKeyboards[i]); LoadKeyboardOptions(&_td->lpKeyboards[i]); return TRUE; } /* * Instead of performing a straightforward calculation of the 32 bit * CRC using a series of logical operations, this program uses the * faster table lookup method. This routine is called once when the * program starts up to build the table which will be used later * when calculating the CRC values. */ #define CRC32_POLYNOMIAL 0xEDB88320L unsigned long CRCTable[256]; void BuildCRCTable(void) { static BOOL TableBuilt = FALSE; int i; int j; unsigned long crc; if(!TableBuilt) { for(i = 0; i <= 255; i++) { crc = i; for(j = 8; j > 0; j--) if(crc & 1) crc = (crc >> 1) ^ CRC32_POLYNOMIAL; else crc >>= 1; CRCTable[i] = crc; } } } /* * This routine calculates the CRC for a block of data using the * table lookup method. It accepts an original value for the crc, * and returns the updated value. */ unsigned long CalculateBufferCRC(unsigned long count, BYTE *p) { unsigned long temp1; unsigned long temp2; unsigned long crc = 0xFFFFFFFFL; BuildCRCTable(); while (count-- != 0) { temp1 = ( crc >> 8 ) & 0x00FFFFFFL; temp2 = CRCTable[((int) crc ^ *p++) & 0xff]; crc = temp1 ^ temp2; } return crc; } //#define Err(s) void Err(char *s) { SendDebugMessageFormat(0, sdmLoad, 0, "LoadKeyboard: %s", s); } BOOL LoadKeyboard(LPSTR fileName, LPKEYBOARD *lpKeyboard) { DWORD sz; LPBYTE buf; HANDLE hFile; LPKEYBOARD kbp; PBYTE filebase; if(!fileName || !lpKeyboard) { Err("Bad Filename"); return FALSE; } hFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if(hFile == INVALID_HANDLE_VALUE) { Err("Could not open file"); return FALSE; } sz = GetFileSize(hFile, NULL); #ifdef _WIN64 buf = new BYTE[sz*3]; #else buf = new BYTE[sz]; #endif if(!buf) { CloseHandle(hFile); Err("Not allocmem"); return FALSE; } #ifdef _WIN64 filebase = buf + sz*2; #else filebase = buf; #endif ReadFile(hFile, filebase, sz, &sz, NULL); CloseHandle(hFile); PKEYMAN64THREADDATA _td = ThreadGlobals(); if(!_td) return FALSE; if(*LPDWORD(filebase) != FILEID_COMPILED) { delete buf; Err("Invalid file"); return FALSE; } if(!VerifyKeyboard(filebase, sz)) return FALSE; #ifdef _WIN64 kbp = CopyKeyboard(buf, filebase, sz); #else kbp = FixupKeyboard(buf, filebase, sz); #endif if(!kbp) return FALSE; if(kbp->dwIdentifier != FILEID_COMPILED) { delete buf; Err("errNotFileID"); return FALSE; } kbp->hBitmap = LoadBitmapFileEx(filebase); *lpKeyboard = kbp; return TRUE; } // These next two structs represent how the icon information is stored // in an ICO file. typedef struct { BYTE bWidth; // Width of the image BYTE bHeight; // Height of the image (times 2) BYTE bColorCount; // Number of colors in image (0 if >=8bpp) BYTE bReserved; // Reserved WORD wPlanes; // Color Planes WORD wBitCount; // Bits per pixel DWORD dwBytesInRes; // how many bytes in this resource? DWORD dwImageOffset; // where in the file is this image } ICONDIRENTRY, *LPICONDIRENTRY; typedef struct { WORD idReserved; // Reserved WORD idType; // resource type (1 for icons) WORD idCount; // how many images? ICONDIRENTRY idEntries[1]; // the entries for each image } ICONDIR, *LPICONDIR; // The following two structs are for the use of this program in // manipulating icons. They are more closely tied to the operation // of this program than the structures listed above. One of the // main differences is that they provide a pointer to the DIB // information of the masks. typedef struct { UINT Width, Height, Colors; // Width, Height and bpp LPBYTE lpBits; // ptr to DIB bits DWORD dwNumBytes; // how many bytes? LPBITMAPINFO lpbi; // ptr to header LPBYTE lpXOR; // ptr to XOR image bits LPBYTE lpAND; // ptr to AND image bits } ICONIMAGE, *LPICONIMAGE; typedef struct { UINT nNumImages; // How many images? ICONIMAGE IconImages[1]; // Image entries } ICONRESOURCE, *LPICONRESOURCE; /****************************************************************************/ LPICONRESOURCE ReadIconFromICOFile( PBYTE buf, int sz ); void FreeIconResource(LPICONRESOURCE lpIR); HICON MakeIconFromResource( LPICONIMAGE lpIcon ); HBITMAP LoadBitmapFile(LPBYTE data, DWORD sz) { BITMAPFILEHEADER *bmfh; BITMAPINFO *bmi; HBITMAP hBitmap, hBitmap2, hOldBmp1, hOldBmp2; HDC hDC, hSrcDC, hSrcDC2; LPICONRESOURCE lpir = NULL; bmfh = (BITMAPFILEHEADER *) data; if(bmfh->bfType == 0x4D42) { SendDebugMessageFormat(0, sdmLoad, 0, "LoadKeyboard: Bitmap found"); bmi = (BITMAPINFO *) (data + sizeof(BITMAPFILEHEADER)); hDC = GetDC(GetDesktopWindow()); hSrcDC = CreateCompatibleDC(hDC); hSrcDC2 = CreateCompatibleDC(hDC); hBitmap = CreateDIBitmap(hDC, &bmi->bmiHeader, CBM_INIT, data + bmfh->bfOffBits, bmi, DIB_RGB_COLORS); hBitmap2 = CreateCompatibleBitmap(hDC, 16, 16); ReleaseDC(GetDesktopWindow(), hDC); hOldBmp1 = (HBITMAP) SelectObject(hSrcDC, hBitmap); hOldBmp2 = (HBITMAP) SelectObject(hSrcDC2, hBitmap2); BitBlt(hSrcDC2, 0, 0, 16, 16, hSrcDC, 0, 0, SRCCOPY); SelectObject(hSrcDC, hOldBmp1); SelectObject(hSrcDC2, hOldBmp2); DeleteDC(hSrcDC); DeleteDC(hSrcDC2); DeleteObject(hBitmap); } else { SendDebugMessageFormat(0, sdmLoad, 0, "LoadKeyboard: Icon found"); lpir = ReadIconFromICOFile(data, sz); if(!lpir) { SendDebugMessageFormat(0, sdmLoad, 0, "LoadKeyboard: icon not loaded"); return 0; } if(lpir->nNumImages == 0) { FreeIconResource(lpir); return 0; } HICON hIcon = MakeIconFromResource(&lpir->IconImages[0]); //HICON hIcon = CreateIcon(GetModuleHandle(LIBRARY_NAME), lpir->IconImages[0].Width, lpir->IconImages[0].Height, // 1, lpir->IconImages[0].Colors, lpir->IconImages[0].lpAND, lpir->IconImages[0].lpXOR); FreeIconResource(lpir); if(hIcon == 0) { DebugLastError("MakeIconFromResource"); return 0; } hDC = GetDC(GetDesktopWindow()); hBitmap2 = CreateCompatibleBitmap(hDC, 16, 16); hSrcDC = CreateCompatibleDC(hDC); ReleaseDC(GetDesktopWindow(), hDC); hOldBmp2 = (HBITMAP) SelectObject(hSrcDC, hBitmap2); DrawIconEx(hSrcDC, 0, 0, hIcon, 16, 16, 0, NULL, DI_NORMAL); SelectObject(hSrcDC, hOldBmp2); DeleteDC(hSrcDC); DestroyIcon(hIcon); } return hBitmap2; } /**************************************************************************** * * FUNCTION: ReadICOHeader * * PURPOSE: Reads the header from an ICO file * * PARAMS: HANDLE hFile - handle to the file * * RETURNS: UINT - Number of images in file, -1 for failure * * History: * July '95 - Created * \****************************************************************************/ UINT ReadICOHeader( PBYTE buf ) { if(*(PWORD)(buf) != 0) return (UINT)-1; if(*(PWORD)(buf+2) != 1) return (UINT)-1; return *(PWORD)(buf+4); } /* End ReadICOHeader() ****************************************************/ /**************************************************************************** * * FUNCTION: DIBNumColors * * PURPOSE: Calculates the number of entries in the color table. * * PARAMS: LPSTR lpbi - pointer to the CF_DIB memory block * * RETURNS: WORD - Number of entries in the color table. * * History: * July '95 - Copied <g> * \****************************************************************************/ WORD DIBNumColors( LPSTR lpbi ) { WORD wBitCount; DWORD dwClrUsed; dwClrUsed = ((LPBITMAPINFOHEADER) lpbi)->biClrUsed; if (dwClrUsed) return (WORD) dwClrUsed; wBitCount = ((LPBITMAPINFOHEADER) lpbi)->biBitCount; switch (wBitCount) { case 1: return 2; case 4: return 16; case 8: return 256; } return 0; } /* End DIBNumColors() ******************************************************/ /**************************************************************************** * * FUNCTION: PaletteSize * * PURPOSE: Calculates the number of bytes in the color table. * * PARAMS: LPSTR lpbi - pointer to the CF_DIB memory block * * RETURNS: WORD - number of bytes in the color table * * * History: * July '95 - Copied <g> * \****************************************************************************/ WORD PaletteSize( LPSTR lpbi ) { return ( DIBNumColors( lpbi ) * sizeof( RGBQUAD ) ); } /* End PaletteSize() ********************************************************/ /**************************************************************************** * * FUNCTION: FindDIBits * * PURPOSE: Locate the image bits in a CF_DIB format DIB. * * PARAMS: LPSTR lpbi - pointer to the CF_DIB memory block * * RETURNS: LPSTR - pointer to the image bits * * History: * July '95 - Copied <g> * \****************************************************************************/ LPSTR FindDIBBits( LPSTR lpbi ) { return ( lpbi + *(LPDWORD)lpbi + PaletteSize( lpbi ) ); } /* End FindDIBits() *********************************************************/ // How wide, in bytes, would this many bits be, DWORD aligned? #define WIDTHBYTES(bits) ((((bits) + 31)>>5)<<2) /**************************************************************************** * * FUNCTION: BytesPerLine * * PURPOSE: Calculates the number of bytes in one scan line. * * PARAMS: LPBITMAPINFOHEADER lpBMIH - pointer to the BITMAPINFOHEADER * that begins the CF_DIB block * * RETURNS: DWORD - number of bytes in one scan line (DWORD aligned) * * History: * July '95 - Created * \****************************************************************************/ DWORD BytesPerLine( LPBITMAPINFOHEADER lpBMIH ) { return WIDTHBYTES(lpBMIH->biWidth * lpBMIH->biPlanes * lpBMIH->biBitCount); } /* End BytesPerLine() ********************************************************/ /**************************************************************************** * * FUNCTION: AdjustIconImagePointers * * PURPOSE: Adjusts internal pointers in icon resource struct * * PARAMS: LPICONIMAGE lpImage - the resource to handle * * RETURNS: BOOL - TRUE for success, FALSE for failure * * History: * July '95 - Created * \****************************************************************************/ BOOL AdjustIconImagePointers( LPICONIMAGE lpImage ) { // Sanity check if( lpImage==NULL ) return FALSE; // BITMAPINFO is at beginning of bits lpImage->lpbi = (LPBITMAPINFO)lpImage->lpBits; // Width - simple enough lpImage->Width = lpImage->lpbi->bmiHeader.biWidth; // Icons are stored in funky format where height is doubled - account for it lpImage->Height = (lpImage->lpbi->bmiHeader.biHeight)/2; // How many colors? lpImage->Colors = lpImage->lpbi->bmiHeader.biPlanes * lpImage->lpbi->bmiHeader.biBitCount; // XOR bits follow the header and color table lpImage->lpXOR = (LPBYTE) FindDIBBits((LPSTR)lpImage->lpbi); // AND bits follow the XOR bits lpImage->lpAND = lpImage->lpXOR + (lpImage->Height*BytesPerLine((LPBITMAPINFOHEADER)(lpImage->lpbi))); return TRUE; } /* End AdjustIconImagePointers() *******************************************/ /**************************************************************************** * * FUNCTION: ReadIconFromICOFile * * PURPOSE: Reads an Icon Resource from an ICO file * * PARAMS: LPCTSTR szFileName - Name of the ICO file * * RETURNS: LPICONRESOURCE - pointer to the resource, NULL for failure * * History: * July '95 - Created * \****************************************************************************/ LPICONRESOURCE ReadIconFromICOFile( PBYTE buf, int sz ) { UNREFERENCED_PARAMETER(sz); LPICONRESOURCE lpIR = NULL, lpNew = NULL; HANDLE hFile = NULL; //LPRESOURCEPOSINFO lpRPI = NULL; UINT i; LPICONDIRENTRY lpIDE = NULL; // Allocate memory for the resource structure if( (lpIR = (LPICONRESOURCE) malloc( sizeof(ICONRESOURCE) )) == NULL ) { SendDebugMessageFormat(0, sdmLoad, 0, "Error Allocating Memory"); return NULL; } // Read in the header if( (lpIR->nNumImages = ReadICOHeader(buf)) == (UINT)-1 ) { SendDebugMessageFormat(0, sdmLoad, 0, "Error Reading File Header"); free( lpIR ); return NULL; } // Adjust the size of the struct to account for the images if( (lpNew = (LPICONRESOURCE) realloc( lpIR, sizeof(ICONRESOURCE) + ((lpIR->nNumImages-1) * sizeof(ICONIMAGE)) )) == NULL ) { SendDebugMessageFormat(0, sdmLoad, 0, "Error Allocating Memory"); CloseHandle( hFile ); free( lpIR ); return NULL; } lpIR = lpNew; // Store the original name // Allocate enough memory for the icon directory entries if( (lpIDE = (LPICONDIRENTRY) malloc( lpIR->nNumImages * sizeof( ICONDIRENTRY ) ) ) == NULL ) { SendDebugMessageFormat(0, sdmLoad, 0, "Error Allocating Memory"); free( lpIR ); return NULL; } memcpy(lpIDE, buf + 6, lpIR->nNumImages * sizeof( ICONDIRENTRY )); // Loop through and read in each image for( i = 0; i < lpIR->nNumImages; i++ ) { // Allocate memory for the resource if( (lpIR->IconImages[i].lpBits = (LPBYTE) malloc(lpIDE[i].dwBytesInRes)) == NULL ) { SendDebugMessageFormat(0, sdmLoad, 0, "Error Allocating Memory"); free( lpIR ); free( lpIDE ); return NULL; } lpIR->IconImages[i].dwNumBytes = lpIDE[i].dwBytesInRes; // Seek to beginning of this image memcpy(lpIR->IconImages[i].lpBits, buf + lpIDE[i].dwImageOffset, lpIDE[i].dwBytesInRes); // Set the internal pointers appropriately if( ! AdjustIconImagePointers( &(lpIR->IconImages[i]) ) ) { SendDebugMessageFormat(0, sdmLoad, 0, "Error Converting to Internal Format"); free( lpIDE ); free( lpIR ); return NULL; } } // Clean up free( lpIDE ); //free( lpRPI ); return lpIR; } /* End ReadIconFromICOFile() **********************************************/ void FreeIconResource(LPICONRESOURCE lpIR) { for( UINT i = 0; i < lpIR->nNumImages; i++ ) // Allocate memory for the resource free(lpIR->IconImages[i].lpBits); free( lpIR ); } /**************************************************************************** * * FUNCTION: MakeIconFromResource * * PURPOSE: Makes an HICON from an icon resource * * PARAMS: LPICONIMAGE lpIcon - pointer to the icon resource * * RETURNS: HICON - handle to the new icon, NULL for failure * * History: * July '95 - Created * \****************************************************************************/ HICON MakeIconFromResource( LPICONIMAGE lpIcon ) { HICON hIcon = NULL; // Sanity Check if( lpIcon == NULL ) return NULL; if( lpIcon->lpBits == NULL ) return NULL; // Let the OS do the real work :) hIcon = CreateIconFromResourceEx( lpIcon->lpBits, lpIcon->dwNumBytes, TRUE, 0x00030000, (*(LPBITMAPINFOHEADER)(lpIcon->lpBits)).biWidth, (*(LPBITMAPINFOHEADER)(lpIcon->lpBits)).biHeight/2, 0 ); // It failed, odds are good we're on NT so try the non-Ex way if( hIcon == NULL ) { // We would break on NT if we try with a 16bpp image if(lpIcon->lpbi->bmiHeader.biBitCount != 16) { hIcon = CreateIconFromResource( lpIcon->lpBits, lpIcon->dwNumBytes, TRUE, 0x00030000 ); } } return hIcon; } /* End MakeIconFromResource() **********************************************/ PWCHAR StringOffset(PBYTE base, DWORD offset) { if(offset == 0) return NULL; return (PWCHAR)(base + offset); } #ifdef _WIN64 /** CopyKeyboard will copy the data read into bufp from x86-sized structures into x64-sized structures starting at base * We know the base is dwFileSize * 3 * After this function finishes, we still need to keep the original data */ LPKEYBOARD CopyKeyboard(PBYTE bufp, PBYTE base, DWORD dwFileSize) { UNREFERENCED_PARAMETER(dwFileSize); PCOMP_KEYBOARD ckbp = (PCOMP_KEYBOARD) base; /* Copy keyboard structure */ LPKEYBOARD kbp = (LPKEYBOARD) bufp; bufp += sizeof(KEYBOARD); kbp->dwIdentifier = ckbp->dwIdentifier; kbp->dwFileVersion = ckbp->dwFileVersion; kbp->dwCheckSum = ckbp->dwCheckSum; kbp->xxkbdlayout = ckbp->KeyboardID; kbp->IsRegistered = ckbp->IsRegistered; kbp->version = ckbp->version; kbp->cxStoreArray = ckbp->cxStoreArray; kbp->cxGroupArray = ckbp->cxGroupArray; kbp->StartGroup[0] = ckbp->StartGroup[0]; kbp->StartGroup[1] = ckbp->StartGroup[1]; kbp->dwFlags = ckbp->dwFlags; kbp->dwHotKey = ckbp->dwHotKey; kbp->hBitmap = 0; // will be built later kbp->dpStoreArray = (LPSTORE) bufp; bufp += sizeof(STORE) * kbp->cxStoreArray; kbp->dpGroupArray = (LPGROUP) bufp; bufp += sizeof(GROUP) * kbp->cxGroupArray; PCOMP_STORE csp; LPSTORE sp; DWORD i; for( csp = (PCOMP_STORE)(base + ckbp->dpStoreArray), sp = kbp->dpStoreArray, i = 0; i < kbp->cxStoreArray; i++, sp++, csp++) { sp->dwSystemID = csp->dwSystemID; sp->dpName = StringOffset(base, csp->dpName); sp->dpString = StringOffset(base, csp->dpString); } PCOMP_GROUP cgp; LPGROUP gp; for( cgp = (PCOMP_GROUP)(base + ckbp->dpGroupArray), gp = kbp->dpGroupArray, i = 0; i < kbp->cxGroupArray; i++, gp++, cgp++) { gp->dpName = (PWCHAR)(base + cgp->dpName); gp->dpKeyArray = (LPKEY) bufp; gp->cxKeyArray = cgp->cxKeyArray; bufp += sizeof(KEY) * gp->cxKeyArray; gp->dpMatch = StringOffset(base, cgp->dpMatch); gp->dpNoMatch = StringOffset(base, cgp->dpNoMatch); gp->fUsingKeys = cgp->fUsingKeys; PCOMP_KEY ckp; LPKEY kp; DWORD j; for( ckp = (PCOMP_KEY)(base + cgp->dpKeyArray), kp = gp->dpKeyArray, j = 0; j < gp->cxKeyArray; j++, kp++, ckp++) { kp->Key = ckp->Key; kp->Line = ckp->Line; kp->ShiftFlags = ckp->ShiftFlags; kp->dpOutput = StringOffset(base, ckp->dpOutput); kp->dpContext = StringOffset(base, ckp->dpContext); } } return kbp; } #else LPKEYBOARD FixupKeyboard(PBYTE bufp, PBYTE base, DWORD dwFileSize) { UNREFERENCED_PARAMETER(dwFileSize); DWORD i, j; PCOMP_KEYBOARD ckbp = (PCOMP_KEYBOARD) base; PCOMP_GROUP cgp; PCOMP_STORE csp; PCOMP_KEY ckp; LPKEYBOARD kbp = (LPKEYBOARD) bufp; LPSTORE sp; LPGROUP gp; LPKEY kp; kbp->dpStoreArray = (LPSTORE) (base + ckbp->dpStoreArray); kbp->dpGroupArray = (LPGROUP) (base + ckbp->dpGroupArray); /*if( ckbp->dwBitmapSize > 0 ) kbp->hBitmap = LoadBitmapFile((buf + ckbp->dpBitmapOffset), ckbp->dwBitmapSize); else kbp->hBitmap = NULL; */ for(sp = kbp->dpStoreArray, csp = (PCOMP_STORE) sp, i = 0; i < kbp->cxStoreArray; i++, sp++, csp++) { sp->dpName = StringOffset(base, csp->dpName); sp->dpString = StringOffset(base, csp->dpString); } for(gp = kbp->dpGroupArray, cgp = (PCOMP_GROUP) gp, i = 0; i < kbp->cxGroupArray; i++, gp++, cgp++) { gp->dpName = StringOffset(base, cgp->dpName); gp->dpKeyArray = (LPKEY) (base + cgp->dpKeyArray); if(cgp->dpMatch != NULL) gp->dpMatch = (PWSTR) (base + cgp->dpMatch); if(cgp->dpNoMatch != NULL) gp->dpNoMatch = (PWSTR) (base + cgp->dpNoMatch); for(kp = gp->dpKeyArray, ckp = (PCOMP_KEY) kp, j = 0; j < gp->cxKeyArray; j++, kp++, ckp++) { kp->dpOutput = (PWSTR) (base + ckp->dpOutput); kp->dpContext = (PWSTR) (base + ckp->dpContext); } } return kbp; } #endif HBITMAP LoadBitmapFileEx(PBYTE filebase) { PCOMP_KEYBOARD ckbp = (PCOMP_KEYBOARD) filebase; if( ckbp->dwBitmapSize > 0 ) return LoadBitmapFile(filebase + ckbp->dpBitmapOffset, ckbp->dwBitmapSize); else return NULL; } BOOL VerifyChecksum(LPBYTE buf, DWORD sz) { DWORD tempcs; PCOMP_KEYBOARD ckbp; ckbp = (PCOMP_KEYBOARD) buf; tempcs = ckbp->dwCheckSum; ckbp->dwCheckSum = 0; return tempcs == CalculateBufferCRC(sz, buf); } BOOL VerifyKeyboard(LPBYTE filebase, DWORD sz) { DWORD i; PCOMP_KEYBOARD ckbp = (PCOMP_KEYBOARD) filebase; PCOMP_STORE csp; /* Check file version */ if(ckbp->dwFileVersion < VERSION_MIN || ckbp->dwFileVersion > VERSION_MAX) { /* Old or new version -- identify the desired program version */ if(VerifyChecksum(filebase, sz)) { for(csp = (PCOMP_STORE)(filebase + ckbp->dpStoreArray), i = 0; i < ckbp->cxStoreArray; i++, csp++) if(csp->dwSystemID == TSS_COMPILEDVERSION) { char buf2[256]; if(csp->dpString == 0) wsprintf(buf2, "errWrongFileVersion:NULL"); else wsprintf(buf2, "errWrongFileVersion:%10.10ls", StringOffset(filebase, csp->dpString)); Err(buf2); return FALSE; } } Err("errWrongFileVersion"); return FALSE; } if(!VerifyChecksum(filebase, sz)) { Err("errBadChecksum"); return FALSE; } return TRUE; }
28.741898
154
0.597028
ermshiperete
cb8ac503cfc3f79e44eee8044a27f068a1109725
2,990
cpp
C++
molecule/src/molecule_tautomer_utils.cpp
00Green27/Indigo
dc09f838b8b05d4bba2f79d0af5617d637f0b70e
[ "Apache-2.0" ]
null
null
null
molecule/src/molecule_tautomer_utils.cpp
00Green27/Indigo
dc09f838b8b05d4bba2f79d0af5617d637f0b70e
[ "Apache-2.0" ]
null
null
null
molecule/src/molecule_tautomer_utils.cpp
00Green27/Indigo
dc09f838b8b05d4bba2f79d0af5617d637f0b70e
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** * Copyright (C) from 2009 to Present EPAM Systems. * * This file is part of Indigo toolkit. * * 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 "molecule/molecule_tautomer_utils.h" using namespace indigo; bool MoleculeTautomerUtils::_isRepMetal(int elem) { static const int list[] = {ELEM_Li, ELEM_Na, ELEM_K, ELEM_Rb, ELEM_Cs, ELEM_Be, ELEM_Mg, ELEM_Ca, ELEM_Sr, ELEM_Ba}; for (int i = 0; i < (int)NELEM(list); i++) if (elem == list[i]) return true; return false; } // Count potential hydrogens (+, - charges or metal bonds) void MoleculeTautomerUtils::countHReplacements(BaseMolecule& m, Array<int>& h_rep_count) { h_rep_count.clear_resize(m.vertexEnd()); for (int i : m.vertices()) { const Vertex& vertex = m.getVertex(i); h_rep_count[i] = 0; for (int bond_idx : vertex.neighbors()) { if (_isRepMetal(m.getAtomNumber(vertex.neiVertex(bond_idx)))) { int bond_type = m.getBondOrder(vertex.neiEdge(bond_idx)); if (bond_type != BOND_AROMATIC) h_rep_count[i] += bond_type; } } // + or - charge also count as potential hydrogens int charge = m.getAtomCharge(i); if (charge != CHARGE_UNKNOWN) h_rep_count[i] += abs(charge); } } // If core_2 != 0 highlights g1 too void MoleculeTautomerUtils::highlightChains(BaseMolecule& g1, BaseMolecule& g2, const Array<int>& chains_2, const int* core_2) { int i; for (i = g2.vertexBegin(); i < g2.vertexEnd(); i = g2.vertexNext(i)) { if (chains_2[i] > 0 || (core_2 != 0 && core_2[i] >= 0)) g2.highlightAtom(i); } for (i = g2.edgeBegin(); i < g2.edgeEnd(); i = g2.edgeNext(i)) { const Edge& edge = g2.getEdge(i); // zeroed bond? if (g2.getBondOrder(i) == -1 && g2.possibleBondOrder(i, BOND_SINGLE)) continue; if (chains_2[edge.beg] > 0 && chains_2[edge.end] > 0 && abs(chains_2[edge.beg] - chains_2[edge.end]) == 1) g2.highlightBond(i); else if (core_2 != 0 && core_2[edge.beg] >= 0 && core_2[edge.end] >= 0) { if (g1.findEdgeIndex(core_2[edge.beg], core_2[edge.end]) != -1) g2.highlightBond(i); } } }
32.150538
126
0.580602
00Green27
cb8b164073545b49850380576d5c5daf872f92c9
1,493
cpp
C++
src/main.cpp
NDelt/Mini-Search-Engine
c7c64a7d365e5112e0a6eb320d3ff3e399bd9e18
[ "Apache-2.0" ]
null
null
null
src/main.cpp
NDelt/Mini-Search-Engine
c7c64a7d365e5112e0a6eb320d3ff3e399bd9e18
[ "Apache-2.0" ]
null
null
null
src/main.cpp
NDelt/Mini-Search-Engine
c7c64a7d365e5112e0a6eb320d3ff3e399bd9e18
[ "Apache-2.0" ]
1
2019-04-11T03:02:05.000Z
2019-04-11T03:02:05.000Z
/*************************************************************************** * Copyright 2019 HYUNWOO O * * 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 <iostream> #include "TableIndexer.hpp" #include "TableSearcher.hpp" #define MAX_QUERY_SIZE 1000 int main() { HashMap hashMap; TableIndexer tableIndexer; tableIndexer.createIndex("../resources/amazon_jobs.csv", hashMap); TableSearcher tableSearcher; while (true) { std::cout << "Input queries: (type 'exitsearch' to exit) "; char temp[MAX_QUERY_SIZE]; std::cin.getline(temp, MAX_QUERY_SIZE, '\n'); std::string searchQuery(temp); if (searchQuery == "exitsearch") { std::cout << "===== Shut down search engine... =====\n"; break; } tableSearcher.search(searchQuery, hashMap); } return 0; }
30.469388
76
0.583389
NDelt
cb8c968fa166b95b8a5674447afc69c8b9cd0f6f
324
hpp
C++
native/sample/headers/mcpe/LevelChunk.hpp
Molybdocene-dichloride/GregTech_BE
b19171ff4e41826c0bd4cf2dbdd9916f46254d67
[ "MIT" ]
4
2021-01-15T08:33:44.000Z
2022-03-13T19:11:08.000Z
native/sample/headers/mcpe/LevelChunk.hpp
Molybdocene-dichloride/GregTech_BE
b19171ff4e41826c0bd4cf2dbdd9916f46254d67
[ "MIT" ]
null
null
null
native/sample/headers/mcpe/LevelChunk.hpp
Molybdocene-dichloride/GregTech_BE
b19171ff4e41826c0bd4cf2dbdd9916f46254d67
[ "MIT" ]
null
null
null
#pragma once #include <mcpe\BlockPos.hpp> #include <mcpe\Block.hpp> #include <mcpe\Dimension.hpp> class LevelChunk { public: Level getLevel() const; Dimension getDimension() const; Block getBlock(ChunkBlockPos const&) const; ChunkLocalHeight getHeightRange() const; ChunkPos* getPosition() const; };
24.923077
47
0.722222
Molybdocene-dichloride
cb8eb92813d5ae8dc1699cdd1ab54e63d08b8617
2,007
cc
C++
tests/api/mpi/comm/probe-intercomm.cc
jpkenny/sst-macro
bcc1f43034281885104962586d8b104df84b58bd
[ "BSD-Source-Code" ]
20
2017-01-26T09:28:23.000Z
2022-01-17T11:31:55.000Z
tests/api/mpi/comm/probe-intercomm.cc
jpkenny/sst-macro
bcc1f43034281885104962586d8b104df84b58bd
[ "BSD-Source-Code" ]
542
2016-03-29T22:50:58.000Z
2022-03-22T20:14:08.000Z
tests/api/mpi/comm/probe-intercomm.cc
jpkenny/sst-macro
bcc1f43034281885104962586d8b104df84b58bd
[ "BSD-Source-Code" ]
36
2016-03-10T21:33:54.000Z
2021-12-01T07:44:12.000Z
/* * * (C) 2003 by Argonne National Laboratory. * See COPYRIGHT in top-level directory. */ #include <sstmac/replacements/mpi/mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpitest.h" namespace probe_intercomm{ /** static char MTEST_Descrip[] = "Test MPI_Probe() for an intercomm"; */ #define MAX_DATA_LEN 100 int probe_intercomm( int argc, char *argv[] ) { int errs = 0, recvlen, isLeft; MPI_Status status; int rank, size; MPI_Comm intercomm; char buf[MAX_DATA_LEN]; const char *test_str = "test"; MTest_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &rank ); MPI_Comm_size( MPI_COMM_WORLD, &size ); if (size < 2) { fprintf( stderr, "This test requires at least two processes." ); MPI_Abort( MPI_COMM_WORLD, 1 ); } while (MTestGetIntercomm( &intercomm, &isLeft, 2 )) { if (intercomm == MPI_COMM_NULL) continue; MPI_Comm_rank(intercomm, &rank); /** 0 ranks on each side communicate, everyone else does nothing */ if(rank == 0) { if (isLeft) { recvlen = -1; MPI_Probe(0, 0, intercomm, &status); MPI_Get_count(&status, MPI_CHAR, &recvlen); if (recvlen != (strlen(test_str) + 1)) { printf(" Error: recvlen (%d) != strlen(\"%s\")+1 (%d)\n", recvlen, test_str, (int)strlen(test_str) + 1); ++errs; } buf[0] = '\0'; MPI_Recv(buf, recvlen, MPI_CHAR, 0, 0, intercomm, &status); if (strcmp(test_str,buf)) { printf(" Error: strcmp(test_str,buf)!=0\n"); ++errs; } } else { strncpy(buf, test_str, 5); MPI_Send(buf, strlen(buf)+1, MPI_CHAR, 0, 0, intercomm); } } MTestFreeComm(&intercomm); } MTest_Finalize( errs ); MPI_Finalize(); return 0; } }
26.76
124
0.540608
jpkenny
cb8eb99ac87328b3295e2a216dc5fdb43219b1a5
3,660
cpp
C++
cxxtest/cxxtest/LinkedList.cpp
coreyp1/graphlab
637be90021c5f83ab7833ca15c48e76039057969
[ "ECL-2.0", "Apache-2.0" ]
333
2016-07-29T19:22:07.000Z
2022-03-30T02:40:34.000Z
cxxtest/cxxtest/LinkedList.cpp
HybridGraph/GraphLab-PowerGraph
ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94
[ "ECL-2.0", "Apache-2.0" ]
17
2016-09-15T00:31:59.000Z
2022-02-08T07:51:07.000Z
cxxtest/cxxtest/LinkedList.cpp
HybridGraph/GraphLab-PowerGraph
ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94
[ "ECL-2.0", "Apache-2.0" ]
163
2016-07-29T19:22:11.000Z
2022-03-07T07:15:24.000Z
/* ------------------------------------------------------------------------- CxxTest: A lightweight C++ unit testing library. Copyright (c) 2008 Sandia Corporation. This software is distributed under the LGPL License v2.1 For more information, see the COPYING file in the top CxxTest directory. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. ------------------------------------------------------------------------- */ #ifndef __cxxtest__LinkedList_cpp__ #define __cxxtest__LinkedList_cpp__ #include <cxxtest/LinkedList.h> namespace CxxTest { List GlobalFixture::_list = { 0, 0 }; List RealSuiteDescription::_suites = { 0, 0 }; void List::initialize() { _head = _tail = 0; } Link *List::head() { Link *l = _head; while ( l && !l->active() ) l = l->next(); return l; } const Link *List::head() const { Link *l = _head; while ( l && !l->active() ) l = l->next(); return l; } Link *List::tail() { Link *l = _tail; while ( l && !l->active() ) l = l->prev(); return l; } const Link *List::tail() const { Link *l = _tail; while ( l && !l->active() ) l = l->prev(); return l; } bool List::empty() const { return (_head == 0); } unsigned List::size() const { unsigned count = 0; for ( const Link *l = head(); l != 0; l = l->next() ) ++ count; return count; } Link *List::nth( unsigned n ) { Link *l = head(); while ( n -- ) l = l->next(); return l; } void List::activateAll() { for ( Link *l = _head; l != 0; l = l->justNext() ) l->setActive( true ); } void List::leaveOnly( const Link &link ) { for ( Link *l = head(); l != 0; l = l->next() ) if ( l != &link ) l->setActive( false ); } Link::Link() : _next( 0 ), _prev( 0 ), _active( true ) { } Link::~Link() { } bool Link::active() const { return _active; } void Link::setActive( bool value ) { _active = value; } Link * Link::justNext() { return _next; } Link * Link::justPrev() { return _prev; } Link * Link::next() { Link *l = _next; while ( l && !l->_active ) l = l->_next; return l; } Link * Link::prev() { Link *l = _prev; while ( l && !l->_active ) l = l->_prev; return l; } const Link * Link::next() const { Link *l = _next; while ( l && !l->_active ) l = l->_next; return l; } const Link * Link::prev() const { Link *l = _prev; while ( l && !l->_active ) l = l->_prev; return l; } void Link::attach( List &l ) { if ( l._tail ) l._tail->_next = this; _prev = l._tail; _next = 0; if ( l._head == 0 ) l._head = this; l._tail = this; } void Link::detach( List &l ) { if ( _prev ) _prev->_next = _next; else l._head = _next; if ( _next ) _next->_prev = _prev; else l._tail = _prev; } } #endif // __cxxtest__LinkedList_cpp__
19.891304
73
0.428415
coreyp1
cb8f1953a88140b9afa9a18898b6c177720b6f8a
9,131
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
3,294
2016-10-30T05:27:20.000Z
2022-03-31T15:59:30.000Z
samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
16,739
2016-10-28T19:41:29.000Z
2022-03-31T22:38:48.000Z
samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
6,701
2016-10-29T20:56:11.000Z
2022-03-31T12:32:26.000Z
using namespace System; using namespace System::Globalization; void ShowZeroPlaceholder() { // <Snippet1> double value; value = 123; Console::WriteLine(value.ToString("00000")); Console::WriteLine(String::Format("{0:00000}", value)); // Displays 00123 value = 1.2; Console::WriteLine(value.ToString("0.00", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.00}", value)); // Displays 1.20 Console::WriteLine(value.ToString("00.00", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:00.00}", value)); // Displays 01.20 CultureInfo^ daDK = CultureInfo::CreateSpecificCulture("da-DK"); Console::WriteLine(value.ToString("00.00", daDK)); Console::WriteLine(String::Format(daDK, "{0:00.00}", value)); // Displays 01,20 value = .56; Console::WriteLine(value.ToString("0.0", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.0}", value)); // Displays 0.6 value = 1234567890; Console::WriteLine(value.ToString("0,0", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0,0}", value)); // Displays 1,234,567,890 CultureInfo^ elGR = CultureInfo::CreateSpecificCulture("el-GR"); Console::WriteLine(value.ToString("0,0", elGR)); Console::WriteLine(String::Format(elGR, "{0:0,0}", value)); // Displays 1.234.567.890 value = 1234567890.123456; Console::WriteLine(value.ToString("0,0.0", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0,0.0}", value)); // Displays 1,234,567,890.1 value = 1234.567890; Console::WriteLine(value.ToString("0,0.00", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0,0.00}", value)); // Displays 1,234.57 // </Snippet1> } void ShowDigitPlaceholder() { // <Snippet2> double value; value = 1.2; Console::WriteLine(value.ToString("#.##", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#.##}", value)); // Displays 1.2 value = 123; Console::WriteLine(value.ToString("#####")); Console::WriteLine(String::Format("{0:#####}", value)); // Displays 123 value = 123456; Console::WriteLine(value.ToString("[##-##-##]")); Console::WriteLine(String::Format("{0:[##-##-##]}", value)); // Displays [12-34-56] value = 1234567890; Console::WriteLine(value.ToString("#")); Console::WriteLine(String::Format("{0:#}", value)); // Displays 1234567890 Console::WriteLine(value.ToString("(###) ###-####")); Console::WriteLine(String::Format("{0:(###) ###-####}", value)); // Displays (123) 456-7890 // </Snippet2> } void ShowDecimalPoint() { // <Snippet3> double value; value = 1.2; Console::WriteLine(value.ToString("0.00", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.00}", value)); // Displays 1.20 Console::WriteLine(value.ToString("00.00", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:00.00}", value)); // Displays 01.20 Console::WriteLine(value.ToString("00.00", CultureInfo::CreateSpecificCulture("da-DK"))); Console::WriteLine(String::Format(CultureInfo::CreateSpecificCulture("da-DK"), "{0:00.00}", value)); // Displays 01,20 value = .086; Console::WriteLine(value.ToString("#0.##%", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#0.##%}", value)); // Displays 8.6% value = 86000; Console::WriteLine(value.ToString("0.###E+0", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.###E+0}", value)); // Displays 8.6E+4 // </Snippet3> } void ShowThousandSpecifier() { // <Snippet4> double value = 1234567890; Console::WriteLine(value.ToString("#,#", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#,#}", value)); // Displays 1,234,567,890 Console::WriteLine(value.ToString("#,##0,,", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#,##0,,}", value)); // Displays 1,235 // </Snippet4> } void ShowScalingSpecifier() { // <Snippet5> double value = 1234567890; Console::WriteLine(value.ToString("#,,", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#,,}", value)); // Displays 1235 Console::WriteLine(value.ToString("#,,,", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#,,,}", value)); // Displays 1 Console::WriteLine(value.ToString("#,##0,,", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#,##0,,}", value)); // Displays 1,235 // </Snippet5> } void ShowPercentagePlaceholder() { // <Snippet6> double value = .086; Console::WriteLine(value.ToString("#0.##%", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#0.##%}", value)); // Displays 8.6% // </Snippet6> } void ShowScientificNotation() { // <Snippet7> double value = 86000; Console::WriteLine(value.ToString("0.###E+0", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.###E+0}", value)); // Displays 8.6E+4 Console::WriteLine(value.ToString("0.###E+000", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.###E+000}", value)); // Displays 8.6E+004 Console::WriteLine(value.ToString("0.###E-000", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.###E-000}", value)); // Displays 8.6E004 // </Snippet7> } void ShowSectionSpecifier() { // <Snippet8> double posValue = 1234; double negValue = -1234; double zeroValue = 0; String^ fmt2 = "##;(##)"; String^ fmt3 = "##;(##);**Zero**"; Console::WriteLine(posValue.ToString(fmt2)); Console::WriteLine(String::Format("{0:" + fmt2 + "}", posValue)); // Displays 1234 Console::WriteLine(negValue.ToString(fmt2)); Console::WriteLine(String::Format("{0:" + fmt2 + "}", negValue)); // Displays (1234) Console::WriteLine(zeroValue.ToString(fmt3)); Console::WriteLine(String::Format("{0:" + fmt3 + "}", zeroValue)); // Displays **Zero** // </Snippet8> } void ShowPerMillePlaceholder() { // <Snippet9> double value = .00354; String^ perMilleFmt = "#0.## " + '\u2030'; Console::WriteLine(value.ToString(perMilleFmt, CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:" + perMilleFmt + "}", value)); // Displays 3.54‰ // </Snippet9> } void main() { Console::WriteLine("Zero Placeholder:"); ShowZeroPlaceholder(); Console::WriteLine(); Console::WriteLine("Digit Placeholder:"); ShowDigitPlaceholder(); Console::WriteLine(); Console::WriteLine("Decimal Point:"); ShowDecimalPoint(); Console::WriteLine(); Console::WriteLine("Thousand Specifier:"); ShowThousandSpecifier(); Console::WriteLine(); Console::WriteLine("Scaling Specifier:"); ShowScalingSpecifier(); Console::WriteLine(); Console::WriteLine("Percentage Placeholder:"); ShowPercentagePlaceholder(); Console::WriteLine(); Console::WriteLine("Scientific Notation:"); ShowScientificNotation(); Console::WriteLine(); Console::WriteLine("Section Specifier:"); ShowSectionSpecifier(); Console::WriteLine(); Console::WriteLine("Per Mille Placeholder:"); ShowPerMillePlaceholder(); }
34.587121
88
0.584273
BaruaSourav
cb8f5f99ee52b47d12b2b22e88ec05420a77959c
1,226
cpp
C++
imap/src/protocol/StoreResponseParser.cpp
webOS-ports/mojomail
49358ac2878e010f5c6e3bd962f047c476c11fc3
[ "Apache-2.0" ]
6
2015-01-09T02:20:27.000Z
2021-01-02T08:14:23.000Z
mojomail/imap/src/protocol/StoreResponseParser.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
3
2019-05-11T19:17:56.000Z
2021-11-24T16:04:36.000Z
mojomail/imap/src/protocol/StoreResponseParser.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
6
2015-01-09T02:21:13.000Z
2021-01-02T02:37:10.000Z
// @@@LICENSE // // Copyright (c) 2010-2013 LG Electronics, 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. // // LICENSE@@@ #include "protocol/StoreResponseParser.h" StoreResponseParser::StoreResponseParser(ImapSession& session, DoneSignal::SlotRef doneSlot) : ImapResponseParser(session, doneSlot), m_responsesLeft(0) { } StoreResponseParser::~StoreResponseParser() { } void StoreResponseParser::HandleResponse(ImapStatusCode status, const std::string& response) { // FIXME handle errors m_responsesLeft--; } void StoreResponseParser::AddExpectedResponse() { m_responsesLeft++; } void StoreResponseParser::Done() { if(m_responsesLeft < 1 || m_status == STATUS_EXCEPTION) m_doneSignal.fire(); }
26.085106
92
0.750408
webOS-ports
cb921de5fe541c257bb94857dfbcc47a3e146bf7
984
cpp
C++
src/scripting/Sandbox.cpp
AlxAce/CyberEngineTweaks
3b1d2dba1717a69eae1972497dbde1952fef6d47
[ "MIT" ]
null
null
null
src/scripting/Sandbox.cpp
AlxAce/CyberEngineTweaks
3b1d2dba1717a69eae1972497dbde1952fef6d47
[ "MIT" ]
null
null
null
src/scripting/Sandbox.cpp
AlxAce/CyberEngineTweaks
3b1d2dba1717a69eae1972497dbde1952fef6d47
[ "MIT" ]
null
null
null
#include <stdafx.h> #include "Sandbox.h" #include "Scripting.h" Sandbox::Sandbox(Scripting* apScripting, sol::environment aBaseEnvironment, const std::filesystem::path& acRootPath) : m_pScripting(apScripting) , m_env(apScripting->GetState().Get(), sol::create) , m_path(acRootPath) { // copy base environment, do not set it as fallback, as it may cause globals to bleed into other things! for (const auto& cKV : aBaseEnvironment) m_env[cKV.first].set(cKV.second.as<sol::object>()); } sol::protected_function_result Sandbox::ExecuteFile(const std::string& acPath) const { return m_pScripting->GetState().Get().script_file(acPath, m_env); } sol::protected_function_result Sandbox::ExecuteString(const std::string& acString) const { return m_pScripting->GetState().Get().script(acString, m_env); } sol::environment& Sandbox::GetEnvironment() { return m_env; } const std::filesystem::path& Sandbox::GetRootPath() const { return m_path; }
28.114286
116
0.723577
AlxAce
cb923eaa13a4528dda916d9bd8bfb0930d92e117
3,031
cpp
C++
NEERC/Subregionals/2010-2011/C/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
2
2018-11-08T05:57:22.000Z
2018-11-08T05:57:27.000Z
NEERC/Subregionals/2010-2011/C/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
null
null
null
NEERC/Subregionals/2010-2011/C/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
null
null
null
#define __USE_MINGW_ANSI_STDIO 0 #include<bits/stdc++.h> using namespace std; #define PI acos(-1) #define pb push_back #define fi first #define se second #define TASK "commuting" #define sz(a) (int)(a).size() #define all(c) (c).begin(), (c).end() #define TIMESTAMP fprintf(stderr, "Execution time: %.3lf s.\n", (double)clock()/CLOCKS_PER_SEC) typedef long long ll; typedef long double ld; typedef vector <int> vi; typedef vector <ll> vll; typedef pair <int, int> pii; typedef vector <vi> vvi; typedef vector <pii> vpii; typedef vector <string> vs; const int MAXN = 2e5 + 9; const int MOD = (int)(1e9 + 7); const int INF = 1e9; int gg[MAXN], rr[MAXN]; int n; int ans[MAXN]; int T[MAXN]; int cnt = 0; int tmp[MAXN], posTmp; mt19937_64 rnd(chrono::high_resolution_clock::now().time_since_epoch().count()); void input() { cin >> n; for(int i = 1; i <= n; i++) { int x; cin >> x; gg[i] = x; rr[x] = i; } } void go(int pos) { if(pos == n + 1) { cnt++; bool ok = 1; for(int i = 1; i <= n; i++) if(T[i] < ans[i]) ok = 0; else if(ok && ans[i] < T[i]) { return; } for(int i = 1; i <= n; i++) { if(gg[T[i]] != T[gg[i]]) return; } if(!ok) { cout << " found " << endl; cout << " input " << endl; for(int i = 1; i <= n; i++) cout << gg[i] << ' '; cout << endl; cout << " ans " << endl; for(int i = 1; i <= n; i++) cout << ans[i] << ' '; cout << endl; cout << " bettter ans " << endl; for(int i = 1; i <= n; i++) cout << T[i] << ' '; cout << endl; cout << " checking " << endl; for(int i = 1; i <= n; i++) cout << gg[T[i]] - T[gg[i]] << ' '; cout << endl; exit(0); } return; } for(int i = 1; i <= n; i++) { T[pos] = i; go(pos + 1); } } void solve() { memset(ans, -1, sizeof(ans)); vi cycles(n + 1, INF); vi used(n + 1, 0); for(int i = 1; i <= n; i++) { if(used[i]) continue; posTmp = 0; tmp[posTmp++] = gg[i]; int v = gg[gg[i]]; while(v != gg[i]) { used[v] = 1; tmp[posTmp++] = v; v = gg[v]; } int curMin = *min_element(tmp, tmp + posTmp); cycles[posTmp] = min(cycles[posTmp], curMin); } for(int i = 1; i <= n; i++) { if(ans[i] != -1) continue; posTmp = 0; tmp[posTmp++] = gg[i]; int v = gg[gg[i]]; while(v != gg[i]) { tmp[posTmp++] = v; v = gg[v]; } int cur = INF; cerr << i << ' ' << posTmp << endl; TIMESTAMP; for(int j = 1; j <= posTmp; j++) if(posTmp % j == 0) cur = min(cur, cycles[j]); for(int j = 0; j < posTmp; j++) { ans[rr[tmp[j]]] = cur; cur = gg[cur]; } } for(int i = 1; i <= n; i++) assert(ans[gg[i]] == gg[ans[i]]); //go(1); for(int i = 1; i <= n; i++) cout << ans[i] << ' '; cout << endl; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); #ifdef LOCAL freopen("xxx.in", "r", stdin); freopen("xxx.out", "w", stdout); #else freopen(TASK".in", "r", stdin); freopen(TASK".out", "w", stdout); #endif input(); solve(); #ifdef LOCAL TIMESTAMP; #endif return 0; }
20.206667
95
0.509733
Zovube
cb9360ba1b46f7dbb3d672f5808f37bfdb08724b
266
cpp
C++
source/tm/constant_generation.cpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
7
2021-03-05T16:50:19.000Z
2022-02-02T04:30:07.000Z
source/tm/constant_generation.cpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
47
2021-02-01T18:54:23.000Z
2022-03-06T19:06:16.000Z
source/tm/constant_generation.cpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
1
2021-01-28T13:10:41.000Z
2021-01-28T13:10:41.000Z
// Handles challenges / current battles // Copyright David Stone 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <tm/constant_generation.hpp>
33.25
61
0.763158
davidstone
cb95c2999d027993521319f9c7945c1a8074c6e1
49,799
cpp
C++
src/core/SkColorSpaceXform.cpp
juanpca12/Google-Skia
42e6798696ac3a93a2b7ba7a9d6a84b77eba0116
[ "Apache-2.0" ]
null
null
null
src/core/SkColorSpaceXform.cpp
juanpca12/Google-Skia
42e6798696ac3a93a2b7ba7a9d6a84b77eba0116
[ "Apache-2.0" ]
null
null
null
src/core/SkColorSpaceXform.cpp
juanpca12/Google-Skia
42e6798696ac3a93a2b7ba7a9d6a84b77eba0116
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorPriv.h" #include "SkColorSpace_Base.h" #include "SkColorSpaceXform.h" #include "SkOpts.h" static inline bool compute_gamut_xform(SkMatrix44* srcToDst, const SkMatrix44& srcToXYZ, const SkMatrix44& dstToXYZ) { if (!dstToXYZ.invert(srcToDst)) { return false; } srcToDst->postConcat(srcToXYZ); return true; } std::unique_ptr<SkColorSpaceXform> SkColorSpaceXform::New(const sk_sp<SkColorSpace>& srcSpace, const sk_sp<SkColorSpace>& dstSpace) { if (!srcSpace || !dstSpace) { // Invalid input return nullptr; } if (as_CSB(dstSpace)->colorLUT()) { // It would be really weird for a dst profile to have a color LUT. I don't think // we need to support this. return nullptr; } SkMatrix44 srcToDst(SkMatrix44::kUninitialized_Constructor); if (!compute_gamut_xform(&srcToDst, srcSpace->xyz(), dstSpace->xyz())) { return nullptr; } if (0.0f == srcToDst.getFloat(3, 0) && 0.0f == srcToDst.getFloat(3, 1) && 0.0f == srcToDst.getFloat(3, 2) && !as_CSB(srcSpace)->colorLUT()) { switch (srcSpace->gammaNamed()) { case SkColorSpace::kSRGB_GammaNamed: if (SkColorSpace::kSRGB_GammaNamed == dstSpace->gammaNamed()) { return std::unique_ptr<SkColorSpaceXform>( new SkFastXform<SkColorSpace::kSRGB_GammaNamed, SkColorSpace::kSRGB_GammaNamed>(srcToDst)); } else if (SkColorSpace::k2Dot2Curve_GammaNamed == dstSpace->gammaNamed()) { return std::unique_ptr<SkColorSpaceXform>( new SkFastXform<SkColorSpace::kSRGB_GammaNamed, SkColorSpace::k2Dot2Curve_GammaNamed>(srcToDst)); } break; case SkColorSpace::k2Dot2Curve_GammaNamed: if (SkColorSpace::kSRGB_GammaNamed == dstSpace->gammaNamed()) { return std::unique_ptr<SkColorSpaceXform>( new SkFastXform<SkColorSpace::k2Dot2Curve_GammaNamed, SkColorSpace::kSRGB_GammaNamed>(srcToDst)); } else if (SkColorSpace::k2Dot2Curve_GammaNamed == dstSpace->gammaNamed()) { return std::unique_ptr<SkColorSpaceXform>( new SkFastXform<SkColorSpace::k2Dot2Curve_GammaNamed, SkColorSpace::k2Dot2Curve_GammaNamed>(srcToDst)); } break; default: break; } } return std::unique_ptr<SkColorSpaceXform>(new SkDefaultXform(srcSpace, srcToDst, dstSpace)); } /////////////////////////////////////////////////////////////////////////////////////////////////// static void build_src_to_dst(float srcToDstArray[12], const SkMatrix44& srcToDstMatrix) { // Build the following row major matrix: // rX gX bX 0 // rY gY bY 0 // rZ gZ bZ 0 // Swap R and B if necessary to make sure that we output SkPMColor order. #ifdef SK_PMCOLOR_IS_BGRA srcToDstArray[0] = srcToDstMatrix.getFloat(0, 2); srcToDstArray[1] = srcToDstMatrix.getFloat(0, 1); srcToDstArray[2] = srcToDstMatrix.getFloat(0, 0); srcToDstArray[3] = 0.0f; srcToDstArray[4] = srcToDstMatrix.getFloat(1, 2); srcToDstArray[5] = srcToDstMatrix.getFloat(1, 1); srcToDstArray[6] = srcToDstMatrix.getFloat(1, 0); srcToDstArray[7] = 0.0f; srcToDstArray[8] = srcToDstMatrix.getFloat(2, 2); srcToDstArray[9] = srcToDstMatrix.getFloat(2, 1); srcToDstArray[10] = srcToDstMatrix.getFloat(2, 0); srcToDstArray[11] = 0.0f; #else srcToDstArray[0] = srcToDstMatrix.getFloat(0, 0); srcToDstArray[1] = srcToDstMatrix.getFloat(0, 1); srcToDstArray[2] = srcToDstMatrix.getFloat(0, 2); srcToDstArray[3] = 0.0f; srcToDstArray[4] = srcToDstMatrix.getFloat(1, 0); srcToDstArray[5] = srcToDstMatrix.getFloat(1, 1); srcToDstArray[6] = srcToDstMatrix.getFloat(1, 2); srcToDstArray[7] = 0.0f; srcToDstArray[8] = srcToDstMatrix.getFloat(2, 0); srcToDstArray[9] = srcToDstMatrix.getFloat(2, 1); srcToDstArray[10] = srcToDstMatrix.getFloat(2, 2); srcToDstArray[11] = 0.0f; #endif } template <SkColorSpace::GammaNamed Src, SkColorSpace::GammaNamed Dst> SkFastXform<Src, Dst>::SkFastXform(const SkMatrix44& srcToDst) { build_src_to_dst(fSrcToDst, srcToDst); } template <> void SkFastXform<SkColorSpace::kSRGB_GammaNamed, SkColorSpace::kSRGB_GammaNamed> ::xform_RGB1_8888(uint32_t* dst, const uint32_t* src, uint32_t len) const { SkOpts::color_xform_RGB1_srgb_to_srgb(dst, src, len, fSrcToDst); } template <> void SkFastXform<SkColorSpace::kSRGB_GammaNamed, SkColorSpace::k2Dot2Curve_GammaNamed> ::xform_RGB1_8888(uint32_t* dst, const uint32_t* src, uint32_t len) const { SkOpts::color_xform_RGB1_srgb_to_2dot2(dst, src, len, fSrcToDst); } template <> void SkFastXform<SkColorSpace::k2Dot2Curve_GammaNamed, SkColorSpace::kSRGB_GammaNamed> ::xform_RGB1_8888(uint32_t* dst, const uint32_t* src, uint32_t len) const { SkOpts::color_xform_RGB1_2dot2_to_srgb(dst, src, len, fSrcToDst); } template <> void SkFastXform<SkColorSpace::k2Dot2Curve_GammaNamed, SkColorSpace::k2Dot2Curve_GammaNamed> ::xform_RGB1_8888(uint32_t* dst, const uint32_t* src, uint32_t len) const { SkOpts::color_xform_RGB1_2dot2_to_2dot2(dst, src, len, fSrcToDst); } /////////////////////////////////////////////////////////////////////////////////////////////////// extern const float sk_linear_from_srgb[256] = { 0.000000000000000000f, 0.000303526983548838f, 0.000607053967097675f, 0.000910580950646513f, 0.001214107934195350f, 0.001517634917744190f, 0.001821161901293030f, 0.002124688884841860f, 0.002428215868390700f, 0.002731742851939540f, 0.003034518678424960f, 0.003346535763899160f, 0.003676507324047440f, 0.004024717018496310f, 0.004391442037410290f, 0.004776953480693730f, 0.005181516702338390f, 0.005605391624202720f, 0.006048833022857060f, 0.006512090792594470f, 0.006995410187265390f, 0.007499032043226180f, 0.008023192985384990f, 0.008568125618069310f, 0.009134058702220790f, 0.009721217320237850f, 0.010329823029626900f, 0.010960094006488200f, 0.011612245179743900f, 0.012286488356915900f, 0.012983032342173000f, 0.013702083047289700f, 0.014443843596092500f, 0.015208514422912700f, 0.015996293365509600f, 0.016807375752887400f, 0.017641954488384100f, 0.018500220128379700f, 0.019382360956935700f, 0.020288563056652400f, 0.021219010376003600f, 0.022173884793387400f, 0.023153366178110400f, 0.024157632448504800f, 0.025186859627361600f, 0.026241221894849900f, 0.027320891639074900f, 0.028426039504420800f, 0.029556834437808800f, 0.030713443732993600f, 0.031896033073011500f, 0.033104766570885100f, 0.034339806808682200f, 0.035601314875020300f, 0.036889450401100000f, 0.038204371595346500f, 0.039546235276732800f, 0.040915196906853200f, 0.042311410620809700f, 0.043735029256973500f, 0.045186204385675500f, 0.046665086336880100f, 0.048171824226889400f, 0.049706565984127200f, 0.051269458374043200f, 0.052860647023180200f, 0.054480276442442400f, 0.056128490049600100f, 0.057805430191067200f, 0.059511238162981200f, 0.061246054231617600f, 0.063010017653167700f, 0.064803266692905800f, 0.066625938643772900f, 0.068478169844400200f, 0.070360095696595900f, 0.072271850682317500f, 0.074213568380149600f, 0.076185381481307900f, 0.078187421805186300f, 0.080219820314468300f, 0.082282707129814800f, 0.084376211544148800f, 0.086500462036549800f, 0.088655586285772900f, 0.090841711183407700f, 0.093058962846687500f, 0.095307466630964700f, 0.097587347141862500f, 0.099898728247113900f, 0.102241733088101000f, 0.104616484091104000f, 0.107023102978268000f, 0.109461710778299000f, 0.111932427836906000f, 0.114435373826974000f, 0.116970667758511000f, 0.119538427988346000f, 0.122138772229602000f, 0.124771817560950000f, 0.127437680435647000f, 0.130136476690364000f, 0.132868321553818000f, 0.135633329655206000f, 0.138431615032452000f, 0.141263291140272000f, 0.144128470858058000f, 0.147027266497595000f, 0.149959789810609000f, 0.152926151996150000f, 0.155926463707827000f, 0.158960835060880000f, 0.162029375639111000f, 0.165132194501668000f, 0.168269400189691000f, 0.171441100732823000f, 0.174647403655585000f, 0.177888415983629000f, 0.181164244249860000f, 0.184474994500441000f, 0.187820772300678000f, 0.191201682740791000f, 0.194617830441576000f, 0.198069319559949000f, 0.201556253794397000f, 0.205078736390317000f, 0.208636870145256000f, 0.212230757414055000f, 0.215860500113899000f, 0.219526199729269000f, 0.223227957316809000f, 0.226965873510098000f, 0.230740048524349000f, 0.234550582161005000f, 0.238397573812271000f, 0.242281122465555000f, 0.246201326707835000f, 0.250158284729953000f, 0.254152094330827000f, 0.258182852921596000f, 0.262250657529696000f, 0.266355604802862000f, 0.270497791013066000f, 0.274677312060385000f, 0.278894263476810000f, 0.283148740429992000f, 0.287440837726918000f, 0.291770649817536000f, 0.296138270798321000f, 0.300543794415777000f, 0.304987314069886000f, 0.309468922817509000f, 0.313988713375718000f, 0.318546778125092000f, 0.323143209112951000f, 0.327778098056542000f, 0.332451536346179000f, 0.337163615048330000f, 0.341914424908661000f, 0.346704056355030000f, 0.351532599500439000f, 0.356400144145944000f, 0.361306779783510000f, 0.366252595598840000f, 0.371237680474149000f, 0.376262122990906000f, 0.381326011432530000f, 0.386429433787049000f, 0.391572477749723000f, 0.396755230725627000f, 0.401977779832196000f, 0.407240211901737000f, 0.412542613483904000f, 0.417885070848138000f, 0.423267669986072000f, 0.428690496613907000f, 0.434153636174749000f, 0.439657173840919000f, 0.445201194516228000f, 0.450785782838223000f, 0.456411023180405000f, 0.462076999654407000f, 0.467783796112159000f, 0.473531496148010000f, 0.479320183100827000f, 0.485149940056070000f, 0.491020849847836000f, 0.496932995060870000f, 0.502886458032569000f, 0.508881320854934000f, 0.514917665376521000f, 0.520995573204354000f, 0.527115125705813000f, 0.533276404010505000f, 0.539479489012107000f, 0.545724461370187000f, 0.552011401512000000f, 0.558340389634268000f, 0.564711505704929000f, 0.571124829464873000f, 0.577580440429651000f, 0.584078417891164000f, 0.590618840919337000f, 0.597201788363763000f, 0.603827338855338000f, 0.610495570807865000f, 0.617206562419651000f, 0.623960391675076000f, 0.630757136346147000f, 0.637596873994033000f, 0.644479681970582000f, 0.651405637419824000f, 0.658374817279448000f, 0.665387298282272000f, 0.672443156957688000f, 0.679542469633094000f, 0.686685312435314000f, 0.693871761291990000f, 0.701101891932973000f, 0.708375779891687000f, 0.715693500506481000f, 0.723055128921969000f, 0.730460740090354000f, 0.737910408772731000f, 0.745404209540387000f, 0.752942216776078000f, 0.760524504675292000f, 0.768151147247507000f, 0.775822218317423000f, 0.783537791526194000f, 0.791297940332630000f, 0.799102738014409000f, 0.806952257669252000f, 0.814846572216101000f, 0.822785754396284000f, 0.830769876774655000f, 0.838799011740740000f, 0.846873231509858000f, 0.854992608124234000f, 0.863157213454102000f, 0.871367119198797000f, 0.879622396887832000f, 0.887923117881966000f, 0.896269353374266000f, 0.904661174391149000f, 0.913098651793419000f, 0.921581856277295000f, 0.930110858375424000f, 0.938685728457888000f, 0.947306536733200000f, 0.955973353249286000f, 0.964686247894465000f, 0.973445290398413000f, 0.982250550333117000f, 0.991102097113830000f, 1.000000000000000000f, }; extern const float sk_linear_from_2dot2[256] = { 0.000000000000000000f, 0.000005077051900662f, 0.000023328004666099f, 0.000056921765712193f, 0.000107187362341244f, 0.000175123977503027f, 0.000261543754548491f, 0.000367136269815943f, 0.000492503787191433f, 0.000638182842167022f, 0.000804658499513058f, 0.000992374304074325f, 0.001201739522438400f, 0.001433134589671860f, 0.001686915316789280f, 0.001963416213396470f, 0.002262953160706430f, 0.002585825596234170f, 0.002932318323938360f, 0.003302703032003640f, 0.003697239578900130f, 0.004116177093282750f, 0.004559754922526020f, 0.005028203456855540f, 0.005521744850239660f, 0.006040593654849810f, 0.006584957382581690f, 0.007155037004573030f, 0.007751027397660610f, 0.008373117745148580f, 0.009021491898012130f, 0.009696328701658230f, 0.010397802292555300f, 0.011126082368383200f, 0.011881334434813700f, 0.012663720031582100f, 0.013473396940142600f, 0.014310519374884100f, 0.015175238159625200f, 0.016067700890886900f, 0.016988052089250000f, 0.017936433339950200f, 0.018912983423721500f, 0.019917838438785700f, 0.020951131914781100f, 0.022012994919336500f, 0.023103556157921400f, 0.024222942067534200f, 0.025371276904734600f, 0.026548682828472900f, 0.027755279978126000f, 0.028991186547107800f, 0.030256518852388700f, 0.031551391400226400f, 0.032875916948383800f, 0.034230206565082000f, 0.035614369684918800f, 0.037028514161960200f, 0.038472746320194600f, 0.039947171001525600f, 0.041451891611462500f, 0.042987010162657100f, 0.044552627316421400f, 0.046148842422351000f, 0.047775753556170600f, 0.049433457555908000f, 0.051122050056493400f, 0.052841625522879000f, 0.054592277281760300f, 0.056374097551979800f, 0.058187177473685400f, 0.060031607136313200f, 0.061907475605455800f, 0.063814870948677200f, 0.065753880260330100f, 0.067724589685424300f, 0.069727084442598800f, 0.071761448846239100f, 0.073827766327784600f, 0.075926119456264800f, 0.078056589958101900f, 0.080219258736215100f, 0.082414205888459200f, 0.084641510725429500f, 0.086901251787660300f, 0.089193506862247800f, 0.091518352998919500f, 0.093875866525577800f, 0.096266123063339700f, 0.098689197541094500f, 0.101145164209600000f, 0.103634096655137000f, 0.106156067812744000f, 0.108711149979039000f, 0.111299414824660000f, 0.113920933406333000f, 0.116575776178572000f, 0.119264013005047000f, 0.121985713169619000f, 0.124740945387051000f, 0.127529777813422000f, 0.130352278056244000f, 0.133208513184300000f, 0.136098549737202000f, 0.139022453734703000f, 0.141980290685736000f, 0.144972125597231000f, 0.147998022982685000f, 0.151058046870511000f, 0.154152260812165000f, 0.157280727890073000f, 0.160443510725344000f, 0.163640671485290000f, 0.166872271890766000f, 0.170138373223312000f, 0.173439036332135000f, 0.176774321640903000f, 0.180144289154390000f, 0.183548998464951000f, 0.186988508758844000f, 0.190462878822409000f, 0.193972167048093000f, 0.197516431440340000f, 0.201095729621346000f, 0.204710118836677000f, 0.208359655960767000f, 0.212044397502288000f, 0.215764399609395000f, 0.219519718074868000f, 0.223310408341127000f, 0.227136525505149000f, 0.230998124323267000f, 0.234895259215880000f, 0.238827984272048000f, 0.242796353254002000f, 0.246800419601550000f, 0.250840236436400000f, 0.254915856566385000f, 0.259027332489606000f, 0.263174716398492000f, 0.267358060183772000f, 0.271577415438375000f, 0.275832833461245000f, 0.280124365261085000f, 0.284452061560024000f, 0.288815972797219000f, 0.293216149132375000f, 0.297652640449211000f, 0.302125496358853000f, 0.306634766203158000f, 0.311180499057984000f, 0.315762743736397000f, 0.320381548791810000f, 0.325036962521076000f, 0.329729032967515000f, 0.334457807923889000f, 0.339223334935327000f, 0.344025661302187000f, 0.348864834082879000f, 0.353740900096629000f, 0.358653905926199000f, 0.363603897920553000f, 0.368590922197487000f, 0.373615024646202000f, 0.378676250929840000f, 0.383774646487975000f, 0.388910256539059000f, 0.394083126082829000f, 0.399293299902674000f, 0.404540822567962000f, 0.409825738436323000f, 0.415148091655907000f, 0.420507926167587000f, 0.425905285707146000f, 0.431340213807410000f, 0.436812753800359000f, 0.442322948819202000f, 0.447870841800410000f, 0.453456475485731000f, 0.459079892424160000f, 0.464741134973889000f, 0.470440245304218000f, 0.476177265397440000f, 0.481952237050698000f, 0.487765201877811000f, 0.493616201311074000f, 0.499505276603030000f, 0.505432468828216000f, 0.511397818884880000f, 0.517401367496673000f, 0.523443155214325000f, 0.529523222417277000f, 0.535641609315311000f, 0.541798355950137000f, 0.547993502196972000f, 0.554227087766085000f, 0.560499152204328000f, 0.566809734896638000f, 0.573158875067523000f, 0.579546611782525000f, 0.585972983949661000f, 0.592438030320847000f, 0.598941789493296000f, 0.605484299910907000f, 0.612065599865624000f, 0.618685727498780000f, 0.625344720802427000f, 0.632042617620641000f, 0.638779455650817000f, 0.645555272444935000f, 0.652370105410821000f, 0.659223991813387000f, 0.666116968775851000f, 0.673049073280942000f, 0.680020342172095000f, 0.687030812154625000f, 0.694080519796882000f, 0.701169501531402000f, 0.708297793656032000f, 0.715465432335048000f, 0.722672453600255000f, 0.729918893352071000f, 0.737204787360605000f, 0.744530171266715000f, 0.751895080583051000f, 0.759299550695091000f, 0.766743616862161000f, 0.774227314218442000f, 0.781750677773962000f, 0.789313742415586000f, 0.796916542907978000f, 0.804559113894567000f, 0.812241489898490000f, 0.819963705323528000f, 0.827725794455034000f, 0.835527791460841000f, 0.843369730392169000f, 0.851251645184515000f, 0.859173569658532000f, 0.867135537520905000f, 0.875137582365205000f, 0.883179737672745000f, 0.891262036813419000f, 0.899384513046529000f, 0.907547199521614000f, 0.915750129279253000f, 0.923993335251873000f, 0.932276850264543000f, 0.940600707035753000f, 0.948964938178195000f, 0.957369576199527000f, 0.965814653503130000f, 0.974300202388861000f, 0.982826255053791000f, 0.991392843592940000f, 1.000000000000000000f, }; static void build_table_linear_from_gamma(float* outTable, float exponent) { for (float x = 0.0f; x <= 1.0f; x += (1.0f/255.0f)) { *outTable++ = powf(x, exponent); } } // Interpolating lookup in a variably sized table. static float interp_lut(float input, const float* table, int tableSize) { float index = input * (tableSize - 1); float diff = index - sk_float_floor2int(index); return table[(int) sk_float_floor2int(index)] * (1.0f - diff) + table[(int) sk_float_ceil2int(index)] * diff; } // outTable is always 256 entries, inTable may be larger or smaller. static void build_table_linear_from_gamma(float* outTable, const float* inTable, int inTableSize) { if (256 == inTableSize) { memcpy(outTable, inTable, sizeof(float) * 256); return; } for (float x = 0.0f; x <= 1.0f; x += (1.0f/255.0f)) { *outTable++ = interp_lut(x, inTable, inTableSize); } } static void build_table_linear_from_gamma(float* outTable, float g, float a, float b, float c, float d, float e, float f) { // Y = (aX + b)^g + c for X >= d // Y = eX + f otherwise for (float x = 0.0f; x <= 1.0f; x += (1.0f/255.0f)) { if (x >= d) { *outTable++ = powf(a * x + b, g) + c; } else { *outTable++ = e * x + f; } } } static constexpr uint8_t linear_to_srgb[1024] = { 0, 3, 6, 10, 13, 15, 18, 20, 22, 23, 25, 27, 28, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 49, 50, 51, 52, 53, 53, 54, 55, 56, 56, 57, 58, 58, 59, 60, 61, 61, 62, 62, 63, 64, 64, 65, 66, 66, 67, 67, 68, 68, 69, 70, 70, 71, 71, 72, 72, 73, 73, 74, 74, 75, 76, 76, 77, 77, 78, 78, 79, 79, 79, 80, 80, 81, 81, 82, 82, 83, 83, 84, 84, 85, 85, 85, 86, 86, 87, 87, 88, 88, 88, 89, 89, 90, 90, 91, 91, 91, 92, 92, 93, 93, 93, 94, 94, 95, 95, 95, 96, 96, 97, 97, 97, 98, 98, 98, 99, 99, 99, 100, 100, 101, 101, 101, 102, 102, 102, 103, 103, 103, 104, 104, 104, 105, 105, 106, 106, 106, 107, 107, 107, 108, 108, 108, 109, 109, 109, 110, 110, 110, 110, 111, 111, 111, 112, 112, 112, 113, 113, 113, 114, 114, 114, 115, 115, 115, 115, 116, 116, 116, 117, 117, 117, 118, 118, 118, 118, 119, 119, 119, 120, 120, 120, 121, 121, 121, 121, 122, 122, 122, 123, 123, 123, 123, 124, 124, 124, 125, 125, 125, 125, 126, 126, 126, 126, 127, 127, 127, 128, 128, 128, 128, 129, 129, 129, 129, 130, 130, 130, 130, 131, 131, 131, 131, 132, 132, 132, 133, 133, 133, 133, 134, 134, 134, 134, 135, 135, 135, 135, 136, 136, 136, 136, 137, 137, 137, 137, 138, 138, 138, 138, 138, 139, 139, 139, 139, 140, 140, 140, 140, 141, 141, 141, 141, 142, 142, 142, 142, 143, 143, 143, 143, 143, 144, 144, 144, 144, 145, 145, 145, 145, 146, 146, 146, 146, 146, 147, 147, 147, 147, 148, 148, 148, 148, 148, 149, 149, 149, 149, 150, 150, 150, 150, 150, 151, 151, 151, 151, 152, 152, 152, 152, 152, 153, 153, 153, 153, 153, 154, 154, 154, 154, 155, 155, 155, 155, 155, 156, 156, 156, 156, 156, 157, 157, 157, 157, 157, 158, 158, 158, 158, 158, 159, 159, 159, 159, 159, 160, 160, 160, 160, 160, 161, 161, 161, 161, 161, 162, 162, 162, 162, 162, 163, 163, 163, 163, 163, 164, 164, 164, 164, 164, 165, 165, 165, 165, 165, 166, 166, 166, 166, 166, 167, 167, 167, 167, 167, 168, 168, 168, 168, 168, 168, 169, 169, 169, 169, 169, 170, 170, 170, 170, 170, 171, 171, 171, 171, 171, 171, 172, 172, 172, 172, 172, 173, 173, 173, 173, 173, 173, 174, 174, 174, 174, 174, 175, 175, 175, 175, 175, 175, 176, 176, 176, 176, 176, 177, 177, 177, 177, 177, 177, 178, 178, 178, 178, 178, 178, 179, 179, 179, 179, 179, 179, 180, 180, 180, 180, 180, 181, 181, 181, 181, 181, 181, 182, 182, 182, 182, 182, 182, 183, 183, 183, 183, 183, 183, 184, 184, 184, 184, 184, 184, 185, 185, 185, 185, 185, 185, 186, 186, 186, 186, 186, 186, 187, 187, 187, 187, 187, 187, 188, 188, 188, 188, 188, 188, 189, 189, 189, 189, 189, 189, 190, 190, 190, 190, 190, 190, 191, 191, 191, 191, 191, 191, 191, 192, 192, 192, 192, 192, 192, 193, 193, 193, 193, 193, 193, 194, 194, 194, 194, 194, 194, 194, 195, 195, 195, 195, 195, 195, 196, 196, 196, 196, 196, 196, 197, 197, 197, 197, 197, 197, 197, 198, 198, 198, 198, 198, 198, 199, 199, 199, 199, 199, 199, 199, 200, 200, 200, 200, 200, 200, 200, 201, 201, 201, 201, 201, 201, 202, 202, 202, 202, 202, 202, 202, 203, 203, 203, 203, 203, 203, 203, 204, 204, 204, 204, 204, 204, 204, 205, 205, 205, 205, 205, 205, 206, 206, 206, 206, 206, 206, 206, 207, 207, 207, 207, 207, 207, 207, 208, 208, 208, 208, 208, 208, 208, 209, 209, 209, 209, 209, 209, 209, 210, 210, 210, 210, 210, 210, 210, 211, 211, 211, 211, 211, 211, 211, 212, 212, 212, 212, 212, 212, 212, 212, 213, 213, 213, 213, 213, 213, 213, 214, 214, 214, 214, 214, 214, 214, 215, 215, 215, 215, 215, 215, 215, 216, 216, 216, 216, 216, 216, 216, 216, 217, 217, 217, 217, 217, 217, 217, 218, 218, 218, 218, 218, 218, 218, 219, 219, 219, 219, 219, 219, 219, 219, 220, 220, 220, 220, 220, 220, 220, 221, 221, 221, 221, 221, 221, 221, 221, 222, 222, 222, 222, 222, 222, 222, 222, 223, 223, 223, 223, 223, 223, 223, 224, 224, 224, 224, 224, 224, 224, 224, 225, 225, 225, 225, 225, 225, 225, 225, 226, 226, 226, 226, 226, 226, 226, 227, 227, 227, 227, 227, 227, 227, 227, 228, 228, 228, 228, 228, 228, 228, 228, 229, 229, 229, 229, 229, 229, 229, 229, 230, 230, 230, 230, 230, 230, 230, 230, 231, 231, 231, 231, 231, 231, 231, 231, 232, 232, 232, 232, 232, 232, 232, 232, 233, 233, 233, 233, 233, 233, 233, 233, 234, 234, 234, 234, 234, 234, 234, 234, 235, 235, 235, 235, 235, 235, 235, 235, 236, 236, 236, 236, 236, 236, 236, 236, 236, 237, 237, 237, 237, 237, 237, 237, 237, 238, 238, 238, 238, 238, 238, 238, 238, 239, 239, 239, 239, 239, 239, 239, 239, 239, 240, 240, 240, 240, 240, 240, 240, 240, 241, 241, 241, 241, 241, 241, 241, 241, 241, 242, 242, 242, 242, 242, 242, 242, 242, 243, 243, 243, 243, 243, 243, 243, 243, 243, 244, 244, 244, 244, 244, 244, 244, 244, 245, 245, 245, 245, 245, 245, 245, 245, 245, 246, 246, 246, 246, 246, 246, 246, 246, 246, 247, 247, 247, 247, 247, 247, 247, 247, 248, 248, 248, 248, 248, 248, 248, 248, 248, 249, 249, 249, 249, 249, 249, 249, 249, 249, 250, 250, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253, 253, 253, 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255 }; static constexpr uint8_t linear_to_2dot2[1024] = { 0, 11, 15, 18, 21, 23, 25, 26, 28, 30, 31, 32, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 45, 46, 47, 48, 49, 50, 50, 51, 52, 53, 54, 54, 55, 56, 56, 57, 58, 58, 59, 60, 60, 61, 62, 62, 63, 63, 64, 65, 65, 66, 66, 67, 68, 68, 69, 69, 70, 70, 71, 71, 72, 72, 73, 73, 74, 74, 75, 75, 76, 76, 77, 77, 78, 78, 79, 79, 80, 80, 81, 81, 81, 82, 82, 83, 83, 84, 84, 84, 85, 85, 86, 86, 87, 87, 87, 88, 88, 89, 89, 89, 90, 90, 91, 91, 91, 92, 92, 93, 93, 93, 94, 94, 94, 95, 95, 96, 96, 96, 97, 97, 97, 98, 98, 98, 99, 99, 99, 100, 100, 101, 101, 101, 102, 102, 102, 103, 103, 103, 104, 104, 104, 105, 105, 105, 106, 106, 106, 107, 107, 107, 108, 108, 108, 108, 109, 109, 109, 110, 110, 110, 111, 111, 111, 112, 112, 112, 112, 113, 113, 113, 114, 114, 114, 115, 115, 115, 115, 116, 116, 116, 117, 117, 117, 117, 118, 118, 118, 119, 119, 119, 119, 120, 120, 120, 121, 121, 121, 121, 122, 122, 122, 123, 123, 123, 123, 124, 124, 124, 124, 125, 125, 125, 125, 126, 126, 126, 127, 127, 127, 127, 128, 128, 128, 128, 129, 129, 129, 129, 130, 130, 130, 130, 131, 131, 131, 131, 132, 132, 132, 132, 133, 133, 133, 133, 134, 134, 134, 134, 135, 135, 135, 135, 136, 136, 136, 136, 137, 137, 137, 137, 138, 138, 138, 138, 138, 139, 139, 139, 139, 140, 140, 140, 140, 141, 141, 141, 141, 142, 142, 142, 142, 142, 143, 143, 143, 143, 144, 144, 144, 144, 144, 145, 145, 145, 145, 146, 146, 146, 146, 146, 147, 147, 147, 147, 148, 148, 148, 148, 148, 149, 149, 149, 149, 149, 150, 150, 150, 150, 151, 151, 151, 151, 151, 152, 152, 152, 152, 152, 153, 153, 153, 153, 154, 154, 154, 154, 154, 155, 155, 155, 155, 155, 156, 156, 156, 156, 156, 157, 157, 157, 157, 157, 158, 158, 158, 158, 158, 159, 159, 159, 159, 159, 160, 160, 160, 160, 160, 161, 161, 161, 161, 161, 162, 162, 162, 162, 162, 163, 163, 163, 163, 163, 164, 164, 164, 164, 164, 165, 165, 165, 165, 165, 165, 166, 166, 166, 166, 166, 167, 167, 167, 167, 167, 168, 168, 168, 168, 168, 168, 169, 169, 169, 169, 169, 170, 170, 170, 170, 170, 171, 171, 171, 171, 171, 171, 172, 172, 172, 172, 172, 173, 173, 173, 173, 173, 173, 174, 174, 174, 174, 174, 174, 175, 175, 175, 175, 175, 176, 176, 176, 176, 176, 176, 177, 177, 177, 177, 177, 177, 178, 178, 178, 178, 178, 179, 179, 179, 179, 179, 179, 180, 180, 180, 180, 180, 180, 181, 181, 181, 181, 181, 181, 182, 182, 182, 182, 182, 182, 183, 183, 183, 183, 183, 183, 184, 184, 184, 184, 184, 185, 185, 185, 185, 185, 185, 186, 186, 186, 186, 186, 186, 186, 187, 187, 187, 187, 187, 187, 188, 188, 188, 188, 188, 188, 189, 189, 189, 189, 189, 189, 190, 190, 190, 190, 190, 190, 191, 191, 191, 191, 191, 191, 192, 192, 192, 192, 192, 192, 192, 193, 193, 193, 193, 193, 193, 194, 194, 194, 194, 194, 194, 195, 195, 195, 195, 195, 195, 195, 196, 196, 196, 196, 196, 196, 197, 197, 197, 197, 197, 197, 197, 198, 198, 198, 198, 198, 198, 199, 199, 199, 199, 199, 199, 199, 200, 200, 200, 200, 200, 200, 201, 201, 201, 201, 201, 201, 201, 202, 202, 202, 202, 202, 202, 202, 203, 203, 203, 203, 203, 203, 204, 204, 204, 204, 204, 204, 204, 205, 205, 205, 205, 205, 205, 205, 206, 206, 206, 206, 206, 206, 206, 207, 207, 207, 207, 207, 207, 207, 208, 208, 208, 208, 208, 208, 209, 209, 209, 209, 209, 209, 209, 210, 210, 210, 210, 210, 210, 210, 211, 211, 211, 211, 211, 211, 211, 212, 212, 212, 212, 212, 212, 212, 213, 213, 213, 213, 213, 213, 213, 213, 214, 214, 214, 214, 214, 214, 214, 215, 215, 215, 215, 215, 215, 215, 216, 216, 216, 216, 216, 216, 216, 217, 217, 217, 217, 217, 217, 217, 218, 218, 218, 218, 218, 218, 218, 218, 219, 219, 219, 219, 219, 219, 219, 220, 220, 220, 220, 220, 220, 220, 221, 221, 221, 221, 221, 221, 221, 221, 222, 222, 222, 222, 222, 222, 222, 223, 223, 223, 223, 223, 223, 223, 223, 224, 224, 224, 224, 224, 224, 224, 225, 225, 225, 225, 225, 225, 225, 225, 226, 226, 226, 226, 226, 226, 226, 226, 227, 227, 227, 227, 227, 227, 227, 228, 228, 228, 228, 228, 228, 228, 228, 229, 229, 229, 229, 229, 229, 229, 229, 230, 230, 230, 230, 230, 230, 230, 230, 231, 231, 231, 231, 231, 231, 231, 232, 232, 232, 232, 232, 232, 232, 232, 233, 233, 233, 233, 233, 233, 233, 233, 234, 234, 234, 234, 234, 234, 234, 234, 235, 235, 235, 235, 235, 235, 235, 235, 236, 236, 236, 236, 236, 236, 236, 236, 237, 237, 237, 237, 237, 237, 237, 237, 238, 238, 238, 238, 238, 238, 238, 238, 238, 239, 239, 239, 239, 239, 239, 239, 239, 240, 240, 240, 240, 240, 240, 240, 240, 241, 241, 241, 241, 241, 241, 241, 241, 242, 242, 242, 242, 242, 242, 242, 242, 243, 243, 243, 243, 243, 243, 243, 243, 243, 244, 244, 244, 244, 244, 244, 244, 244, 245, 245, 245, 245, 245, 245, 245, 245, 245, 246, 246, 246, 246, 246, 246, 246, 246, 247, 247, 247, 247, 247, 247, 247, 247, 248, 248, 248, 248, 248, 248, 248, 248, 248, 249, 249, 249, 249, 249, 249, 249, 249, 249, 250, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253, 253, 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, }; // Expand range from 0-1 to 0-255, then convert. static uint8_t clamp_normalized_float_to_byte(float v) { // The ordering of the logic is a little strange here in order // to make sure we convert NaNs to 0. v = v * 255.0f; if (v >= 254.5f) { return 255; } else if (v >= 0.5f) { return (uint8_t) (v + 0.5f); } else { return 0; } } static void build_table_linear_to_gamma(uint8_t* outTable, int outTableSize, float exponent) { float toGammaExp = 1.0f / exponent; for (int i = 0; i < outTableSize; i++) { float x = ((float) i) * (1.0f / ((float) (outTableSize - 1))); outTable[i] = clamp_normalized_float_to_byte(powf(x, toGammaExp)); } } // Inverse table lookup. Ex: what index corresponds to the input value? This will // have strange results when the table is non-increasing. But any sane gamma // function will be increasing. static float inverse_interp_lut(float input, float* table, int tableSize) { if (input <= table[0]) { return table[0]; } else if (input >= table[tableSize - 1]) { return 1.0f; } for (int i = 1; i < tableSize; i++) { if (table[i] >= input) { // We are guaranteed that input is greater than table[i - 1]. float diff = input - table[i - 1]; float distance = table[i] - table[i - 1]; float index = (i - 1) + diff / distance; return index / (tableSize - 1); } } // Should be unreachable, since we'll return before the loop if input is // larger than the last entry. SkASSERT(false); return 0.0f; } static void build_table_linear_to_gamma(uint8_t* outTable, int outTableSize, float* inTable, int inTableSize) { for (int i = 0; i < outTableSize; i++) { float x = ((float) i) * (1.0f / ((float) (outTableSize - 1))); float y = inverse_interp_lut(x, inTable, inTableSize); outTable[i] = clamp_normalized_float_to_byte(y); } } static float inverse_parametric(float x, float g, float a, float b, float c, float d, float e, float f) { // We need to take the inverse of the following piecewise function. // Y = (aX + b)^g + c for X >= d // Y = eX + f otherwise // Assume that the gamma function is continuous, or this won't make much sense anyway. // Plug in |d| to the first equation to calculate the new piecewise interval. // Then simply use the inverse of the original functions. float interval = e * d + f; if (x < interval) { // X = (Y - F) / E if (0.0f == e) { // The gamma curve for this segment is constant, so the inverse is undefined. // Since this is the lower segment, guess zero. return 0.0f; } return (x - f) / e; } // X = ((Y - C)^(1 / G) - B) / A if (0.0f == a || 0.0f == g) { // The gamma curve for this segment is constant, so the inverse is undefined. // Since this is the upper segment, guess one. return 1.0f; } return (powf(x - c, 1.0f / g) - b) / a; } static void build_table_linear_to_gamma(uint8_t* outTable, int outTableSize, float g, float a, float b, float c, float d, float e, float f) { for (int i = 0; i < outTableSize; i++) { float x = ((float) i) * (1.0f / ((float) (outTableSize - 1))); float y = inverse_parametric(x, g, a, b, c, d, e, f); outTable[i] = clamp_normalized_float_to_byte(y); } } SkDefaultXform::SkDefaultXform(const sk_sp<SkColorSpace>& srcSpace, const SkMatrix44& srcToDst, const sk_sp<SkColorSpace>& dstSpace) : fColorLUT(sk_ref_sp((SkColorLookUpTable*) as_CSB(srcSpace)->colorLUT())) , fSrcToDst(srcToDst) { // Build tables to transform src gamma to linear. switch (srcSpace->gammaNamed()) { case SkColorSpace::kSRGB_GammaNamed: fSrcGammaTables[0] = fSrcGammaTables[1] = fSrcGammaTables[2] = sk_linear_from_srgb; break; case SkColorSpace::k2Dot2Curve_GammaNamed: fSrcGammaTables[0] = fSrcGammaTables[1] = fSrcGammaTables[2] = sk_linear_from_2dot2; break; case SkColorSpace::kLinear_GammaNamed: build_table_linear_from_gamma(fSrcGammaTableStorage, 1.0f); fSrcGammaTables[0] = fSrcGammaTables[1] = fSrcGammaTables[2] = fSrcGammaTableStorage; break; default: { const SkGammas* gammas = as_CSB(srcSpace)->gammas(); SkASSERT(gammas); for (int i = 0; i < 3; i++) { const SkGammaCurve& curve = (*gammas)[i]; if (i > 0) { // Check if this curve matches the first curve. In this case, we can // share the same table pointer. Logically, this should almost always // be true. I've never seen a profile where all three gamma curves // didn't match. But it is possible that they won't. // TODO (msarett): // This comparison won't catch the case where each gamma curve has a // pointer to its own look-up table, but the tables actually match. // Should we perform a deep compare of gamma tables here? Or should // we catch this when parsing the profile? Or should we not worry // about a bit of redundant work? if (curve.quickEquals((*gammas)[0])) { fSrcGammaTables[i] = fSrcGammaTables[0]; continue; } } if (curve.isNamed()) { switch (curve.fNamed) { case SkColorSpace::kSRGB_GammaNamed: fSrcGammaTables[i] = sk_linear_from_srgb; break; case SkColorSpace::k2Dot2Curve_GammaNamed: fSrcGammaTables[i] = sk_linear_from_2dot2; break; case SkColorSpace::kLinear_GammaNamed: build_table_linear_from_gamma(&fSrcGammaTableStorage[i * 256], 1.0f); fSrcGammaTables[i] = &fSrcGammaTableStorage[i * 256]; break; default: SkASSERT(false); break; } } else if (curve.isValue()) { build_table_linear_from_gamma(&fSrcGammaTableStorage[i * 256], curve.fValue); fSrcGammaTables[i] = &fSrcGammaTableStorage[i * 256]; } else if (curve.isTable()) { build_table_linear_from_gamma(&fSrcGammaTableStorage[i * 256], curve.fTable.get(), curve.fTableSize); fSrcGammaTables[i] = &fSrcGammaTableStorage[i * 256]; } else { SkASSERT(curve.isParametric()); build_table_linear_from_gamma(&fSrcGammaTableStorage[i * 256], curve.fG, curve.fA, curve.fB, curve.fC, curve.fD, curve.fE, curve.fF); fSrcGammaTables[i] = &fSrcGammaTableStorage[i * 256]; } } } } // Build tables to transform linear to dst gamma. switch (dstSpace->gammaNamed()) { case SkColorSpace::kSRGB_GammaNamed: fDstGammaTables[0] = fDstGammaTables[1] = fDstGammaTables[2] = linear_to_srgb; break; case SkColorSpace::k2Dot2Curve_GammaNamed: fDstGammaTables[0] = fDstGammaTables[1] = fDstGammaTables[2] = linear_to_2dot2; break; case SkColorSpace::kLinear_GammaNamed: build_table_linear_to_gamma(fDstGammaTableStorage, kDstGammaTableSize, 1.0f); fDstGammaTables[0] = fDstGammaTables[1] = fDstGammaTables[2] = fDstGammaTableStorage; break; default: { const SkGammas* gammas = as_CSB(dstSpace)->gammas(); SkASSERT(gammas); for (int i = 0; i < 3; i++) { const SkGammaCurve& curve = (*gammas)[i]; if (i > 0) { // Check if this curve matches the first curve. In this case, we can // share the same table pointer. Logically, this should almost always // be true. I've never seen a profile where all three gamma curves // didn't match. But it is possible that they won't. // TODO (msarett): // This comparison won't catch the case where each gamma curve has a // pointer to its own look-up table (but the tables actually match). // Should we perform a deep compare of gamma tables here? Or should // we catch this when parsing the profile? Or should we not worry // about a bit of redundant work? if (curve.quickEquals((*gammas)[0])) { fDstGammaTables[i] = fDstGammaTables[0]; continue; } } if (curve.isNamed()) { switch (curve.fNamed) { case SkColorSpace::kSRGB_GammaNamed: fDstGammaTables[i] = linear_to_srgb; break; case SkColorSpace::k2Dot2Curve_GammaNamed: fDstGammaTables[i] = linear_to_2dot2; break; case SkColorSpace::kLinear_GammaNamed: build_table_linear_to_gamma( &fDstGammaTableStorage[i * kDstGammaTableSize], kDstGammaTableSize, 1.0f); fDstGammaTables[i] = &fDstGammaTableStorage[i * kDstGammaTableSize]; break; default: SkASSERT(false); break; } } else if (curve.isValue()) { build_table_linear_to_gamma(&fDstGammaTableStorage[i * kDstGammaTableSize], kDstGammaTableSize, curve.fValue); fDstGammaTables[i] = &fDstGammaTableStorage[i * kDstGammaTableSize]; } else if (curve.isTable()) { build_table_linear_to_gamma(&fDstGammaTableStorage[i * kDstGammaTableSize], kDstGammaTableSize, curve.fTable.get(), curve.fTableSize); fDstGammaTables[i] = &fDstGammaTableStorage[i * kDstGammaTableSize]; } else { SkASSERT(curve.isParametric()); build_table_linear_to_gamma(&fDstGammaTableStorage[i * kDstGammaTableSize], kDstGammaTableSize, curve.fG, curve.fA, curve.fB, curve.fC, curve.fD, curve.fE, curve.fF); fDstGammaTables[i] = &fDstGammaTableStorage[i * kDstGammaTableSize]; } } } } } static float byte_to_float(uint8_t byte) { return ((float) byte) * (1.0f / 255.0f); } // Clamp to the 0-1 range. static float clamp_normalized_float(float v) { if (v > 1.0f) { return 1.0f; } else if ((v < 0.0f) || (v != v)) { return 0.0f; } else { return v; } } static void interp_3d_clut(float dst[3], float src[3], const SkColorLookUpTable* colorLUT) { // Call the src components x, y, and z. uint8_t maxX = colorLUT->fGridPoints[0] - 1; uint8_t maxY = colorLUT->fGridPoints[1] - 1; uint8_t maxZ = colorLUT->fGridPoints[2] - 1; // An approximate index into each of the three dimensions of the table. float x = src[0] * maxX; float y = src[1] * maxY; float z = src[2] * maxZ; // This gives us the low index for our interpolation. int ix = sk_float_floor2int(x); int iy = sk_float_floor2int(y); int iz = sk_float_floor2int(z); // Make sure the low index is not also the max index. ix = (maxX == ix) ? ix - 1 : ix; iy = (maxY == iy) ? iy - 1 : iy; iz = (maxZ == iz) ? iz - 1 : iz; // Weighting factors for the interpolation. float diffX = x - ix; float diffY = y - iy; float diffZ = z - iz; // Constants to help us navigate the 3D table. // Ex: Assume x = a, y = b, z = c. // table[a * n001 + b * n010 + c * n100] logically equals table[a][b][c]. const int n000 = 0; const int n001 = 3 * colorLUT->fGridPoints[1] * colorLUT->fGridPoints[2]; const int n010 = 3 * colorLUT->fGridPoints[2]; const int n011 = n001 + n010; const int n100 = 3; const int n101 = n100 + n001; const int n110 = n100 + n010; const int n111 = n110 + n001; // Base ptr into the table. float* ptr = &colorLUT->fTable[ix*n001 + iy*n010 + iz*n100]; // The code below performs a tetrahedral interpolation for each of the three // dst components. Once the tetrahedron containing the interpolation point is // identified, the interpolation is a weighted sum of grid values at the // vertices of the tetrahedron. The claim is that tetrahedral interpolation // provides a more accurate color conversion. // blogs.mathworks.com/steve/2006/11/24/tetrahedral-interpolation-for-colorspace-conversion/ // // I have one test image, and visually I can't tell the difference between // tetrahedral and trilinear interpolation. In terms of computation, the // tetrahedral code requires more branches but less computation. The // SampleICC library provides an option for the client to choose either // tetrahedral or trilinear. for (int i = 0; i < 3; i++) { if (diffZ < diffY) { if (diffZ < diffX) { dst[i] = (ptr[n000] + diffZ * (ptr[n110] - ptr[n010]) + diffY * (ptr[n010] - ptr[n000]) + diffX * (ptr[n111] - ptr[n110])); } else if (diffY < diffX) { dst[i] = (ptr[n000] + diffZ * (ptr[n111] - ptr[n011]) + diffY * (ptr[n011] - ptr[n001]) + diffX * (ptr[n001] - ptr[n000])); } else { dst[i] = (ptr[n000] + diffZ * (ptr[n111] - ptr[n011]) + diffY * (ptr[n010] - ptr[n000]) + diffX * (ptr[n011] - ptr[n010])); } } else { if (diffZ < diffX) { dst[i] = (ptr[n000] + diffZ * (ptr[n101] - ptr[n001]) + diffY * (ptr[n111] - ptr[n101]) + diffX * (ptr[n001] - ptr[n000])); } else if (diffY < diffX) { dst[i] = (ptr[n000] + diffZ * (ptr[n100] - ptr[n000]) + diffY * (ptr[n111] - ptr[n101]) + diffX * (ptr[n101] - ptr[n100])); } else { dst[i] = (ptr[n000] + diffZ * (ptr[n100] - ptr[n000]) + diffY * (ptr[n110] - ptr[n100]) + diffX * (ptr[n111] - ptr[n110])); } } // Increment the table ptr in order to handle the next component. // Note that this is the how table is designed: all of nXXX // variables are multiples of 3 because there are 3 output // components. ptr++; } } void SkDefaultXform::xform_RGB1_8888(uint32_t* dst, const uint32_t* src, uint32_t len) const { while (len-- > 0) { uint8_t r = (*src >> 0) & 0xFF, g = (*src >> 8) & 0xFF, b = (*src >> 16) & 0xFF; if (fColorLUT) { float in[3]; float out[3]; in[0] = byte_to_float(r); in[1] = byte_to_float(g); in[2] = byte_to_float(b); interp_3d_clut(out, in, fColorLUT.get()); r = sk_float_round2int(255.0f * clamp_normalized_float(out[0])); g = sk_float_round2int(255.0f * clamp_normalized_float(out[1])); b = sk_float_round2int(255.0f * clamp_normalized_float(out[2])); } // Convert to linear. float srcFloats[3]; srcFloats[0] = fSrcGammaTables[0][r]; srcFloats[1] = fSrcGammaTables[1][g]; srcFloats[2] = fSrcGammaTables[2][b]; // Convert to dst gamut. float dstFloats[3]; dstFloats[0] = srcFloats[0] * fSrcToDst.getFloat(0, 0) + srcFloats[1] * fSrcToDst.getFloat(1, 0) + srcFloats[2] * fSrcToDst.getFloat(2, 0) + fSrcToDst.getFloat(3, 0); dstFloats[1] = srcFloats[0] * fSrcToDst.getFloat(0, 1) + srcFloats[1] * fSrcToDst.getFloat(1, 1) + srcFloats[2] * fSrcToDst.getFloat(2, 1) + fSrcToDst.getFloat(3, 1); dstFloats[2] = srcFloats[0] * fSrcToDst.getFloat(0, 2) + srcFloats[1] * fSrcToDst.getFloat(1, 2) + srcFloats[2] * fSrcToDst.getFloat(2, 2) + fSrcToDst.getFloat(3, 2); // Clamp to 0-1. dstFloats[0] = clamp_normalized_float(dstFloats[0]); dstFloats[1] = clamp_normalized_float(dstFloats[1]); dstFloats[2] = clamp_normalized_float(dstFloats[2]); // Convert to dst gamma. r = fDstGammaTables[0][sk_float_round2int((kDstGammaTableSize - 1) * dstFloats[0])]; g = fDstGammaTables[1][sk_float_round2int((kDstGammaTableSize - 1) * dstFloats[1])]; b = fDstGammaTables[2][sk_float_round2int((kDstGammaTableSize - 1) * dstFloats[2])]; *dst = SkPackARGB32NoCheck(0xFF, r, g, b); dst++; src++; } }
58.312646
99
0.60935
juanpca12
cb95e773334cdb7a1987d606b331094a86caa808
9,838
cc
C++
onnxruntime/test/providers/cpu/tensor/scatter_op_test.cc
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
5
2021-02-20T04:53:48.000Z
2021-03-09T19:29:27.000Z
onnxruntime/test/providers/cpu/tensor/scatter_op_test.cc
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
5
2021-03-01T21:35:50.000Z
2022-03-09T05:38:38.000Z
onnxruntime/test/providers/cpu/tensor/scatter_op_test.cc
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
2
2021-02-20T12:10:05.000Z
2021-03-09T19:15:20.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "gtest/gtest.h" #include "test/providers/provider_test_utils.h" namespace onnxruntime { namespace test { static void scatter_without_axis_tests(const char* op_name, int op_version) { OpTester test(op_name, op_version); std::vector<float> input; input.resize(3 * 3); std::fill(input.begin(), input.end(), .0f); test.AddInput<float>("data", {3, 3}, input); test.AddInput<int64_t>("indices", {2, 3}, {1, 0, 2, 0, 2, 1}); test.AddInput<float>("updates", {2, 3}, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}); test.AddOutput<float>("y", {3, 3}, {2.0f, 1.1f, 0.0f, 1.0f, 0.0f, 2.2f, 0.0f, 2.1f, 1.2f}); test.Run(); } TEST(Scatter, WithoutAxis) { scatter_without_axis_tests("Scatter", 9); scatter_without_axis_tests("ScatterElements", 11); } static void scatter_with_axis_tests(const char* op_name, int op_version) { OpTester test(op_name, op_version); test.AddAttribute<int64_t>("axis", 1); test.AddInput<float>("data", {1, 5}, {1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); test.AddInput<int64_t>("indices", {1, 2}, {1, 3}); test.AddInput<float>("updates", {1, 2}, {1.1f, 2.1f}); test.AddOutput<float>("y", {1, 5}, {1.0f, 1.1f, 3.0f, 2.1f, 5.0f}); test.Run(); } TEST(Scatter, WithAxis) { scatter_with_axis_tests("Scatter", 9); scatter_with_axis_tests("ScatterElements", 11); } static void scatter_three_dim_with_axis_0(const char* op_name, int op_version) { OpTester test(op_name, op_version); test.AddAttribute<int64_t>("axis", 0); test.AddInput<int64_t>("data", {1, 3, 3}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); // Because axis 0 is only 1 dimension it should be all zeros test.AddInput<int64_t>("indices", {1, 3, 3}, {0, 0, 0, 0, 0, 0, 0, 0, 0}); test.AddInput<int64_t>("updates", {1, 3, 3}, {11, 12, 13, 14, 15, 16, 17, 18, 19}); test.AddOutput<int64_t>("y", {1, 3, 3}, {11, 12, 13, 14, 15, 16, 17, 18, 19}); test.Run(); } TEST(Scatter, ThreeDimsWithAxis_0) { scatter_three_dim_with_axis_0("Scatter", 9); scatter_three_dim_with_axis_0("ScatterElements", 11); } static void scatter_three_dim_with_axis_negative_2(const char* op_name, int op_version) { OpTester test(op_name, op_version); test.AddAttribute<int64_t>("axis", -2); test.AddInput<int64_t>("data", {2, 2, 2}, {1, 2, 3, 4, 5, 6, 7, 8}); test.AddInput<int64_t>("indices", {2, 1, 2}, {0, 1, 1, 0}); test.AddInput<int64_t>("updates", {2, 1, 2}, {11, 12, 13, 14}); test.AddOutput<int64_t>("y", {2, 2, 2}, {11, 2, 3, 12, 5, 14, 13, 8}); test.Run(); } TEST(Scatter, ThreeDimsWithAxisNegative_2) { scatter_three_dim_with_axis_negative_2("Scatter", 9); scatter_three_dim_with_axis_negative_2("ScatterElements", 11); } static void scatter_three_dim_with_axis_2(const char* op_name, int op_version) { OpTester test(op_name, op_version); test.AddAttribute<int64_t>("axis", 2); test.AddInput<int64_t>("data", {1, 3, 3}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); test.AddInput<int64_t>("indices", {1, 3, 3}, {2, 1, 0, 2, 1, 0, 2, 1, 0}); test.AddInput<int64_t>("updates", {1, 3, 3}, {11, 12, 13, 14, 15, 16, 17, 18, 19}); test.AddOutput<int64_t>("y", {1, 3, 3}, {13, 12, 11, 16, 15, 14, 19, 18, 17}); test.Run(); } TEST(Scatter, ThreeDimsWithAxis_2) { scatter_three_dim_with_axis_2("Scatter", 9); scatter_three_dim_with_axis_2("ScatterElements", 11); } static void scatter_string(const char* op_name, int op_version) { OpTester test(op_name, op_version); test.AddAttribute<int64_t>("axis", 1); test.AddInput<std::string>("data", {1, 5}, {"1.0f", "2.0f", "3.0f", "4.0f", "5.0f"}); test.AddInput<int64_t>("indices", {1, 2}, {1, 3}); test.AddInput<std::string>("updates", {1, 2}, {"1.1f", "2.1f"}); test.AddOutput<std::string>("y", {1, 5}, {"1.0f", "1.1f", "3.0f", "2.1f", "5.0f"}); test.Run(); } TEST(Scatter, String) { scatter_string("Scatter", 9); scatter_string("ScatterElements", 11); } static void scatter_negative_axis(const char* op_name, int op_version) { OpTester test(op_name, op_version); test.AddAttribute<int64_t>("axis", -1); test.AddInput<float>("data", {1, 5}, {1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); test.AddInput<int64_t>("indices", {1, 2}, {1, 3}); test.AddInput<float>("updates", {1, 2}, {1.1f, 2.1f}); test.AddOutput<float>("y", {1, 5}, {1.0f, 1.1f, 3.0f, 2.1f, 5.0f}); #if defined(OPENVINO_CONFIG_MYRIAD) || defined(OPENVINO_CONFIG_VAD_M) //TBD temporarily disabling for openvino test.Run(OpTester::ExpectResult::kExpectSuccess, "", {kOpenVINOExecutionProvider}); #else test.Run(); #endif } TEST(Scatter, NegativeAxis) { scatter_negative_axis("Scatter", 9); scatter_negative_axis("ScatterElements", 11); } static void scatter_indices_updates_dont_match(const char* op_name, int op_version) { OpTester test(op_name, op_version); test.AddAttribute<int64_t>("axis", 1); test.AddInput<float>("data", {1, 5}, {1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); test.AddInput<int64_t>("indices", {1, 3}, {1, 3, 3}); test.AddInput<float>("updates", {1, 2}, {1.1f, 2.1f}); test.AddOutput<float>("y", {1, 5}, {1.0f, 1.1f, 3.0f, 2.1f, 5.0f}); test.Run(OpTester::ExpectResult::kExpectFailure, "Indices vs updates dimensions differs at position=1 3 vs 2"); } TEST(Scatter, IndicesUpdatesDontMatch) { scatter_indices_updates_dont_match("Scatter", 9); scatter_indices_updates_dont_match("ScatterElements", 11); } static void scatter_valid_index(const char* op_name, int op_version) { OpTester test(op_name, op_version); test.AddAttribute<int64_t>("axis", 0); test.AddInput<float>("data", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}); test.AddInput<int64_t>("indices", {1, 1, 1}, {3}); test.AddInput<float>("updates", {1, 1, 1}, {5.0f}); test.AddOutput<float>("y", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 0.0f}); test.Run(); } TEST(Scatter, ValidAxis) { scatter_valid_index("Scatter", 9); scatter_valid_index("ScatterElements", 11); } static void scatter_invalid_index(const char* op_name, int op_version) { OpTester test(op_name, op_version); test.AddAttribute<int64_t>("axis", 0); test.AddInput<float>("data", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}); test.AddInput<int64_t>("indices", {1, 1, 1}, {4}); test.AddInput<float>("updates", {1, 1, 1}, {5.0f}); test.AddOutput<float>("y", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 0.0f}); test.Run(OpTester::ExpectResult::kExpectFailure, "indices element out of data bounds, idx=4 must be within the inclusive range [-4,3]", {kCudaExecutionProvider}); } TEST(Scatter, InvalidIndex) { scatter_invalid_index("Scatter", 9); scatter_invalid_index("ScatterElements", 11); } static void scatter_valid_negative_index(const char* op_name, int op_version) { OpTester test(op_name, op_version); test.AddAttribute<int64_t>("axis", 0); test.AddInput<float>("data", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}); test.AddInput<int64_t>("indices", {1, 1, 1}, {-1}); test.AddInput<float>("updates", {1, 1, 1}, {5.0f}); test.AddOutput<float>("y", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 0.0f}); #if defined(OPENVINO_CONFIG_MYRIAD) || defined(OPENVINO_CONFIG_VAD_M) //TBD temporarily disabling for openvino test.Run(OpTester::ExpectResult::kExpectSuccess, "", {kOpenVINOExecutionProvider}); #else test.Run(); #endif } TEST(Scatter, ValidNegativeIndex) { scatter_valid_negative_index("Scatter", 9); scatter_valid_negative_index("ScatterElements", 11); } static void scatter_bool_with_axis_tests(const char* op_name, int op_version) { OpTester test(op_name, op_version); test.AddAttribute<int64_t>("axis", 1); test.AddInput<bool>("data", {1, 5}, {false, false, false, true, false}); test.AddInput<int64_t>("indices", {1, 2}, {1, 3}); test.AddInput<bool>("updates", {1, 2}, {true, false}); test.AddOutput<bool>("y", {1, 5}, {false, true, false, false, false}); test.Run(); } TEST(Scatter, BoolInputWithAxis) { scatter_bool_with_axis_tests("Scatter", 9); scatter_bool_with_axis_tests("ScatterElements", 11); } static void scatter_same_updates_tests(const char* op_name, int op_version) { OpTester test(op_name, op_version); std::vector<float> input; input.resize(3 * 3); std::fill(input.begin(), input.end(), .0f); test.AddInput<float>("data", {3, 3}, input); test.AddInput<int64_t>("indices", {1, 2}, {1, 1}, /*is_initializer*/ true); test.AddInput<float>("updates", {1, 2}, {2.0f, 2.0f}); test.AddOutput<float>("y", {3, 3}, {0.0f, 0.0f, 0.0f, 2.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f}); test.Run(); } TEST(Scatter, SameUpdateWithoutAxis) { scatter_same_updates_tests("Scatter", 9); scatter_same_updates_tests("ScatterElements", 11); } } // namespace test } // namespace onnxruntime
34.763251
113
0.590466
dennyac
cb9863f34d686fb48bfc2af58d5286f3624a4547
1,098
cpp
C++
tools/auto-tester/src/Downloader.cpp
kevinhouyang/hifi
cfb0d0aeb6d8961ec802909d4439d58383252e59
[ "Apache-2.0" ]
null
null
null
tools/auto-tester/src/Downloader.cpp
kevinhouyang/hifi
cfb0d0aeb6d8961ec802909d4439d58383252e59
[ "Apache-2.0" ]
null
null
null
tools/auto-tester/src/Downloader.cpp
kevinhouyang/hifi
cfb0d0aeb6d8961ec802909d4439d58383252e59
[ "Apache-2.0" ]
null
null
null
// // Downloader.cpp // // Created by Nissim Hadar on 1 Mar 2018. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Downloader.h" #include <QtWidgets/QMessageBox> Downloader::Downloader(QUrl fileURL, QObject *parent) : QObject(parent) { connect( &_networkAccessManager, SIGNAL (finished(QNetworkReply*)), this, SLOT (fileDownloaded(QNetworkReply*)) ); QNetworkRequest request(fileURL); _networkAccessManager.get(request); } void Downloader::fileDownloaded(QNetworkReply* reply) { QNetworkReply::NetworkError error = reply->error(); if (error != QNetworkReply::NetworkError::NoError) { QMessageBox::information(0, "Test Aborted", "Failed to download file: " + reply->errorString()); return; } _downloadedData = reply->readAll(); //emit a signal reply->deleteLater(); emit downloaded(); } QByteArray Downloader::downloadedData() const { return _downloadedData; }
27.45
104
0.693078
kevinhouyang
cb98c32601e70e620f0b17364d4492831bda8af3
871
cpp
C++
Chapter10/10_3.cpp
GeertArien/c-accelerated
c0ae9f66b1733de04f3133db2e9d8af6d555fe6e
[ "MIT" ]
27
2019-03-12T02:24:43.000Z
2022-02-18T22:49:00.000Z
Chapter10/10_3.cpp
GeertArien/C-Accelerated
c0ae9f66b1733de04f3133db2e9d8af6d555fe6e
[ "MIT" ]
1
2020-06-24T18:34:45.000Z
2020-06-28T12:55:05.000Z
Chapter10/10_3.cpp
GeertArien/c-accelerated
c0ae9f66b1733de04f3133db2e9d8af6d555fe6e
[ "MIT" ]
12
2019-04-22T03:49:19.000Z
2021-08-31T17:39:35.000Z
/** Accelerated C++, Exercise 10-3, 10_3.cpp Write a test program to verify that the median function operates correctly. Ensure that calling median does not change the order of the elements in the container. */ #include "stdafx.h" #include "10_3.h" #include "10_2.h" #include <vector> using std::vector; #include <iostream> using std::cout; using std::endl; using std::ostream; template<class T> ostream& print_vector(const vector<T> v, ostream& os) { if (v.size() > 0) { os << v[0]; for (vector<T>::size_type i = 1; i < v.size(); i++) os << ", " << v[i]; os << endl; } return os; } int ex10_3() { vector<double> v_double = { 12.5, 5.25, 25.7, 16.3, 1.26 }; print_vector(v_double, cout); cout << median<double, vector<double>::iterator>(v_double.begin(), v_double.end()) << endl; print_vector(v_double, cout); return 0; }
18.145833
93
0.641791
GeertArien
cb98fc5934e877a91e897b0f52334baee41a760b
781
cpp
C++
src/queue.cpp
zivkovicmilos/OS1Kernel
8a77c6a9b62d27719c5f7f61492f8dce6866c38a
[ "MIT" ]
null
null
null
src/queue.cpp
zivkovicmilos/OS1Kernel
8a77c6a9b62d27719c5f7f61492f8dce6866c38a
[ "MIT" ]
null
null
null
src/queue.cpp
zivkovicmilos/OS1Kernel
8a77c6a9b62d27719c5f7f61492f8dce6866c38a
[ "MIT" ]
null
null
null
#include "queue.h" Queue::Queue() { first = 0; last = 0; size = 0; } void Queue::addElem(PCB* pcb) { if (first == 0) { first = new Elem(pcb); last = first; } else { Elem* temp = new Elem(pcb); last->next = temp; last = temp; } size++; } PCB* Queue::getElem() { if (first == 0) return 0; PCB* ret = 0; if (first->next != 0) { ret = first->data; Elem* temp = first; first = first->next; delete temp; } else { ret = first->data; delete first; first = last = 0; } size--; return ret; } int Queue::getSize() { return size; } Queue::~Queue() { Elem* temp = first; Elem* prev = 0; while (temp != 0) { prev = temp; temp = temp->next; delete prev; } first = last = 0; size = 0; }
14.462963
32
0.510883
zivkovicmilos
cb9910fa098641be0c52b70076718f3aad44d7ac
389
cpp
C++
uva/10298.cpp
larc/competitive_programming
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
1
2019-05-23T19:05:39.000Z
2019-05-23T19:05:39.000Z
uva/10298.cpp
larc/oremor
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
null
null
null
uva/10298.cpp
larc/oremor
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
null
null
null
// 10298 - Power Strings #include <cstdio> #define N 1000001 int main() { int i, j; int b[N]; char str[N]; while(scanf("%s", str), str[0] != '.') { // KMP algorithm i = 0; j = -1; b[0] = -1; while(str[i]) { while(j >= 0 && str[i] != str[j]) j = b[j]; i++; j++; b[i] = j; } if(i % (i - j)) printf("1\n"); else printf("%d\n", i / (i - j)); } return 0; }
12.548387
46
0.44473
larc
ed80a4dddec6ede720ff4cb69f5cb4a2a23bec1e
5,630
hpp
C++
include/System/__Filters.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/System/__Filters.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/System/__Filters.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Reflection namespace System::Reflection { // Forward declaring type: MemberInfo class MemberInfo; } // Completed forward declares // Type namespace: System namespace System { // Forward declaring type: __Filters class __Filters; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::__Filters); DEFINE_IL2CPP_ARG_TYPE(::System::__Filters*, "System", "__Filters"); // Type namespace: System namespace System { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: System.__Filters // [TokenAttribute] Offset: FFFFFFFF class __Filters : public ::Il2CppObject { public: // Get static field: static readonly System.__Filters Instance static ::System::__Filters* _get_Instance(); // Set static field: static readonly System.__Filters Instance static void _set_Instance(::System::__Filters* value); // static private System.Void .cctor() // Offset: 0x298CE34 static void _cctor(); // System.Boolean FilterAttribute(System.Reflection.MemberInfo m, System.Object filterCriteria) // Offset: 0x298C794 bool FilterAttribute(::System::Reflection::MemberInfo* m, ::Il2CppObject* filterCriteria); // System.Boolean FilterName(System.Reflection.MemberInfo m, System.Object filterCriteria) // Offset: 0x298CAEC bool FilterName(::System::Reflection::MemberInfo* m, ::Il2CppObject* filterCriteria); // System.Boolean FilterIgnoreCase(System.Reflection.MemberInfo m, System.Object filterCriteria) // Offset: 0x298CC84 bool FilterIgnoreCase(::System::Reflection::MemberInfo* m, ::Il2CppObject* filterCriteria); // public System.Void .ctor() // Offset: 0x298CE2C // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static __Filters* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::__Filters::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<__Filters*, creationType>())); } }; // System.__Filters #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::__Filters::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::__Filters::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::__Filters*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::__Filters::FilterAttribute // Il2CppName: FilterAttribute template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::__Filters::*)(::System::Reflection::MemberInfo*, ::Il2CppObject*)>(&System::__Filters::FilterAttribute)> { static const MethodInfo* get() { static auto* m = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg; static auto* filterCriteria = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::__Filters*), "FilterAttribute", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{m, filterCriteria}); } }; // Writing MetadataGetter for method: System::__Filters::FilterName // Il2CppName: FilterName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::__Filters::*)(::System::Reflection::MemberInfo*, ::Il2CppObject*)>(&System::__Filters::FilterName)> { static const MethodInfo* get() { static auto* m = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg; static auto* filterCriteria = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::__Filters*), "FilterName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{m, filterCriteria}); } }; // Writing MetadataGetter for method: System::__Filters::FilterIgnoreCase // Il2CppName: FilterIgnoreCase template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::__Filters::*)(::System::Reflection::MemberInfo*, ::Il2CppObject*)>(&System::__Filters::FilterIgnoreCase)> { static const MethodInfo* get() { static auto* m = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg; static auto* filterCriteria = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::__Filters*), "FilterIgnoreCase", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{m, filterCriteria}); } }; // Writing MetadataGetter for method: System::__Filters::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
52.616822
191
0.717584
RedBrumbler
ed81bf4e8ffc5eccc76a5f72851fb85c3827fed8
423
cpp
C++
Code Forces/71-A/71A Way-Too-Long-Words.cpp
canxkoz/Competitive-Programming
c5aba7ff3537e0ecb5cf0972e5b605498995e82a
[ "MIT" ]
10
2019-06-20T09:36:19.000Z
2021-07-19T12:45:42.000Z
Code Forces/71-A/71A Way-Too-Long-Words.cpp
canxkoz/Competitive-Programming
c5aba7ff3537e0ecb5cf0972e5b605498995e82a
[ "MIT" ]
null
null
null
Code Forces/71-A/71A Way-Too-Long-Words.cpp
canxkoz/Competitive-Programming
c5aba7ff3537e0ecb5cf0972e5b605498995e82a
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; for(int i=0;i<n;i++) { string s; cin >> s; if(s.length()>10) { stringstream ss; int l; l=s.length()-2; ss << s[0] << l << s[s.length()-1]; cout << ss.str() << endl; } else cout << s << endl; } return 0; }
16.92
45
0.36643
canxkoz
ed81d0c8516309b107e0070d82087c6017d6cee0
371
cpp
C++
MDE/Object.cpp
dmitriyha/Magic-Dungeon-Epidemic
37d19f416d36f1abb2393af1e43f76b24f57001a
[ "Unlicense" ]
null
null
null
MDE/Object.cpp
dmitriyha/Magic-Dungeon-Epidemic
37d19f416d36f1abb2393af1e43f76b24f57001a
[ "Unlicense" ]
null
null
null
MDE/Object.cpp
dmitriyha/Magic-Dungeon-Epidemic
37d19f416d36f1abb2393af1e43f76b24f57001a
[ "Unlicense" ]
null
null
null
#include "Object.h" Object::Object() { } void Object::render(){ SDL_RenderCopy(texture->getRenderer(), texture->getTexture(), &sprite, &location); } /** \brief Sets the texture to the character * * \param Texture* _texture: The texture which you want to set to character * */ void Object::setTexture(Texture* _texture){ texture = _texture; } Object::~Object() { }
15.458333
83
0.695418
dmitriyha
ed82443b297dd63ffca152b82387e03252605e84
1,597
cpp
C++
src/Core/Service/ServerHandler.cpp
Loki-Astari/ThorsNisse
75fd6891959d6e9deb7c07cb26660e65ba7f51bd
[ "MIT" ]
6
2017-08-07T07:01:48.000Z
2022-02-27T20:58:44.000Z
src/Core/Service/ServerHandler.cpp
Loki-Astari/ThorsNisse
75fd6891959d6e9deb7c07cb26660e65ba7f51bd
[ "MIT" ]
18
2017-08-10T20:34:50.000Z
2017-09-05T19:48:52.000Z
src/Core/Service/ServerHandler.cpp
Loki-Astari/ThorsNisse
75fd6891959d6e9deb7c07cb26660e65ba7f51bd
[ "MIT" ]
1
2019-02-20T19:06:13.000Z
2019-02-20T19:06:13.000Z
#include "Handler.h" #include "ServerHandler.h" using namespace ThorsAnvil::Nisse::Core::Service; TimerHandler::TimerHandler(Server& parent, double timeOut, std::function<void()>&& action) : HandlerNonSuspendable(parent, -1, EV_PERSIST, timeOut) , action(std::move(action)) {} short TimerHandler::eventActivate(LibSocketId /*sockId*/, short /*eventType*/) { action(); return 0; } #ifdef COVERAGE_TEST /* * This code is only compiled into the unit tests for code coverage purposes * It is not part of the live code. */ #include "ServerHandler.tpp" #include "test/Action.h" #include "ThorsNisseCoreSocket/Socket.h" template ThorsAnvil::Nisse::Core::Service::ServerHandler<Action, void>::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&); template ThorsAnvil::Nisse::Core::Service::ServerHandler<ActionUnReg, void>::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&); template ThorsAnvil::Nisse::Core::Service::ServerHandler<TestHandler, std::tuple<bool, bool, bool> >::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&, std::tuple<bool, bool, bool>&); template ThorsAnvil::Nisse::Core::Service::ServerHandler<InHandlerTest, std::tuple<bool, std::function<void (ThorsAnvil::Nisse::Core::Service::Server&)> > >::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&, std::tuple<bool, std::function<void (ThorsAnvil::Nisse::Core::Service::Server&)> >&); #endif
51.516129
349
0.745147
Loki-Astari
ed832226bf229488cd6137fb15495fac5b35ec54
5,182
cpp
C++
src/master/RejudgeJob/RejudgeJobBase.cpp
WentsingNee/tsoj_core_cpp
8a83d6cc81c247a1299da207ac54b62419b75bab
[ "MIT" ]
1
2019-03-08T06:15:52.000Z
2019-03-08T06:15:52.000Z
src/master/RejudgeJob/RejudgeJobBase.cpp
WentsingNee/tsoj_core_cpp
8a83d6cc81c247a1299da207ac54b62419b75bab
[ "MIT" ]
null
null
null
src/master/RejudgeJob/RejudgeJobBase.cpp
WentsingNee/tsoj_core_cpp
8a83d6cc81c247a1299da207ac54b62419b75bab
[ "MIT" ]
null
null
null
/* * RejudgeJobBase.cpp * * Created on: 2018年11月20日 * Author: peter */ #include "RejudgeJobBase.hpp" #include "logger.hpp" #ifndef MYSQLPP_MYSQL_HEADERS_BURIED # define MYSQLPP_MYSQL_HEADERS_BURIED #endif #include <mysql++/transaction.h> #include <mysql_conn_factory.hpp> extern std::ofstream log_fp; RejudgeJobBase::RejudgeJobBase(int jobType, ojv4::s_id_type s_id, kerbal::redis_v2::connection & redis_conn) : UpdateJobBase(jobType, s_id, redis_conn), rejudge_time(mysqlpp::DateTime::now()) { LOG_DEBUG(jobType, s_id, log_fp, BOOST_CURRENT_FUNCTION); } void RejudgeJobBase::handle() { LOG_DEBUG(jobType, s_id, log_fp, BOOST_CURRENT_FUNCTION); std::exception_ptr move_solution_exception = nullptr; std::exception_ptr update_solution_exception = nullptr; std::exception_ptr update_compile_error_info_exception = nullptr; std::exception_ptr update_user_exception = nullptr; std::exception_ptr update_problem_exception = nullptr; std::exception_ptr update_user_problem_exception = nullptr; std::exception_ptr update_user_problem_status_exception = nullptr; std::exception_ptr commit_exception = nullptr; // 本次更新任务的 mysql 连接 auto mysql_conn_handle = sync_fetch_mysql_conn(); mysqlpp::Connection & mysql_conn = *mysql_conn_handle; mysqlpp::Transaction trans(mysql_conn); try { this->move_orig_solution_to_rejudge_solution(mysql_conn); } catch (const std::exception & e) { move_solution_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Move original solution failed!", e); //DO NOT THROW } if (move_solution_exception == nullptr) { try { this->update_solution(mysql_conn); } catch (const std::exception & e) { move_solution_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Update solution failed!", e); //DO NOT THROW } if (update_solution_exception == nullptr) { try { this->update_compile_info(mysql_conn); } catch (const std::exception & e) { update_compile_error_info_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Update compile error info failed!", e); //DO NOT THROW } try { this->update_user(mysql_conn); } catch (const std::exception & e) { update_user_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Update user failed!", e); //DO NOT THROW } try { this->update_problem(mysql_conn); } catch (const std::exception & e) { update_problem_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Update problem failed!", e); //DO NOT THROW } try { this->update_user_problem(mysql_conn); } catch (const std::exception & e) { update_user_problem_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Update user problem failed!", e); //DO NOT THROW } // try { // this->update_user_problem_status(mysql_conn); // } catch (const std::exception & e) { // update_user_problem_status_exception = std::current_exception(); // EXCEPT_FATAL(jobType, s_id, log_fp, "Update user problem status failed!", e); // //DO NOT THROW // } try { this->send_rejudge_notification(mysql_conn); } catch (const std::exception & e){ EXCEPT_WARNING(jobType, s_id, log_fp, "Send rejudge notification failed!", e); //DO NOT THROW } } try { trans.commit(); } catch (const std::exception & e) { EXCEPT_FATAL(jobType, s_id, log_fp, "MySQL commit failed!", e); commit_exception = std::current_exception(); //DO NOT THROW } catch (...) { UNKNOWN_EXCEPT_FATAL(jobType, s_id, log_fp, "MySQL commit failed!"); commit_exception = std::current_exception(); //DO NOT THROW } } this->clear_redis_info(); } void RejudgeJobBase::clear_redis_info() noexcept try { this->UpdateJobBase::clear_this_jobs_info_in_redis(); auto redis_conn_handler = sync_fetch_redis_conn(); kerbal::redis_v2::operation opt(*redis_conn_handler); try { boost::format judge_status_templ("judge_status:%d:%d"); if (opt.del((judge_status_templ % jobType % s_id).str()) == false) { LOG_WARNING(jobType, s_id, log_fp, "Doesn't delete judge_status actually!"); } } catch (const std::exception & e) { LOG_WARNING(jobType, s_id, log_fp, "Exception occurred while deleting judge_status!"); //DO NOT THROW } try { boost::format similarity_details("similarity_details:%d:%d"); if (opt.del((similarity_details % jobType % s_id).str()) == false) { // LOG_WARNING(jobType, s_id, log_fp, "Doesn't delete similarity_details actually!"); } } catch (const std::exception & e) { LOG_WARNING(jobType, s_id, log_fp, "Exception occurred while deleting similarity_details!"); //DO NOT THROW } try { boost::format job_info("job_info:%d:%d"); if (opt.del((job_info % jobType % s_id).str()) == false) { // LOG_WARNING(jobType, s_id, log_fp, "Doesn't delete job_info actually!"); } } catch (const std::exception & e) { LOG_WARNING(jobType, s_id, log_fp, "Exception occurred while deleting job_info!"); //DO NOT THROW } } catch (...) { UNKNOWN_EXCEPT_FATAL(jobType, s_id, log_fp, "Clear this jobs info in redis failed!"); }
30.662722
110
0.710922
WentsingNee
ed8570b4c3ce9ed25904a28725f3e759ad4832b4
4,734
cpp
C++
hphp/runtime/vm/jit/stack-overflow.cpp
jmurret/hhvm
f005fa3ca2793291cf59e217db3e9ce074d22f71
[ "PHP-3.01", "Zend-2.0" ]
1
2020-01-17T02:24:38.000Z
2020-01-17T02:24:38.000Z
hphp/runtime/vm/jit/stack-overflow.cpp
jmurret/hhvm
f005fa3ca2793291cf59e217db3e9ce074d22f71
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/vm/jit/stack-overflow.cpp
jmurret/hhvm
f005fa3ca2793291cf59e217db3e9ce074d22f71
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/jit/stack-overflow.h" #include "hphp/runtime/base/exceptions.h" #include "hphp/runtime/base/typed-value.h" #include "hphp/runtime/vm/bytecode.h" #include "hphp/runtime/vm/func.h" #include "hphp/runtime/vm/hhbc.h" #include "hphp/runtime/vm/hhbc-codec.h" #include "hphp/runtime/vm/unit.h" #include "hphp/runtime/vm/unwind.h" #include "hphp/runtime/vm/vm-regs.h" #include "hphp/runtime/vm/jit/translator-inline.h" #include "hphp/util/assertions.h" namespace HPHP { namespace jit { /////////////////////////////////////////////////////////////////////////////// bool checkCalleeStackOverflow(const TypedValue* calleeFP, const Func* callee) { auto const limit = callee->maxStackCells() + kStackCheckPadding; const void* const needed_top = calleeFP - limit; const void* const lower_limit = static_cast<char*>(vmRegsUnsafe().stack.getStackLowAddress()) + Stack::sSurprisePageSize; return needed_top < lower_limit; } void handleStackOverflow(ActRec* calleeAR) { // We didn't finish setting up the prologue, so let the unwinder know that // locals are already freed so it doesn't try to decref the garbage. Do not // bother decrefing numArgs, as we are going to fail the request anyway. calleeAR->setLocalsDecRefd(); // sync_regstate in unwind-itanium.cpp doesn't have enough context to properly // sync registers, so do it here. Sync them to correspond to the state on // function entry. This is not really true, but it's good enough for unwinder. auto& unsafeRegs = vmRegsUnsafe(); unsafeRegs.fp = calleeAR; unsafeRegs.pc = calleeAR->func()->getEntry(); unsafeRegs.stack.top() = reinterpret_cast<TypedValue*>(calleeAR) - calleeAR->func()->numSlotsInFrame(); unsafeRegs.jitReturnAddr = nullptr; tl_regState = VMRegState::CLEAN; throw_stack_overflow(); } void handlePossibleStackOverflow(ActRec* calleeAR) { assert_native_stack_aligned(); // If it's not an overflow, it was probably a surprise flag trip. But we // can't assert that it is because background threads are allowed to clear // surprise bits concurrently, so it could be cleared again by now. auto const calleeFP = reinterpret_cast<const TypedValue*>(calleeAR); if (!checkCalleeStackOverflow(calleeFP, calleeAR->func())) return; /* * Stack overflows in this situation are a slightly different case than * handleStackOverflow: * * A function prologue already did all the work to prepare to enter the * function, but then it found out it didn't have enough room on the stack. * It may even have written uninits deeper than the stack base (but we limit * it to sSurprisePageSize, so it's harmless). * * Most importantly, it might have pulled args /off/ the eval stack and * shoved them into an array for a variadic capture param. We need to get * things into an appropriate state for handleStackOverflow to be able to * synchronize things to throw from the PC of the caller's FCall. * * We don't actually need to make sure the stack is the right depth for the * FCall: the unwinder will expect to see a pre-live ActRec (and we'll set it * up so it will), but it doesn't care how many args (or what types of args) * are below it on the stack. * * So, all that boils down to this: we set calleeAR->m_numArgs to indicate * how many things are actually on the stack (so handleStackOverflow knows * what to set the vmsp to)---we just set it to the function's numLocals, * which might mean decreffing some uninits unnecessarily, but that's ok. */ calleeAR->setNumArgs(calleeAR->m_func->numLocals()); handleStackOverflow(calleeAR); } /////////////////////////////////////////////////////////////////////////////// }}
43.833333
82
0.635192
jmurret
ed8860f8c27bfd49ec8e7677bd71d1712e76aa88
4,347
cc
C++
samples/graph/bfs.cc
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
63
2018-06-21T14:11:59.000Z
2022-03-30T11:24:36.000Z
samples/graph/bfs.cc
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
5
2018-09-22T14:01:53.000Z
2021-12-27T16:11:05.000Z
samples/graph/bfs.cc
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
12
2018-08-23T15:59:44.000Z
2022-02-20T06:47:22.000Z
#include <frovedis.hpp> #include <frovedis/ml/graph/graph.hpp> #include <boost/program_options.hpp> using namespace boost; using namespace frovedis; using namespace std; template <class T> void call_bfs(const std::string& data_p, const std::string& out_p, bool if_prep, size_t source_vertex, int opt_level, double threshold, size_t depth_limit) { graph<T> gr; time_spent t(INFO); if(if_prep) gr = read_edgelist<T>(data_p); else { auto mat = make_crs_matrix_load<T>(data_p); gr = graph<T>(mat); } t.show("data loading time: "); auto res = gr.bfs(source_vertex, opt_level, threshold, depth_limit); t.show("bfs computation time: "); res.save(out_p); res.debug_print(5); } int main(int argc, char* argv[]){ frovedis::use_frovedis use(argc, argv); using namespace boost::program_options; options_description opt("option"); opt.add_options() ("help,h", "produce help message") ("input,i" , value<std::string>(), "input data path containing either edgelist or adjacency matrix data") ("dtype,t" , value<std::string>(), "input data type (int, float or double) [default: int]") ("output,o" , value<std::string>(), "output data path to save cc results") ("source,s", value<size_t>(), "source vertex id [1 ~ nvert] (default: 1)") ("opt-level", value<int>(), "optimization level 0, 1 or 2 (default: 1)") ("hyb-threshold", value<double>(), "threshold value for hybrid optimization [0.0 ~ 1.0] (default: 0.4)") ("depth-limit", value<size_t>(), "depth limit to which tree is to be traversed (default: Max depth)") ("verbose", "set loglevel to DEBUG") ("verbose2", "set loglevel to TRACE") ("prepare,p" , "whether to generate the CRS matrix from original edgelist file "); variables_map argmap; store(command_line_parser(argc,argv).options(opt).allow_unregistered(). run(), argmap); notify(argmap); bool if_prep = 0; // true if prepare data from raw dataset std::string data_p, out_p, dtype = "int"; size_t source_vertex = 1; int opt_level = 1; double threshold = 0.4; size_t depth_limit = std::numeric_limits<size_t>::max(); if(argmap.count("help")){ std::cerr << opt << std::endl; exit(1); } if(argmap.count("input")){ data_p = argmap["input"].as<std::string>(); } else { std::cerr << "input path is not specified" << std::endl; std::cerr << opt << std::endl; exit(1); } if(argmap.count("output")){ out_p = argmap["output"].as<std::string>(); } else { std::cerr << "output path is not specified" << std::endl; std::cerr << opt << std::endl; exit(1); } if(argmap.count("prepare")){ if_prep = true; } if(argmap.count("dtype")){ dtype = argmap["dtype"].as<std::string>(); } if(argmap.count("source")){ source_vertex = argmap["source"].as<size_t>(); } if(argmap.count("opt-level")){ opt_level = argmap["opt-level"].as<int>(); } if(argmap.count("hyb-threshold")){ threshold = argmap["hyb-threshold"].as<double>(); } if(argmap.count("depth-limit")){ depth_limit = argmap["depth-limit"].as<size_t>(); } if(argmap.count("verbose")){ set_loglevel(DEBUG); } if(argmap.count("verbose2")){ set_loglevel(TRACE); } try { if (dtype == "int") { call_bfs<int>(data_p, out_p, if_prep, source_vertex, opt_level, threshold, depth_limit); } else if (dtype == "float") { call_bfs<float>(data_p, out_p, if_prep, source_vertex, opt_level, threshold, depth_limit); } else if (dtype == "double") { call_bfs<double>(data_p, out_p, if_prep, source_vertex, opt_level, threshold, depth_limit); } else { std::cerr << "Supported dtypes are only int, float and double!\n"; std::cerr << opt << std::endl; exit(1); } } catch (std::exception& e) { std::cout << "exception caught: " << e.what() << std::endl; } return 0; }
33.697674
114
0.569818
XpressAI
ed88ddd16f4960650be9f1c52ab4695e4deca3d1
16,845
cpp
C++
mozilla/gfx/2d/Path.cpp
naver/webgraphics
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
[ "MS-PL" ]
5
2016-12-20T15:48:05.000Z
2020-05-01T20:12:09.000Z
mozilla/gfx/2d/Path.cpp
naver/webgraphics
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
[ "MS-PL" ]
null
null
null
mozilla/gfx/2d/Path.cpp
naver/webgraphics
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
[ "MS-PL" ]
2
2016-12-20T15:48:13.000Z
2019-12-10T15:15:05.000Z
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "2D.h" #include "PathAnalysis.h" #include "PathHelpers.h" namespace mozilla { namespace gfx { static float CubicRoot(float aValue) { if (aValue < 0.0) { return -CubicRoot(-aValue); } else { return powf(aValue, 1.0f / 3.0f); } } struct BezierControlPoints { BezierControlPoints() {} BezierControlPoints(const Point &aCP1, const Point &aCP2, const Point &aCP3, const Point &aCP4) : mCP1(aCP1), mCP2(aCP2), mCP3(aCP3), mCP4(aCP4) { } Point mCP1, mCP2, mCP3, mCP4; }; void FlattenBezier(const BezierControlPoints &aPoints, PathSink *aSink, Float aTolerance); Path::Path() { } Path::~Path() { } Float Path::ComputeLength() { EnsureFlattenedPath(); return mFlattenedPath->ComputeLength(); } Point Path::ComputePointAtLength(Float aLength, Point* aTangent) { EnsureFlattenedPath(); return mFlattenedPath->ComputePointAtLength(aLength, aTangent); } void Path::EnsureFlattenedPath() { if (!mFlattenedPath) { mFlattenedPath = new FlattenedPath(); StreamToSink(mFlattenedPath); } } // This is the maximum deviation we allow (with an additional ~20% margin of // error) of the approximation from the actual Bezier curve. const Float kFlatteningTolerance = 0.0001f; void FlattenedPath::MoveTo(const Point &aPoint) { MOZ_ASSERT(!mCalculatedLength); FlatPathOp op; op.mType = FlatPathOp::OP_MOVETO; op.mPoint = aPoint; mPathOps.push_back(op); mLastMove = aPoint; } void FlattenedPath::LineTo(const Point &aPoint) { MOZ_ASSERT(!mCalculatedLength); FlatPathOp op; op.mType = FlatPathOp::OP_LINETO; op.mPoint = aPoint; mPathOps.push_back(op); } void FlattenedPath::BezierTo(const Point &aCP1, const Point &aCP2, const Point &aCP3) { MOZ_ASSERT(!mCalculatedLength); FlattenBezier(BezierControlPoints(CurrentPoint(), aCP1, aCP2, aCP3), this, kFlatteningTolerance); } void FlattenedPath::QuadraticBezierTo(const Point &aCP1, const Point &aCP2) { MOZ_ASSERT(!mCalculatedLength); // We need to elevate the degree of this quadratic B�zier to cubic, so we're // going to add an intermediate control point, and recompute control point 1. // The first and last control points remain the same. // This formula can be found on http://fontforge.sourceforge.net/bezier.html Point CP0 = CurrentPoint(); Point CP1 = (CP0 + aCP1 * 2.0) / 3.0; Point CP2 = (aCP2 + aCP1 * 2.0) / 3.0; Point CP3 = aCP2; BezierTo(CP1, CP2, CP3); } void FlattenedPath::Close() { MOZ_ASSERT(!mCalculatedLength); LineTo(mLastMove); } void FlattenedPath::Arc(const Point &aOrigin, float aRadius, float aStartAngle, float aEndAngle, bool aAntiClockwise) { ArcToBezier(this, aOrigin, Size(aRadius, aRadius), aStartAngle, aEndAngle, aAntiClockwise); } Float FlattenedPath::ComputeLength() { if (!mCalculatedLength) { Point currentPoint; for (uint32_t i = 0; i < mPathOps.size(); i++) { if (mPathOps[i].mType == FlatPathOp::OP_MOVETO) { currentPoint = mPathOps[i].mPoint; } else { mCachedLength += Distance(currentPoint, mPathOps[i].mPoint); currentPoint = mPathOps[i].mPoint; } } mCalculatedLength = true; } return mCachedLength; } Point FlattenedPath::ComputePointAtLength(Float aLength, Point *aTangent) { // We track the last point that -wasn't- in the same place as the current // point so if we pass the edge of the path with a bunch of zero length // paths we still get the correct tangent vector. Point lastPointSinceMove; Point currentPoint; for (uint32_t i = 0; i < mPathOps.size(); i++) { if (mPathOps[i].mType == FlatPathOp::OP_MOVETO) { if (Distance(currentPoint, mPathOps[i].mPoint)) { lastPointSinceMove = currentPoint; } currentPoint = mPathOps[i].mPoint; } else { Float segmentLength = Distance(currentPoint, mPathOps[i].mPoint); if (segmentLength) { lastPointSinceMove = currentPoint; if (segmentLength > aLength) { Point currentVector = mPathOps[i].mPoint - currentPoint; Point tangent = currentVector / segmentLength; if (aTangent) { *aTangent = tangent; } return currentPoint + tangent * aLength; } } aLength -= segmentLength; currentPoint = mPathOps[i].mPoint; } } Point currentVector = currentPoint - lastPointSinceMove; if (aTangent) { if (hypotf(currentVector.x, currentVector.y)) { *aTangent = currentVector / hypotf(currentVector.x, currentVector.y); } else { *aTangent = Point(); } } return currentPoint; } // This function explicitly permits aControlPoints to refer to the same object // as either of the other arguments. static void SplitBezier(const BezierControlPoints &aControlPoints, BezierControlPoints *aFirstSegmentControlPoints, BezierControlPoints *aSecondSegmentControlPoints, Float t) { MOZ_ASSERT(aSecondSegmentControlPoints); *aSecondSegmentControlPoints = aControlPoints; Point cp1a = aControlPoints.mCP1 + (aControlPoints.mCP2 - aControlPoints.mCP1) * t; Point cp2a = aControlPoints.mCP2 + (aControlPoints.mCP3 - aControlPoints.mCP2) * t; Point cp1aa = cp1a + (cp2a - cp1a) * t; Point cp3a = aControlPoints.mCP3 + (aControlPoints.mCP4 - aControlPoints.mCP3) * t; Point cp2aa = cp2a + (cp3a - cp2a) * t; Point cp1aaa = cp1aa + (cp2aa - cp1aa) * t; aSecondSegmentControlPoints->mCP4 = aControlPoints.mCP4; if(aFirstSegmentControlPoints) { aFirstSegmentControlPoints->mCP1 = aControlPoints.mCP1; aFirstSegmentControlPoints->mCP2 = cp1a; aFirstSegmentControlPoints->mCP3 = cp1aa; aFirstSegmentControlPoints->mCP4 = cp1aaa; } aSecondSegmentControlPoints->mCP1 = cp1aaa; aSecondSegmentControlPoints->mCP2 = cp2aa; aSecondSegmentControlPoints->mCP3 = cp3a; } static void FlattenBezierCurveSegment(const BezierControlPoints &aControlPoints, PathSink *aSink, Float aTolerance) { /* The algorithm implemented here is based on: * http://cis.usouthal.edu/~hain/general/Publications/Bezier/Bezier%20Offset%20Curves.pdf * * The basic premise is that for a small t the third order term in the * equation of a cubic bezier curve is insignificantly small. This can * then be approximated by a quadratic equation for which the maximum * difference from a linear approximation can be much more easily determined. */ BezierControlPoints currentCP = aControlPoints; Float t = 0; while (t < 1.0f) { Point cp21 = currentCP.mCP2 - currentCP.mCP3; Point cp31 = currentCP.mCP3 - currentCP.mCP1; /* To remove divisions and check for divide-by-zero, this is optimized from: * Float s3 = (cp31.x * cp21.y - cp31.y * cp21.x) / hypotf(cp21.x, cp21.y); * t = 2 * Float(sqrt(aTolerance / (3. * std::abs(s3)))); */ Float cp21x31 = cp31.x * cp21.y - cp31.y * cp21.x; Float h = hypotf(cp21.x, cp21.y); if (cp21x31 * h == 0) { break; } Float s3inv = h / cp21x31; t = 2 * Float(sqrt(aTolerance * std::abs(s3inv) / 3.)); if (t >= 1.0f) { break; } Point prevCP2, prevCP3, nextCP1, nextCP2, nextCP3; SplitBezier(currentCP, nullptr, &currentCP, t); aSink->LineTo(currentCP.mCP1); } aSink->LineTo(currentCP.mCP4); } static inline void FindInflectionApproximationRange(BezierControlPoints aControlPoints, Float *aMin, Float *aMax, Float aT, Float aTolerance) { SplitBezier(aControlPoints, nullptr, &aControlPoints, aT); Point cp21 = aControlPoints.mCP2 - aControlPoints.mCP1; Point cp41 = aControlPoints.mCP4 - aControlPoints.mCP1; if (cp21.x == 0.f && cp21.y == 0.f) { // In this case s3 becomes lim[n->0] (cp41.x * n) / n - (cp41.y * n) / n = cp41.x - cp41.y. // Use the absolute value so that Min and Max will correspond with the // minimum and maximum of the range. *aMin = aT - CubicRoot(std::abs(aTolerance / (cp41.x - cp41.y))); *aMax = aT + CubicRoot(std::abs(aTolerance / (cp41.x - cp41.y))); return; } Float s3 = (cp41.x * cp21.y - cp41.y * cp21.x) / hypotf(cp21.x, cp21.y); if (s3 == 0) { // This means within the precision we have it can be approximated // infinitely by a linear segment. Deal with this by specifying the // approximation range as extending beyond the entire curve. *aMin = -1.0f; *aMax = 2.0f; return; } Float tf = CubicRoot(std::abs(aTolerance / s3)); *aMin = aT - tf * (1 - aT); *aMax = aT + tf * (1 - aT); } /* Find the inflection points of a bezier curve. Will return false if the * curve is degenerate in such a way that it is best approximated by a straight * line. * * The below algorithm was written by Jeff Muizelaar <jmuizelaar@mozilla.com>, explanation follows: * * The lower inflection point is returned in aT1, the higher one in aT2. In the * case of a single inflection point this will be in aT1. * * The method is inspired by the algorithm in "analysis of in?ection points for planar cubic bezier curve" * * Here are some differences between this algorithm and versions discussed elsewhere in the literature: * * zhang et. al compute a0, d0 and e0 incrementally using the follow formula: * * Point a0 = CP2 - CP1 * Point a1 = CP3 - CP2 * Point a2 = CP4 - CP1 * * Point d0 = a1 - a0 * Point d1 = a2 - a1 * Point e0 = d1 - d0 * * this avoids any multiplications and may or may not be faster than the approach take below. * * "fast, precise flattening of cubic bezier path and ofset curves" by hain et. al * Point a = CP1 + 3 * CP2 - 3 * CP3 + CP4 * Point b = 3 * CP1 - 6 * CP2 + 3 * CP3 * Point c = -3 * CP1 + 3 * CP2 * Point d = CP1 * the a, b, c, d can be expressed in terms of a0, d0 and e0 defined above as: * c = 3 * a0 * b = 3 * d0 * a = e0 * * * a = 3a = a.y * b.x - a.x * b.y * b = 3b = a.y * c.x - a.x * c.y * c = 9c = b.y * c.x - b.x * c.y * * The additional multiples of 3 cancel each other out as show below: * * x = (-b + sqrt(b * b - 4 * a * c)) / (2 * a) * x = (-3 * b + sqrt(3 * b * 3 * b - 4 * a * 3 * 9 * c / 3)) / (2 * 3 * a) * x = 3 * (-b + sqrt(b * b - 4 * a * c)) / (2 * 3 * a) * x = (-b + sqrt(b * b - 4 * a * c)) / (2 * a) * * I haven't looked into whether the formulation of the quadratic formula in * hain has any numerical advantages over the one used below. */ static inline void FindInflectionPoints(const BezierControlPoints &aControlPoints, Float *aT1, Float *aT2, uint32_t *aCount) { // Find inflection points. // See www.faculty.idc.ac.il/arik/quality/appendixa.html for an explanation // of this approach. Point A = aControlPoints.mCP2 - aControlPoints.mCP1; Point B = aControlPoints.mCP3 - (aControlPoints.mCP2 * 2) + aControlPoints.mCP1; Point C = aControlPoints.mCP4 - (aControlPoints.mCP3 * 3) + (aControlPoints.mCP2 * 3) - aControlPoints.mCP1; Float a = Float(B.x) * C.y - Float(B.y) * C.x; Float b = Float(A.x) * C.y - Float(A.y) * C.x; Float c = Float(A.x) * B.y - Float(A.y) * B.x; if (a == 0) { // Not a quadratic equation. if (b == 0) { // Instead of a linear acceleration change we have a constant // acceleration change. This means the equation has no solution // and there are no inflection points, unless the constant is 0. // In that case the curve is a straight line, essentially that means // the easiest way to deal with is is by saying there's an inflection // point at t == 0. The inflection point approximation range found will // automatically extend into infinity. if (c == 0) { *aCount = 1; *aT1 = 0; return; } *aCount = 0; return; } *aT1 = -c / b; *aCount = 1; return; } else { Float discriminant = b * b - 4 * a * c; if (discriminant < 0) { // No inflection points. *aCount = 0; } else if (discriminant == 0) { *aCount = 1; *aT1 = -b / (2 * a); } else { /* Use the following formula for computing the roots: * * q = -1/2 * (b + sign(b) * sqrt(b^2 - 4ac)) * t1 = q / a * t2 = c / q */ Float q = sqrtf(discriminant); if (b < 0) { q = b - q; } else { q = b + q; } q *= Float(-1./2); *aT1 = q / a; *aT2 = c / q; if (*aT1 > *aT2) { std::swap(*aT1, *aT2); } *aCount = 2; } } return; } void FlattenBezier(const BezierControlPoints &aControlPoints, PathSink *aSink, Float aTolerance) { Float t1; Float t2; uint32_t count; FindInflectionPoints(aControlPoints, &t1, &t2, &count); // Check that at least one of the inflection points is inside [0..1] if (count == 0 || ((t1 < 0 || t1 > 1.0) && (count == 1 || (t2 < 0 || t2 > 1.0))) ) { FlattenBezierCurveSegment(aControlPoints, aSink, aTolerance); return; } Float t1min = t1, t1max = t1, t2min = t2, t2max = t2; BezierControlPoints remainingCP = aControlPoints; // For both inflection points, calulate the range where they can be linearly // approximated if they are positioned within [0,1] if (count > 0 && t1 >= 0 && t1 < 1.0) { FindInflectionApproximationRange(aControlPoints, &t1min, &t1max, t1, aTolerance); } if (count > 1 && t2 >= 0 && t2 < 1.0) { FindInflectionApproximationRange(aControlPoints, &t2min, &t2max, t2, aTolerance); } BezierControlPoints nextCPs = aControlPoints; BezierControlPoints prevCPs; // Process ranges. [t1min, t1max] and [t2min, t2max] are approximated by line // segments. if (count == 1 && t1min <= 0 && t1max >= 1.0) { // The whole range can be approximated by a line segment. aSink->LineTo(aControlPoints.mCP4); return; } if (t1min > 0) { // Flatten the Bezier up until the first inflection point's approximation // point. SplitBezier(aControlPoints, &prevCPs, &remainingCP, t1min); FlattenBezierCurveSegment(prevCPs, aSink, aTolerance); } if (t1max >= 0 && t1max < 1.0 && (count == 1 || t2min > t1max)) { // The second inflection point's approximation range begins after the end // of the first, approximate the first inflection point by a line and // subsequently flatten up until the end or the next inflection point. SplitBezier(aControlPoints, nullptr, &nextCPs, t1max); aSink->LineTo(nextCPs.mCP1); if (count == 1 || (count > 1 && t2min >= 1.0)) { // No more inflection points to deal with, flatten the rest of the curve. FlattenBezierCurveSegment(nextCPs, aSink, aTolerance); } } else if (count > 1 && t2min > 1.0) { // We've already concluded t2min <= t1max, so if this is true the // approximation range for the first inflection point runs past the // end of the curve, draw a line to the end and we're done. aSink->LineTo(aControlPoints.mCP4); return; } if (count > 1 && t2min < 1.0 && t2max > 0) { if (t2min > 0 && t2min < t1max) { // In this case the t2 approximation range starts inside the t1 // approximation range. SplitBezier(aControlPoints, nullptr, &nextCPs, t1max); aSink->LineTo(nextCPs.mCP1); } else if (t2min > 0 && t1max > 0) { SplitBezier(aControlPoints, nullptr, &nextCPs, t1max); // Find a control points describing the portion of the curve between t1max and t2min. Float t2mina = (t2min - t1max) / (1 - t1max); SplitBezier(nextCPs, &prevCPs, &nextCPs, t2mina); FlattenBezierCurveSegment(prevCPs, aSink, aTolerance); } else if (t2min > 0) { // We have nothing interesting before t2min, find that bit and flatten it. SplitBezier(aControlPoints, &prevCPs, &nextCPs, t2min); FlattenBezierCurveSegment(prevCPs, aSink, aTolerance); } if (t2max < 1.0) { // Flatten the portion of the curve after t2max SplitBezier(aControlPoints, nullptr, &nextCPs, t2max); // Draw a line to the start, this is the approximation between t2min and // t2max. aSink->LineTo(nextCPs.mCP1); FlattenBezierCurveSegment(nextCPs, aSink, aTolerance); } else { // Our approximation range extends beyond the end of the curve. aSink->LineTo(aControlPoints.mCP4); return; } } } } // namespace gfx } // namespace mozilla
31.194444
110
0.639656
naver
ed8953dbe4132319a7738c97bc09a74f76558e7c
4,437
cpp
C++
Rocket/Engine/FileSystem/OsFileSync.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
Rocket/Engine/FileSystem/OsFileSync.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
Rocket/Engine/FileSystem/OsFileSync.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
#include "FileSystem/OsFileSync.h" #include "Log/Log.h" #include <exception> namespace Rocket { int32_t OsFileSync::Initialize(const std::string& path, const std::string& file_name, FileOperateMode mode) { mode_ = mode; file_.file_path = path; file_.file_name = file_name; file_.full_name = path + file_name; return Initialize(file_.full_name.data(), mode_); } int32_t OsFileSync::Initialize(const std::string& path, FileOperateMode mode) { mode_ = mode; file_.full_name = path; switch(mode_) { case FileOperateMode::READ_BINARY: file_.file_pointer = (void*)fopen(file_.full_name.data(), "rb"); break; case FileOperateMode::WRITE_BINARY: file_.file_pointer = (void*)fopen(file_.full_name.data(), "wb"); break; case FileOperateMode::READ_TEXT: file_.file_pointer = (void*)fopen(file_.full_name.data(), "r"); break; case FileOperateMode::WRITE_TEXT: file_.file_pointer = (void*)fopen(file_.full_name.data(), "w"); break; default: break; }; SeekToEnd(); file_.total_size = Tell(); Seek(0); initialized_ = true; RK_TRACE(File, "Open File {} Success", file_.full_name); if(file_.file_pointer == nullptr) return 1; else return 0; } void OsFileSync::Finalize() { if(file_.file_pointer != nullptr) fclose((FILE*)file_.file_pointer); if(file_.extra_file_info != nullptr) delete file_.extra_file_info; initialized_ = false; } std::size_t OsFileSync::Read(FileBuffer& buffer, std::size_t length) { if(mode_ == FileOperateMode::READ_BINARY) { buffer.size = length; buffer.buffer = new uint8_t[length]; auto result = fread(buffer.buffer, buffer.size, 1, (FILE*)file_.file_pointer); if(result == 1) return length; else return 0; } else if(mode_ == FileOperateMode::READ_TEXT) { buffer.size = length + 1; buffer.buffer = new uint8_t[length + 1]; auto result = fread(buffer.buffer, buffer.size, 1, (FILE*)file_.file_pointer); static_cast<char*>(buffer.buffer)[length] = '\0'; if(result == 0) return buffer.size; else return 0; } else { return 0; } } std::size_t OsFileSync::ReadAll(FileBuffer& buffer) { if(mode_ == FileOperateMode::READ_BINARY || mode_ == FileOperateMode::READ_TEXT) return Read(buffer, file_.total_size); else return 0; } std::size_t OsFileSync::Write(FileBuffer& buffer, std::size_t length) { std::size_t real_length = 0; if(length == 0 || length > buffer.size) real_length = buffer.size; else real_length = length; auto result = fwrite(buffer.buffer, real_length, 1, (FILE*)file_.file_pointer); if(result == 1) return length; else return 0; } std::size_t OsFileSync::WriteAll(FileBuffer& buffer) { auto result = fwrite(buffer.buffer, buffer.size, 1, (FILE*)file_.file_pointer); if(result == 1) return buffer.size; else return 0; } void OsFileSync::Seek(std::size_t position) { auto result = fseek((FILE*)file_.file_pointer, position, SEEK_SET); if(result != 0) { RK_ERROR(File, "{} File Seek {} Error", file_.full_name, position); throw std::runtime_error("File Seek Error"); } } void OsFileSync::SeekToEnd(void) { auto result = fseek((FILE*)file_.file_pointer, 0, SEEK_END); if(result != 0) { RK_ERROR(File, "{} File Seek End Error", file_.full_name); throw std::runtime_error("File Seek End Error"); } } void OsFileSync::Skip(std::size_t bytes) { auto result = fseek((FILE*)file_.file_pointer, bytes, SEEK_CUR); if(result != 0) { RK_ERROR(File, "{} File Skip {} Error", file_.full_name); throw std::runtime_error("File Skip Error"); } } std::size_t OsFileSync::Tell(void) const { std::size_t result = ftell((FILE*)file_.file_pointer); return result; } }
33.360902
119
0.572459
rocketman123456
ed8e6b442228e6aa14ede0f0daa3f79932d78ded
2,756
cpp
C++
src/io/lnk4archive.cpp
HououinKyouma29/impacto
8d4bf2605f54630b1b1cf7dbf3d05e5fd0249c2d
[ "ISC" ]
2
2021-02-08T12:01:16.000Z
2021-07-01T22:54:41.000Z
src/io/lnk4archive.cpp
HououinKyouma29/impacto
8d4bf2605f54630b1b1cf7dbf3d05e5fd0249c2d
[ "ISC" ]
null
null
null
src/io/lnk4archive.cpp
HououinKyouma29/impacto
8d4bf2605f54630b1b1cf7dbf3d05e5fd0249c2d
[ "ISC" ]
null
null
null
#include "lnk4archive.h" #include "../log.h" #include "uncompressedstream.h" #include "vfs.h" #include "../util.h" #include <SDL_endian.h> namespace Impacto { namespace Io { struct Lnk4MetaEntry : FileMeta { int64_t Offset; }; Lnk4Archive::~Lnk4Archive() { if (TOC) delete[] TOC; } IoError Lnk4Archive::Open(FileMeta* file, InputStream** outStream) { Lnk4MetaEntry* entry = (Lnk4MetaEntry*)file; IoError err = UncompressedStream::Create(BaseStream, entry->Offset, entry->Size, outStream); if (err != IoError_OK) { ImpLog(LL_Error, LC_IO, "LNK4 file open failed for file \"%s\" in archive \"%s\"\n", entry->FileName.c_str(), BaseStream->Meta.FileName.c_str()); } return err; } IoError Lnk4Archive::Create(InputStream* stream, VfsArchive** outArchive) { ImpLog(LL_Trace, LC_IO, "Trying to mount \"%s\" as LNK4\n", stream->Meta.FileName.c_str()); Lnk4Archive* result = 0; uint32_t* rawToc = 0; uint32_t offsetBlockSize = 2048; uint32_t blockSize = 1024; uint32_t const magic = 0x4C4E4B34; uint32_t const tocOffset = 8; uint32_t maxFileCount; uint32_t fileCount; uint32_t dataOffset; char fileName[6]; if (ReadBE<uint32_t>(stream) != magic) { ImpLog(LL_Trace, LC_IO, "Not LNK4\n"); goto fail; } dataOffset = ReadLE<uint32_t>(stream); if (dataOffset < tocOffset) { ImpLog(LL_Error, LC_IO, "LNK4 header too short\n"); goto fail; } maxFileCount = (dataOffset - tocOffset) / 8; rawToc = (uint32_t*)ImpStackAlloc(dataOffset - tocOffset); if (stream->Read(rawToc, dataOffset - tocOffset) != dataOffset - tocOffset) goto fail; fileCount = 0; for (uint32_t* it = rawToc; it < rawToc + (maxFileCount * 2); it += 2) { // first file starts at 0 if (SDL_SwapLE32(*it) == 0 && it != rawToc) break; fileCount++; } result = new Lnk4Archive; result->BaseStream = stream; result->NamesToIds.reserve(fileCount); result->IdsToFiles.reserve(fileCount); result->TOC = new Lnk4MetaEntry[fileCount]; for (uint32_t i = 0; i < fileCount; i++) { snprintf(fileName, 6, "%05i", i); result->TOC[i].FileName = fileName; result->TOC[i].Id = i; result->TOC[i].Offset = SDL_SwapLE32(rawToc[i * 2]) * offsetBlockSize + dataOffset; result->TOC[i].Size = SDL_SwapLE32(rawToc[i * 2 + 1]) * blockSize; result->IdsToFiles[i] = &result->TOC[i]; result->NamesToIds[result->TOC[i].FileName] = i; } ImpStackFree(rawToc); result->IsInit = true; *outArchive = result; return IoError_OK; fail: stream->Seek(0, RW_SEEK_SET); if (result) delete result; if (rawToc) ImpStackFree(rawToc); return IoError_Fail; } } // namespace Io } // namespace Impacto
26
77
0.651669
HououinKyouma29
ed93051395b2052ef71d21b0ffdf4c36d8b4419b
5,968
cpp
C++
libs/SysmelCompiler/Environment/Template.cpp
ronsaldo/sysmel-beta
14237d780527c6ca1bb34f74195838f78f0c6acc
[ "MIT" ]
2
2021-10-30T15:31:43.000Z
2021-11-08T09:45:15.000Z
libs/SysmelCompiler/Environment/Template.cpp
ronsaldo/sysmel-beta
14237d780527c6ca1bb34f74195838f78f0c6acc
[ "MIT" ]
null
null
null
libs/SysmelCompiler/Environment/Template.cpp
ronsaldo/sysmel-beta
14237d780527c6ca1bb34f74195838f78f0c6acc
[ "MIT" ]
null
null
null
#include "Environment/Template.hpp" #include "Environment/TemplateInstance.hpp" #include "Environment/ArgumentVariable.hpp" #include "Environment/ASTCallNode.hpp" #include "Environment/ASTSemanticAnalyzer.hpp" #include "Environment/SSATemplate.hpp" #include "Environment/BootstrapTypeRegistration.hpp" #include "Environment/StringUtilities.hpp" namespace Sysmel { namespace Environment { static BootstrapTypeRegistration<Template> templateTypeRegistration; bool Template::isTemplate() const { return true; } void Template::recordChildProgramEntityDefinition(const ProgramEntityPtr &newChild) { children.push_back(newChild); newChild->setParentProgramEntity(selfFromThis()); } AnyValuePtr Template::getName() const { return name; } void Template::setName(const AnyValuePtr &newName) { name = newName; } SSAValuePtr Template::asSSAValueRequiredInPosition(const ASTSourcePositionPtr &) { if(!ssaTemplate) { ssaTemplate = basicMakeObject<SSATemplate> (); ssaTemplate->setName(getValidName()); ssaTemplate->setExternalLanguageMode(externalLanguageMode); ssaTemplate->setVisibility(visibility); ssaTemplate->setDllLinkageMode(dllLinkageMode); auto ssaParent = getParentProgramEntity()->asProgramEntitySSAValue(); if(ssaParent) { sysmelAssert(ssaParent->isSSAProgramEntity()); ssaParent.staticAs<SSAProgramEntity>()->addChild(ssaTemplate); } } return ssaTemplate; } void Template::setDeclarationNode(const ASTNodePtr &node) { declarationPosition = node->sourcePosition; declarationNode = node; } void Template::addDefinition(const ASTNodePtr &node, const ASTNodePtr &bodyNode, const ASTAnalysisEnvironmentPtr &bodyEnvironment) { definitionFragments.push_back({ node->sourcePosition, node, bodyNode, bodyEnvironment }); } void Template::setArgumentTypes(const TypePtrList &argumentTypes) { arguments.reserve(argumentTypes.size()); for(const auto &type : argumentTypes) { auto argument = basicMakeObject<ArgumentVariable> (); recordChildProgramEntityDefinition(argument); argument->setType(type); arguments.push_back(argument); } } void Template::setArgumentDeclarationNode(size_t index, const ASTArgumentDefinitionNodePtr &argumentNode) { sysmelAssert(index < arguments.size()); arguments[index]->setArgumentDeclarationNode(argumentNode); } void Template::setArgumentDefinitionNode(size_t index, const ASTArgumentDefinitionNodePtr &argumentNode) { sysmelAssert(index < arguments.size()); arguments[index]->setArgumentDefinitionNode(argumentNode); } TemplateInstancePtr Template::getOrCreateTemplateInstanceWithArguments(const AnyValuePtrList &instanceArguments) { sysmelAssert(instanceArguments.size() == arguments.size()); auto it = instanceCache.find(instanceArguments); if(it != instanceCache.end()) return it->second; auto instance = basicMakeObject<TemplateInstance> (); instanceCache.insert({instanceArguments, instance}); // TODO: Record this on a module specific program entity if needed. recordChildProgramEntityDefinition(instance); for(size_t i = 0; i < instanceArguments.size(); ++i) instance->addArgumentBinding(arguments[i]->getName(), instanceArguments[i]); for(auto &fragment : definitionFragments) instance->evaluateDefinitionFragment(fragment); return instance; } AnyValuePtr Template::getOrCreateTemplateInstanceValueWithArguments(const AnyValuePtrList &instanceArguments) { return getOrCreateTemplateInstanceWithArguments(instanceArguments)->getValue(); } ASTNodePtr Template::analyzeCallNode(const ASTCallNodePtr &callNode, const ASTSemanticAnalyzerPtr &semanticAnalyzer) { if(callNode->arguments.size() != arguments.size()) return semanticAnalyzer->recordSemanticErrorInNode(callNode, formatString("Template {0} expects {1} arguments instead of the {2} provided arguments.", {printString(), castToString(arguments.size()), castToString(callNode->arguments.size())})); if(definitionFragments.empty()) return semanticAnalyzer->recordSemanticErrorInNode(callNode, formatString("Cannot instance template {0} without a definition body.", {printString()})); auto templateInstanceNode = semanticAnalyzer->guardCompileTimeEvaluationForNode(callNode, [&](){ AnyValuePtrList instanceArguments; instanceArguments.reserve(arguments.size()); bool hasError = false; ASTNodePtr errorNode; for(size_t i = 0; i < arguments.size(); ++i) { auto expectedType = arguments[i]->getValueType(); auto argumentNode = semanticAnalyzer->analyzeNodeIfNeededWithExpectedType(callNode->arguments[i], expectedType); if(argumentNode->isASTErrorNode()) { if(!hasError) errorNode = argumentNode; hasError = true; continue; } auto argumentValue = semanticAnalyzer->evaluateInCompileTime(argumentNode); if(validAnyValue(argumentValue)->isCompilationErrorValue()) { if(!hasError) errorNode = semanticAnalyzer->recordSemanticErrorInNode(callNode, "Failed to evaluate template instance argument."); hasError = true; continue; } instanceArguments.push_back(argumentValue); } if(hasError) { sysmelAssert(errorNode); return errorNode; } return validAnyValue(getOrCreateTemplateInstanceValueWithArguments(instanceArguments))->asASTNodeRequiredInPosition(callNode->sourcePosition); }); return semanticAnalyzer->analyzeNodeIfNeededWithCurrentExpectedType(templateInstanceNode); } } // End of namespace Environment } // End of namespace Sysmel
33.717514
159
0.714645
ronsaldo
ed937cfe046aadb3ef15f24d05f5e7fe23898d81
371
inl
C++
TAO/tao/Acceptor_Registry.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/Acceptor_Registry.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/Acceptor_Registry.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// -*- C++ -*- // // $Id: Acceptor_Registry.inl 73791 2006-07-27 20:54:56Z wotte $ TAO_BEGIN_VERSIONED_NAMESPACE_DECL ACE_INLINE TAO_AcceptorSetIterator TAO_Acceptor_Registry::begin (void) { return this->acceptors_; } ACE_INLINE TAO_AcceptorSetIterator TAO_Acceptor_Registry::end (void) { return this->acceptors_ + this->size_; } TAO_END_VERSIONED_NAMESPACE_DECL
18.55
64
0.773585
cflowe
ed938ba7c93d8f0b90d9bd881f8eba96f41b3c08
16,130
cpp
C++
rEFIt_UEFI/entry_scan/legacy.cpp
harperse/CloverBootloader
8d1baad2a62c66aae776cfd45d832399632c299e
[ "BSD-2-Clause" ]
null
null
null
rEFIt_UEFI/entry_scan/legacy.cpp
harperse/CloverBootloader
8d1baad2a62c66aae776cfd45d832399632c299e
[ "BSD-2-Clause" ]
null
null
null
rEFIt_UEFI/entry_scan/legacy.cpp
harperse/CloverBootloader
8d1baad2a62c66aae776cfd45d832399632c299e
[ "BSD-2-Clause" ]
null
null
null
/* * refit/scan/legacy.c * * Copyright (c) 2006-2010 Christoph Pfisterer * 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 Christoph Pfisterer nor the names of the * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <Platform.h> // Only use angled for Platform, else, xcode project won't compile #include "entry_scan.h" #include "../refit/screen.h" #include "../refit/menu.h" #include "../gui/REFIT_MENU_SCREEN.h" #include "../gui/REFIT_MAINMENU_SCREEN.h" #include "../Platform/Volumes.h" #include "../libeg/XTheme.h" #include "../include/OSFlags.h" #ifndef DEBUG_ALL #define DEBUG_SCAN_LEGACY 1 #else #define DEBUG_SCAN_LEGACY DEBUG_ALL #endif #if DEBUG_SCAN_LEGACY == 0 #define DBG(...) #else #define DBG(...) DebugLog(DEBUG_SCAN_LEGACY, __VA_ARGS__) #endif //the function is not in the class and deals always with MainMenu //I made args as pointers to have an ability to call with NULL XBool AddLegacyEntry(IN const XStringW& FullTitle, IN const XStringW& _LoaderTitle, IN REFIT_VOLUME *Volume, IN const XIcon* Image, IN const XIcon* DriveImage, IN char32_t Hotkey, IN XBool CustomEntry) { LEGACY_ENTRY *Entry, *SubEntry; REFIT_MENU_SCREEN *SubScreen; XStringW VolDesc; CHAR16 ShortcutLetter = 0; // INTN i; DBG(" AddLegacyEntry:\n"); DBG(" FullTitle=%ls\n", FullTitle.wc_str()); DBG(" LoaderTitle=%ls\n", _LoaderTitle.wc_str()); DBG(" Volume->LegacyOS->Name=%ls\n", Volume->LegacyOS->Name.wc_str()); if (Volume == NULL) { return false; } // Ignore this loader if it's device path is already present in another loader for (UINTN i = 0; i < MainMenu.Entries.size(); ++i) { REFIT_ABSTRACT_MENU_ENTRY& MainEntry = MainMenu.Entries[i]; // DBG("entry %lld\n", i); // Only want legacy if (MainEntry.getLEGACY_ENTRY()) { if ( MainEntry.getLEGACY_ENTRY()->DevicePathString.isEqualIC(Volume->DevicePathString) ) { return true; } } } XStringW LoaderTitle; if ( _LoaderTitle.isEmpty() ) { LoaderTitle = Volume->LegacyOS->Name; }else{ LoaderTitle = _LoaderTitle; } XStringW LTitle; if (LoaderTitle.isEmpty()) { if (Volume->LegacyOS->Name.notEmpty()) { LTitle.takeValueFrom(Volume->LegacyOS->Name); if (Volume->LegacyOS->Name[0] == 'W' || Volume->LegacyOS->Name[0] == 'L') ShortcutLetter = (wchar_t)Volume->LegacyOS->Name[0]; // cast safe because value is 'W' or 'L' } else LTitle = L"Legacy OS"_XSW; } else LTitle = LoaderTitle; if (Volume->VolName.notEmpty()) VolDesc = Volume->VolName; else VolDesc.takeValueFrom((Volume->DiskKind == DISK_KIND_OPTICAL) ? L"CD" : L"HD"); //DBG("VolDesc=%ls\n", VolDesc); // prepare the menu entry Entry = new LEGACY_ENTRY; if ( FullTitle.notEmpty() ) { Entry->Title = FullTitle; } else { if (ThemeX.BootCampStyle) { Entry->Title = LTitle; } else { Entry->Title.SWPrintf("Boot %ls from %ls", LoaderTitle.wc_str(), VolDesc.wc_str()); } } DBG(" Entry->Title=%ls\n", Entry->Title.wc_str()); Entry->Row = 0; Entry->ShortcutLetter = (Hotkey == 0) ? ShortcutLetter : Hotkey; if ( Image && !Image->isEmpty() ) { Entry->Image = *Image; } else { Entry->Image = ThemeX.LoadOSIcon(Volume->LegacyOS->IconName); if (Entry->Image.Image.isEmpty()) { Entry->Image = ThemeX.GetIcon("os_win"_XS8); //we have no legacy.png } } // DBG("IconName=%ls\n", Volume->LegacyOS->IconName); Entry->DriveImage = (DriveImage != NULL) ? *DriveImage : ScanVolumeDefaultIcon(Volume, Volume->LegacyOS->Type, Volume->DevicePath); // DBG("HideBadges=%d Volume=%ls\n", GlobalConfig.HideBadges, Volume->VolName); // DBG("Title=%ls OSName=%ls OSIconName=%ls\n", LoaderTitle, Volume->OSName, Volume->OSIconName); //actions Entry->AtClick = ActionSelect; Entry->AtDoubleClick = ActionEnter; Entry->AtRightClick = ActionDetails; if (ThemeX.HideBadges & HDBADGES_SHOW) { if (ThemeX.HideBadges & HDBADGES_SWAP) { //will be scaled later Entry->BadgeImage.Image = XImage(Entry->DriveImage.Image, 0); //ThemeX.BadgeScale/16.f); //0 accepted } else { Entry->BadgeImage.Image = XImage(Entry->Image.Image, 0); //ThemeX.BadgeScale/16.f); } } Entry->Volume = Volume; Entry->DevicePathString = Volume->DevicePathString; // Entry->LoadOptions = (Volume->DiskKind == DISK_KIND_OPTICAL) ? "CD"_XS8 : ((Volume->DiskKind == DISK_KIND_EXTERNAL) ? "USB"_XS8 : "HD"_XS8); Entry->LoadOptions.setEmpty(); Entry->LoadOptions.Add((Volume->DiskKind == DISK_KIND_OPTICAL) ? "CD" : ((Volume->DiskKind == DISK_KIND_EXTERNAL) ? "USB" : "HD")); // If this isn't a custom entry make sure it's not hidden by a custom entry if (!CustomEntry) { for (size_t CustomIndex = 0 ; CustomIndex < GlobalConfig.CustomLegacyEntries.size() ; ++CustomIndex ) { CUSTOM_LEGACY_ENTRY& Custom = GlobalConfig.CustomLegacyEntries[CustomIndex]; if ( Custom.settings.Disabled || OSFLAG_ISSET(Custom.getFlags(), OSFLAG_DISABLED) || Custom.settings.Hidden ) { if (Custom.settings.Volume.notEmpty()) { if ( !Volume->DevicePathString.contains(Custom.settings.Volume) && !Volume->VolName.contains(Custom.settings.Volume) ) { if (Custom.settings.Type != 0) { if (Custom.settings.Type == Volume->LegacyOS->Type) { Entry->Hidden = true; } } else { Entry->Hidden = true; } } } else if (Custom.settings.Type != 0) { if (Custom.settings.Type == Volume->LegacyOS->Type) { Entry->Hidden = true; } } } } } // create the submenu SubScreen = new REFIT_MENU_SCREEN; // SubScreen->Title = L"Boot Options for "_XSW + LoaderTitle + L" on "_XSW + VolDesc; SubScreen->Title.SWPrintf("Boot Options for %ls on %ls", LoaderTitle.wc_str(), VolDesc.wc_str()); SubScreen->TitleImage = Entry->Image; //it is XIcon SubScreen->ID = SCREEN_BOOT; SubScreen->GetAnime(); // default entry SubEntry = new LEGACY_ENTRY; SubEntry->Title = L"Boot "_XSW + LoaderTitle; // SubEntry->Tag = TAG_LEGACY; SubEntry->Volume = Entry->Volume; SubEntry->DevicePathString = Entry->DevicePathString; SubEntry->LoadOptions = Entry->LoadOptions; SubEntry->AtClick = ActionEnter; SubScreen->AddMenuEntry(SubEntry, true); SubScreen->AddMenuEntry(&MenuEntryReturn, false); Entry->SubScreen = SubScreen; MainMenu.AddMenuEntry(Entry, true); // DBG(" added '%ls' OSType=%d Icon=%ls\n", Entry->Title, Volume->LegacyOS->Type, Volume->LegacyOS->IconName); return true; } void ScanLegacy(void) { UINTN VolumeIndex, VolumeIndex2; XBool ShowVolume, HideIfOthersFound; REFIT_VOLUME *Volume; DBG("Scanning legacy ...\n"); for (VolumeIndex = 0; VolumeIndex < Volumes.size(); VolumeIndex++) { Volume = &Volumes[VolumeIndex]; // DBG("test VI=%d\n", VolumeIndex); if ((Volume->BootType != BOOTING_BY_PBR) && (Volume->BootType != BOOTING_BY_MBR) && (Volume->BootType != BOOTING_BY_CD)) { // DBG(" not legacy\n"); continue; } // DBG("%2d: '%ls' (%ls)", VolumeIndex, Volume->VolName, Volume->LegacyOS->IconName); #if 0 // REFIT_DEBUG > 0 DBG(" %d %ls\n %d %d %ls %d %ls\n", VolumeIndex, FileDevicePathToStr(Volume->DevicePath), Volume->DiskKind, Volume->MbrPartitionIndex, Volume->IsAppleLegacy ? L"AL" : L"--", Volume->HasBootCode, Volume->VolName ? Volume->VolName : L"(no name)"); #endif // skip volume if its kind is configured as disabled /* if ((Volume->DiskKind == DISK_KIND_OPTICAL && (GlobalConfig.DisableFlags & VOLTYPE_OPTICAL)) || (Volume->DiskKind == DISK_KIND_EXTERNAL && (GlobalConfig.DisableFlags & VOLTYPE_EXTERNAL)) || (Volume->DiskKind == DISK_KIND_INTERNAL && (GlobalConfig.DisableFlags & VOLTYPE_INTERNAL)) || (Volume->DiskKind == DISK_KIND_FIREWIRE && (GlobalConfig.DisableFlags & VOLTYPE_FIREWIRE))) */ if (((1ull<<Volume->DiskKind) & GlobalConfig.DisableFlags) != 0) { // DBG(" hidden\n"); continue; } // DBG("not hidden\n"); ShowVolume = false; HideIfOthersFound = false; if (Volume->IsAppleLegacy) { ShowVolume = true; HideIfOthersFound = true; } else if (Volume->HasBootCode) { ShowVolume = true; // DBG("Volume %d will be shown BlockIo=%X WholeIo=%X\n", // VolumeIndex, Volume->BlockIO, Volume->WholeDiskBlockIO); if ((Volume->WholeDiskBlockIO == 0) && Volume->BlockIOOffset == 0 /* && Volume->OSName == NULL */) // this is a whole disk (MBR) entry; hide if we have entries for partitions HideIfOthersFound = true; // DBG("Hide it!\n"); } if (HideIfOthersFound) { // check for other bootable entries on the same disk //if PBR exists then Hide MBR for (VolumeIndex2 = 0; VolumeIndex2 < Volumes.size(); VolumeIndex2++) { // DBG("what to hide %d\n", VolumeIndex2); if (VolumeIndex2 != VolumeIndex && Volumes[VolumeIndex2].HasBootCode && Volumes[VolumeIndex2].WholeDiskBlockIO == Volume->BlockIO){ ShowVolume = false; // DBG("PBR volume at index %d\n", VolumeIndex2); break; } } } if (ShowVolume && (!Volume->Hidden)){ // DBG(" add legacy\n"); if (!AddLegacyEntry(L""_XSW, L""_XSW, Volume, NULL, NULL, 0, false)) { DBG("...entry not added\n"); }; } else { DBG(" hidden\n"); } } } // Add custom legacy void AddCustomLegacy(void) { UINTN VolumeIndex, VolumeIndex2; XBool ShowVolume, HideIfOthersFound; REFIT_VOLUME *Volume; XIcon MainIcon; XIcon DriveIcon; // DBG("Custom legacy start\n"); if (GlobalConfig.CustomLegacyEntries.notEmpty()) { DbgHeader("AddCustomLegacy"); } // Traverse the custom entries for (size_t i = 0 ; i < GlobalConfig.CustomLegacyEntries.size() ; ++i ) { CUSTOM_LEGACY_ENTRY& Custom = GlobalConfig.CustomLegacyEntries[i]; if (Custom.settings.Disabled || OSFLAG_ISSET(Custom.getFlags(), OSFLAG_DISABLED)) { DBG("Custom legacy %zu skipped because it is disabled.\n", i); continue; } // if (!gSettings.ShowHiddenEntries && OSFLAG_ISSET(Custom.Flags, OSFLAG_HIDDEN)) { // DBG("Custom legacy %llu skipped because it is hidden.\n", i); // continue; // } if (Custom.settings.Volume.notEmpty()) { DBG("Custom legacy %zu matching \"%ls\" ...\n", i, Custom.settings.Volume.wc_str()); } for (VolumeIndex = 0; VolumeIndex < Volumes.size(); ++VolumeIndex) { Volume = &Volumes[VolumeIndex]; DBG(" Checking volume \"%ls\" (%ls) ... ", Volume->VolName.wc_str(), Volume->DevicePathString.wc_str()); // skip volume if its kind is configured as disabled if (((1ull<<Volume->DiskKind) & GlobalConfig.DisableFlags) != 0) { DBG("skipped because media is disabled\n"); continue; } if (Custom.settings.VolumeType != 0) { if (((1ull<<Volume->DiskKind) & Custom.settings.VolumeType) == 0) { DBG("skipped because media is ignored\n"); continue; } } if ((Volume->BootType != BOOTING_BY_PBR) && (Volume->BootType != BOOTING_BY_MBR) && (Volume->BootType != BOOTING_BY_CD)) { DBG("skipped because volume is not legacy bootable\n"); continue; } ShowVolume = false; HideIfOthersFound = false; if (Volume->IsAppleLegacy) { ShowVolume = true; HideIfOthersFound = true; } else if (Volume->HasBootCode) { ShowVolume = true; if ((Volume->WholeDiskBlockIO == 0) && Volume->BlockIOOffset == 0) { // this is a whole disk (MBR) entry; hide if we have entries for partitions HideIfOthersFound = true; } } if (HideIfOthersFound) { // check for other bootable entries on the same disk //if PBR exists then Hide MBR for (VolumeIndex2 = 0; VolumeIndex2 < Volumes.size(); VolumeIndex2++) { if (VolumeIndex2 != VolumeIndex && Volumes[VolumeIndex2].HasBootCode && Volumes[VolumeIndex2].WholeDiskBlockIO == Volume->BlockIO) { ShowVolume = false; break; } } } if ( !ShowVolume ) { DBG("skipped because volume ShowVolume==false\n"); continue; } if ( Volume->Hidden ) { DBG("skipped because volume is hidden\n"); continue; } // Check for exact volume matches if (Custom.settings.Volume.notEmpty()) { if ((StrStr(Volume->DevicePathString.wc_str(), Custom.settings.Volume.wc_str()) == NULL) && ((Volume->VolName.isEmpty()) || (StrStr(Volume->VolName.wc_str(), Custom.settings.Volume.wc_str()) == NULL))) { DBG("skipped\n"); continue; } // Check if the volume should be of certain os type if ((Custom.settings.Type != 0) && (Custom.settings.Type != Volume->LegacyOS->Type)) { DBG("skipped because wrong type\n"); continue; } } else if ((Custom.settings.Type != 0) && (Custom.settings.Type != Volume->LegacyOS->Type)) { DBG("skipped because wrong type\n"); continue; } // Change to custom image if needed MainIcon = Custom.Image; if (MainIcon.Image.isEmpty()) { MainIcon.Image.LoadXImage(&ThemeX.getThemeDir(), Custom.settings.ImagePath); } // Change to custom drive image if needed DriveIcon = Custom.DriveImage; if (DriveIcon.Image.isEmpty()) { DriveIcon.Image.LoadXImage(&ThemeX.getThemeDir(), Custom.settings.DriveImagePath); } // Create a legacy entry for this volume DBG("\n"); if (AddLegacyEntry(Custom.settings.FullTitle, Custom.settings.Title, Volume, &MainIcon, &DriveIcon, Custom.settings.Hotkey, true)) { // DBG("match!\n"); } } } //DBG("Custom legacy end\n"); }
39.05569
202
0.614445
harperse
ed93d24e740d446f00bec865166bd46f1da6ac20
2,308
cpp
C++
src/protocols/kde/decoration.cpp
Link1J/Awning
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
[ "MIT" ]
null
null
null
src/protocols/kde/decoration.cpp
Link1J/Awning
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
[ "MIT" ]
null
null
null
src/protocols/kde/decoration.cpp
Link1J/Awning
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
[ "MIT" ]
null
null
null
#include "decoration.hpp" #include <spdlog/spdlog.h> #include "protocols/wl/surface.hpp" namespace Awning::Protocols::KDE::Decoration { const struct org_kde_kwin_server_decoration_interface interface = { .release = Interface::Release, .request_mode = Interface::Request_Mode, }; std::unordered_map<wl_resource*,Instance> instances; namespace Interface { void Release(struct wl_client *client, struct wl_resource *resource) { } void Request_Mode(struct wl_client *client, struct wl_resource *resource, uint32_t mode) { auto surface = instances[resource].surface; WL::Surface::instances[surface].window->Frame(mode == ORG_KDE_KWIN_SERVER_DECORATION_MANAGER_MODE_SERVER); org_kde_kwin_server_decoration_send_mode(resource, mode); } } wl_resource* Create(struct wl_client* wl_client, uint32_t version, uint32_t id, wl_resource* surface) { struct wl_resource* resource = wl_resource_create(wl_client, &org_kde_kwin_server_decoration_interface, version, id); if (resource == nullptr) { wl_client_post_no_memory(wl_client); return resource; } wl_resource_set_implementation(resource, &interface, nullptr, Destroy); instances[resource].surface = surface; return resource; } void Destroy(struct wl_resource* resource) { } } namespace Awning::Protocols::KDE::Decoration_Manager { const struct org_kde_kwin_server_decoration_manager_interface interface = { .create = Interface::Create, }; namespace Interface { void Create(struct wl_client *client, struct wl_resource *resource, uint32_t id, struct wl_resource *surface) { Decoration::Create(client, 1, id, surface); } } void Bind(struct wl_client* wl_client, void* data, uint32_t version, uint32_t id) { struct wl_resource* resource = wl_resource_create(wl_client, &org_kde_kwin_server_decoration_manager_interface, version, id); if (resource == nullptr) { wl_client_post_no_memory(wl_client); return; } wl_resource_set_implementation(resource, &interface, data, nullptr); org_kde_kwin_server_decoration_manager_send_default_mode(resource, ORG_KDE_KWIN_SERVER_DECORATION_MANAGER_MODE_SERVER); } wl_global* Add(struct wl_display* display, void* data) { return wl_global_create(display, &org_kde_kwin_server_decoration_manager_interface, 1, data, Bind); } }
30.368421
127
0.774263
Link1J
ed94bbbde94044be0cca4333f3bd721277f2a4f6
2,642
cc
C++
content/renderer/dom_storage/webstoragearea_impl.cc
junmin-zhu/chromium-rivertrail
eb1a57aca71fe68d96e48af8998dcfbe45171ee1
[ "BSD-3-Clause" ]
5
2018-03-10T13:08:42.000Z
2021-07-26T15:02:11.000Z
content/renderer/dom_storage/webstoragearea_impl.cc
sanyaade-mobiledev/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
1
2015-07-21T08:02:01.000Z
2015-07-21T08:02:01.000Z
content/renderer/dom_storage/webstoragearea_impl.cc
jianglong0156/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
6
2016-11-14T10:13:35.000Z
2021-01-23T15:29:53.000Z
// Copyright (c) 2012 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 "content/renderer/dom_storage/webstoragearea_impl.h" #include "base/lazy_instance.h" #include "base/metrics/histogram.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "content/common/dom_storage_messages.h" #include "content/renderer/dom_storage/dom_storage_dispatcher.h" #include "content/renderer/render_thread_impl.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" #include "webkit/dom_storage/dom_storage_cached_area.h" using dom_storage::DomStorageCachedArea; using WebKit::WebString; using WebKit::WebURL; namespace content { namespace { typedef IDMap<WebStorageAreaImpl> AreaImplMap; base::LazyInstance<AreaImplMap>::Leaky g_all_areas_map = LAZY_INSTANCE_INITIALIZER; DomStorageDispatcher* dispatcher() { return RenderThreadImpl::current()->dom_storage_dispatcher(); } } // namespace // static WebStorageAreaImpl* WebStorageAreaImpl::FromConnectionId(int id) { return g_all_areas_map.Pointer()->Lookup(id); } WebStorageAreaImpl::WebStorageAreaImpl( int64 namespace_id, const GURL& origin) : ALLOW_THIS_IN_INITIALIZER_LIST( connection_id_(g_all_areas_map.Pointer()->Add(this))), cached_area_(dispatcher()-> OpenCachedArea(connection_id_, namespace_id, origin)) { } WebStorageAreaImpl::~WebStorageAreaImpl() { g_all_areas_map.Pointer()->Remove(connection_id_); if (dispatcher()) dispatcher()->CloseCachedArea(connection_id_, cached_area_); } unsigned WebStorageAreaImpl::length() { return cached_area_->GetLength(connection_id_); } WebString WebStorageAreaImpl::key(unsigned index) { return cached_area_->GetKey(connection_id_, index); } WebString WebStorageAreaImpl::getItem(const WebString& key) { return cached_area_->GetItem(connection_id_, key); } void WebStorageAreaImpl::setItem( const WebString& key, const WebString& value, const WebURL& page_url, WebStorageArea::Result& result) { if (!cached_area_->SetItem(connection_id_, key, value, page_url)) result = ResultBlockedByQuota; else result = ResultOK; } void WebStorageAreaImpl::removeItem( const WebString& key, const WebURL& page_url) { cached_area_->RemoveItem(connection_id_, key, page_url); } void WebStorageAreaImpl::clear(const WebURL& page_url) { cached_area_->Clear(connection_id_, page_url); } size_t WebStorageAreaImpl::memoryBytesUsedByCache() const { return cached_area_->MemoryBytesUsedByCache(); } } // namespace content
30.367816
77
0.774792
junmin-zhu
ed95a6a1373036eb62be5e560e77bcba19dc9d94
1,415
cpp
C++
network.cpp
rohith-nagamalla/Ooad_project
ffdc9e34153afe46dbb94061737e92642b186599
[ "Apache-2.0" ]
1
2019-11-28T13:48:45.000Z
2019-11-28T13:48:45.000Z
network.cpp
rohith-nagamalla/Ooad_project
ffdc9e34153afe46dbb94061737e92642b186599
[ "Apache-2.0" ]
null
null
null
network.cpp
rohith-nagamalla/Ooad_project
ffdc9e34153afe46dbb94061737e92642b186599
[ "Apache-2.0" ]
null
null
null
#ifndef network_cpp #define network_cpp #include<bits/stdc++.h> #include "customer.cpp" #include "utilities.cpp" using namespace std; namespace Network { string sms_otp(string name,string number) { string processed_name; for(int i=0;i<name.size() && name[i]!=' ';i++) processed_name.push_back(name[i]); string otp=Utilities::generate_otp(); string command="python3 sms_otp.py "+number+" "+otp+" "+processed_name; cout<<"> Sending OTP.............\n"; system(command.c_str()); fstream file(".junk"); int status; file>>status; if(status==-1) { cout<<"> OTP Sending Faliure. Please Check Your Network And Try Later.\n"; string empty; return empty; } cout<<"> OTP Sent Success\n"; return otp; } string mail_otp(string name,string email) { string processed_name; for(int i=0;i<name.size() && name[i]!=' ';i++) processed_name.push_back(name[i]); string otp=Utilities::generate_otp(); string command="python3 mail_otp.py "+email+" "+otp+" "+processed_name; cout<<"> Sending OTP.............\n"; system(command.c_str()); fstream file(".junk"); int status; file>>status; if(status==-1) { cout<<"> OTP Sending Faliure. Please Check Your Network And Try Later.\n"; string empty; return empty; } cout<<"> OTP Sent Success\n"; return otp; } }; #endif
26.203704
82
0.609894
rohith-nagamalla
ed95f18d3c589af673cf33428c51878f74a78973
8,236
cpp
C++
XivAlexanderLoader/App.cpp
ClarenceShalave/XivAlexander
c0f27cad381a48e097e5476e7cb7e2620b738ca7
[ "Apache-2.0" ]
1
2021-04-07T22:04:37.000Z
2021-04-07T22:04:37.000Z
XivAlexanderLoader/App.cpp
ClarenceShalave/XivAlexander
c0f27cad381a48e097e5476e7cb7e2620b738ca7
[ "Apache-2.0" ]
null
null
null
XivAlexanderLoader/App.cpp
ClarenceShalave/XivAlexander
c0f27cad381a48e097e5476e7cb7e2620b738ca7
[ "Apache-2.0" ]
null
null
null
#include "pch.h" static void* GetModulePointer(HANDLE hProcess, const wchar_t* sDllPath) { Utils::Win32Handle<> th32(CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetProcessId(hProcess))); MODULEENTRY32W mod{ sizeof MODULEENTRY32W }; if (!Module32FirstW(th32, &mod)) return nullptr; do { if (_wcsicmp(mod.szExePath, sDllPath) == 0) return mod.modBaseAddr; } while (Module32NextW(th32, &mod)); return nullptr; } static std::wstring GetProcessExecutablePath(HANDLE hProcess) { std::wstring sPath(PATHCCH_MAX_CCH, L'\0'); while (true) { auto length = static_cast<DWORD>(sPath.size()); QueryFullProcessImageNameW(hProcess, 0, &sPath[0], &length); if (length < sPath.size() - 1) { sPath.resize(length); break; } } return sPath; } static int CallRemoteFunction(HANDLE hProcess, void* rpfn, void* rpParam) { Utils::Win32Handle<> hLoadLibraryThread(CreateRemoteThread(hProcess, nullptr, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(rpfn), rpParam, 0, nullptr)); WaitForSingleObject(hLoadLibraryThread, INFINITE); DWORD exitCode; GetExitCodeThread(hLoadLibraryThread, &exitCode); return exitCode; } static int InjectDll(HANDLE hProcess, const wchar_t* pszDllPath) { const size_t nDllPathLength = wcslen(pszDllPath) + 1; if (GetModulePointer(hProcess, pszDllPath)) return 0; const auto nNumberOfBytes = nDllPathLength * sizeof pszDllPath[0]; void* rpszDllPath = VirtualAllocEx(hProcess, nullptr, nNumberOfBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (!rpszDllPath) return -1; if (!WriteProcessMemory(hProcess, rpszDllPath, pszDllPath, nNumberOfBytes, nullptr)) { VirtualFreeEx(hProcess, rpszDllPath, 0, MEM_RELEASE); return -1; } const auto exitCode = CallRemoteFunction(hProcess, LoadLibraryW, rpszDllPath); VirtualFreeEx(hProcess, rpszDllPath, 0, MEM_RELEASE); return exitCode; } BOOL SetPrivilege(HANDLE hToken, LPCTSTR Privilege, BOOL bEnablePrivilege) { TOKEN_PRIVILEGES tp; LUID luid; TOKEN_PRIVILEGES tpPrevious; DWORD cbPrevious = sizeof(TOKEN_PRIVILEGES); if (!LookupPrivilegeValue(NULL, Privilege, &luid)) return FALSE; // // first pass. get current privilege setting // tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = 0; AdjustTokenPrivileges( hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &tpPrevious, &cbPrevious ); if (GetLastError() != ERROR_SUCCESS) return FALSE; // // second pass. set privilege based on previous setting // tpPrevious.PrivilegeCount = 1; tpPrevious.Privileges[0].Luid = luid; if (bEnablePrivilege) tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED); else tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED & tpPrevious.Privileges[0].Attributes); AdjustTokenPrivileges( hToken, FALSE, &tpPrevious, cbPrevious, NULL, NULL); if (GetLastError() != ERROR_SUCCESS) return FALSE; return TRUE; } const char* AddDebugPrivilege() { Utils::Win32Handle<> token; { HANDLE hToken; if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)) { if (GetLastError() == ERROR_NO_TOKEN) { if (!ImpersonateSelf(SecurityImpersonation)) return "ImpersonateSelf"; if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)) { return "OpenThreadToken2"; } } else return "OpenThreadToken1"; } token = hToken; } if (!SetPrivilege(token, SE_DEBUG_NAME, TRUE)) return "SetPrivilege"; return nullptr; } void* FindModuleAddress(HANDLE hProcess, const wchar_t* szDllPath) { HMODULE hMods[1024]; DWORD cbNeeded; unsigned int i; bool skip = false; if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) { for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) { WCHAR szModName[MAX_PATH]; if (GetModuleFileNameExW(hProcess, hMods[i], szModName, MAX_PATH)) { if (wcsncmp(szModName, szDllPath, MAX_PATH) == 0) return hMods[i]; } } } return nullptr; } extern "C" __declspec(dllimport) int __stdcall LoadXivAlexander(void* lpReserved); extern "C" __declspec(dllimport) int __stdcall UnloadXivAlexander(void* lpReserved); int WINAPI wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nShowCmd ) { struct { bool noask = false; bool noerror = false; } params; int nArgs; LPWSTR *szArgList = CommandLineToArgvW(lpCmdLine, &nArgs); if (nArgs > 1) { for (int i = 1; i < nArgs; i++) { if (wcsncmp(L"/noask", szArgList[i], 6) == 0) params.noask = true; if (wcsncmp(L"/noerror", szArgList[i], 8) == 0) params.noerror = true; } } LocalFree(szArgList); DWORD pid; HWND hwnd = nullptr; wchar_t szDllPath[PATHCCH_MAX_CCH] = { 0 }; GetModuleFileNameW(nullptr, szDllPath, _countof(szDllPath)); PathCchRemoveFileSpec(szDllPath, _countof(szDllPath)); PathCchAppend(szDllPath, _countof(szDllPath), L"XivAlexander.dll"); const auto szDebugPrivError = AddDebugPrivilege(); const std::wstring ProcessName(L"ffxiv_dx11.exe"); bool found = false; while (hwnd = FindWindowExW(nullptr, hwnd, L"FFXIVGAME", nullptr)) { GetWindowThreadProcessId(hwnd, &pid); std::wstring sExePath; try { { Utils::Win32Handle<> hProcess(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid)); sExePath = GetProcessExecutablePath(hProcess); } if (sExePath.length() < ProcessName.length() || (0 != sExePath.compare(sExePath.length() - ProcessName.length(), ProcessName.length(), ProcessName))) continue; found = true; void* rpModule; { Utils::Win32Handle<> hProcess(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid)); rpModule = FindModuleAddress(hProcess, szDllPath); } std::wstring msg; UINT nMsgType; if (rpModule) { msg = Utils::FormatString( L"XivAlexander detected in FFXIV Process (%d:%s)\n" L"Press Yes to try loading again if it hasn't loaded properly,\n" L"Press No to skip,\n" L"Press Cancel to unload.\n" L"\n" L"Note: your anti-virus software will probably classify DLL injection as a malicious action, " L"and you will have to add both XivAlexanderLoader.exe and XivAlexander.dll to exceptions.", static_cast<int>(pid), sExePath.c_str()); nMsgType = (MB_YESNOCANCEL | MB_ICONQUESTION | MB_DEFBUTTON1); } else { msg = Utils::FormatString( L"FFXIV Process found (%d:%s)\n" L"Continue loading XivAlexander into this process?\n" L"\n" L"Note: your anti-virus software will probably classify DLL injection as a malicious action, " L"and you will have to add both XivAlexanderLoader.exe and XivAlexander.dll to exceptions.", static_cast<int>(pid), sExePath.c_str()); nMsgType = (MB_YESNO | MB_DEFBUTTON1); } int response = params.noask ? IDYES : MessageBoxW(nullptr, msg.c_str(), L"XivAlexander Loader", nMsgType); if (response == IDNO) continue; { Utils::Win32Handle<> hProcess(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, false, pid)); rpModule = FindModuleAddress(hProcess, szDllPath); if (response == IDCANCEL && !rpModule) continue; if (!rpModule) { InjectDll(hProcess, szDllPath); rpModule = FindModuleAddress(hProcess, szDllPath); } DWORD loadResult = 0; if (response == IDYES) { loadResult = CallRemoteFunction(hProcess, LoadXivAlexander, nullptr); if (loadResult != 0) { response = IDCANCEL; } } if (response == IDCANCEL) { if (CallRemoteFunction(hProcess, UnloadXivAlexander, nullptr)) { CallRemoteFunction(hProcess, FreeLibrary, rpModule); } } if (loadResult) throw std::exception(Utils::FormatString("Failed to start the addon: %d", loadResult).c_str()); } } catch (std::exception& e) { if (!params.noerror) MessageBoxW(nullptr, Utils::FromUtf8(Utils::FormatString("PID %d: %s\nDebug Privilege: %s", pid, e.what(), szDebugPrivError ? szDebugPrivError : "OK")).c_str(), L"Error", MB_OK | MB_ICONERROR); } } if (!found) { if (!params.noerror) MessageBoxW(nullptr, L"ffxiv_dx11.exe not found", L"Error", MB_OK | MB_ICONERROR); } return 0; }
30.6171
197
0.711875
ClarenceShalave
ed97526dd2144357bba8959470a4c497127b9181
3,029
cpp
C++
src/PE/CodeIntegrity.cpp
ienho/LIEF
29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8
[ "Apache-2.0" ]
2
2021-12-31T07:25:05.000Z
2022-03-05T15:03:00.000Z
src/PE/CodeIntegrity.cpp
ienho/LIEF
29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8
[ "Apache-2.0" ]
null
null
null
src/PE/CodeIntegrity.cpp
ienho/LIEF
29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 - 2021 R. Thomas * Copyright 2017 - 2021 Quarkslab * * 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 <numeric> #include <iomanip> #include <sstream> #include "LIEF/PE/hash.hpp" #include "LIEF/PE/Structures.hpp" #include "LIEF/PE/EnumToString.hpp" #include "LIEF/PE/CodeIntegrity.hpp" namespace LIEF { namespace PE { CodeIntegrity::~CodeIntegrity() = default; CodeIntegrity& CodeIntegrity::operator=(const CodeIntegrity&) = default; CodeIntegrity::CodeIntegrity(const CodeIntegrity&) = default; CodeIntegrity::CodeIntegrity() : flags_{0}, catalog_{0}, catalog_offset_{0}, reserved_{0} {} CodeIntegrity::CodeIntegrity(const pe_code_integrity *header) : flags_{header->Flags}, catalog_{header->Catalog}, catalog_offset_{header->CatalogOffset}, reserved_{header->Reserved} {} uint16_t CodeIntegrity::flags() const { return this->flags_; } uint16_t CodeIntegrity::catalog() const { return this->catalog_; } uint32_t CodeIntegrity::catalog_offset() const { return this->catalog_offset_; } uint32_t CodeIntegrity::reserved() const { return this->reserved_; } void CodeIntegrity::flags(uint16_t flags) { this->flags_ = flags; } void CodeIntegrity::catalog(uint16_t catalog) { this->catalog_ = catalog; } void CodeIntegrity::catalog_offset(uint32_t catalog_offset) { this->catalog_offset_ = catalog_offset; } void CodeIntegrity::reserved(uint32_t reserved) { this->reserved_ = reserved; } void CodeIntegrity::accept(LIEF::Visitor& visitor) const { visitor.visit(*this); } bool CodeIntegrity::operator==(const CodeIntegrity& rhs) const { size_t hash_lhs = Hash::hash(*this); size_t hash_rhs = Hash::hash(rhs); return hash_lhs == hash_rhs; } bool CodeIntegrity::operator!=(const CodeIntegrity& rhs) const { return not (*this == rhs); } std::ostream& operator<<(std::ostream& os, const CodeIntegrity& entry) { os << std::hex << std::left << std::showbase; os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Flags:" << std::hex << entry.flags() << std::endl; os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Catalog:" << std::hex << entry.catalog() << std::endl; os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Catalog offset:" << std::hex << entry.catalog_offset() << std::endl; os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Reserved:" << std::hex << entry.reserved() << std::endl; return os; } } }
28.308411
139
0.699241
ienho
ed97f70765144ce53e7f800ea9feee523b65f31d
12,218
cc
C++
src/video/FBPostProcessor.cc
D15C0DE/openMSX
5119a9657de4b82115c745f670cdc55dc7363133
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/video/FBPostProcessor.cc
D15C0DE/openMSX
5119a9657de4b82115c745f670cdc55dc7363133
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/video/FBPostProcessor.cc
D15C0DE/openMSX
5119a9657de4b82115c745f670cdc55dc7363133
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#include "FBPostProcessor.hh" #include "RawFrame.hh" #include "StretchScalerOutput.hh" #include "ScalerOutput.hh" #include "RenderSettings.hh" #include "Scaler.hh" #include "ScalerFactory.hh" #include "SDLOutputSurface.hh" #include "aligned.hh" #include "checked_cast.hh" #include "random.hh" #include "xrange.hh" #include <algorithm> #include <cassert> #include <cmath> #include <cstdint> #include <cstddef> #include <numeric> #ifdef __SSE2__ #include <emmintrin.h> #endif namespace openmsx { constexpr unsigned NOISE_SHIFT = 8192; constexpr unsigned NOISE_BUF_SIZE = 2 * NOISE_SHIFT; ALIGNAS_SSE static signed char noiseBuf[NOISE_BUF_SIZE]; template<typename Pixel> void FBPostProcessor<Pixel>::preCalcNoise(float factor) { // We skip noise drawing if the factor is 0, so there is no point in // initializing the random data in that case. if (factor == 0.0f) return; // for 32bpp groups of 4 consecutive noiseBuf elements (starting at // 4 element boundaries) must have the same value. Later optimizations // depend on it. float scale[4]; if (sizeof(Pixel) == 4) { // 32bpp // TODO ATM we compensate for big endian here. A better // alternative is to turn noiseBuf into an array of ints (it's // now bytes) and in the 16bpp code extract R,G,B components // from those ints const auto p = Pixel(OPENMSX_BIGENDIAN ? 0x00010203 : 0x03020100); // TODO we can also fill the array with 'factor' and only set // 'alpha' to 0.0. But PixelOperations doesn't offer a simple // way to get the position of the alpha byte (yet). scale[0] = scale[1] = scale[2] = scale[3] = 0.0f; scale[pixelOps.red (p)] = factor; scale[pixelOps.green(p)] = factor; scale[pixelOps.blue (p)] = factor; } else { // 16bpp scale[0] = (pixelOps.getMaxRed() / 255.0f) * factor; scale[1] = (pixelOps.getMaxGreen() / 255.0f) * factor; scale[2] = (pixelOps.getMaxBlue() / 255.0f) * factor; scale[3] = 0.0f; } auto& generator = global_urng(); // fast (non-cryptographic) random numbers std::normal_distribution<float> distribution(0.0f, 1.0f); for (unsigned i = 0; i < NOISE_BUF_SIZE; i += 4) { float r = distribution(generator); noiseBuf[i + 0] = std::clamp(int(roundf(r * scale[0])), -128, 127); noiseBuf[i + 1] = std::clamp(int(roundf(r * scale[1])), -128, 127); noiseBuf[i + 2] = std::clamp(int(roundf(r * scale[2])), -128, 127); noiseBuf[i + 3] = std::clamp(int(roundf(r * scale[3])), -128, 127); } } #ifdef __SSE2__ static inline void drawNoiseLineSse2(uint32_t* buf_, signed char* noise, size_t width) { // To each of the RGBA color components (a value in range [0..255]) we // want to add a signed noise value (in range [-128..127]) and also clip // the result to the range [0..255]. There is no SSE instruction that // directly performs this operation. But we can: // - subtract 128 from the RGBA component to get a signed byte // - perform the addition with signed saturation // - add 128 to the result to get back to the unsigned byte range // For 8-bit values the following 3 expressions are equivalent: // x + 128 == x - 128 == x ^ 128 // So the expression becomes: // signed_add_sat(value ^ 128, noise) ^ 128 // The following loop does just that, though it processes 64 bytes per // iteration. ptrdiff_t x = width * sizeof(uint32_t); assert((x & 63) == 0); assert((uintptr_t(buf_) & 15) == 0); char* buf = reinterpret_cast<char*>(buf_) + x; char* nse = reinterpret_cast<char*>(noise) + x; x = -x; __m128i b7 = _mm_set1_epi8(-128); // 0x80 do { __m128i i0 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 0)); __m128i i1 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 16)); __m128i i2 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 32)); __m128i i3 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 48)); __m128i n0 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 0)); __m128i n1 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 16)); __m128i n2 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 32)); __m128i n3 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 48)); __m128i o0 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i0, b7), n0), b7); __m128i o1 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i1, b7), n1), b7); __m128i o2 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i2, b7), n2), b7); __m128i o3 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i3, b7), n3), b7); _mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 0), o0); _mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 16), o1); _mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 32), o2); _mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 48), o3); x += 4 * sizeof(__m128i); } while (x < 0); } #endif /** Add noise to the given pixel. * @param p contains 4 8-bit unsigned components, so components have range [0, 255] * @param n contains 4 8-bit signed components, so components have range [-128, 127] * @result per component result of clip<0, 255>(p + n) */ static constexpr uint32_t addNoise4(uint32_t p, uint32_t n) { // unclipped result (lower 8 bits of each component) // alternative: // uint32_t s20 = ((p & 0x00FF00FF) + (n & 0x00FF00FF)) & 0x00FF00FF; // uint32_t s31 = ((p & 0xFF00FF00) + (n & 0xFF00FF00)) & 0xFF00FF00; // uint32_t s = s20 | s31; uint32_t s0 = p + n; // carry spills to neighbors uint32_t ci = (p ^ n ^ s0) & 0x01010100; // carry-in bits of prev sum uint32_t s = s0 - ci; // subtract carry bits again // Underflow of a component happens ONLY // WHEN input component is in range [0, 127] // AND noise component is negative // AND result component is in range [128, 255] // Overflow of a component happens ONLY // WHEN input component in in range [128, 255] // AND noise component is positive // AND result component is in range [0, 127] // Create a mask per component containing 00 for no under/overflow, // FF for under/overflow // ((~p & n & s) | (p & ~n & ~s)) == ((p ^ n) & (p ^ s)) uint32_t t = (p ^ n) & (p ^ s) & 0x80808080; uint32_t u1 = t & s; // underflow (alternative: u1 = t & n) // alternative1: uint32_t u2 = u1 | (u1 >> 1); // uint32_t u4 = u2 | (u2 >> 2); // uint32_t u8 = u4 | (u4 >> 4); // alternative2: uint32_t u8 = (u1 >> 7) * 0xFF; uint32_t u8 = (u1 << 1) - (u1 >> 7); uint32_t o1 = t & p; // overflow uint32_t o8 = (o1 << 1) - (o1 >> 7); // clip result return (s & (~u8)) | o8; } template<typename Pixel> void FBPostProcessor<Pixel>::drawNoiseLine( Pixel* buf, signed char* noise, size_t width) { #ifdef __SSE2__ if (sizeof(Pixel) == 4) { // cast to avoid compilation error in case of 16bpp (even // though this code is dead in that case). auto* buf32 = reinterpret_cast<uint32_t*>(buf); drawNoiseLineSse2(buf32, noise, width); return; } #endif // c++ version if (sizeof(Pixel) == 4) { // optimized version for 32bpp auto* noise4 = reinterpret_cast<uint32_t*>(noise); for (auto i : xrange(width)) { buf[i] = addNoise4(buf[i], noise4[i]); } } else { int mr = pixelOps.getMaxRed(); int mg = pixelOps.getMaxGreen(); int mb = pixelOps.getMaxBlue(); for (auto i : xrange(width)) { Pixel p = buf[i]; int r = pixelOps.red(p); int g = pixelOps.green(p); int b = pixelOps.blue(p); r += noise[4 * i + 0]; g += noise[4 * i + 1]; b += noise[4 * i + 2]; r = std::min(std::max(r, 0), mr); g = std::min(std::max(g, 0), mg); b = std::min(std::max(b, 0), mb); buf[i] = pixelOps.combine(r, g, b); } } } template<typename Pixel> void FBPostProcessor<Pixel>::drawNoise(OutputSurface& output_) { if (renderSettings.getNoise() == 0.0f) return; auto& output = checked_cast<SDLOutputSurface&>(output_); auto [w, h] = output.getLogicalSize(); auto pixelAccess = output.getDirectPixelAccess(); for (auto y : xrange(h)) { auto* buf = pixelAccess.getLinePtr<Pixel>(y); drawNoiseLine(buf, &noiseBuf[noiseShift[y]], w); } } template<typename Pixel> void FBPostProcessor<Pixel>::update(const Setting& setting) noexcept { VideoLayer::update(setting); auto& noiseSetting = renderSettings.getNoiseSetting(); if (&setting == &noiseSetting) { preCalcNoise(noiseSetting.getDouble()); } } template<typename Pixel> FBPostProcessor<Pixel>::FBPostProcessor(MSXMotherBoard& motherBoard_, Display& display_, OutputSurface& screen_, const std::string& videoSource, unsigned maxWidth_, unsigned height_, bool canDoInterlace_) : PostProcessor( motherBoard_, display_, screen_, videoSource, maxWidth_, height_, canDoInterlace_) , noiseShift(screen.getLogicalHeight()) , pixelOps(screen.getPixelFormat()) { scaleAlgorithm = RenderSettings::NO_SCALER; scaleFactor = unsigned(-1); stretchWidth = unsigned(-1); auto& noiseSetting = renderSettings.getNoiseSetting(); noiseSetting.attach(*this); preCalcNoise(noiseSetting.getDouble()); assert((screen.getLogicalWidth() * sizeof(Pixel)) < NOISE_SHIFT); } template<typename Pixel> FBPostProcessor<Pixel>::~FBPostProcessor() { renderSettings.getNoiseSetting().detach(*this); } template<typename Pixel> void FBPostProcessor<Pixel>::paint(OutputSurface& output_) { auto& output = checked_cast<SDLOutputSurface&>(output_); if (renderSettings.getInterleaveBlackFrame()) { interleaveCount ^= 1; if (interleaveCount) { output.clearScreen(); return; } } if (!paintFrame) return; // New scaler algorithm selected? Or different horizontal stretch? auto algo = renderSettings.getScaleAlgorithm(); unsigned factor = renderSettings.getScaleFactor(); unsigned inWidth = lrintf(renderSettings.getHorizontalStretch()); if ((scaleAlgorithm != algo) || (scaleFactor != factor) || (inWidth != stretchWidth) || (lastOutput != &output)) { scaleAlgorithm = algo; scaleFactor = factor; stretchWidth = inWidth; lastOutput = &output; currScaler = ScalerFactory<Pixel>::createScaler( PixelOperations<Pixel>(output.getPixelFormat()), renderSettings); stretchScaler = StretchScalerOutputFactory<Pixel>::create( output, pixelOps, inWidth); } // Scale image. const unsigned srcHeight = paintFrame->getHeight(); const unsigned dstHeight = output.getLogicalHeight(); unsigned g = std::gcd(srcHeight, dstHeight); unsigned srcStep = srcHeight / g; unsigned dstStep = dstHeight / g; // TODO: Store all MSX lines in RawFrame and only scale the ones that fit // on the PC screen, as a preparation for resizable output window. unsigned srcStartY = 0; unsigned dstStartY = 0; while (dstStartY < dstHeight) { // Currently this is true because the source frame height // is always >= dstHeight/(dstStep/srcStep). assert(srcStartY < srcHeight); // get region with equal lineWidth unsigned lineWidth = getLineWidth(paintFrame, srcStartY, srcStep); unsigned srcEndY = srcStartY + srcStep; unsigned dstEndY = dstStartY + dstStep; while ((srcEndY < srcHeight) && (dstEndY < dstHeight) && (getLineWidth(paintFrame, srcEndY, srcStep) == lineWidth)) { srcEndY += srcStep; dstEndY += dstStep; } // fill region //fprintf(stderr, "post processing lines %d-%d: %d\n", // srcStartY, srcEndY, lineWidth); currScaler->scaleImage( *paintFrame, superImposeVideoFrame, srcStartY, srcEndY, lineWidth, // source *stretchScaler, dstStartY, dstEndY); // dest // next region srcStartY = srcEndY; dstStartY = dstEndY; } drawNoise(output); output.flushFrameBuffer(); } template<typename Pixel> std::unique_ptr<RawFrame> FBPostProcessor<Pixel>::rotateFrames( std::unique_ptr<RawFrame> finishedFrame, EmuTime::param time) { auto& generator = global_urng(); // fast (non-cryptographic) random numbers std::uniform_int_distribution<int> distribution(0, NOISE_SHIFT / 16 - 1); for (auto y : xrange(screen.getLogicalHeight())) { noiseShift[y] = distribution(generator) * 16; } return PostProcessor::rotateFrames(std::move(finishedFrame), time); } // Force template instantiation. #if HAVE_16BPP template class FBPostProcessor<uint16_t>; #endif #if HAVE_32BPP template class FBPostProcessor<uint32_t>; #endif } // namespace openmsx
34.22409
86
0.681863
D15C0DE
ed99985d7d4633f995927ad9b442b3d26e063028
6,827
cc
C++
RecoParticleFlow/PFClusterProducer/plugins/Basic2DGenericPFlowPositionCalc.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
RecoParticleFlow/PFClusterProducer/plugins/Basic2DGenericPFlowPositionCalc.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
RecoParticleFlow/PFClusterProducer/plugins/Basic2DGenericPFlowPositionCalc.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "Basic2DGenericPFlowPositionCalc.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Utilities/interface/isFinite.h" #include <cmath> #include "CommonTools/Utils/interface/DynArray.h" #include<iterator> #include <boost/function_output_iterator.hpp> #include "vdt/vdtMath.h" namespace { inline bool isBarrel(int cell_layer){ return (cell_layer == PFLayer::HCAL_BARREL1 || cell_layer == PFLayer::HCAL_BARREL2 || cell_layer == PFLayer::ECAL_BARREL); } } void Basic2DGenericPFlowPositionCalc:: calculateAndSetPosition(reco::PFCluster& cluster) { calculateAndSetPositionActual(cluster); } void Basic2DGenericPFlowPositionCalc:: calculateAndSetPositions(reco::PFClusterCollection& clusters) { for( reco::PFCluster& cluster : clusters ) { calculateAndSetPositionActual(cluster); } } void Basic2DGenericPFlowPositionCalc:: calculateAndSetPositionActual(reco::PFCluster& cluster) const { if( !cluster.seed() ) { throw cms::Exception("ClusterWithNoSeed") << " Found a cluster with no seed: " << cluster; } double cl_energy = 0; double cl_time = 0; double cl_timeweight=0.0; double max_e = 0.0; PFLayer::Layer max_e_layer = PFLayer::NONE; // find the seed and max layer and also calculate time //Michalis : Even if we dont use timing in clustering here we should fill //the time information for the cluster. This should use the timing resolution(1/E) //so the weight should be fraction*E^2 //calculate a simplistic depth now. The log weighted will be done //in different stage auto const recHitCollection = &(*cluster.recHitFractions()[0].recHitRef()) - cluster.recHitFractions()[0].recHitRef().key(); auto nhits = cluster.recHitFractions().size(); struct LHit{ reco::PFRecHit const * hit; float energy; float fraction;}; declareDynArray(LHit,nhits,hits); for(auto i=0U; i<nhits; ++i) { auto const & hf = cluster.recHitFractions()[i]; auto k = hf.recHitRef().key(); auto p = recHitCollection+k; hits[i]= {p,(*p).energy(), float(hf.fraction())}; } bool resGiven = bool(_timeResolutionCalcBarrel) & bool(_timeResolutionCalcEndcap); LHit mySeed={nullptr}; for( auto const & rhf : hits ) { const reco::PFRecHit & refhit = *rhf.hit; if( refhit.detId() == cluster.seed() ) mySeed = rhf; const auto rh_fraction = rhf.fraction; const auto rh_rawenergy = rhf.energy; const auto rh_energy = rh_rawenergy * rh_fraction; #ifdef PF_DEBUG if UNLIKELY( edm::isNotFinite(rh_energy) ) { throw cms::Exception("PFClusterAlgo") <<"rechit " << refhit.detId() << " has a NaN energy... " << "The input of the particle flow clustering seems to be corrupted."; } #endif cl_energy += rh_energy; // If time resolution is given, calculated weighted average if ( resGiven ) { double res2 = 1.e-4; int cell_layer = (int)refhit.layer(); res2 = isBarrel(cell_layer) ? 1./_timeResolutionCalcBarrel->timeResolution2(rh_rawenergy) : 1./_timeResolutionCalcEndcap->timeResolution2(rh_rawenergy); cl_time += rh_fraction*refhit.time()*res2; cl_timeweight += rh_fraction*res2; } else { // assume resolution = 1/E**2 const double rh_rawenergy2 = rh_rawenergy*rh_rawenergy; cl_timeweight+=rh_rawenergy2*rh_fraction; cl_time += rh_rawenergy2*rh_fraction*refhit.time(); } if( rh_energy > max_e ) { max_e = rh_energy; max_e_layer = refhit.layer(); } } cluster.setEnergy(cl_energy); cluster.setTime(cl_time/cl_timeweight); if (resGiven) { cluster.setTimeError(std::sqrt(1.0f/float(cl_timeweight))); } cluster.setLayer(max_e_layer); // calculate the position double depth = 0.0; double position_norm = 0.0; double x(0.0),y(0.0),z(0.0); if( nullptr != mySeed.hit ) { auto seedNeighbours = mySeed.hit->neighbours(); switch( _posCalcNCrystals ) { case 5: seedNeighbours = mySeed.hit->neighbours4(); break; case 9: seedNeighbours = mySeed.hit->neighbours8(); break; default: break; } auto compute = [&](LHit const& rhf) { const reco::PFRecHit & refhit = *rhf.hit; int cell_layer = (int)refhit.layer(); float threshold=0; for (unsigned int j=0; j<(std::get<2>(_logWeightDenom)).size(); ++j) { // barrel is detecor type1 int detectorEnum=std::get<0>(_logWeightDenom)[j]; int depth=std::get<1>(_logWeightDenom)[j]; if( ( cell_layer == PFLayer::HCAL_BARREL1 && detectorEnum==1 && refhit.depth()== depth) || ( cell_layer == PFLayer::HCAL_ENDCAP && detectorEnum==2 && refhit.depth()== depth) || detectorEnum==0 ) threshold=std::get<2>(_logWeightDenom)[j]; } const auto rh_energy = rhf.energy * rhf.fraction; const auto norm = ( rhf.fraction < _minFractionInCalc ? 0.0f : std::max(0.0f,vdt::fast_logf(rh_energy*threshold)) ); const auto rhpos_xyz = refhit.position()*norm; x += rhpos_xyz.x(); y += rhpos_xyz.y(); z += rhpos_xyz.z(); depth += refhit.depth()*norm; position_norm += norm; }; if(_posCalcNCrystals != -1) // sorted to make neighbour search faster (maybe) std::sort(hits.begin(),hits.end(),[](LHit const& a, LHit const& b) { return a.hit<b.hit;}); if(_posCalcNCrystals == -1) for( auto const & rhf : hits ) compute(rhf); else { // only seed and its neighbours compute(mySeed); // search seedNeighbours to find energy fraction in cluster (sic) unInitDynArray(reco::PFRecHit const *,seedNeighbours.size(),nei); for(auto k : seedNeighbours){ nei.push_back(recHitCollection+k); } std::sort(nei.begin(),nei.end()); struct LHitLess { auto operator()(LHit const &a, reco::PFRecHit const * b) const {return a.hit<b;} auto operator()(reco::PFRecHit const * b, LHit const &a) const {return b<a.hit;} }; std::set_intersection(hits.begin(),hits.end(),nei.begin(),nei.end(), boost::make_function_output_iterator(compute), LHitLess() ); } } else { throw cms::Exception("Basic2DGenerticPFlowPositionCalc") << "Cluster seed hit is null, something is wrong with PFlow RecHit!"; } if( position_norm < _minAllowedNorm ) { edm::LogError("WeirdClusterNormalization") << "PFCluster too far from seeding cell: set position to (0,0,0)."; cluster.setPosition(math::XYZPoint(0,0,0)); cluster.calculatePositionREP(); } else { const double norm_inverse = 1.0/position_norm; x *= norm_inverse; y *= norm_inverse; z *= norm_inverse; depth *= norm_inverse; cluster.setPosition(math::XYZPoint(x,y,z)); cluster.setDepth(depth); cluster.calculatePositionREP(); } }
33.79703
126
0.661198
nistefan
ed99ea5cbdebc35466252de3163fb7e0094d3d32
8,223
cpp
C++
OpenSees/SRC/material/nD/J2PlaneStrain.cpp
kuanshi/ductile-fracture
ccb350564df54f5c5ec3a079100effe261b46650
[ "MIT" ]
8
2019-03-05T16:25:10.000Z
2020-04-17T14:12:03.000Z
SRC/material/nD/J2PlaneStrain.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
null
null
null
SRC/material/nD/J2PlaneStrain.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
3
2019-09-21T03:11:11.000Z
2020-01-19T07:29:37.000Z
/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** ****************************************************************** */ // $Revision: 1.7 $ // $Date: 2008-10-20 22:23:03 $ // $Source: /usr/local/cvs/OpenSees/SRC/material/nD/J2PlaneStrain.cpp,v $ // Written: Ed "C++" Love // // J2PlaneStrain isotropic hardening material class // // Elastic Model // sigma = K*trace(epsilion_elastic) + (2*G)*dev(epsilon_elastic) // // Yield Function // phi(sigma,q) = || dev(sigma) || - sqrt(2/3)*q(xi) // // Saturation Isotropic Hardening with linear term // q(xi) = simga_infty + (sigma_0 - sigma_infty)*exp(-delta*xi) + H*xi // // Flow Rules // \dot{epsilon_p} = gamma * d_phi/d_sigma // \dot{xi} = -gamma * d_phi/d_q // // Linear Viscosity // gamma = phi / eta ( if phi > 0 ) // // Backward Euler Integration Routine // Yield condition enforced at time n+1 // // Send strains in following format : // // strain_vec = { eps_00 // eps_11 // 2 eps_01 } <--- note the 2 // // set eta := 0 for rate independent case // #include <J2PlaneStrain.h> #include <Channel.h> #include <FEM_ObjectBroker.h> //static vectors and matrices Vector J2PlaneStrain :: strain_vec(3) ; Vector J2PlaneStrain :: stress_vec(3) ; Matrix J2PlaneStrain :: tangent_matrix(3,3) ; //null constructor J2PlaneStrain :: J2PlaneStrain( ) : J2Plasticity( ) { } //full constructor J2PlaneStrain :: J2PlaneStrain( int tag, double K, double G, double yield0, double yield_infty, double d, double H, double viscosity, double rho) : J2Plasticity( tag, ND_TAG_J2PlaneStrain, K, G, yield0, yield_infty, d, H, viscosity, rho ) { } //elastic constructor J2PlaneStrain :: J2PlaneStrain( int tag, double K, double G ) : J2Plasticity( tag, ND_TAG_J2PlaneStrain, K, G ) { } //destructor J2PlaneStrain :: ~J2PlaneStrain( ) { } //make a clone of this material NDMaterial* J2PlaneStrain :: getCopy( ) { J2PlaneStrain *clone; clone = new J2PlaneStrain() ; //new instance of this class *clone = *this ; //asignment to make copy return clone ; } //send back type of material const char* J2PlaneStrain :: getType( ) const { return "PlaneStrain" ; } //send back order of strain in vector form int J2PlaneStrain :: getOrder( ) const { return 3 ; } //get the strain and integrate plasticity equations int J2PlaneStrain :: setTrialStrain( const Vector &strain_from_element) { strain.Zero( ) ; strain(0,0) = strain_from_element(0) ; strain(1,1) = strain_from_element(1) ; strain(0,1) = 0.50 * strain_from_element(2) ; strain(1,0) = strain(0,1) ; this->plastic_integrator( ) ; return 0 ; } //unused trial strain functions int J2PlaneStrain :: setTrialStrain( const Vector &v, const Vector &r ) { return this->setTrialStrain( v ) ; } int J2PlaneStrain :: setTrialStrainIncr( const Vector &v ) { static Vector newStrain(3); newStrain(0) = strain(0,0) + v(0); newStrain(1) = strain(1,1) + v(1); newStrain(2) = 2.0 * strain(0,1) + v(2); return this->setTrialStrain(newStrain); } int J2PlaneStrain :: setTrialStrainIncr( const Vector &v, const Vector &r ) { return this->setTrialStrainIncr(v); } //send back the strain const Vector& J2PlaneStrain :: getStrain( ) { strain_vec(0) = strain(0,0) ; strain_vec(1) = strain(1,1) ; strain_vec(2) = 2.0 * strain(0,1) ; return strain_vec ; } //send back the stress const Vector& J2PlaneStrain :: getStress( ) { stress_vec(0) = stress(0,0) ; stress_vec(1) = stress(1,1) ; stress_vec(2) = stress(0,1) ; return stress_vec ; } //send back the tangent const Matrix& J2PlaneStrain :: getTangent( ) { // matrix to tensor mapping // Matrix Tensor // ------- ------- // 0 0 0 // 1 1 1 // 2 0 1 ( or 1 0 ) // tangent_matrix(0,0) = tangent [0][0] [0][0] ; tangent_matrix(1,1) = tangent [1][1] [1][1] ; tangent_matrix(2,2) = tangent [0][1] [0][1] ; tangent_matrix(0,1) = tangent [0][0] [1][1] ; tangent_matrix(1,0) = tangent [1][1] [0][0] ; tangent_matrix(0,2) = tangent [0][0] [0][1] ; tangent_matrix(2,0) = tangent [0][1] [0][0] ; tangent_matrix(1,2) = tangent [1][1] [0][1] ; tangent_matrix(2,1) = tangent [0][1] [1][1] ; return tangent_matrix ; } //send back the tangent const Matrix& J2PlaneStrain :: getInitialTangent( ) { // matrix to tensor mapping // Matrix Tensor // ------- ------- // 0 0 0 // 1 1 1 // 2 0 1 ( or 1 0 ) // this->doInitialTangent(); tangent_matrix(0,0) = initialTangent [0][0] [0][0] ; tangent_matrix(1,1) = initialTangent [1][1] [1][1] ; tangent_matrix(2,2) = initialTangent [0][1] [0][1] ; tangent_matrix(0,1) = initialTangent [0][0] [1][1] ; tangent_matrix(1,0) = initialTangent [1][1] [0][0] ; tangent_matrix(0,2) = initialTangent [0][0] [0][1] ; tangent_matrix(2,0) = initialTangent [0][1] [0][0] ; tangent_matrix(1,2) = initialTangent [1][1] [0][1] ; tangent_matrix(2,1) = initialTangent [0][1] [1][1] ; return tangent_matrix ; } int J2PlaneStrain::commitState( ) { epsilon_p_n = epsilon_p_nplus1; xi_n = xi_nplus1; return 0; } int J2PlaneStrain::revertToLastCommit( ) { return 0; } int J2PlaneStrain::revertToStart( ) { this->zero( ) ; return 0; } int J2PlaneStrain::sendSelf (int commitTag, Channel &theChannel) { // we place all the data needed to define material and it's state // int a vector object static Vector data(19); int cnt = 0; data(cnt++) = this->getTag(); data(cnt++) = bulk; data(cnt++) = shear; data(cnt++) = sigma_0; data(cnt++) = sigma_infty; data(cnt++) = delta; data(cnt++) = Hard; data(cnt++) = eta; data(cnt++) = rho; data(cnt++) = xi_n; // data(cnt++) = commitEps22; for (int i=0; i<3; i++) for (int j=0; j<3; j++) data(cnt++) = epsilon_p_n(i,j); // send the vector object to the channel if (theChannel.sendVector(this->getDbTag(), commitTag, data) < 0) { opserr << "J2PlaneStrain::sendSelf - failed to send vector to channel\n"; return -1; } return 0; } int J2PlaneStrain::recvSelf (int commitTag, Channel &theChannel, FEM_ObjectBroker &theBroker) { // recv the vector object from the channel which defines material param and state static Vector data(19); if (theChannel.recvVector(this->getDbTag(), commitTag, data) < 0) { opserr << "J2PlaneStrain::recvSelf - failed to sned vectorto channel\n"; return -1; } // set the material parameters and state variables int cnt = 0; this->setTag(data(cnt++)); bulk = data(cnt++); shear = data(cnt++); sigma_0 = data(cnt++); sigma_infty = data(cnt++); delta = data(cnt++); Hard = data(cnt++); eta = data(cnt++); rho = data(cnt++); xi_n = data(cnt++); for (int i=0; i<3; i++) for (int j=0; j<3; j++) epsilon_p_n(i,j) = data(cnt++); epsilon_p_nplus1 = epsilon_p_n; xi_nplus1 = xi_n; return 0; }
23.973761
83
0.563055
kuanshi
ed9b56a08d18cd0d8b4728595e32efa030bbd3ac
103
cpp
C++
prototypes_cinder/PinballWarping/xcode/Location.cpp
redpaperheart/pinball_dreams
f1b873dc451157d9f2987501080a907635c80350
[ "Unlicense" ]
1
2016-07-29T21:19:12.000Z
2016-07-29T21:19:12.000Z
prototypes_cinder/PinballWarping/xcode/Location.cpp
redpaperheart/pinball_dreams
f1b873dc451157d9f2987501080a907635c80350
[ "Unlicense" ]
null
null
null
prototypes_cinder/PinballWarping/xcode/Location.cpp
redpaperheart/pinball_dreams
f1b873dc451157d9f2987501080a907635c80350
[ "Unlicense" ]
null
null
null
// // Location.cpp // PinballWarping // // Created by Eric on 6/10/15. // // #include "Location.h"
10.3
31
0.592233
redpaperheart
ed9ba3c47988be5ffd20aee496fdc10cbac0ae5a
3,102
cpp
C++
Greedy/948. Bag of Tokens.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
138
2020-02-08T05:25:26.000Z
2021-11-04T11:59:28.000Z
Greedy/948. Bag of Tokens.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
null
null
null
Greedy/948. Bag of Tokens.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
24
2021-01-02T07:18:43.000Z
2022-03-20T08:17:54.000Z
/* Bad Question Description: https://leetcode.com/problems/bag-of-tokens/discuss/197856/Bad-descriptions! Description Rewrite: You have a bag of tokens, from which you can take whichever token you want, and after you take one, you can't put it back to the bag, meaning you can use every token at most once. You start the game with P power and 0 point. For every tokens[i], you can use it in either way: - plus tokens[i] powers, and minus 1 point; - or, minus tokens[i] powers, and plus 1 point. (meaning you exchange your powers to get 1 point, or exchange your point to get more powers) But you have to make sure that during the process, both your powers>=0 and points>=0, otherwise you would have to stop playing the game. And you can use just some of the tokens (don't have to use all of them). Your target is to get the maximum points possible. */ //2020 class Solution { public: int bagOfTokensScore(vector<int>& tokens, int P) { sort(tokens.begin(), tokens.end()); int point = 0; for(int i = 0, j = tokens.size()-1; i<=j;){ if(tokens[i] <= P){ point++; P -= tokens[i++]; } else if(i!=j && point > 0){ //i != j, 若只剩下一个点,不用了 point--; P+= tokens[j--]; } else{ break; } } return point; } }; class Solution { public: int bagOfTokensScore(vector<int>& tokens, int P) { sort(tokens.begin(), tokens.end()); int res = 0, points = 0, i = 0, j = tokens.size() - 1; while (i <= j) { if (P >= tokens[i]) { P -= tokens[i++]; res = max(res, ++points); } else if (points > 0) { points--; P += tokens[j--]; } else { break; } } return res; } }; class Solution { public: int bagOfTokensScore(vector<int>& tokens, int P) { sort(tokens.begin(), tokens.end()); return helper(tokens, 0, tokens.size()-1, P, 0); } int helper(vector<int>& tokens, int i, int j, int p, int points){ if(i > j) return points; int res = points; if(tokens[i] <= p) res = max(res, helper(tokens, i+1, j, p-tokens[i], points+1)); else if(points >= 1) res = max(res, helper(tokens, i, j-1, p+tokens[j], points-1)); return res; } }; class Solution { public: int bagOfTokensScore(vector<int>& tokens, int P) { int N = tokens.size(); if (!N) return 0; sort(tokens.begin(), tokens.end()); if (P < tokens[0]) return 0; int l = 0, h = N-1; int points = 0; while (l <= h) { if (P < tokens[l] && points) { P += tokens[h--]; points--; } if (P < tokens[l]) return points; P -= tokens[l++]; points++; } return points; } };
24.425197
136
0.503224
beckswu
ed9e58847541e3510e6f7161d7367d43711e4229
6,210
cpp
C++
tests/test_shuffled_indices.cpp
LLNL/LBANN
8bcc5d461e52de70e329d73081ca7eee3e5c580a
[ "Apache-2.0" ]
null
null
null
tests/test_shuffled_indices.cpp
LLNL/LBANN
8bcc5d461e52de70e329d73081ca7eee3e5c580a
[ "Apache-2.0" ]
null
null
null
tests/test_shuffled_indices.cpp
LLNL/LBANN
8bcc5d461e52de70e329d73081ca7eee3e5c580a
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2021, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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. // // lbann_proto.cpp - prototext application //////////////////////////////////////////////////////////////////////////////// #include "lbann/lbann.hpp" #include "lbann/proto/proto_common.hpp" #include <lbann.pb.h> #include <reader.pb.h> #include <string> using namespace lbann; int mini_batch_size = 128; void test_is_shuffled(const generic_data_reader &reader, bool is_shuffled, const char *msg = nullptr); int main(int argc, char *argv[]) { world_comm_ptr comm = initialize(argc, argv); // Initialize the general RNGs and the data sequence RNGs int random_seed = lbann_default_random_seed; init_random(random_seed); init_data_seq_random(random_seed); const bool master = comm->am_world_master(); try { // Initialize options db (this parses the command line) auto& arg_parser = global_argument_parser(); construct_all_options(); arg_parser.add_flag("fn", {"--fn"}, "TODO"); arg_parser.parse(argc, argv); if (arg_parser.help_requested() or argc == 1) { if (master) std::cout << arg_parser << std::endl; return EXIT_SUCCESS; } //read data_reader prototext file if (arg_parser.get<std::string>("fn") == "") { std::cerr << __FILE__ << " " << __LINE__ << " :: " << "you must run with: --fn=<string> where <string> is\n" << "a data_reader prototext filePathName\n"; return EXIT_FAILURE; } lbann_data::LbannPB pb; std::string reader_fn = arg_parser.get<std::string>("fn"); read_prototext_file(reader_fn.c_str(), pb, master); const lbann_data::DataReader & d_reader = pb.data_reader(); int size = d_reader.reader_size(); for (int j=0; j<size; j++) { const lbann_data::Reader& readme = d_reader.reader(j); if (readme.role() == "train") { bool shuffle = true; auto reader = std::make_unique<mnist_reader>(shuffle); if (readme.data_filename() != "") { reader->set_data_filename( readme.data_filename() ); } if (readme.label_filename() != "") { reader->set_label_filename( readme.label_filename() ); } if (readme.data_filedir() != "") { reader->set_file_dir( readme.data_filedir() ); } reader->load(); test_is_shuffled(*reader, true, "TEST #1"); //test: indices should not be shuffled; same as previous, except we call // shuffle(true); shuffle = false; reader = std::make_unique<mnist_reader>(shuffle); if (readme.data_filename() != "") { reader->set_data_filename( readme.data_filename() ); } if (readme.label_filename() != "") { reader->set_label_filename( readme.label_filename() ); } if (readme.data_filedir() != "") { reader->set_file_dir( readme.data_filedir() ); } reader->set_shuffle(shuffle); reader->load(); test_is_shuffled(*reader, false, "TEST #2"); //test: indices should not be shuffled, due to ctor argument shuffle = false; reader = std::make_unique<mnist_reader>(shuffle); if (readme.data_filename() != "") { reader->set_data_filename( readme.data_filename() ); } if (readme.label_filename() != "") { reader->set_label_filename( readme.label_filename() ); } if (readme.data_filedir() != "") { reader->set_file_dir( readme.data_filedir() ); } reader->load(); test_is_shuffled(*reader, false, "TEST #3"); //test: set_shuffled_indices; indices should not be shuffled shuffle = true; reader = std::make_unique<mnist_reader>(shuffle); if (readme.data_filename() != "") { reader->set_data_filename( readme.data_filename() ); } if (readme.label_filename() != "") { reader->set_label_filename( readme.label_filename() ); } if (readme.data_filedir() != "") { reader->set_file_dir( readme.data_filedir() ); } reader->load(); //at this point the indices should be shuffled (same as first test) test_is_shuffled(*reader, true, "TEST #4"); std::vector<int> indices(mini_batch_size); std::iota(indices.begin(), indices.end(), 0); reader->set_shuffled_indices(indices); test_is_shuffled(*reader, false, "TEST #5"); break; } } } catch (lbann_exception& e) { e.print_report(); return EXIT_FAILURE; } return EXIT_SUCCESS; } void test_is_shuffled(const generic_data_reader &reader, bool is_shuffled, const char *msg) { const std::vector<int> &indices = reader.get_shuffled_indices(); std::cerr << "\nstarting test_is_suffled; mini_batch_size: " << mini_batch_size << " indices.size(): " << indices.size(); if (msg) { std::cout << " :: " << msg; } std::cout << std::endl; bool yes = false; //if true true: indices are actaully shuffled for (int h=0; h<mini_batch_size; h++) { if (indices[h] != h) { yes = true; } } std::cout << "testing for is_shuffled = " << is_shuffled << " test shows the shuffled is actually " << yes << " :: "; if (yes == is_shuffled) { std::cout << "PASSED!\n"; } else { std::cout << "FAILED!\n"; } }
39.056604
102
0.628019
LLNL
eda0ba695c8196e54fb03f20d256c759c85c81ca
8,509
cpp
C++
libvvmjit/Ext.cpp
vaporyco/vvmjit
e6ade8d34d44581081bcc45a9f6652263a606656
[ "MIT" ]
null
null
null
libvvmjit/Ext.cpp
vaporyco/vvmjit
e6ade8d34d44581081bcc45a9f6652263a606656
[ "MIT" ]
null
null
null
libvvmjit/Ext.cpp
vaporyco/vvmjit
e6ade8d34d44581081bcc45a9f6652263a606656
[ "MIT" ]
null
null
null
#include "Ext.h" #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/IntrinsicInst.h> #include "preprocessor/llvm_includes_end.h" #include "RuntimeManager.h" #include "Memory.h" #include "Type.h" #include "Endianness.h" namespace dev { namespace vap { namespace jit { Ext::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan): RuntimeHelper(_runtimeManager), m_memoryMan(_memoryMan) { m_funcs = decltype(m_funcs)(); m_argAllocas = decltype(m_argAllocas)(); m_size = m_builder.CreateAlloca(Type::Size, nullptr, "env.size"); } using FuncDesc = std::tuple<char const*, llvm::FunctionType*>; llvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list<llvm::Type*> const& _argsTypes) { return llvm::FunctionType::get(_returnType, llvm::ArrayRef<llvm::Type*>{_argsTypes.begin(), _argsTypes.size()}, false); } std::array<FuncDesc, sizeOf<EnvFunc>::value> const& getEnvFuncDescs() { static std::array<FuncDesc, sizeOf<EnvFunc>::value> descs{{ FuncDesc{"env_sload", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_sstore", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_sha3", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_balance", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_create", getFunctionType(Type::Void, {Type::EnvPtr, Type::GasPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_call", getFunctionType(Type::Bool, {Type::EnvPtr, Type::GasPtr, Type::Gas, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size})}, FuncDesc{"env_log", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_blockhash", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_extcode", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})}, }}; return descs; } llvm::Function* createFunc(EnvFunc _id, llvm::Module* _module) { auto&& desc = getEnvFuncDescs()[static_cast<size_t>(_id)]; return llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module); } llvm::Value* Ext::getArgAlloca() { auto& a = m_argAllocas[m_argCounter]; if (!a) { InsertPointGuard g{m_builder}; auto allocaIt = getMainFunction()->front().begin(); auto allocaPtr = &(*allocaIt); std::advance(allocaIt, m_argCounter); // Skip already created allocas m_builder.SetInsertPoint(allocaPtr); a = m_builder.CreateAlloca(Type::Word, nullptr, {"a.", std::to_string(m_argCounter)}); } ++m_argCounter; return a; } llvm::Value* Ext::byPtr(llvm::Value* _value) { auto a = getArgAlloca(); m_builder.CreateStore(_value, a); return a; } llvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list<llvm::Value*> const& _args) { auto& func = m_funcs[static_cast<size_t>(_funcId)]; if (!func) func = createFunc(_funcId, getModule()); m_argCounter = 0; return m_builder.CreateCall(func, {_args.begin(), _args.size()}); } llvm::Value* Ext::sload(llvm::Value* _index) { auto ret = getArgAlloca(); createCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); // Uses native endianness return m_builder.CreateLoad(ret); } void Ext::sstore(llvm::Value* _index, llvm::Value* _value) { createCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); // Uses native endianness } llvm::Value* Ext::calldataload(llvm::Value* _idx) { auto ret = getArgAlloca(); auto result = m_builder.CreateBitCast(ret, Type::BytePtr); auto callDataSize = getRuntimeManager().getCallDataSize(); auto callDataSize64 = m_builder.CreateTrunc(callDataSize, Type::Size); auto idxValid = m_builder.CreateICmpULT(_idx, callDataSize); auto idx = m_builder.CreateTrunc(m_builder.CreateSelect(idxValid, _idx, callDataSize), Type::Size, "idx"); auto end = m_builder.CreateNUWAdd(idx, m_builder.getInt64(32)); end = m_builder.CreateSelect(m_builder.CreateICmpULE(end, callDataSize64), end, callDataSize64); auto copySize = m_builder.CreateNUWSub(end, idx); auto padSize = m_builder.CreateNUWSub(m_builder.getInt64(32), copySize); auto dataBegin = m_builder.CreateGEP(Type::Byte, getRuntimeManager().getCallData(), idx); m_builder.CreateMemCpy(result, dataBegin, copySize, 1); auto pad = m_builder.CreateGEP(Type::Byte, result, copySize); m_builder.CreateMemSet(pad, m_builder.getInt8(0), padSize, 1); m_argCounter = 0; // Release args allocas. TODO: This is a bad design return Endianness::toNative(m_builder, m_builder.CreateLoad(ret)); } llvm::Value* Ext::balance(llvm::Value* _address) { auto address = Endianness::toBE(m_builder, _address); auto ret = getArgAlloca(); createCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret}); return m_builder.CreateLoad(ret); } llvm::Value* Ext::blockHash(llvm::Value* _number) { auto hash = getArgAlloca(); createCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash}); hash = m_builder.CreateLoad(hash); return Endianness::toNative(m_builder, hash); } llvm::Value* Ext::create(llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize) { auto ret = getArgAlloca(); auto begin = m_memoryMan.getBytePtr(_initOff); auto size = m_builder.CreateTrunc(_initSize, Type::Size, "size"); createCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), byPtr(_endowment), begin, size, ret}); llvm::Value* address = m_builder.CreateLoad(ret); address = Endianness::toNative(m_builder, address); return address; } llvm::Value* Ext::call(llvm::Value* _callGas, llvm::Value* _senderAddress, llvm::Value* _receiveAddress, llvm::Value* _codeAddress, llvm::Value* _valueTransfer, llvm::Value* _apparentValue, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize) { auto senderAddress = Endianness::toBE(m_builder, _senderAddress); auto receiveAddress = Endianness::toBE(m_builder, _receiveAddress); auto inBeg = m_memoryMan.getBytePtr(_inOff); auto inSize = m_builder.CreateTrunc(_inSize, Type::Size, "in.size"); auto outBeg = m_memoryMan.getBytePtr(_outOff); auto outSize = m_builder.CreateTrunc(_outSize, Type::Size, "out.size"); auto codeAddress = Endianness::toBE(m_builder, _codeAddress); auto callGas = m_builder.CreateSelect( m_builder.CreateICmpULE(_callGas, m_builder.CreateZExt(Constant::gasMax, Type::Word)), m_builder.CreateTrunc(_callGas, Type::Gas), Constant::gasMax); auto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), callGas, byPtr(senderAddress), byPtr(receiveAddress), byPtr(codeAddress), byPtr(_valueTransfer), byPtr(_apparentValue), inBeg, inSize, outBeg, outSize}); return m_builder.CreateZExt(ret, Type::Word, "ret"); } llvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize) { auto begin = m_memoryMan.getBytePtr(_inOff); auto size = m_builder.CreateTrunc(_inSize, Type::Size, "size"); auto ret = getArgAlloca(); createCall(EnvFunc::sha3, {begin, size, ret}); llvm::Value* hash = m_builder.CreateLoad(ret); hash = Endianness::toNative(m_builder, hash); return hash; } MemoryRef Ext::extcode(llvm::Value* _addr) { auto addr = Endianness::toBE(m_builder, _addr); auto code = createCall(EnvFunc::extcode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size}); auto codeSize = m_builder.CreateLoad(m_size); auto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word); return {code, codeSize256}; } void Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array<llvm::Value*,4> const& _topics) { auto begin = m_memoryMan.getBytePtr(_memIdx); auto size = m_builder.CreateTrunc(_numBytes, Type::Size, "size"); llvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()}; auto topicArgPtr = &args[3]; for (auto&& topic : _topics) { if (topic) m_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr); else *topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr); ++topicArgPtr; } createCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); // TODO: use std::initializer_list<> } } } }
39.948357
277
0.734164
vaporyco
eda0f587865b486a279f453d1c5a33422465cb54
3,478
cxx
C++
odb-tests-2.4.0/evolution/add-index/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
odb-tests-2.4.0/evolution/add-index/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
odb-tests-2.4.0/evolution/add-index/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
// file : evolution/add-index/driver.cxx // copyright : Copyright (c) 2009-2015 Code Synthesis Tools CC // license : GNU GPL v2; see accompanying LICENSE file // Test adding a new index. // #include <memory> // std::auto_ptr #include <cassert> #include <iostream> #include <odb/database.hxx> #include <odb/transaction.hxx> #include <odb/schema-catalog.hxx> #include <common/common.hxx> #include "test2.hxx" #include "test3.hxx" #include "test2-odb.hxx" #include "test3-odb.hxx" using namespace std; using namespace odb::core; int main (int argc, char* argv[]) { try { auto_ptr<database> db (create_database (argc, argv, false)); bool embedded (schema_catalog::exists (*db)); // 1 - base version // 2 - migration // 3 - current version // unsigned short pass (*argv[argc - 1] - '0'); switch (pass) { case 1: { using namespace v2; if (embedded) { transaction t (db->begin ()); schema_catalog::drop_schema (*db); schema_catalog::create_schema (*db, "", false); schema_catalog::migrate_schema (*db, 2); t.commit (); } object o0 (0); o0.num = 123; object o1 (1); o1.num = 234; object o2 (2); o2.num = 234; // Duplicates are ok. // { transaction t (db->begin ()); db->persist (o0); db->persist (o1); db->persist (o2); t.commit (); } break; } case 2: { using namespace v3; if (embedded) { transaction t (db->begin ()); schema_catalog::migrate_schema_pre (*db, 3); t.commit (); } object o3 (3); o3.num = 234; // Duplicates are still ok but we need to remove them before the // post migration step. // { transaction t (db->begin ()); db->persist (o3); t.commit (); } { typedef odb::query<object> query; typedef odb::result<object> result; transaction t (db->begin ()); result r (db->query<object> ( "ORDER BY" + query::num + "," + query::id)); unsigned long prev (0); for (result::iterator i (r.begin ()); i != r.end (); ++i) { if (i->num == prev) db->erase (*i); prev = i->num; } t.commit (); } if (embedded) { transaction t (db->begin ()); schema_catalog::migrate_schema_post (*db, 3); t.commit (); } break; } case 3: { using namespace v3; { transaction t (db->begin ()); auto_ptr<object> p0 (db->load<object> (0)); auto_ptr<object> p1 (db->load<object> (1)); assert (p0->num == 123); assert (p1->num == 234); t.commit (); } try { object o2 (2); o2.num = 234; transaction t (db->begin ()); db->persist (o2); assert (false); } catch (const odb::exception& ) {} break; } default: { cerr << "unknown pass number '" << argv[argc - 1] << "'" << endl; return 1; } } } catch (const odb::exception& e) { cerr << e.what () << endl; return 1; } }
20.826347
73
0.47211
edidada
eda1fe88ca42e7a3983e17b1b6955b02e7a46225
61,772
cpp
C++
RobotRaconteurCore/src/Discovery.cpp
robotraconteur/robotraconteur
ff997351761a687be364234684202e3348c4083c
[ "Apache-2.0" ]
37
2019-01-31T06:05:17.000Z
2022-03-21T06:56:18.000Z
RobotRaconteurCore/src/Discovery.cpp
robotraconteur/robotraconteur
ff997351761a687be364234684202e3348c4083c
[ "Apache-2.0" ]
14
2019-07-18T04:09:45.000Z
2021-08-31T02:04:22.000Z
RobotRaconteurCore/src/Discovery.cpp
robotraconteur/robotraconteur
ff997351761a687be364234684202e3348c4083c
[ "Apache-2.0" ]
3
2018-11-23T22:03:22.000Z
2021-11-02T10:03:39.000Z
// Copyright 2011-2020 Wason Technology, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifdef ROBOTRACONTEUR_CORE_USE_STDAFX #include "stdafx.h" #endif #include "Discovery_private.h" #include "Subscription_private.h" #include <boost/foreach.hpp> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> #include <boost/algorithm/string.hpp> namespace RobotRaconteur { ServiceInfo2::ServiceInfo2() { } ServiceInfo2::ServiceInfo2(const RobotRaconteurServiceIndex::ServiceInfo &info, const RobotRaconteurServiceIndex::NodeInfo &ninfo) { Name = info.Name; RootObjectType = info.RootObjectType; if (info.RootObjectImplements) { BOOST_FOREACH(RR_INTRUSIVE_PTR<RobotRaconteur::RRArray<char> >& e, *info.RootObjectImplements | boost::adaptors::map_values) { RootObjectImplements.push_back(RRArrayToString(e)); } } if (info.ConnectionURL) { BOOST_FOREACH(RR_INTRUSIVE_PTR<RobotRaconteur::RRArray<char> >& e, *info.ConnectionURL | boost::adaptors::map_values) { ConnectionURL.push_back(RRArrayToString(e)); } } Attributes = info.Attributes->GetStorageContainer(); NodeID = RobotRaconteur::NodeID(RRArrayToArray<uint8_t, 16>(ninfo.NodeID)); NodeName = ninfo.NodeName; } namespace detail { Discovery_updatediscoverednodes::Discovery_updatediscoverednodes(RR_SHARED_PTR<RobotRaconteurNode> node) { active_count = 0; searching = true; this->node = node; } void Discovery_updatediscoverednodes::timeout_timer_callback(const TimerEvent& e) { boost::mutex::scoped_lock lock(work_lock); if (!e.stopped) { { //boost::mutex::scoped_lock lock(searching_lock); if (!searching) return; searching = false; } { boost::mutex::scoped_lock lock(timeout_timer_lock); try { if (timeout_timer) timeout_timer->Stop(); } catch (std::exception&) {} timeout_timer.reset(); } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateDiscoveredNodes timed out, returning current results"); detail::InvokeHandler(node, handler); } } void Discovery_updatediscoverednodes::getdetectednodes_callback(RR_SHARED_PTR<std::vector<NodeDiscoveryInfo> > ret, int32_t key) { boost::mutex::scoped_lock lock(work_lock); bool c; { //boost::mutex::scoped_lock lock(searching_lock); c = searching; } if (!c) return; BOOST_FOREACH(NodeDiscoveryInfo& e, *ret) { node->NodeDetected(e); } bool done = false; { boost::mutex::scoped_lock lock(active_lock); active.remove(key); if (active.size() == 0) done = true; } if (done) { { //boost::mutex::scoped_lock lock(searching_lock); c = searching; searching = false; } if (!c) return; { boost::mutex::scoped_lock lock(timeout_timer_lock); try { if (timeout_timer) timeout_timer->Stop(); } catch (std::exception&) {} timeout_timer.reset(); } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateDiscoveredNodes completed successfully"); detail::InvokeHandler(node, handler); } } void Discovery_updatediscoverednodes::UpdateDiscoveredNodes(const std::vector<std::string>& schemes, const std::vector<RR_SHARED_PTR<Transport> >& transports, RR_MOVE_ARG(boost::function<void()>) handler, int32_t timeout) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin UpdateDiscoveredNodes"); boost::mutex::scoped_lock lock(work_lock); this->handler = handler; this->schemes = schemes; searching = true; if (timeout != RR_TIMEOUT_INFINITE) { timeout_timer = node->CreateTimer(boost::posix_time::milliseconds(timeout), boost::bind(&Discovery_updatediscoverednodes::timeout_timer_callback, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1)), true); timeout_timer->Start(); } { boost::mutex::scoped_lock lock(active_lock); int32_t timeout1 = timeout; if (timeout1 > 0) { timeout1 = (3 * timeout) / 4; } BOOST_FOREACH(const RR_SHARED_PTR<Transport>& e, transports) { int32_t key = active_count++; try { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin GetDetectedNodes for transport " << e->GetUrlSchemeString()); boost::function<void(RR_SHARED_PTR<std::vector<NodeDiscoveryInfo> >)> h = boost::bind(&Discovery_updatediscoverednodes::getdetectednodes_callback, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), key); e->AsyncGetDetectedNodes(schemes, h, timeout1); } catch (std::exception& exp) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Begin GetDetectedNodes failed for transport " << e->GetUrlSchemeString() << ": " << exp.what()); } active.push_back(key); } } bool done = false; { boost::mutex::scoped_lock lock(active_lock); if (active.size() == 0) done = true; } if (done) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "No transports available for node discovery"); detail::InvokeHandler(node, handler); } } Discovery_findservicebytype::Discovery_findservicebytype(RR_SHARED_PTR<RobotRaconteurNode> node) { active_count = 0; searching = true; ret = RR_MAKE_SHARED<std::vector<ServiceInfo2> >(); this->node = node; } void Discovery_findservicebytype::handle_error(const int32_t& key, RR_SHARED_PTR<RobotRaconteurException> err) { boost::recursive_mutex::scoped_lock lock2(work_lock); { //boost::mutex::scoped_lock lock(searching_lock); if (!searching) return; } ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType candidate failed: " << err->what()); { boost::mutex::scoped_lock lock(active_lock); active.remove(key); errors.push_back(err); if (active.size() != 0) return; } //All activities have completed, assume failure { //boost::mutex::scoped_lock lock(searching_lock); searching = false; } { boost::mutex::scoped_lock lock(timeout_timer_lock); try { if (timeout_timer) timeout_timer->Stop(); } catch (std::exception&) {} timeout_timer.reset(); } boost::mutex::scoped_lock lock(ret_lock); ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType last candidate failed, returning " << ret->size() << " discovered services"); detail::InvokeHandler(node, handler, ret); } void Discovery_findservicebytype::timeout_timer_callback(const TimerEvent& e) { boost::recursive_mutex::scoped_lock lock2(work_lock); if (!e.stopped) { { //boost::mutex::scoped_lock lock(searching_lock); if (!searching) return; searching = false; } { boost::mutex::scoped_lock lock(timeout_timer_lock); try { if (timeout_timer) timeout_timer->Stop(); } catch (std::exception&) {} timeout_timer.reset(); } boost::mutex::scoped_lock lock(ret_lock); ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType timed out, returning " << ret->size() << " discovered services"); detail::InvokeHandler(node, handler, ret); } } void Discovery_findservicebytype::rr_empty_handler() { } void Discovery_findservicebytype::serviceinfo_callback(RR_INTRUSIVE_PTR<MessageEntry> ret1, RR_SHARED_PTR<RobotRaconteurException> err, RR_SHARED_PTR<ServiceStub> client, std::string url, uint32_t key) { boost::recursive_mutex::scoped_lock lock2(work_lock); if (err) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType getting ServiceInfo2 from " << url << " failed: " << err->what()); try { node->AsyncDisconnectService(client, &Discovery_findservicebytype::rr_empty_handler); } catch (std::exception&) { } handle_error(key, err); return; } bool c; { //boost::mutex::scoped_lock lock(searching_lock); c = searching; } if (!c) { try { node->AsyncDisconnectService(client, &Discovery_findservicebytype::rr_empty_handler); } catch (std::exception&) { } } else { try { RR_SHARED_PTR<RobotRaconteurServiceIndex::NodeInfo> n = RR_MAKE_SHARED<RobotRaconteurServiceIndex::NodeInfo>(); n->NodeID = ArrayToRRArray<uint8_t>(rr_cast<ServiceStub>(client)->GetContext()->GetRemoteNodeID().ToByteArray()); n->NodeName = rr_cast<ServiceStub>(client)->GetContext()->GetRemoteNodeName(); try { node->AsyncDisconnectService(client, &Discovery_findservicebytype::rr_empty_handler); } catch (std::exception&) { } boost::smatch url_result; boost::regex reg("^([^:]+)://(.*)$"); boost::regex_search(url, url_result, reg); if (url_result.size() < 3) throw InvalidArgumentException("Malformed URL"); std::string scheme = url_result[1]; if (ret1->Error == RobotRaconteur::MessageErrorType_None) { RR_INTRUSIVE_PTR<RobotRaconteur::MessageElement> me = ret1->FindElement("return"); RR_INTRUSIVE_PTR<RobotRaconteur::RRMap<int32_t, RobotRaconteurServiceIndex::ServiceInfo> > ret = RobotRaconteur::rr_cast<RobotRaconteur::RRMap<int32_t, RobotRaconteurServiceIndex::ServiceInfo > >((node->UnpackMapType<int32_t, RobotRaconteurServiceIndex::ServiceInfo >(me->CastData<RobotRaconteur::MessageElementNestedElementList >()))); if (ret) { BOOST_FOREACH(RR_INTRUSIVE_PTR<RobotRaconteurServiceIndex::ServiceInfo>& ii, *ret | boost::adaptors::map_values) { if (!ii) continue; if (ii->RootObjectType == servicetype) { boost::mutex::scoped_lock lock(ret_lock); ServiceInfo2 si(*ii, *n); //TODO: what is this? BOOST_FOREACH(std::string& iii, si.ConnectionURL) { /*if (!boost::starts_with(*iii, scheme + "://")) { boost::smatch url_result2; boost::regex_search(*iii, url_result2, reg); if (url_result2.size() < 3) continue; *iii = scheme + "://" + url_result2[2]; }*/ } this->ret->push_back(si); } else { BOOST_FOREACH(RR_INTRUSIVE_PTR<RRArray<char> >& impl, *ii->RootObjectImplements | boost::adaptors::map_values) { if (RRArrayToString(impl) == servicetype) { boost::mutex::scoped_lock lock(ret_lock); ServiceInfo2 si(*ii, *n); //TODO: What is this? BOOST_FOREACH(std::string &iii, si.ConnectionURL) { /*if (!boost::starts_with(*iii, scheme + "://")) { boost::smatch url_result2; boost::regex_search(*iii, url_result2, reg); if (url_result2.size() < 3) continue; *iii = scheme + "://" + url_result2[2]; }*/ } this->ret->push_back(si); break; } } } } } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType getting ServiceInfo2 from " << url << " completed successfully"); } else { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType getting ServiceInfo2 from " << url << " failed: " << ret1->Error); } bool done = false; { boost::mutex::scoped_lock lock(active_lock); active.remove(key); done = active.empty(); } if (done) { bool c2; { //boost::mutex::scoped_lock lock(searching_lock); c2 = searching; searching = false; } if (c2) { { boost::mutex::scoped_lock lock(timeout_timer_lock); try { if (timeout_timer) timeout_timer->Stop(); } catch (std::exception&) {} timeout_timer.reset(); } boost::mutex::scoped_lock lock(ret_lock); ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType completed successfully with " << this->ret->size() << " discovered services"); detail::InvokeHandler(node, handler, this->ret); } } } catch (std::exception& err2) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType getting ServiceInfo2 from " << url << " failed: " << err2.what()); handle_error(key, RobotRaconteurExceptionUtil::ExceptionToSharedPtr(err2, MessageErrorType_ConnectionError)); } } } void Discovery_findservicebytype::connect_callback(RR_SHARED_PTR<RRObject> client, RR_SHARED_PTR<RobotRaconteurException> err, std::string url, uint32_t key) { boost::recursive_mutex::scoped_lock lock2(work_lock); if (err) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType connecting to " << url << " failed: " << err->what()); handle_error(key, err); return; } bool c; { //boost::mutex::scoped_lock lock(searching_lock); c = searching; } if (!c) { try { node->AsyncDisconnectService(client, &Discovery_findservicebytype::rr_empty_handler); } catch (std::exception&) { } } else { try { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType connectted to " << url << ", begin getting ServiceInfo2"); int32_t key2; { boost::mutex::scoped_lock lock(active_lock); active_count++; key2 = active_count; RR_SHARED_PTR<ServiceStub> client3 = rr_cast<ServiceStub>(client); RR_INTRUSIVE_PTR<RobotRaconteur::MessageEntry> rr_req = RobotRaconteur::CreateMessageEntry(RobotRaconteur::MessageEntryType_FunctionCallReq, "GetLocalNodeServices"); client3->AsyncProcessRequest(rr_req, boost::bind(&Discovery_findservicebytype::serviceinfo_callback, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2), client3, url, key2), 5000); active.push_back(key2); active.remove(key); } } catch (std::exception& err2) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType begin getting ServiceInfo2 from url " << url << " failed: " << err2.what()); try { node->AsyncDisconnectService(client, &Discovery_findservicebytype::rr_empty_handler); } catch (std::exception&) { } handle_error(key, RobotRaconteurExceptionUtil::ExceptionToSharedPtr(err2, MessageErrorType_ConnectionError)); } } } void Discovery_findservicebytype::find2() { boost::recursive_mutex::scoped_lock lock2(work_lock); std::list<std::vector<std::string> > urls; std::vector<NodeDiscoveryInfo> n1 = node->GetDetectedNodes(); BOOST_FOREACH(NodeDiscoveryInfo& ee, n1) { try { std::vector<std::string> urls1 = std::vector<std::string>(); BOOST_FOREACH(NodeDiscoveryInfoURL& url, ee.URLs) { BOOST_FOREACH(const std::string& e, schemes) { std::string t2 = (e + "://"); if (boost::starts_with(url.URL, t2)) { urls1.push_back(url.URL); break; } } } if (!urls1.empty()) urls.push_back(urls1); } catch (std::exception& exp) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType error processing NodeDiscoveryInfo for NodeID " << ee.NodeID.ToString() << ": " << exp.what() ); } } if (urls.empty()) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType could not find any candidate URLs"); RR_SHARED_PTR<std::vector<ServiceInfo2> > ret = RR_MAKE_SHARED<std::vector<ServiceInfo2> >(); detail::PostHandler(node,handler, ret,true); return; } if (timeout_timer) timeout_timer->Start(); BOOST_FOREACH(std::vector<std::string>& e, urls) { try { int32_t key; { boost::mutex::scoped_lock lock(active_lock); active_count++; key = active_count; ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType connecting to node using candidate URLs " << boost::join(e,", ")); node->AsyncConnectService(e, "", (RR_INTRUSIVE_PTR<RRMap<std::string, RRValue> >()), NULL, "", boost::bind(&Discovery_findservicebytype::connect_callback, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2), e.front(), key), timeout); active.push_back(key); } } catch (std::exception& exp2) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType connecting to node using candidate URLs " << boost::join(e,", ") << " failed: " << exp2.what()); } } } void Discovery_findservicebytype::AsyncFindServiceByType(boost::string_ref servicetype, const std::vector<std::string>& schemes, RR_MOVE_ARG(boost::function<void(RR_SHARED_PTR<std::vector<ServiceInfo2> >)>) handler, int32_t timeout) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin FindServiceByType for type \"" << servicetype << "\" with schemes " << boost::join(schemes, ", ")); boost::recursive_mutex::scoped_lock lock2(work_lock); this->handler = handler; this->schemes = schemes; this->timeout = timeout; this->servicetype = RR_MOVE(servicetype.to_string()); if (timeout != RR_TIMEOUT_INFINITE) { timeout_timer = node->CreateTimer(boost::posix_time::milliseconds(timeout), boost::bind(&Discovery_findservicebytype::timeout_timer_callback, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1)), true); //timeout_timer->Start(); } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType begin update detected nodes"); //int32_t timeout2=(timeout==RR_TIMEOUT_INFINITE) ? RR_TIMEOUT_INFINITE : timeout/4; node->AsyncUpdateDetectedNodes(schemes, boost::bind(&Discovery_findservicebytype::find2, shared_from_this()), timeout / 4); } //class Discovery_updateserviceinfo Discovery_updateserviceinfo::Discovery_updateserviceinfo(RR_WEAK_PTR<RobotRaconteurNode> node) { this->node = node; retry_count = 0; backoff = 0; } void Discovery_updateserviceinfo::handle_error(RR_SHARED_PTR<RobotRaconteurException> err) { RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) return; if (client) { try { n->AsyncDisconnectService(client, boost::bind(&Discovery_updateserviceinfo::rr_empty_handler)); } catch (std::exception&) {} } client.reset(); retry_count++; if (retry_count < 3) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo for remote node " << this->remote_nodeid.ToString() << " failed, retrying: " << err->what()); //Restart the process 3 times backoff = n->GetRandomInt(0, 500); RR_SHARED_PTR<Timer> t = n->CreateTimer(boost::posix_time::milliseconds(backoff), boost::bind(&Discovery_updateserviceinfo::backoff_timer_handler, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1)), true); t->Start(); timeout_timer = t; return; } ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo for remote node " << this->remote_nodeid.ToString() << " failed, out of retries: " << err->what()); boost::function<void(RR_SHARED_PTR<Discovery_nodestorage>, RR_SHARED_PTR<std::vector<ServiceInfo2> >, boost::string_ref, RR_SHARED_PTR<RobotRaconteurException>)> handler2 = handler; handler.clear(); { boost::mutex::scoped_lock lock2(storage->this_lock); if (storage->updater.lock() == shared_from_this()) { storage->updater.reset(); } } if (!handler2) return; RobotRaconteurNode::TryPostToThreadPool(node, boost::bind(handler2, storage, RR_SHARED_PTR<std::vector<ServiceInfo2> >(), service_nonce, err), true); } void Discovery_updateserviceinfo::rr_empty_handler() { } static std::vector<std::string> Discovery_updateserviceinfo_convertmap(RR_INTRUSIVE_PTR<RRMap<int32_t, RRArray<char> > > d) { RR_NULL_CHECK(d); std::vector<std::string> o; o.reserve(d->size()); BOOST_FOREACH(RR_INTRUSIVE_PTR<RRArray<char> > d2, *d | boost::adaptors::map_values) { o.push_back(RRArrayToString(d2)); } return o; } void Discovery_updateserviceinfo::serviceinfo_handler(RR_INTRUSIVE_PTR<MessageEntry> ret1, RR_SHARED_PTR<RobotRaconteurException> err) { boost::mutex::scoped_lock lock(this_lock); if (err) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo getting ServiceInfo2 for remote node " << this->remote_nodeid.ToString() << " failed: " << err->what()); handle_error(err); return; } RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) { handle_error(RR_MAKE_SHARED<ServiceException>("Node has been released")); return; } try { if (n) { n->AsyncDisconnectService(client, boost::bind(&Discovery_updateserviceinfo::rr_empty_handler)); } } catch (std::exception&) {} if (!ret1) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo for remote node " << this->remote_nodeid.ToString() << " failed: Invalid return"); handle_error(RR_MAKE_SHARED<ServiceException>("Invalid return")); return; } if (ret1->Error != MessageErrorType_None) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo getting ServiceInfo2 for remote node " << this->remote_nodeid.ToString() << " failed: " << ret1->Error); handle_error(RobotRaconteurExceptionUtil::MessageEntryToException(ret1)); return; }; RR_SHARED_PTR<std::vector<ServiceInfo2> > o = RR_MAKE_SHARED<std::vector<ServiceInfo2> >(); try { RR_INTRUSIVE_PTR<RobotRaconteur::MessageElement> me = ret1->FindElement("return"); // Limit size to protect from memory leak attacks if (me->ElementSize > 64*1024) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo dropping response from remote node " << this->remote_nodeid.ToString() << " to prevent overflow"); handle_error(RR_MAKE_SHARED<ServiceException>("Return from remote node too large")); return; } RR_INTRUSIVE_PTR<RobotRaconteur::RRMap<int32_t, RobotRaconteurServiceIndex::ServiceInfo> > ret = RobotRaconteur::rr_cast<RobotRaconteur::RRMap<int32_t, RobotRaconteurServiceIndex::ServiceInfo> >((n->UnpackMapType<int32_t, RobotRaconteurServiceIndex::ServiceInfo>(me->CastDataToNestedList()))); if (ret) { BOOST_FOREACH(RR_INTRUSIVE_PTR<RobotRaconteurServiceIndex::ServiceInfo>& e, *ret | boost::adaptors::map_values) { ServiceInfo2 o1; o1.NodeID = remote_nodeid; o1.NodeName = remote_nodename; o1.Name = e->Name; o1.ConnectionURL = Discovery_updateserviceinfo_convertmap(e->ConnectionURL); o1.RootObjectType = e->RootObjectType; o1.RootObjectImplements = Discovery_updateserviceinfo_convertmap(e->RootObjectImplements); o1.Attributes = e->Attributes->GetStorageContainer(); o->push_back(o1); } } } catch (RobotRaconteurException& err) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo getting ServiceInfo2 for remote node " << this->remote_nodeid.ToString() << " failed: " << err.what()); handle_error(RobotRaconteurExceptionUtil::DownCastException(err)); return; } catch (std::exception& err) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo getting ServiceInfo2 for remote node " << this->remote_nodeid.ToString() << " failed: " << err.what()); handle_error(RR_MAKE_SHARED<ServiceException>(err.what())); return; } boost::function<void(RR_SHARED_PTR<Discovery_nodestorage>, RR_SHARED_PTR<std::vector<ServiceInfo2> >, boost::string_ref, RR_SHARED_PTR<RobotRaconteurException>)> handler2 = handler; handler.clear(); lock.unlock(); { boost::mutex::scoped_lock lock2(storage->this_lock); if (storage->updater.lock() == shared_from_this()) { storage->updater.reset(); } } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateServiceInfo getting ServiceInfo2 for remote node " << this->remote_nodeid.ToString() << " completed successfully"); if (!handler2) return; RobotRaconteurNode::TryPostToThreadPool(node, boost::bind(handler2, storage, o, service_nonce, RR_SHARED_PTR<RobotRaconteurException>()), true); } void Discovery_updateserviceinfo::connect_handler(RR_SHARED_PTR<RRObject> client, RR_SHARED_PTR<RobotRaconteurException> err) { boost::mutex::scoped_lock lock(this_lock); if (err) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connect for remote node " << this->remote_nodeid.ToString() << " failed: " << err->what()); handle_error(err); return; } RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) { handle_error(RR_MAKE_SHARED<ConnectionException>("Node has been released")); return; } this->client = client; try { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connected to remote node " << this->remote_nodeid.ToString() << ", begin getting ServiceInfo2"); RR_SHARED_PTR<ServiceStub> client3 = rr_cast<ServiceStub>(client); remote_nodeid=client3->GetContext()->GetRemoteNodeID(); remote_nodename = client3->GetContext()->GetRemoteNodeName(); if (remote_nodeid != storage->info->NodeID || (!storage->info->NodeName.empty() && remote_nodename != storage->info->NodeName)) { //Very unlikely unless a node is on the fritz try { handle_error(RR_MAKE_SHARED <ConnectionException>("Node identification mismatch")); return; } catch (std::exception&) {} } RR_INTRUSIVE_PTR<RobotRaconteur::MessageEntry> rr_req = RobotRaconteur::CreateMessageEntry(RobotRaconteur::MessageEntryType_FunctionCallReq, "GetLocalNodeServices"); client3->AsyncProcessRequest(rr_req, boost::bind(&Discovery_updateserviceinfo::serviceinfo_handler, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2)),5000); } catch (RobotRaconteurException& err) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connect for remote node " << this->remote_nodeid.ToString() << " failed: " << err.what()); handle_error(RobotRaconteurExceptionUtil::DownCastException(err)); return; } catch (std::exception& err) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connect for remote node " << this->remote_nodeid.ToString() << " failed: " << err.what()); handle_error(RR_MAKE_SHARED<ServiceException>(err.what())); return; } } void Discovery_updateserviceinfo::backoff_timer_handler(const TimerEvent& evt) { boost::mutex::scoped_lock lock(this_lock); timeout_timer.reset(); RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) { handle_error(RR_MAKE_SHARED<ConnectionException>("Node has been released")); return; } std::vector<std::string> urls; { boost::mutex::scoped_lock lock(storage->this_lock); urls.reserve(storage->info->URLs.size()); BOOST_FOREACH(NodeDiscoveryInfoURL& u, storage->info->URLs) { urls.push_back(u.URL); } } try { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connecting to remote node " << this->remote_nodeid.ToString() << " using candidate URLs " << boost::join(urls,", ")); n->AsyncConnectService(urls, "", RR_INTRUSIVE_PTR<RRMap<std::string, RRValue> >(), NULL, "", boost::bind(&Discovery_updateserviceinfo::connect_handler, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2)), 15000); } catch (RobotRaconteurException& err) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connecting to remote node " << this->remote_nodeid.ToString() << " using candidate URLs " << boost::join(urls,", ") << " failed: " << err.what()); handle_error(RobotRaconteurExceptionUtil::DownCastException(err)); return; } catch (std::exception& err) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connecting to remote node " << this->remote_nodeid.ToString() << " using candidate URLs " << boost::join(urls,", ") << " failed: " << err.what()); handle_error(RR_MAKE_SHARED<ServiceException>(err.what())); return; } } void Discovery_updateserviceinfo::AsyncUpdateServiceInfo(RR_SHARED_PTR<Discovery_nodestorage> storage, boost::string_ref service_nonce, RR_MOVE_ARG(boost::function<void(RR_SHARED_PTR<Discovery_nodestorage>, RR_SHARED_PTR<std::vector<ServiceInfo2> >, boost::string_ref, RR_SHARED_PTR<RobotRaconteurException>)>) handler, int32_t extra_backoff) { this->storage = storage; this->handler = handler; this->retry_count = 0; this->service_nonce = RR_MOVE(service_nonce.to_string()); RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) return; backoff = n->GetRandomInt(100, 600) + extra_backoff; RR_SHARED_PTR<Timer> t = n->CreateTimer(boost::posix_time::milliseconds(backoff), boost::bind(&Discovery_updateserviceinfo::backoff_timer_handler, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1)), true); t->Start(); timeout_timer = t; ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin UpdateServiceInfo to remote node " << this->remote_nodeid.ToString() << " using " << backoff << " ms backoff"); } //class Discovery Discovery::Discovery(RR_SHARED_PTR<RobotRaconteurNode> node) { max_DiscoveredNodes.data() = 4096; this->node = node; ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Discovery created"); } std::vector<NodeDiscoveryInfo> Discovery::GetDetectedNodes() { std::vector<NodeDiscoveryInfo> o; boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); BOOST_FOREACH(RR_SHARED_PTR<Discovery_nodestorage>& o1, m_DiscoveredNodes | boost::adaptors::map_values) { boost::mutex::scoped_lock lock2(o1->this_lock); o.push_back(*o1->info); } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "GetDetectedNodes returning " << o.size() << " detected nodes"); return o; } NodeInfo2 Discovery::GetDetectedNodeCacheInfo(const RobotRaconteur::NodeID& nodeid) { NodeInfo2 nodeinfo2; bool res = TryGetDetectedNodeCacheInfo(nodeid, nodeinfo2); if (!res) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node " << nodeid.ToString() << "not in node cache"); throw NodeNotFoundException("Node " + nodeid.ToString() + "not in node cache"); } return nodeinfo2; } bool Discovery::TryGetDetectedNodeCacheInfo(const RobotRaconteur::NodeID& nodeid, NodeInfo2& nodeinfo2) { boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); std::map<std::string, RR_SHARED_PTR<Discovery_nodestorage> >::iterator e1 = m_DiscoveredNodes.find(nodeid.ToString()); if (e1 == m_DiscoveredNodes.end()) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "TryGetDetectedNodeCacheInfo node " << nodeid.ToString() << " not found"); return false; } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "TryGetDetectedNodeCacheInfo node " << nodeid.ToString() << " returning " << nodeinfo2.ConnectionURL.size() << " urls"); nodeinfo2.NodeID = e1->second->info->NodeID; nodeinfo2.NodeName = e1->second->info->NodeName; nodeinfo2.ConnectionURL.clear(); BOOST_FOREACH(NodeDiscoveryInfoURL u, e1->second->info->URLs) { nodeinfo2.ConnectionURL.push_back(u.URL); } return true; } static std::string Discovery_log_NodeDiscoveryInfoURLs_url_field(const NodeDiscoveryInfoURL& url) { return url.URL; } static std::string Discovery_log_NodeDiscoveryInfoURLs(const std::vector<NodeDiscoveryInfoURL>& urls) { return boost::join(urls | boost::adaptors::transformed(&Discovery_log_NodeDiscoveryInfoURLs_url_field), ", "); } void Discovery::NodeDetected(const NodeDiscoveryInfo& info) { if (info.NodeID.IsAnyNode()) return; RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) return; ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " NodeName " << info.NodeName << " URLs " << Discovery_log_NodeDiscoveryInfoURLs(info.URLs)); if (info.ServiceStateNonce.size() > 32) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " invalid ServiceStateNonce"); return; } try { boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); if (info.NodeName.size() > 128) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " invalid NodeName"); return; } std::string id = info.NodeID.ToString(); std::map<std::string, RR_SHARED_PTR<Discovery_nodestorage> >::iterator e1 = m_DiscoveredNodes.find(id); if (e1 == m_DiscoveredNodes.end()) { if (m_DiscoveredNodes.size() >= max_DiscoveredNodes) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Detected node NodeID " << info.NodeID.ToString() << " dropped due to full node cache"); return; } RR_SHARED_PTR<NodeDiscoveryInfo> info2 = RR_MAKE_SHARED<NodeDiscoveryInfo>(info); for (std::vector<NodeDiscoveryInfoURL>::iterator e = info2->URLs.begin(); e != info2->URLs.end();) { bool valid = true; if (e->URL.size() > 256) { valid = false; } if (valid) { try { ParseConnectionURLResult u = ParseConnectionURL(e->URL); if (u.nodeid != info.NodeID) { valid = false; } } catch (std::exception& exp2) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " provides invalid URL: " << e->URL << ": " << exp2.what()); valid = false; } } if (valid) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " accepting candidate URL " << e->URL); e++; } else { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " rejecting candidate URL " << e->URL); e = info2->URLs.erase(e); } } if (info2->URLs.size() == 0) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " did not find any valid candidate URLs"); return; } RR_SHARED_PTR<Discovery_nodestorage> storage = RR_MAKE_SHARED<Discovery_nodestorage>(); storage->info = info2; RR_SHARED_PTR<Discovery_updateserviceinfo> update = RR_MAKE_SHARED<Discovery_updateserviceinfo>(node); storage->updater = update; storage->recent_service_nonce.push_back(info2->ServiceStateNonce); storage->retry_window_start = n->NowNodeTime(); m_DiscoveredNodes.insert(std::make_pair(id, storage)); if (!subscriptions.empty()) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " updating service info"); update->AsyncUpdateServiceInfo(storage, info2->ServiceStateNonce, boost::bind(&Discovery::EndUpdateServiceInfo, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2), RR_BOOST_PLACEHOLDERS(_3), RR_BOOST_PLACEHOLDERS(_4))); } return; } else { boost::mutex::scoped_lock lock2(e1->second->this_lock); RR_SHARED_PTR<NodeDiscoveryInfo>& i = e1->second->info; BOOST_FOREACH(const NodeDiscoveryInfoURL& e, info.URLs) { bool found = false; BOOST_FOREACH(NodeDiscoveryInfoURL& ee, i->URLs) { if (e.URL == ee.URL) { if (e.LastAnnounceTime > ee.LastAnnounceTime) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " updating last announce time for candidate URL " << e.URL); ee.LastAnnounceTime = e.LastAnnounceTime; } found = true; } } if (!found) { if (e.URL.size() > 256) { continue; } try { ParseConnectionURLResult u = ParseConnectionURL(e.URL); if (u.nodeid != info.NodeID) { continue; } } catch (std::exception& exp2) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " provides invalid URL: " << e.URL << ": " << exp2.what()); continue; } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " accepting candidate URL " << e.URL); i->URLs.push_back(e); } } if (i->ServiceStateNonce != info.ServiceStateNonce && !info.ServiceStateNonce.empty()) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " updating ServiceStateNonce"); i->ServiceStateNonce = info.ServiceStateNonce; } if (!info.ServiceStateNonce.empty()) { if (boost::range::find(e1->second->recent_service_nonce, info.ServiceStateNonce) != e1->second->recent_service_nonce.end()) { return; } else { e1->second->recent_service_nonce.push_back(info.ServiceStateNonce); if (e1->second->recent_service_nonce.size() > 16) { e1->second->recent_service_nonce.pop_front(); } } } if (!subscriptions.empty()) { if (((i->ServiceStateNonce != e1->second->last_update_nonce) || i->ServiceStateNonce.empty()) && !e1->second->updater.lock()) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " updating service info due to change in ServiceStateNonce"); RetryUpdateServiceInfo(e1->second); } } } } catch (std::exception& exp) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " failed: " << exp.what()); } } void Discovery::EndUpdateServiceInfo(RR_SHARED_PTR<Discovery_nodestorage> storage, RR_SHARED_PTR<std::vector<ServiceInfo2> > info, boost::string_ref nonce, RR_SHARED_PTR<RobotRaconteurException> err) { RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) return; if (!info) return; boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); boost::mutex::scoped_lock lock2(storage->this_lock); storage->services = info; storage->last_update_nonce = RR_MOVE(nonce.to_string()); storage->last_update_time = n->NowNodeTime(); if (storage->last_update_nonce != storage->info->ServiceStateNonce) { //We missed an update, do another refresh but delay 5 seconds to prevent flooding if (!storage->updater.lock()) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "ServiceStateNonce for " << storage->info->NodeID.ToString() << " changed during update, retry"); RetryUpdateServiceInfo(storage); } } else { storage->retry_count.data() = 0; } BOOST_FOREACH(RR_WEAK_PTR<IServiceSubscription> s, subscriptions) { RR_SHARED_PTR<IServiceSubscription> s1 = s.lock(); if (!s1) continue; s1->NodeUpdated(storage); } RobotRaconteurNode::TryPostToThreadPool(node, boost::bind(&RobotRaconteurNode::FireNodeDetected, n, storage->info, storage->services)); } void Discovery::RetryUpdateServiceInfo(RR_SHARED_PTR<Discovery_nodestorage> storage) { //If updater is running, return if (storage->updater.lock()) return; ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateServiceInfo retry requested for " << storage->info->NodeID.ToString()); RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) return; boost::posix_time::ptime now = n->NowNodeTime(); if (now > storage->retry_window_start + boost::posix_time::seconds(60)) { storage->retry_window_start = now; storage->retry_count.data() = 0; } uint32_t retry_count = storage->retry_count.data()++; //Add progressive backoffs to prevent flooding uint32_t backoff = n->GetRandomInt<uint32_t>(100,600); if (retry_count > 3) backoff = n->GetRandomInt<uint32_t>(2000, 2500); if (retry_count > 5) backoff = n->GetRandomInt<uint32_t>(4500, 5500); if (retry_count > 8) backoff = n->GetRandomInt<uint32_t>(9000, 11000); if (retry_count > 12) backoff = n->GetRandomInt<uint32_t>(25000, 35000); //If nonce isn't in use, add 15 seconds to delay if (storage->info->ServiceStateNonce.empty() && storage->last_update_nonce.empty() && !storage->last_update_time.is_not_a_date_time()) { backoff += 15000; } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateServiceInfo retry requested for " << storage->info->NodeID.ToString() << " using backoff " << backoff << " ms for retry " << retry_count); RR_SHARED_PTR<Discovery_updateserviceinfo> update = RR_MAKE_SHARED<Discovery_updateserviceinfo>(node); storage->updater = update; update->AsyncUpdateServiceInfo(storage, storage->info->ServiceStateNonce, boost::bind(&Discovery::EndUpdateServiceInfo, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2), RR_BOOST_PLACEHOLDERS(_3), RR_BOOST_PLACEHOLDERS(_4)), backoff); } void Discovery::UpdateDetectedNodes(const std::vector<std::string>& schemes) { ROBOTRACONTEUR_ASSERT_MULTITHREADED(node); RR_SHARED_PTR<detail::sync_async_handler<void> > t = RR_MAKE_SHARED<detail::sync_async_handler<void> >(); boost::function<void()> h = boost::bind(&detail::sync_async_handler<void>::operator(), t); AsyncUpdateDetectedNodes(schemes, h); t->end_void(); } void Discovery::AsyncUpdateDetectedNodes(const std::vector<std::string>& schemes, boost::function<void()>& handler, int32_t timeout) { RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) throw InvalidOperationException("Node has been released"); ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateDetectedNodes requested for schemes " << boost::join(schemes,", ")); std::vector<RR_SHARED_PTR<Transport> > t; { boost::mutex::scoped_lock lock(n->transports_lock); boost::copy(n->transports | boost::adaptors::map_values, std::back_inserter(t)); } RR_SHARED_PTR<Discovery_updatediscoverednodes> d = RR_MAKE_SHARED<Discovery_updatediscoverednodes>(n); d->UpdateDiscoveredNodes(schemes, t, RR_MOVE(handler), timeout); } void Discovery::NodeAnnouncePacketReceived(boost::string_ref packet) { RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) return; try { std::string seed = "Robot Raconteur Node Discovery Packet"; if (packet.substr(0, seed.length()) == seed) { std::vector<std::string> lines; boost::split(lines, packet, boost::is_from_range('\n', '\n')); std::vector<std::string> idline; boost::split(idline, lines.at(1), boost::is_from_range(',', ',')); RobotRaconteur::NodeID nodeid(idline.at(0)); std::string nodename; if (idline.size() > 1) { nodename = idline.at(1); } std::string url = lines.at(2); //If the URL or nodename is excessively long, just ignore it if (url.size() > 256) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Parsing discovery text packet failed: invalid URL"); return; } if (nodename.size() > 128) { nodename.clear(); } try { ParseConnectionURLResult u = ParseConnectionURL(url); if (u.nodeid != nodeid) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Parsing discovery text packet failed: invalid URL"); return; } } catch (ConnectionException& exp2) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Parsing discovery text packet URL failed: " << exp2.what()); return; } std::string services_nonce; try { for (size_t i = 3; i < lines.size(); i++) { std::string& l = lines.at(i); boost::trim(l); if (l.empty()) continue; boost::regex r("^\\s*([\\w+\\.\\-]+)\\s*\\:\\s*(.*)\\s*$"); boost::smatch r_match; if (!boost::regex_match(l, r_match, r)) { continue; } std::string attr_name = boost::trim_copy(r_match[1].str()); std::string attr_value = boost::trim_copy(r_match[2].str()); if (attr_name == "ServiceStateNonce" && attr_value.size() < 32) { services_nonce = attr_value; } } } catch (std::exception& exp2) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Parsing discovery text packet attributes failed: " << exp2.what()); } NodeDiscoveryInfo info; info.NodeID = nodeid; info.NodeName = nodename; NodeDiscoveryInfoURL url1; url1.LastAnnounceTime = n->NowNodeTime(); url1.URL = url; info.URLs.push_back(url1); info.ServiceStateNonce = services_nonce; ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Parsing discovery text packet successful for node " << info.NodeID.ToString()); NodeDetected(info); } else { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Invalid discovery text packet received"); } } catch (std::exception& exp) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Parsing discovery text packet failed: " << exp.what()); }; //Console.WriteLine(packet); } void Discovery::CleanDiscoveredNodes() { RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) return; { boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); boost::posix_time::ptime now = n->NowNodeTime(); std::vector<std::string> keys; boost::copy(m_DiscoveredNodes | boost::adaptors::map_keys, std::back_inserter(keys)); BOOST_FOREACH(std::string& e, keys) { try { std::vector<NodeDiscoveryInfoURL> newurls = std::vector<NodeDiscoveryInfoURL>(); std::map<std::string, RR_SHARED_PTR<Discovery_nodestorage> >::iterator e1 = m_DiscoveredNodes.find(e); if (e1 == m_DiscoveredNodes.end()) continue; boost::mutex::scoped_lock lock2(e1->second->this_lock); std::vector<NodeDiscoveryInfoURL> urls = e1->second->info->URLs; BOOST_FOREACH(NodeDiscoveryInfoURL& u, urls) { int64_t time = (now - u.LastAnnounceTime).total_milliseconds(); if (time < 60000) { newurls.push_back(u); } } e1->second->info->URLs = newurls; if (newurls.empty()) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Discovery lost node " << e1->second->info->NodeID.ToString()); RR_SHARED_PTR<Discovery_nodestorage> e2 = e1->second; BOOST_FOREACH(RR_WEAK_PTR<IServiceSubscription> s, subscriptions) { RR_SHARED_PTR<IServiceSubscription> s1 = s.lock(); if (!s1) continue; try { s1->NodeLost(e2); } catch (std::exception&) {} } lock2.unlock(); m_DiscoveredNodes.erase(e1); RobotRaconteurNode::TryPostToThreadPool(node, boost::bind(&RobotRaconteurNode::FireNodeLost, n, e2->info)); } } catch (std::exception& exp2) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Error cleaning node " << e << ": " << exp2.what()); } } } } uint32_t Discovery::GetNodeDiscoveryMaxCacheCount() { boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); return max_DiscoveredNodes; } void Discovery::SetNodeDiscoveryMaxCacheCount(uint32_t count) { boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); max_DiscoveredNodes.data() = count; ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "NodeDiscoveryMaxCacheCount set to " << count); } void Discovery::AsyncFindServiceByType(boost::string_ref servicetype, const std::vector<std::string>& transportschemes, boost::function<void(RR_SHARED_PTR<std::vector<ServiceInfo2> >) >& handler, int32_t timeout) { RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) throw InvalidOperationException("Node has been released"); std::list<std::vector<std::string> > all_urls; std::vector<ServiceInfo2> services; std::vector<std::string> nodeids; { boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); boost::copy(m_DiscoveredNodes | boost::adaptors::map_keys, std::back_inserter(nodeids)); } for (size_t i = 0; i < nodeids.size(); i++) { boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); try { std::vector<std::string> urls = std::vector<std::string>(); std::map<std::string, RR_SHARED_PTR<Discovery_nodestorage> >::iterator e1 = m_DiscoveredNodes.find(nodeids.at(i)); if (e1 == m_DiscoveredNodes.end()) continue; boost::mutex::scoped_lock lock2(e1->second->this_lock); BOOST_FOREACH(NodeDiscoveryInfoURL& url, e1->second->info->URLs) { BOOST_FOREACH(const std::string& e, transportschemes) { std::string t2 = (e + "://"); if (boost::starts_with(url.URL, t2)) { urls.push_back(url.URL); break; } } } if (!urls.empty()) all_urls.push_back(urls); } catch (std::exception& exp) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Error searching for candidate URLs for FindServiceByType: " << exp.what()); } } RR_SHARED_PTR<Discovery_findservicebytype> f = RR_MAKE_SHARED<Discovery_findservicebytype>(n); f->AsyncFindServiceByType(servicetype, transportschemes, RR_MOVE(handler), timeout); } std::vector<ServiceInfo2> Discovery::FindServiceByType(boost::string_ref servicetype, const std::vector<std::string>& transportschemes) { ROBOTRACONTEUR_ASSERT_MULTITHREADED(node); RR_SHARED_PTR<detail::sync_async_handler<std::vector<ServiceInfo2> > > t = RR_MAKE_SHARED<detail::sync_async_handler<std::vector<ServiceInfo2> > >(); boost::function< void(RR_SHARED_PTR<std::vector<ServiceInfo2> >) > h = boost::bind(&detail::sync_async_handler<std::vector<ServiceInfo2> >::operator(), t, RR_BOOST_PLACEHOLDERS(_1), RR_SHARED_PTR<RobotRaconteurException>()); AsyncFindServiceByType(servicetype, transportschemes, h); return *t->end(); } std::vector<NodeInfo2> Discovery::FindNodeByID(const RobotRaconteur::NodeID& id, const std::vector<std::string>& transportschemes) { ROBOTRACONTEUR_ASSERT_MULTITHREADED(node); RR_SHARED_PTR<detail::sync_async_handler<std::vector<NodeInfo2> > > n = RR_MAKE_SHARED<detail::sync_async_handler<std::vector<NodeInfo2> > >(); boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) > h = boost::bind(&detail::sync_async_handler<std::vector<NodeInfo2> >::operator(), n, RR_BOOST_PLACEHOLDERS(_1), RR_SHARED_PTR<RobotRaconteurException>()); AsyncFindNodeByID(id, transportschemes, h); return *n->end(); } void Discovery::AsyncFindNodeByID(const RobotRaconteur::NodeID& id, const std::vector<std::string>& transportschemes, boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) >& handler, int32_t timeout) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin AsyncFindNodeByID for remote node " << id.ToString()); RobotRaconteur::NodeID id1 = id; boost::function<void()> h = boost::bind(&Discovery::EndAsyncFindNodeByID, shared_from_this(), id1, transportschemes, handler); AsyncUpdateDetectedNodes(transportschemes, h, timeout); } void Discovery::EndAsyncFindNodeByID(RobotRaconteur::NodeID id, std::vector<std::string> transportschemes, boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) >& handler) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "AsyncFindNodeByID for remote node " << id.ToString() << " update complete"); RR_SHARED_PTR<std::vector<NodeInfo2> > ret = RR_MAKE_SHARED<std::vector<NodeInfo2> >(); std::string sid = id.ToString(); { boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); std::map<std::string, RR_SHARED_PTR<Discovery_nodestorage> >::iterator e1 = m_DiscoveredNodes.find(sid); if (e1 != m_DiscoveredNodes.end()) { boost::mutex::scoped_lock lock2(e1->second->this_lock); RR_SHARED_PTR<NodeDiscoveryInfo> ni = e1->second->info; NodeInfo2 n; n.NodeID = NodeID(sid); n.NodeName = ni->NodeName; BOOST_FOREACH(NodeDiscoveryInfoURL& url, ni->URLs) { BOOST_FOREACH(std::string& e, transportschemes) { try { ParseConnectionURLResult u = ParseConnectionURL(url.URL); if (u.scheme == e) { std::string short_url; if (u.port == -1) { short_url = u.scheme + "://" + u.host + u.path + "?nodeid=" + boost::replace_all_copy(boost::replace_all_copy(u.nodeid.ToString(), "{", ""), "}", ""); } else { short_url = u.scheme + "://" + u.host + ":" + boost::lexical_cast<std::string>(u.port) + u.path + "?nodeid=" + boost::replace_all_copy(boost::replace_all_copy(u.nodeid.ToString(), "{", ""), "}", ""); } n.ConnectionURL.push_back(short_url); break; } } catch (std::exception& exp2) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "AsyncFindNodeByID for remote node " << id.ToString() << " failed processing candidate: " << exp2.what()); } } } if (!n.ConnectionURL.empty()) { ret->push_back(n); } } } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "AsyncFindNodeByID for remote node " << id.ToString() << " completed successfully with " << ret->size() << " candidates"); detail::InvokeHandler(node, handler, ret); } std::vector<NodeInfo2> Discovery::FindNodeByName(boost::string_ref name, const std::vector<std::string>& transportschemes) { ROBOTRACONTEUR_ASSERT_MULTITHREADED(node); RR_SHARED_PTR<detail::sync_async_handler<std::vector<NodeInfo2> > > n = RR_MAKE_SHARED<detail::sync_async_handler<std::vector<NodeInfo2> > >(); boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) > h = boost::bind(&detail::sync_async_handler<std::vector<NodeInfo2> >::operator(), n, RR_BOOST_PLACEHOLDERS(_1), RR_SHARED_PTR<RobotRaconteurException>()); AsyncFindNodeByName(name, transportschemes, h); return *n->end(); } void Discovery::AsyncFindNodeByName(boost::string_ref name, const std::vector<std::string>& transportschemes, boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) >& handler, int32_t timeout) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin AsyncFindNodeByName for remote node \"" << name << "\""); boost::function<void()> h = boost::bind(&Discovery::EndAsyncFindNodeByName, shared_from_this(), name.to_string(), transportschemes, handler); AsyncUpdateDetectedNodes(transportschemes, h, timeout); } void Discovery::EndAsyncFindNodeByName(std::string name, std::vector<std::string> transportschemes, boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) >& handler) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "AsyncFindNodeByName for remote node \"" << name << "\" update complete"); RR_SHARED_PTR<std::vector<NodeInfo2> > ret = RR_MAKE_SHARED<std::vector<NodeInfo2> >(); { boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); BOOST_FOREACH(RR_SHARED_PTR<Discovery_nodestorage>& e, m_DiscoveredNodes | boost::adaptors::map_values) { boost::mutex::scoped_lock lock2(e->this_lock); if (e->info->NodeName == name) { NodeInfo2 n; n.NodeID = e->info->NodeID; n.NodeName = e->info->NodeName; BOOST_FOREACH(NodeDiscoveryInfoURL& url, e->info->URLs) { BOOST_FOREACH(std::string& e, transportschemes) { try { ParseConnectionURLResult u = ParseConnectionURL(url.URL); if (u.scheme == e) { std::string short_url; if (u.port == -1) { short_url = u.scheme + "://" + u.host + u.path + "?nodeid=" + boost::replace_all_copy(boost::replace_all_copy(u.nodeid.ToString(), "{", ""), "}", ""); } else { short_url = u.scheme + "://" + u.host + ":" + boost::lexical_cast<std::string>(u.port) + u.path + "?nodeid=" + boost::replace_all_copy(boost::replace_all_copy(u.nodeid.ToString(), "{", ""), "}", ""); } n.ConnectionURL.push_back(short_url); break; } } catch (std::exception& exp2) { ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "AsyncFindNodeByID for remote node \"" << name << "\" failed processing candidate: " << exp2.what()); } } } if (!n.ConnectionURL.empty()) { ret->push_back(n); } } } } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "AsyncFindNodeByID for remote node \"" << name << "\" completed successfully with " << ret->size() << " candidates"); detail::InvokeHandler(node, handler, ret); } RR_SHARED_PTR<RobotRaconteurNode> Discovery::GetNode() { RR_SHARED_PTR<RobotRaconteurNode> n = node.lock(); if (!n) throw InvalidOperationException("Node has been released"); return n; } RR_SHARED_PTR<ServiceSubscription> Discovery::SubscribeService(const std::vector<std::string>& url, boost::string_ref username, RR_INTRUSIVE_PTR<RRMap<std::string,RRValue> > credentials, boost::string_ref objecttype) { RR_SHARED_PTR<ServiceSubscription> s = RR_MAKE_SHARED<ServiceSubscription>(shared_from_this()); s->InitServiceURL(url,username,credentials,objecttype); return s; } RR_SHARED_PTR<ServiceSubscription> Discovery::SubscribeServiceByType(const std::vector<std::string>& service_types, RR_SHARED_PTR<ServiceSubscriptionFilter> filter) { RR_SHARED_PTR<ServiceSubscription> s = RR_MAKE_SHARED<ServiceSubscription>(shared_from_this()); DoSubscribe(service_types, filter, s); return s; } RR_SHARED_PTR<ServiceInfo2Subscription> Discovery::SubscribeServiceInfo2(const std::vector<std::string>& service_types, RR_SHARED_PTR<ServiceSubscriptionFilter> filter) { RR_SHARED_PTR<ServiceInfo2Subscription> s = RR_MAKE_SHARED<ServiceInfo2Subscription>(shared_from_this()); DoSubscribe(service_types, filter, s); return s; } void Discovery::DoSubscribe(const std::vector<std::string>& service_types, RR_SHARED_PTR<ServiceSubscriptionFilter> filter, RR_SHARED_PTR<IServiceSubscription> s) { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin DoSubscribe for service types " << boost::join(service_types, ", ")); boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); subscriptions.push_back(s); s->Init(service_types, filter); std::vector<RR_SHARED_PTR<Discovery_nodestorage> > storage; boost::range::copy(m_DiscoveredNodes | boost::adaptors::map_values, std::back_inserter(storage)); lock.unlock(); BOOST_FOREACH(RR_SHARED_PTR<Discovery_nodestorage>& n, storage) { boost::mutex::scoped_lock(n->this_lock); if (n->last_update_nonce != n->info->ServiceStateNonce || n->info->ServiceStateNonce.empty()) { try { ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Subscription requesting update for node " << n->info->NodeID.ToString()); RetryUpdateServiceInfo(n); } catch (std::exception& exp) { RobotRaconteurNode::TryHandleException(node, &exp); } } s->NodeUpdated(n); } } void Discovery::SubscriptionClosed(RR_SHARED_PTR<IServiceSubscription> subscription) { boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Subscription closed"); for (std::list<RR_WEAK_PTR<IServiceSubscription> >::iterator e = subscriptions.begin(); e != subscriptions.end(); ) { RR_SHARED_PTR<IServiceSubscription> s = e->lock(); if (!s) { e = subscriptions.erase(e); continue; } if (s == subscription) { e = subscriptions.erase(e); } else { e++; } } } void Discovery::Shutdown() { std::list<RR_WEAK_PTR<IServiceSubscription> > subscriptions1; { boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock); is_shutdown.data() = true; subscriptions = RR_MOVE(subscriptions1); } BOOST_FOREACH(RR_WEAK_PTR<IServiceSubscription>& s, subscriptions1) { RR_SHARED_PTR<IServiceSubscription> s1 = s.lock(); if (s1) { s1->Close(); } } ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Discovery shut down"); } } }
33.175081
344
0.673153
robotraconteur
eda638f445c131091d5de5a945bf29c8532f6e0e
552
cpp
C++
stack_two_queues/stack_two_queues.cpp
ryanmcdermott/katas
d23b8c131f03e4df0a3a5268de4b63c5b35058a1
[ "MIT" ]
46
2017-06-26T15:09:10.000Z
2022-03-19T04:21:32.000Z
stack_two_queues/stack_two_queues.cpp
ryanmcdermott/katas
d23b8c131f03e4df0a3a5268de4b63c5b35058a1
[ "MIT" ]
null
null
null
stack_two_queues/stack_two_queues.cpp
ryanmcdermott/katas
d23b8c131f03e4df0a3a5268de4b63c5b35058a1
[ "MIT" ]
13
2017-10-18T05:30:18.000Z
2021-10-04T22:46:35.000Z
#include "./stack_two_queues.hpp" #include <queue> using std::queue; void stack_two_queues::pop() { if (q1.empty()) { return; } while (q1.size() != 1) { q2.push(q1.front()); q1.pop(); } q1.pop(); queue<int> temp = q1; q1 = q2; q2 = temp; } void stack_two_queues::push(int num) { q1.push(num); } int stack_two_queues::top() { while (q1.size() != 1) { q2.push(q1.front()); q1.pop(); } int top_item = q1.front(); q2.push(top_item); queue<int> temp = q1; q1 = q2; q2 = temp; return top_item; }
13.8
54
0.559783
ryanmcdermott
eda87f79f5dcd8a91e728dc73a19ca219e1aa82e
3,181
cpp
C++
sample/main.cpp
vmcraft/remoteprinter
bf0294bb01ec61782daf166a869abd2ee97fba28
[ "Apache-2.0" ]
11
2019-11-18T10:17:25.000Z
2022-01-26T04:48:16.000Z
sample/main.cpp
vmcraft/remoteprinter
bf0294bb01ec61782daf166a869abd2ee97fba28
[ "Apache-2.0" ]
null
null
null
sample/main.cpp
vmcraft/remoteprinter
bf0294bb01ec61782daf166a869abd2ee97fba28
[ "Apache-2.0" ]
5
2016-10-13T14:05:17.000Z
2021-02-09T15:50:29.000Z
#include "thriftlink_server.h" #include "userdef_server.h" #include <Windows.h> #include "stdio.h" #pragma comment(lib, "user32.lib") bool inject_dll(HMODULE &hmodule, HHOOK &hhook, int target_threadid); void eject_dll(HMODULE &hmodule, HHOOK &hhook); BOOL CtrlHandler( DWORD fdwCtrlType ) ; bool _break_loop = false; int main(int argc, char **argv) { if (argc==3 && _stricmp(argv[1], "hook")==0){ int threadid = atoi(argv[2]); HMODULE hmodule = NULL; HHOOK hhook = NULL; // Inject dlls if (!inject_dll(hmodule, hhook, threadid)){ printf("Injection failed.\n"); return 1; } // Set Ctrl handler. if( !SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE ) ) { printf("Could not set control handler.\n"); return 1; } printf("Press CTRL+C to stop.\n"); // Message handler is required for 32bit/64bit platform cross supporting. MSG msg; bool runThread = true; while(runThread) { // Keep pumping... PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE); TranslateMessage(&msg); DispatchMessage(&msg); if (_break_loop) break; Sleep(10); } eject_dll(hmodule, hhook); return 0; } else if ((argc==2||argc==3) && _stricmp(argv[1], "server")==0) { int port = 3900; if (argc==3) atoi(argv[2]); thrift_server_start(port); return 0; } printf("Usage:\n"); printf(" %s hook thread_id\n", argv[0]); printf(" %s server [port_number]\n", argv[0]); return 1; } // // This sample demonstrate how to inject dll by SetWindowsHookEx. // You can inject apifwrd.dll to destination process simply by AppInit_DLLs registry key or // implement your own method like CreateRemoteThread, ... // bool inject_dll(HMODULE &hmodule, HHOOK &hhook, int target_threadid) { // Already hooked. if (hhook!=NULL) return true; // Load library if (hmodule==NULL) { hmodule = LoadLibraryW(L"apifwrd.dll"); if (hmodule==NULL) return false; } // apifwrd.dll is ready to support SetWindowsHookEx() way. HOOKPROC addr = (HOOKPROC) GetProcAddress(hmodule, "HelperHookProcForSetWindowsHookEx"); if (addr==NULL) { FreeLibrary(hmodule); return false; } // Install hook hhook = SetWindowsHookEx(WH_CBT, addr, hmodule, target_threadid); if (hhook==NULL) { FreeLibrary(hmodule); return false; } return true; } void eject_dll(HMODULE &hmodule, HHOOK &hhook) { if (hhook) { UnhookWindowsHookEx(hhook); hhook = NULL; } if (hmodule) { FreeLibrary(hmodule); hmodule = NULL; } return; } BOOL CtrlHandler( DWORD fdwCtrlType ) { switch( fdwCtrlType ) { // Handle the CTRL-C signal. case CTRL_C_EVENT: case CTRL_CLOSE_EVENT: case CTRL_BREAK_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: _break_loop = true; break; default: return FALSE; } return TRUE; }
24.098485
92
0.594467
vmcraft
eda9a8023016c2c2f78c0248d7af05f1c29ba080
9,777
cpp
C++
tests/performance/memory/hipPerfBufferCopySpeed.cpp
parmance/HIP
96ee9d1397f02ac4b4badd9243994728f6a89fe5
[ "MIT" ]
1,935
2017-05-28T04:52:18.000Z
2022-03-30T23:50:43.000Z
tests/performance/memory/hipPerfBufferCopySpeed.cpp
parmance/HIP
96ee9d1397f02ac4b4badd9243994728f6a89fe5
[ "MIT" ]
1,310
2017-05-30T22:16:09.000Z
2022-03-31T08:25:58.000Z
tests/performance/memory/hipPerfBufferCopySpeed.cpp
parmance/HIP
96ee9d1397f02ac4b4badd9243994728f6a89fe5
[ "MIT" ]
495
2017-06-01T01:26:27.000Z
2022-03-28T16:36:51.000Z
/* Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. 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. */ /* HIT_START * BUILD: %t %s ../../src/test_common.cpp ../../src/timer.cpp * TEST: %t * HIT_END */ #include <stdio.h> #include <assert.h> #include <string.h> #include <complex> #include "timer.h" #include "test_common.h" // Quiet pesky warnings #ifdef WIN_OS #define SNPRINTF sprintf_s #else #define SNPRINTF snprintf #endif #define NUM_SIZES 9 //4KB, 8KB, 64KB, 256KB, 1 MB, 4MB, 16 MB, 16MB+10 static const unsigned int Sizes[NUM_SIZES] = {4096, 8192, 65536, 262144, 524288, 1048576, 4194304, 16777216, 16777216+10}; static const unsigned int Iterations[2] = {1, 1000}; #define BUF_TYPES 4 // 16 ways to combine 4 different buffer types #define NUM_SUBTESTS (BUF_TYPES*BUF_TYPES) #define CHECK_RESULT(test, msg) \ if ((test)) \ { \ printf("\n%s\n", msg); \ abort(); \ } void setData(void *ptr, unsigned int size, char value) { char *ptr2 = (char *)ptr; for (unsigned int i = 0; i < size ; i++) { ptr2[i] = value; } } void checkData(void *ptr, unsigned int size, char value) { char *ptr2 = (char *)ptr; for (unsigned int i = 0; i < size; i++) { if (ptr2[i] != value) { printf("Data validation failed at %d! Got 0x%08x\n", i, ptr2[i]); printf("Expected 0x%08x\n", value); CHECK_RESULT(true, "Data validation failed!"); break; } } } int main(int argc, char* argv[]) { HipTest::parseStandardArguments(argc, argv, true); hipError_t err = hipSuccess; hipDeviceProp_t props = {0}; hipGetDeviceProperties(&props, p_gpuDevice); CHECK_RESULT(err != hipSuccess, "hipGetDeviceProperties failed" ); printf("Set device to %d : %s\n", p_gpuDevice, props.name); printf("Legend: unp - unpinned(malloc), hM - hipMalloc(device)\n"); printf(" hHR - hipHostRegister(pinned), hHM - hipHostMalloc(prePinned)\n"); err = hipSetDevice(p_gpuDevice); CHECK_RESULT(err != hipSuccess, "hipSetDevice failed" ); unsigned int bufSize_; bool hostMalloc[2] = {false}; bool hostRegister[2] = {false}; bool unpinnedMalloc[2] = {false}; unsigned int numIter; void *memptr[2] = {NULL}; void *alignedmemptr[2] = {NULL}; void* srcBuffer = NULL; void* dstBuffer = NULL; int numTests = (p_tests == -1) ? (NUM_SIZES*NUM_SUBTESTS*2 - 1) : p_tests; int test = (p_tests == -1) ? 0 : p_tests; for(;test <= numTests; test++) { unsigned int srcTest = (test / NUM_SIZES) % BUF_TYPES; unsigned int dstTest = (test / (NUM_SIZES*BUF_TYPES)) % BUF_TYPES; bufSize_ = Sizes[test % NUM_SIZES]; hostMalloc[0] = hostMalloc[1] = false; hostRegister[0] = hostRegister[1] = false; unpinnedMalloc[0] = unpinnedMalloc[1] = false; srcBuffer = dstBuffer = 0; memptr[0] = memptr[1] = NULL; alignedmemptr[0] = alignedmemptr[1] = NULL; if (srcTest == 3) { hostRegister[0] = true; } else if (srcTest == 2) { hostMalloc[0] = true; } else if (srcTest == 1) { unpinnedMalloc[0] = true; } if (dstTest == 1) { unpinnedMalloc[1] = true; } else if (dstTest == 2) { hostMalloc[1] = true; } else if (dstTest == 3) { hostRegister[1] = true; } numIter = Iterations[test / (NUM_SIZES * NUM_SUBTESTS)]; if (hostMalloc[0]) { err = hipHostMalloc((void**)&srcBuffer, bufSize_, 0); setData(srcBuffer, bufSize_, 0xd0); CHECK_RESULT(err != hipSuccess, "hipHostMalloc failed"); } else if (hostRegister[0]) { memptr[0] = malloc(bufSize_ + 4096); alignedmemptr[0] = (void*)(((size_t)memptr[0] + 4095) & ~4095); srcBuffer = alignedmemptr[0]; setData(srcBuffer, bufSize_, 0xd0); err = hipHostRegister(srcBuffer, bufSize_, 0); CHECK_RESULT(err != hipSuccess, "hipHostRegister failed"); } else if (unpinnedMalloc[0]) { memptr[0] = malloc(bufSize_ + 4096); alignedmemptr[0] = (void*)(((size_t)memptr[0] + 4095) & ~4095); srcBuffer = alignedmemptr[0]; setData(srcBuffer, bufSize_, 0xd0); } else { err = hipMalloc(&srcBuffer, bufSize_); CHECK_RESULT(err != hipSuccess, "hipMalloc failed"); err = hipMemset(srcBuffer, 0xd0, bufSize_); CHECK_RESULT(err != hipSuccess, "hipMemset failed"); } if (hostMalloc[1]) { err = hipHostMalloc((void**)&dstBuffer, bufSize_, 0); CHECK_RESULT(err != hipSuccess, "hipHostMalloc failed"); } else if (hostRegister[1]) { memptr[1] = malloc(bufSize_ + 4096); alignedmemptr[1] = (void*)(((size_t)memptr[1] + 4095) & ~4095); dstBuffer = alignedmemptr[1]; err = hipHostRegister(dstBuffer, bufSize_, 0); CHECK_RESULT(err != hipSuccess, "hipHostRegister failed"); } else if (unpinnedMalloc[1]) { memptr[1] = malloc(bufSize_ + 4096); alignedmemptr[1] = (void*)(((size_t)memptr[1] + 4095) & ~4095); dstBuffer = alignedmemptr[1]; } else { err = hipMalloc(&dstBuffer, bufSize_); CHECK_RESULT(err != hipSuccess, "hipMalloc failed"); } CPerfCounter timer; //warm up err = hipMemcpy(dstBuffer, srcBuffer, bufSize_, hipMemcpyDefault); CHECK_RESULT(err, "hipMemcpy failed"); timer.Reset(); timer.Start(); for (unsigned int i = 0; i < numIter; i++) { err = hipMemcpyAsync(dstBuffer, srcBuffer, bufSize_, hipMemcpyDefault, NULL); CHECK_RESULT(err, "hipMemcpyAsync failed"); } err = hipDeviceSynchronize(); CHECK_RESULT(err, "hipDeviceSynchronize failed"); timer.Stop(); double sec = timer.GetElapsedTime(); // Buffer copy bandwidth in GB/s double perf = ((double)bufSize_*numIter*(double)(1e-09)) / sec; const char *strSrc = NULL; const char *strDst = NULL; if (hostMalloc[0]) strSrc = "hHM"; else if (hostRegister[0]) strSrc = "hHR"; else if (unpinnedMalloc[0]) strSrc = "unp"; else strSrc = "hM"; if (hostMalloc[1]) strDst = "hHM"; else if (hostRegister[1]) strDst = "hHR"; else if (unpinnedMalloc[1]) strDst = "unp"; else strDst = "hM"; // Double results when src and dst are both on device if ((!hostMalloc[0] && !hostRegister[0] && !unpinnedMalloc[0]) && (!hostMalloc[1] && !hostRegister[1] && !unpinnedMalloc[1])) perf *= 2.0; // Double results when src and dst are both in sysmem if ((hostMalloc[0] || hostRegister[0] || unpinnedMalloc[0]) && (hostMalloc[1] || hostRegister[1] || unpinnedMalloc[1])) perf *= 2.0; char buf[256]; SNPRINTF(buf, sizeof(buf), "HIPPerfBufferCopySpeed[%d]\t(%8d bytes)\ts:%s d:%s\ti:%4d\t(GB/s) perf\t%f", test, bufSize_, strSrc, strDst, numIter, (float)perf); printf("%s\n", buf); // Verification void* temp = malloc(bufSize_ + 4096); void* chkBuf = (void*)(((size_t)temp + 4095) & ~4095); err = hipMemcpy(chkBuf, dstBuffer, bufSize_, hipMemcpyDefault); CHECK_RESULT(err, "hipMemcpy failed"); checkData(chkBuf, bufSize_, 0xd0); free(temp); //Free src if (hostMalloc[0]) { hipHostFree(srcBuffer); } else if (hostRegister[0]) { hipHostUnregister(srcBuffer); free(memptr[0]); } else if (unpinnedMalloc[0]) { free(memptr[0]); } else { hipFree(srcBuffer); } //Free dst if (hostMalloc[1]) { hipHostFree(dstBuffer); } else if (hostRegister[1]) { hipHostUnregister(dstBuffer); free(memptr[1]); } else if (unpinnedMalloc[1]) { free(memptr[1]); } else { hipFree(dstBuffer); } } passed(); }
31.846906
122
0.561215
parmance
edaa67352a7ea85bdfe3f9ea126b78b8d7ae713a
3,766
cpp
C++
test/InverseKinematicsTest.cpp
EthanQuist/ENPM808X_Midterm
ab01777bd9da910cd750dffbeaf15ba60b619062
[ "BSD-3-Clause" ]
null
null
null
test/InverseKinematicsTest.cpp
EthanQuist/ENPM808X_Midterm
ab01777bd9da910cd750dffbeaf15ba60b619062
[ "BSD-3-Clause" ]
3
2019-10-13T03:34:25.000Z
2019-10-20T23:57:43.000Z
test/InverseKinematicsTest.cpp
EthanQuist/ENPM808X_Midterm
ab01777bd9da910cd750dffbeaf15ba60b619062
[ "BSD-3-Clause" ]
1
2019-10-10T03:52:53.000Z
2019-10-10T03:52:53.000Z
/* Copyright (c) 2019, Acme Robotics, Ethan Quist, Corbyn Yhap * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <gtest/gtest.h> #include <algorithm> #include "InverseKinematics.hpp" #include "RevoluteJoint.hpp" bool AreSame(double a, double b) { double error = fabs(a - b); double epsilon = 0.00001; return error < epsilon; } TEST(InverseKinematics, checkContract) { InverseKinematicAcmeArm IKsolver; std::vector<JointPtr> result; // Using the Coordinates from the Paper Eigen::Matrix4d T = Eigen::Matrix4d::Identity(); // Transform Matrix - Position T.block<3, 1>(0, 3) = Eigen::Vector3d(2.0, 0.0, 2.5); result = IKsolver.computeIK(T); JointPtr tQ1(new RevoluteJoint(0)); JointPtr tQ2(new RevoluteJoint(0)); JointPtr tQ3(new RevoluteJoint(0)); JointPtr tQ4(new RevoluteJoint(1.5708)); JointPtr tQ5(new RevoluteJoint(1.5708)); JointPtr tQ6(new RevoluteJoint(-1.5708)); std::vector<JointPtr> expected; expected.push_back(tQ1); expected.push_back(tQ2); expected.push_back(tQ3); expected.push_back(tQ4); expected.push_back(tQ5); expected.push_back(tQ6); // Test the number of joints that were output ASSERT_EQ(expected.size(), result.size()); // Test Each element in each matches (in order) JointPtr result1 = result[0]; double r1 = result1->getConfig(); double q1 = tQ1->getConfig(); bool joint_angle1 = AreSame(r1, q1); ASSERT_EQ(joint_angle1, true); JointPtr result2 = result[1]; double r2 = result2->getConfig(); double q2 = tQ2->getConfig(); bool joint_angle2 = AreSame(r2, q2); ASSERT_EQ(joint_angle2, true); JointPtr result3 = result[2]; double r3 = result3->getConfig(); double q3 = tQ3->getConfig(); bool joint_angle3 = AreSame(r3, q3); ASSERT_EQ(joint_angle3, true); JointPtr result4 = result[3]; double r4 = result4->getConfig(); double q4 = tQ4->getConfig(); bool joint_angle4 = AreSame(r4, q4); ASSERT_EQ(joint_angle4, true); JointPtr result5 = result[4]; double r5 = result5->getConfig(); double q5 = tQ5->getConfig(); bool joint_angle5 = AreSame(r5, q5); ASSERT_EQ(joint_angle5, true); JointPtr result6 = result[5]; double r6 = result6->getConfig(); double q6 = tQ6->getConfig(); bool joint_angle6 = AreSame(r6, q6); ASSERT_EQ(joint_angle6, true); }
34.87037
81
0.726766
EthanQuist
edab83287730821302267413d54d4745442a48cb
8,154
cpp
C++
src/modules/socket/server/icmp_socket.cpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
20
2019-12-04T01:28:52.000Z
2022-03-17T14:09:34.000Z
src/modules/socket/server/icmp_socket.cpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
115
2020-02-04T21:29:54.000Z
2022-02-17T13:33:51.000Z
src/modules/socket/server/icmp_socket.cpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
16
2019-12-03T16:41:18.000Z
2021-11-06T04:44:11.000Z
#include <cassert> #include <cstring> #include <numeric> #include <optional> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/uio.h> #include "socket/server/icmp_socket.hpp" #include "socket/server/lwip_utils.hpp" #include "socket/server/raw_socket.hpp" #include "lwip/icmp.h" #include "lwip/icmp6.h" #include "lwip/memp.h" #include "lwip/raw.h" #include "socket/server/compat/linux/icmp.h" #include "socket/server/compat/linux/icmp6.h" namespace openperf::socket::server { /* * XXX: Uses LwIP functions that reference global variables instead of parsing * the pbuf, however this signature is used in case that ever needs to change. */ static uint8_t icmp_type(const pbuf*) { return (ip_current_is_v6() ? ICMPH_TYPE( static_cast<const icmp6_hdr*>(ip_next_header_ptr())) : ICMPH_TYPE(static_cast<const icmp_echo_hdr*>( ip_next_header_ptr()))); } /* RAW receive function; payload should point to IP header */ static uint8_t icmp_receive_raw(void* arg, raw_pcb*, pbuf* p, const ip_addr_t* addr) { assert(addr != nullptr); auto sock = reinterpret_cast<icmp_socket*>(arg); if (sock->is_filtered(icmp_type(p))) { /* packet not handled by socket so return 0 to allow * icmp_input()/icmp6_input() to handle it */ return 0; } auto channel = std::get<dgram_channel*>(sock->channel()); return (channel->send(p, reinterpret_cast<const dgram_ip_addr*>(addr), 0)); } /* DGRAM receive functions; payload should point to ICMP(v6) header */ static uint8_t icmp_receive_dgram(void* arg, raw_pcb*, pbuf* p, const ip_addr_t* addr) { assert(addr != nullptr); auto sock = reinterpret_cast<icmp_socket*>(arg); if (sock->is_filtered(icmp_type(p))) { /* packet not handled by socket so return 0 to allow * icmp_input()/icmp6_input() to handle it */ return 0; } /* * Drop the IP header so that the payload points to the ICMP/ICMPv6 header. * XXX: ip_current_header_tot_len uses a global variable inside LwIP. */ pbuf_remove_header(p, ip_current_header_tot_len()); auto channel = std::get<dgram_channel*>(sock->channel()); return (channel->send(p, reinterpret_cast<const dgram_ip_addr*>(addr), 0)); } static raw_recv_fn get_receive_function(int type) { switch (type) { case SOCK_DGRAM: return (icmp_receive_dgram); case SOCK_RAW: return (icmp_receive_raw); default: throw std::runtime_error("Invalid icmp socket type: " + std::to_string(type)); } } icmp_socket::icmp_socket(openperf::socket::server::allocator& allocator, enum lwip_ip_addr_type ip_type, int flags, int protocol) : raw_socket( allocator, ip_type, flags, protocol, get_receive_function(flags & 0xff)) , m_filter(0) { if (protocol == IPPROTO_ICMPV6) { /* ICMPv6 packets should always have checksum calculated by the stack as * per RFC 3542 chapter 3.1 */ m_pcb->chksum_reqd = 1; m_pcb->chksum_offset = 2; /* Default to just echo reply to avoid issues with NDP */ m_filter.set(); m_filter[ICMP6_TYPE_EREP] = false; } } icmp_socket& icmp_socket::operator=(icmp_socket&& other) noexcept { if (this != &other) { m_filter = other.m_filter; } return (*this); } icmp_socket::icmp_socket(icmp_socket&& other) noexcept : raw_socket(std::move(other)) , m_filter(other.m_filter) {} tl::expected<socklen_t, int> icmp_socket::do_getsockopt(const raw_pcb* pcb, const api::request_getsockopt& getsockopt) { switch (getsockopt.level) { case SOL_RAW: switch (getsockopt.optname) { case LINUX_ICMP_FILTER: { if (pcb->protocol != IPPROTO_ICMP) return (tl::make_unexpected(EOPNOTSUPP)); auto filter = linux_icmp_filter{static_cast<uint32_t>(m_filter.to_ulong())}; auto result = copy_out(getsockopt.id.pid, getsockopt.optval, &filter, std::min(static_cast<unsigned>(sizeof(filter)), getsockopt.optlen)); if (!result) return (tl::make_unexpected(result.error())); return (sizeof(filter)); } default: return (tl::make_unexpected(ENOPROTOOPT)); } case IPPROTO_ICMPV6: return (do_icmp6_getsockopt(pcb, getsockopt)); default: return raw_socket::do_getsockopt(pcb, getsockopt); } } tl::expected<void, int> icmp_socket::do_setsockopt(raw_pcb* pcb, const api::request_setsockopt& setsockopt) { switch (setsockopt.level) { case SOL_RAW: switch (setsockopt.optname) { case LINUX_ICMP_FILTER: { if (pcb->protocol != IPPROTO_ICMP) return (tl::make_unexpected(EOPNOTSUPP)); auto filter = linux_icmp_filter{0}; auto opt = copy_in(reinterpret_cast<char*>(&filter), setsockopt.id.pid, reinterpret_cast<const char*>(setsockopt.optval), sizeof(filter), setsockopt.optlen); if (!opt) return (tl::make_unexpected(opt.error())); m_filter = icmp_filter(filter.data); return {}; } default: return (tl::make_unexpected(ENOPROTOOPT)); } case SOL_SOCKET: return (do_sock_setsockopt(reinterpret_cast<ip_pcb*>(pcb), setsockopt)); case IPPROTO_IP: return (do_ip_setsockopt(reinterpret_cast<ip_pcb*>(pcb), setsockopt)); case IPPROTO_IPV6: return (do_ip6_setsockopt(reinterpret_cast<ip_pcb*>(pcb), setsockopt)); case IPPROTO_ICMPV6: return (do_icmp6_setsockopt(pcb, setsockopt)); default: return (tl::make_unexpected(ENOPROTOOPT)); } } bool icmp_socket::is_filtered(uint8_t type) const { return (m_filter.test(type)); } tl::expected<socklen_t, int> icmp_socket::do_icmp6_getsockopt(const raw_pcb* pcb, const api::request_getsockopt& getsockopt) { assert(getsockopt.level == IPPROTO_ICMPV6); switch (getsockopt.optname) { case LINUX_ICMP6_FILTER: { if (pcb->protocol != IPPROTO_ICMPV6) return (tl::make_unexpected(EOPNOTSUPP)); auto filter = linux_icmp6_filter{0}; for (size_t i = 0; i < m_filter.size(); ++i) { if (m_filter[i]) LINUX_ICMP6_FILTER_SETBLOCK(i, &filter); } auto result = copy_out( getsockopt.id.pid, getsockopt.optval, &filter, std::min(static_cast<unsigned>(sizeof(filter)), getsockopt.optlen)); if (!result) return (tl::make_unexpected(result.error())); return (sizeof(filter)); } default: return (tl::make_unexpected(ENOPROTOOPT)); } } tl::expected<void, int> icmp_socket::do_icmp6_setsockopt(raw_pcb* pcb, const api::request_setsockopt& setsockopt) { assert(setsockopt.level == IPPROTO_ICMPV6); switch (setsockopt.optname) { case LINUX_ICMP6_FILTER: { if (pcb->protocol != IPPROTO_ICMPV6) return (tl::make_unexpected(EOPNOTSUPP)); auto filter = linux_icmp6_filter{0}; auto opt = copy_in(reinterpret_cast<char*>(&filter), setsockopt.id.pid, reinterpret_cast<const char*>(setsockopt.optval), sizeof(filter), setsockopt.optlen); if (!opt) return (tl::make_unexpected(opt.error())); for (size_t i = 0; i < m_filter.size(); ++i) { m_filter[i] = LINUX_ICMP6_FILTER_WILLBLOCK(i, &filter); } return {}; } default: return (tl::make_unexpected(ENOPROTOOPT)); } } } // namespace openperf::socket::server
33.012146
80
0.604366
DerangedMonkeyNinja
edabbfc3844b829d3065f0cbde6a6de2f2528681
6,069
hpp
C++
inference-engine/samples/hello_reshape_ssd/reshape_ssd_extension.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
1
2020-06-21T09:51:42.000Z
2020-06-21T09:51:42.000Z
inference-engine/samples/hello_reshape_ssd/reshape_ssd_extension.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
null
null
null
inference-engine/samples/hello_reshape_ssd/reshape_ssd_extension.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <map> #include <memory> #include <string> #include <algorithm> #include <vector> #include <ie_layouts.h> #include <ie_iextension.h> #include <ie_blob.h> #include <ngraph/op/op.hpp> #include <ngraph/node.hpp> #include <ngraph/opsets/opset.hpp> #define CUSTOM_RELU_TYPE "CustomReLU" class CustomReLUImpl : public InferenceEngine::ILayerExecImpl { public: explicit CustomReLUImpl(const std::shared_ptr<ngraph::Node>& node) : _node(node) {} InferenceEngine::StatusCode getSupportedConfigurations(std::vector<InferenceEngine::LayerConfig>& conf, InferenceEngine::ResponseDesc* /*resp*/) noexcept override { InferenceEngine::LayerConfig layerConfig; layerConfig.dynBatchSupport = true; if (_node->outputs().size() != 1 && _node->inputs().size() != 1) return InferenceEngine::GENERAL_ERROR; InferenceEngine::DataConfig cfg; cfg.constant = false; cfg.inPlace = 0; InferenceEngine::SizeVector order; auto partialShape = _node->get_output_partial_shape(0); if (partialShape.is_dynamic()) return InferenceEngine::GENERAL_ERROR; auto shape = _node->get_output_shape(0); for (size_t i = 0; i < shape.size(); i++) { order.push_back(i); } cfg.desc = InferenceEngine::TensorDesc(InferenceEngine::Precision::FP32, shape, {shape, order}); layerConfig.outConfs.push_back(cfg); layerConfig.inConfs.push_back(cfg); conf.push_back(layerConfig); return InferenceEngine::OK; } InferenceEngine::StatusCode init(InferenceEngine::LayerConfig& /*config*/, InferenceEngine::ResponseDesc* /*resp*/) noexcept override { return InferenceEngine::StatusCode::OK; } InferenceEngine::StatusCode execute(std::vector<InferenceEngine::Blob::Ptr>& inputs, std::vector<InferenceEngine::Blob::Ptr>& outputs, InferenceEngine::ResponseDesc* /*resp*/) noexcept override { static bool wasCalled = false; if (!wasCalled) { std::cout << "Running " + std::string(CUSTOM_RELU_TYPE) + " kernel for the first time (next messages won't be printed)" << std::endl; wasCalled = true; } for (size_t i = 0; i < inputs.size(); i++) { InferenceEngine::MemoryBlob::CPtr minput = InferenceEngine::as<InferenceEngine::MemoryBlob>(inputs[i]); InferenceEngine::MemoryBlob::Ptr moutput = InferenceEngine::as<InferenceEngine::MemoryBlob>(outputs[i]); if (!moutput || !minput) { return InferenceEngine::StatusCode::PARAMETER_MISMATCH; } // locked memory holder should be alive all time while access to its buffer happens auto minputHolder = minput->rmap(); auto moutputHolder = moutput->wmap(); auto inputData = minputHolder.as<const float *>(); auto outputData = moutputHolder.as<float *>(); for (size_t j = 0; j < minput->size(); j++) { outputData[j] = inputData[j] < 0 ? 0 : inputData[j]; } } return InferenceEngine::StatusCode::OK; } private: const std::shared_ptr<ngraph::Node> _node; }; class CustomReluOp: public ngraph::op::Op { public: static constexpr ngraph::NodeTypeInfo type_info{CUSTOM_RELU_TYPE, 0}; const ngraph::NodeTypeInfo& get_type_info() const override { return type_info; } CustomReluOp() = default; explicit CustomReluOp(const ngraph::Output<ngraph::Node>& arg): Op({arg}) { constructor_validate_and_infer_types(); } void validate_and_infer_types() override { auto input_shape = get_input_partial_shape(0).to_shape(); ngraph::Shape output_shape(input_shape); for (size_t i = 0; i < input_shape.size(); ++i) { output_shape[i] = input_shape[i]; } set_output_type(0, get_input_element_type(0), ngraph::PartialShape(output_shape)); } std::shared_ptr<ngraph::Node> copy_with_new_args(const ngraph::NodeVector& new_args) const override { if (new_args.size() != 1) { throw ngraph::ngraph_error("Incorrect number of new arguments"); } return std::make_shared<CustomReluOp>(new_args.at(0)); } bool visit_attributes(ngraph::AttributeVisitor& visitor) override { return true; } }; constexpr ngraph::NodeTypeInfo CustomReluOp::type_info; class InPlaceExtension : public InferenceEngine::IExtension { public: InPlaceExtension() { impls[CUSTOM_RELU_TYPE] = [](const std::shared_ptr<ngraph::Node>& node) -> InferenceEngine::ILayerImpl::Ptr { return std::make_shared<CustomReLUImpl>(node); }; } void GetVersion(const InferenceEngine::Version*& versionInfo) const noexcept override {} void Unload() noexcept override {} void Release() noexcept override {} std::vector<std::string> getImplTypes(const std::shared_ptr<ngraph::Node>& node) override { if (impls.find(node->description()) == impls.end()) return {}; return {"CPU"}; } InferenceEngine::ILayerImpl::Ptr getImplementation(const std::shared_ptr<ngraph::Node>& node, const std::string& implType) override { if (impls.find(node->description()) == impls.end() || implType != "CPU") return nullptr; return impls[node->description()](node); } std::map<std::string, ngraph::OpSet> getOpSets() override { static std::map<std::string, ngraph::OpSet> opsets; if (opsets.empty()) { ngraph::OpSet opset; opset.insert<CustomReluOp>(); opsets["experimental"] = opset; } return opsets; } private: std::map<std::string, std::function<InferenceEngine::ILayerImpl::Ptr(const std::shared_ptr<ngraph::Node>)>> impls; };
36.560241
137
0.633218
anton-potapov
edaec1cce6bf3b60cd02fd6a5a2daa8bb24e0360
95,371
cpp
C++
Classes/Native/Bulk_UnityEngine.UnityWebRequestWWWModule_0.cpp
sashohadz/unityStartDelayTest
875dba86e11fec2e4fd3f0b953007dd6c5e63ab1
[ "MIT" ]
null
null
null
Classes/Native/Bulk_UnityEngine.UnityWebRequestWWWModule_0.cpp
sashohadz/unityStartDelayTest
875dba86e11fec2e4fd3f0b953007dd6c5e63ab1
[ "MIT" ]
null
null
null
Classes/Native/Bulk_UnityEngine.UnityWebRequestWWWModule_0.cpp
sashohadz/unityStartDelayTest
875dba86e11fec2e4fd3f0b953007dd6c5e63ab1
[ "MIT" ]
null
null
null
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "il2cpp-class-internals.h" #include "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" // System.Action`1<UnityEngine.AsyncOperation> struct Action_1_t1617499438; // System.Byte[] struct ByteU5BU5D_t4116647657; // System.Char[] struct CharU5BU5D_t3528271667; // System.Collections.Generic.List`1<System.Byte[]> struct List_1_t1293755103; // System.Collections.Generic.List`1<System.String> struct List_1_t3319525431; // System.Object[] struct ObjectU5BU5D_t2843939325; // System.Reflection.Assembly struct Assembly_t; // System.String struct String_t; // System.Text.DecoderFallback struct DecoderFallback_t3123823036; // System.Text.EncoderFallback struct EncoderFallback_t1188251036; // System.Text.Encoding struct Encoding_t1523322056; // System.Uri struct Uri_t100236324; // System.Void struct Void_t1185182177; // UnityEngine.AssetBundle struct AssetBundle_t1153907252; // UnityEngine.CustomYieldInstruction struct CustomYieldInstruction_t1895667560; // UnityEngine.Networking.CertificateHandler struct CertificateHandler_t2739891000; // UnityEngine.Networking.DownloadHandler struct DownloadHandler_t2937767557; // UnityEngine.Networking.DownloadHandlerAssetBundle struct DownloadHandlerAssetBundle_t197128434; // UnityEngine.Networking.UnityWebRequest struct UnityWebRequest_t463507806; // UnityEngine.Networking.UnityWebRequestAsyncOperation struct UnityWebRequestAsyncOperation_t3852015985; // UnityEngine.Networking.UploadHandler struct UploadHandler_t2993558019; // UnityEngine.Object struct Object_t631007953; // UnityEngine.WWW struct WWW_t3688466362; // UnityEngine.WWWForm struct WWWForm_t4064702195; extern RuntimeClass* ByteU5BU5D_t4116647657_il2cpp_TypeInfo_var; extern RuntimeClass* Debug_t3317548046_il2cpp_TypeInfo_var; extern RuntimeClass* DownloadHandlerAssetBundle_t197128434_il2cpp_TypeInfo_var; extern RuntimeClass* Int64_t3736567304_il2cpp_TypeInfo_var; extern RuntimeClass* Object_t631007953_il2cpp_TypeInfo_var; extern RuntimeClass* String_t_il2cpp_TypeInfo_var; extern RuntimeClass* WWW_t3688466362_il2cpp_TypeInfo_var; extern String_t* _stringLiteral1060465165; extern String_t* _stringLiteral106317971; extern String_t* _stringLiteral1073086928; extern String_t* _stringLiteral1091611732; extern String_t* _stringLiteral1138636386; extern String_t* _stringLiteral1542497020; extern String_t* _stringLiteral1659593328; extern String_t* _stringLiteral1814237603; extern String_t* _stringLiteral1973828197; extern String_t* _stringLiteral2002596717; extern String_t* _stringLiteral2030167956; extern String_t* _stringLiteral2117271536; extern String_t* _stringLiteral2178748878; extern String_t* _stringLiteral2201204884; extern String_t* _stringLiteral2343474426; extern String_t* _stringLiteral2487325543; extern String_t* _stringLiteral2791739693; extern String_t* _stringLiteral3090824594; extern String_t* _stringLiteral3244775435; extern String_t* _stringLiteral3363965078; extern String_t* _stringLiteral3457136609; extern String_t* _stringLiteral3476706848; extern String_t* _stringLiteral3545044340; extern String_t* _stringLiteral356324127; extern String_t* _stringLiteral3604523934; extern String_t* _stringLiteral3739562776; extern String_t* _stringLiteral380657706; extern String_t* _stringLiteral3842069051; extern String_t* _stringLiteral3860885797; extern String_t* _stringLiteral3899005722; extern String_t* _stringLiteral3911804090; extern String_t* _stringLiteral4002396095; extern String_t* _stringLiteral4054833267; extern String_t* _stringLiteral4140321389; extern String_t* _stringLiteral4233297459; extern String_t* _stringLiteral4277434149; extern String_t* _stringLiteral461727106; extern String_t* _stringLiteral560819067; extern String_t* _stringLiteral573727993; extern String_t* _stringLiteral624401215; extern String_t* _stringLiteral757602046; extern String_t* _stringLiteral858510039; extern const uint32_t WWW_GetStatusCodeName_m3580893459_MetadataUsageId; extern const uint32_t WWW_LoadFromCacheOrDownload_m4247140216_MetadataUsageId; extern const uint32_t WWW_WaitUntilDoneIfPossible_m2855479680_MetadataUsageId; extern const uint32_t WWW_get_assetBundle_m3753667806_MetadataUsageId; extern const uint32_t WWW_get_bytes_m3061182897_MetadataUsageId; extern const uint32_t WWW_get_error_m3055313367_MetadataUsageId; extern const uint32_t WWW_get_text_m898164367_MetadataUsageId; struct CertificateHandler_t2739891000_marshaled_com; struct DownloadHandler_t2937767557_marshaled_com; struct UnityWebRequest_t463507806_marshaled_com; struct UnityWebRequest_t463507806_marshaled_pinvoke; struct UploadHandler_t2993558019_marshaled_com; struct ByteU5BU5D_t4116647657; #ifndef U3CMODULEU3E_T692745538_H #define U3CMODULEU3E_T692745538_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t692745538 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CMODULEU3E_T692745538_H #ifndef RUNTIMEOBJECT_H #define RUNTIMEOBJECT_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEOBJECT_H struct Il2CppArrayBounds; #ifndef RUNTIMEARRAY_H #define RUNTIMEARRAY_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Array #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEARRAY_H #ifndef STRING_T_H #define STRING_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.String struct String_t : public RuntimeObject { public: // System.Int32 System.String::length int32_t ___length_0; // System.Char System.String::start_char Il2CppChar ___start_char_1; public: inline static int32_t get_offset_of_length_0() { return static_cast<int32_t>(offsetof(String_t, ___length_0)); } inline int32_t get_length_0() const { return ___length_0; } inline int32_t* get_address_of_length_0() { return &___length_0; } inline void set_length_0(int32_t value) { ___length_0 = value; } inline static int32_t get_offset_of_start_char_1() { return static_cast<int32_t>(offsetof(String_t, ___start_char_1)); } inline Il2CppChar get_start_char_1() const { return ___start_char_1; } inline Il2CppChar* get_address_of_start_char_1() { return &___start_char_1; } inline void set_start_char_1(Il2CppChar value) { ___start_char_1 = value; } }; struct String_t_StaticFields { public: // System.String System.String::Empty String_t* ___Empty_2; // System.Char[] System.String::WhiteChars CharU5BU5D_t3528271667* ___WhiteChars_3; public: inline static int32_t get_offset_of_Empty_2() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_2)); } inline String_t* get_Empty_2() const { return ___Empty_2; } inline String_t** get_address_of_Empty_2() { return &___Empty_2; } inline void set_Empty_2(String_t* value) { ___Empty_2 = value; Il2CppCodeGenWriteBarrier((&___Empty_2), value); } inline static int32_t get_offset_of_WhiteChars_3() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___WhiteChars_3)); } inline CharU5BU5D_t3528271667* get_WhiteChars_3() const { return ___WhiteChars_3; } inline CharU5BU5D_t3528271667** get_address_of_WhiteChars_3() { return &___WhiteChars_3; } inline void set_WhiteChars_3(CharU5BU5D_t3528271667* value) { ___WhiteChars_3 = value; Il2CppCodeGenWriteBarrier((&___WhiteChars_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STRING_T_H #ifndef ENCODING_T1523322056_H #define ENCODING_T1523322056_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.Encoding struct Encoding_t1523322056 : public RuntimeObject { public: // System.Int32 System.Text.Encoding::codePage int32_t ___codePage_0; // System.Int32 System.Text.Encoding::windows_code_page int32_t ___windows_code_page_1; // System.Boolean System.Text.Encoding::is_readonly bool ___is_readonly_2; // System.Text.DecoderFallback System.Text.Encoding::decoder_fallback DecoderFallback_t3123823036 * ___decoder_fallback_3; // System.Text.EncoderFallback System.Text.Encoding::encoder_fallback EncoderFallback_t1188251036 * ___encoder_fallback_4; // System.String System.Text.Encoding::body_name String_t* ___body_name_8; // System.String System.Text.Encoding::encoding_name String_t* ___encoding_name_9; // System.String System.Text.Encoding::header_name String_t* ___header_name_10; // System.Boolean System.Text.Encoding::is_mail_news_display bool ___is_mail_news_display_11; // System.Boolean System.Text.Encoding::is_mail_news_save bool ___is_mail_news_save_12; // System.Boolean System.Text.Encoding::is_browser_save bool ___is_browser_save_13; // System.Boolean System.Text.Encoding::is_browser_display bool ___is_browser_display_14; // System.String System.Text.Encoding::web_name String_t* ___web_name_15; public: inline static int32_t get_offset_of_codePage_0() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___codePage_0)); } inline int32_t get_codePage_0() const { return ___codePage_0; } inline int32_t* get_address_of_codePage_0() { return &___codePage_0; } inline void set_codePage_0(int32_t value) { ___codePage_0 = value; } inline static int32_t get_offset_of_windows_code_page_1() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___windows_code_page_1)); } inline int32_t get_windows_code_page_1() const { return ___windows_code_page_1; } inline int32_t* get_address_of_windows_code_page_1() { return &___windows_code_page_1; } inline void set_windows_code_page_1(int32_t value) { ___windows_code_page_1 = value; } inline static int32_t get_offset_of_is_readonly_2() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___is_readonly_2)); } inline bool get_is_readonly_2() const { return ___is_readonly_2; } inline bool* get_address_of_is_readonly_2() { return &___is_readonly_2; } inline void set_is_readonly_2(bool value) { ___is_readonly_2 = value; } inline static int32_t get_offset_of_decoder_fallback_3() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___decoder_fallback_3)); } inline DecoderFallback_t3123823036 * get_decoder_fallback_3() const { return ___decoder_fallback_3; } inline DecoderFallback_t3123823036 ** get_address_of_decoder_fallback_3() { return &___decoder_fallback_3; } inline void set_decoder_fallback_3(DecoderFallback_t3123823036 * value) { ___decoder_fallback_3 = value; Il2CppCodeGenWriteBarrier((&___decoder_fallback_3), value); } inline static int32_t get_offset_of_encoder_fallback_4() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___encoder_fallback_4)); } inline EncoderFallback_t1188251036 * get_encoder_fallback_4() const { return ___encoder_fallback_4; } inline EncoderFallback_t1188251036 ** get_address_of_encoder_fallback_4() { return &___encoder_fallback_4; } inline void set_encoder_fallback_4(EncoderFallback_t1188251036 * value) { ___encoder_fallback_4 = value; Il2CppCodeGenWriteBarrier((&___encoder_fallback_4), value); } inline static int32_t get_offset_of_body_name_8() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___body_name_8)); } inline String_t* get_body_name_8() const { return ___body_name_8; } inline String_t** get_address_of_body_name_8() { return &___body_name_8; } inline void set_body_name_8(String_t* value) { ___body_name_8 = value; Il2CppCodeGenWriteBarrier((&___body_name_8), value); } inline static int32_t get_offset_of_encoding_name_9() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___encoding_name_9)); } inline String_t* get_encoding_name_9() const { return ___encoding_name_9; } inline String_t** get_address_of_encoding_name_9() { return &___encoding_name_9; } inline void set_encoding_name_9(String_t* value) { ___encoding_name_9 = value; Il2CppCodeGenWriteBarrier((&___encoding_name_9), value); } inline static int32_t get_offset_of_header_name_10() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___header_name_10)); } inline String_t* get_header_name_10() const { return ___header_name_10; } inline String_t** get_address_of_header_name_10() { return &___header_name_10; } inline void set_header_name_10(String_t* value) { ___header_name_10 = value; Il2CppCodeGenWriteBarrier((&___header_name_10), value); } inline static int32_t get_offset_of_is_mail_news_display_11() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___is_mail_news_display_11)); } inline bool get_is_mail_news_display_11() const { return ___is_mail_news_display_11; } inline bool* get_address_of_is_mail_news_display_11() { return &___is_mail_news_display_11; } inline void set_is_mail_news_display_11(bool value) { ___is_mail_news_display_11 = value; } inline static int32_t get_offset_of_is_mail_news_save_12() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___is_mail_news_save_12)); } inline bool get_is_mail_news_save_12() const { return ___is_mail_news_save_12; } inline bool* get_address_of_is_mail_news_save_12() { return &___is_mail_news_save_12; } inline void set_is_mail_news_save_12(bool value) { ___is_mail_news_save_12 = value; } inline static int32_t get_offset_of_is_browser_save_13() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___is_browser_save_13)); } inline bool get_is_browser_save_13() const { return ___is_browser_save_13; } inline bool* get_address_of_is_browser_save_13() { return &___is_browser_save_13; } inline void set_is_browser_save_13(bool value) { ___is_browser_save_13 = value; } inline static int32_t get_offset_of_is_browser_display_14() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___is_browser_display_14)); } inline bool get_is_browser_display_14() const { return ___is_browser_display_14; } inline bool* get_address_of_is_browser_display_14() { return &___is_browser_display_14; } inline void set_is_browser_display_14(bool value) { ___is_browser_display_14 = value; } inline static int32_t get_offset_of_web_name_15() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___web_name_15)); } inline String_t* get_web_name_15() const { return ___web_name_15; } inline String_t** get_address_of_web_name_15() { return &___web_name_15; } inline void set_web_name_15(String_t* value) { ___web_name_15 = value; Il2CppCodeGenWriteBarrier((&___web_name_15), value); } }; struct Encoding_t1523322056_StaticFields { public: // System.Reflection.Assembly System.Text.Encoding::i18nAssembly Assembly_t * ___i18nAssembly_5; // System.Boolean System.Text.Encoding::i18nDisabled bool ___i18nDisabled_6; // System.Object[] System.Text.Encoding::encodings ObjectU5BU5D_t2843939325* ___encodings_7; // System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::asciiEncoding Encoding_t1523322056 * ___asciiEncoding_16; // System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::bigEndianEncoding Encoding_t1523322056 * ___bigEndianEncoding_17; // System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::defaultEncoding Encoding_t1523322056 * ___defaultEncoding_18; // System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf7Encoding Encoding_t1523322056 * ___utf7Encoding_19; // System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf8EncodingWithMarkers Encoding_t1523322056 * ___utf8EncodingWithMarkers_20; // System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf8EncodingWithoutMarkers Encoding_t1523322056 * ___utf8EncodingWithoutMarkers_21; // System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::unicodeEncoding Encoding_t1523322056 * ___unicodeEncoding_22; // System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::isoLatin1Encoding Encoding_t1523322056 * ___isoLatin1Encoding_23; // System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf8EncodingUnsafe Encoding_t1523322056 * ___utf8EncodingUnsafe_24; // System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf32Encoding Encoding_t1523322056 * ___utf32Encoding_25; // System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::bigEndianUTF32Encoding Encoding_t1523322056 * ___bigEndianUTF32Encoding_26; // System.Object System.Text.Encoding::lockobj RuntimeObject * ___lockobj_27; public: inline static int32_t get_offset_of_i18nAssembly_5() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___i18nAssembly_5)); } inline Assembly_t * get_i18nAssembly_5() const { return ___i18nAssembly_5; } inline Assembly_t ** get_address_of_i18nAssembly_5() { return &___i18nAssembly_5; } inline void set_i18nAssembly_5(Assembly_t * value) { ___i18nAssembly_5 = value; Il2CppCodeGenWriteBarrier((&___i18nAssembly_5), value); } inline static int32_t get_offset_of_i18nDisabled_6() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___i18nDisabled_6)); } inline bool get_i18nDisabled_6() const { return ___i18nDisabled_6; } inline bool* get_address_of_i18nDisabled_6() { return &___i18nDisabled_6; } inline void set_i18nDisabled_6(bool value) { ___i18nDisabled_6 = value; } inline static int32_t get_offset_of_encodings_7() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___encodings_7)); } inline ObjectU5BU5D_t2843939325* get_encodings_7() const { return ___encodings_7; } inline ObjectU5BU5D_t2843939325** get_address_of_encodings_7() { return &___encodings_7; } inline void set_encodings_7(ObjectU5BU5D_t2843939325* value) { ___encodings_7 = value; Il2CppCodeGenWriteBarrier((&___encodings_7), value); } inline static int32_t get_offset_of_asciiEncoding_16() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___asciiEncoding_16)); } inline Encoding_t1523322056 * get_asciiEncoding_16() const { return ___asciiEncoding_16; } inline Encoding_t1523322056 ** get_address_of_asciiEncoding_16() { return &___asciiEncoding_16; } inline void set_asciiEncoding_16(Encoding_t1523322056 * value) { ___asciiEncoding_16 = value; Il2CppCodeGenWriteBarrier((&___asciiEncoding_16), value); } inline static int32_t get_offset_of_bigEndianEncoding_17() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___bigEndianEncoding_17)); } inline Encoding_t1523322056 * get_bigEndianEncoding_17() const { return ___bigEndianEncoding_17; } inline Encoding_t1523322056 ** get_address_of_bigEndianEncoding_17() { return &___bigEndianEncoding_17; } inline void set_bigEndianEncoding_17(Encoding_t1523322056 * value) { ___bigEndianEncoding_17 = value; Il2CppCodeGenWriteBarrier((&___bigEndianEncoding_17), value); } inline static int32_t get_offset_of_defaultEncoding_18() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___defaultEncoding_18)); } inline Encoding_t1523322056 * get_defaultEncoding_18() const { return ___defaultEncoding_18; } inline Encoding_t1523322056 ** get_address_of_defaultEncoding_18() { return &___defaultEncoding_18; } inline void set_defaultEncoding_18(Encoding_t1523322056 * value) { ___defaultEncoding_18 = value; Il2CppCodeGenWriteBarrier((&___defaultEncoding_18), value); } inline static int32_t get_offset_of_utf7Encoding_19() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___utf7Encoding_19)); } inline Encoding_t1523322056 * get_utf7Encoding_19() const { return ___utf7Encoding_19; } inline Encoding_t1523322056 ** get_address_of_utf7Encoding_19() { return &___utf7Encoding_19; } inline void set_utf7Encoding_19(Encoding_t1523322056 * value) { ___utf7Encoding_19 = value; Il2CppCodeGenWriteBarrier((&___utf7Encoding_19), value); } inline static int32_t get_offset_of_utf8EncodingWithMarkers_20() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___utf8EncodingWithMarkers_20)); } inline Encoding_t1523322056 * get_utf8EncodingWithMarkers_20() const { return ___utf8EncodingWithMarkers_20; } inline Encoding_t1523322056 ** get_address_of_utf8EncodingWithMarkers_20() { return &___utf8EncodingWithMarkers_20; } inline void set_utf8EncodingWithMarkers_20(Encoding_t1523322056 * value) { ___utf8EncodingWithMarkers_20 = value; Il2CppCodeGenWriteBarrier((&___utf8EncodingWithMarkers_20), value); } inline static int32_t get_offset_of_utf8EncodingWithoutMarkers_21() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___utf8EncodingWithoutMarkers_21)); } inline Encoding_t1523322056 * get_utf8EncodingWithoutMarkers_21() const { return ___utf8EncodingWithoutMarkers_21; } inline Encoding_t1523322056 ** get_address_of_utf8EncodingWithoutMarkers_21() { return &___utf8EncodingWithoutMarkers_21; } inline void set_utf8EncodingWithoutMarkers_21(Encoding_t1523322056 * value) { ___utf8EncodingWithoutMarkers_21 = value; Il2CppCodeGenWriteBarrier((&___utf8EncodingWithoutMarkers_21), value); } inline static int32_t get_offset_of_unicodeEncoding_22() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___unicodeEncoding_22)); } inline Encoding_t1523322056 * get_unicodeEncoding_22() const { return ___unicodeEncoding_22; } inline Encoding_t1523322056 ** get_address_of_unicodeEncoding_22() { return &___unicodeEncoding_22; } inline void set_unicodeEncoding_22(Encoding_t1523322056 * value) { ___unicodeEncoding_22 = value; Il2CppCodeGenWriteBarrier((&___unicodeEncoding_22), value); } inline static int32_t get_offset_of_isoLatin1Encoding_23() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___isoLatin1Encoding_23)); } inline Encoding_t1523322056 * get_isoLatin1Encoding_23() const { return ___isoLatin1Encoding_23; } inline Encoding_t1523322056 ** get_address_of_isoLatin1Encoding_23() { return &___isoLatin1Encoding_23; } inline void set_isoLatin1Encoding_23(Encoding_t1523322056 * value) { ___isoLatin1Encoding_23 = value; Il2CppCodeGenWriteBarrier((&___isoLatin1Encoding_23), value); } inline static int32_t get_offset_of_utf8EncodingUnsafe_24() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___utf8EncodingUnsafe_24)); } inline Encoding_t1523322056 * get_utf8EncodingUnsafe_24() const { return ___utf8EncodingUnsafe_24; } inline Encoding_t1523322056 ** get_address_of_utf8EncodingUnsafe_24() { return &___utf8EncodingUnsafe_24; } inline void set_utf8EncodingUnsafe_24(Encoding_t1523322056 * value) { ___utf8EncodingUnsafe_24 = value; Il2CppCodeGenWriteBarrier((&___utf8EncodingUnsafe_24), value); } inline static int32_t get_offset_of_utf32Encoding_25() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___utf32Encoding_25)); } inline Encoding_t1523322056 * get_utf32Encoding_25() const { return ___utf32Encoding_25; } inline Encoding_t1523322056 ** get_address_of_utf32Encoding_25() { return &___utf32Encoding_25; } inline void set_utf32Encoding_25(Encoding_t1523322056 * value) { ___utf32Encoding_25 = value; Il2CppCodeGenWriteBarrier((&___utf32Encoding_25), value); } inline static int32_t get_offset_of_bigEndianUTF32Encoding_26() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___bigEndianUTF32Encoding_26)); } inline Encoding_t1523322056 * get_bigEndianUTF32Encoding_26() const { return ___bigEndianUTF32Encoding_26; } inline Encoding_t1523322056 ** get_address_of_bigEndianUTF32Encoding_26() { return &___bigEndianUTF32Encoding_26; } inline void set_bigEndianUTF32Encoding_26(Encoding_t1523322056 * value) { ___bigEndianUTF32Encoding_26 = value; Il2CppCodeGenWriteBarrier((&___bigEndianUTF32Encoding_26), value); } inline static int32_t get_offset_of_lockobj_27() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___lockobj_27)); } inline RuntimeObject * get_lockobj_27() const { return ___lockobj_27; } inline RuntimeObject ** get_address_of_lockobj_27() { return &___lockobj_27; } inline void set_lockobj_27(RuntimeObject * value) { ___lockobj_27 = value; Il2CppCodeGenWriteBarrier((&___lockobj_27), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ENCODING_T1523322056_H #ifndef VALUETYPE_T3640485471_H #define VALUETYPE_T3640485471_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ValueType struct ValueType_t3640485471 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t3640485471_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t3640485471_marshaled_com { }; #endif // VALUETYPE_T3640485471_H #ifndef CUSTOMYIELDINSTRUCTION_T1895667560_H #define CUSTOMYIELDINSTRUCTION_T1895667560_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.CustomYieldInstruction struct CustomYieldInstruction_t1895667560 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CUSTOMYIELDINSTRUCTION_T1895667560_H #ifndef WWWFORM_T4064702195_H #define WWWFORM_T4064702195_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.WWWForm struct WWWForm_t4064702195 : public RuntimeObject { public: // System.Collections.Generic.List`1<System.Byte[]> UnityEngine.WWWForm::formData List_1_t1293755103 * ___formData_0; // System.Collections.Generic.List`1<System.String> UnityEngine.WWWForm::fieldNames List_1_t3319525431 * ___fieldNames_1; // System.Collections.Generic.List`1<System.String> UnityEngine.WWWForm::fileNames List_1_t3319525431 * ___fileNames_2; // System.Collections.Generic.List`1<System.String> UnityEngine.WWWForm::types List_1_t3319525431 * ___types_3; // System.Byte[] UnityEngine.WWWForm::boundary ByteU5BU5D_t4116647657* ___boundary_4; // System.Boolean UnityEngine.WWWForm::containsFiles bool ___containsFiles_5; public: inline static int32_t get_offset_of_formData_0() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___formData_0)); } inline List_1_t1293755103 * get_formData_0() const { return ___formData_0; } inline List_1_t1293755103 ** get_address_of_formData_0() { return &___formData_0; } inline void set_formData_0(List_1_t1293755103 * value) { ___formData_0 = value; Il2CppCodeGenWriteBarrier((&___formData_0), value); } inline static int32_t get_offset_of_fieldNames_1() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___fieldNames_1)); } inline List_1_t3319525431 * get_fieldNames_1() const { return ___fieldNames_1; } inline List_1_t3319525431 ** get_address_of_fieldNames_1() { return &___fieldNames_1; } inline void set_fieldNames_1(List_1_t3319525431 * value) { ___fieldNames_1 = value; Il2CppCodeGenWriteBarrier((&___fieldNames_1), value); } inline static int32_t get_offset_of_fileNames_2() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___fileNames_2)); } inline List_1_t3319525431 * get_fileNames_2() const { return ___fileNames_2; } inline List_1_t3319525431 ** get_address_of_fileNames_2() { return &___fileNames_2; } inline void set_fileNames_2(List_1_t3319525431 * value) { ___fileNames_2 = value; Il2CppCodeGenWriteBarrier((&___fileNames_2), value); } inline static int32_t get_offset_of_types_3() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___types_3)); } inline List_1_t3319525431 * get_types_3() const { return ___types_3; } inline List_1_t3319525431 ** get_address_of_types_3() { return &___types_3; } inline void set_types_3(List_1_t3319525431 * value) { ___types_3 = value; Il2CppCodeGenWriteBarrier((&___types_3), value); } inline static int32_t get_offset_of_boundary_4() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___boundary_4)); } inline ByteU5BU5D_t4116647657* get_boundary_4() const { return ___boundary_4; } inline ByteU5BU5D_t4116647657** get_address_of_boundary_4() { return &___boundary_4; } inline void set_boundary_4(ByteU5BU5D_t4116647657* value) { ___boundary_4 = value; Il2CppCodeGenWriteBarrier((&___boundary_4), value); } inline static int32_t get_offset_of_containsFiles_5() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___containsFiles_5)); } inline bool get_containsFiles_5() const { return ___containsFiles_5; } inline bool* get_address_of_containsFiles_5() { return &___containsFiles_5; } inline void set_containsFiles_5(bool value) { ___containsFiles_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // WWWFORM_T4064702195_H #ifndef YIELDINSTRUCTION_T403091072_H #define YIELDINSTRUCTION_T403091072_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.YieldInstruction struct YieldInstruction_t403091072 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.YieldInstruction struct YieldInstruction_t403091072_marshaled_pinvoke { }; // Native definition for COM marshalling of UnityEngine.YieldInstruction struct YieldInstruction_t403091072_marshaled_com { }; #endif // YIELDINSTRUCTION_T403091072_H #ifndef BOOLEAN_T97287965_H #define BOOLEAN_T97287965_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Boolean struct Boolean_t97287965 { public: // System.Boolean System.Boolean::m_value bool ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Boolean_t97287965, ___m_value_2)); } inline bool get_m_value_2() const { return ___m_value_2; } inline bool* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(bool value) { ___m_value_2 = value; } }; struct Boolean_t97287965_StaticFields { public: // System.String System.Boolean::FalseString String_t* ___FalseString_0; // System.String System.Boolean::TrueString String_t* ___TrueString_1; public: inline static int32_t get_offset_of_FalseString_0() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___FalseString_0)); } inline String_t* get_FalseString_0() const { return ___FalseString_0; } inline String_t** get_address_of_FalseString_0() { return &___FalseString_0; } inline void set_FalseString_0(String_t* value) { ___FalseString_0 = value; Il2CppCodeGenWriteBarrier((&___FalseString_0), value); } inline static int32_t get_offset_of_TrueString_1() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___TrueString_1)); } inline String_t* get_TrueString_1() const { return ___TrueString_1; } inline String_t** get_address_of_TrueString_1() { return &___TrueString_1; } inline void set_TrueString_1(String_t* value) { ___TrueString_1 = value; Il2CppCodeGenWriteBarrier((&___TrueString_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BOOLEAN_T97287965_H #ifndef BYTE_T1134296376_H #define BYTE_T1134296376_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Byte struct Byte_t1134296376 { public: // System.Byte System.Byte::m_value uint8_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Byte_t1134296376, ___m_value_2)); } inline uint8_t get_m_value_2() const { return ___m_value_2; } inline uint8_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(uint8_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BYTE_T1134296376_H #ifndef ENUM_T4135868527_H #define ENUM_T4135868527_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Enum struct Enum_t4135868527 : public ValueType_t3640485471 { public: public: }; struct Enum_t4135868527_StaticFields { public: // System.Char[] System.Enum::split_char CharU5BU5D_t3528271667* ___split_char_0; public: inline static int32_t get_offset_of_split_char_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___split_char_0)); } inline CharU5BU5D_t3528271667* get_split_char_0() const { return ___split_char_0; } inline CharU5BU5D_t3528271667** get_address_of_split_char_0() { return &___split_char_0; } inline void set_split_char_0(CharU5BU5D_t3528271667* value) { ___split_char_0 = value; Il2CppCodeGenWriteBarrier((&___split_char_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t4135868527_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t4135868527_marshaled_com { }; #endif // ENUM_T4135868527_H #ifndef INT32_T2950945753_H #define INT32_T2950945753_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int32 struct Int32_t2950945753 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Int32_t2950945753, ___m_value_2)); } inline int32_t get_m_value_2() const { return ___m_value_2; } inline int32_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(int32_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT32_T2950945753_H #ifndef INT64_T3736567304_H #define INT64_T3736567304_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int64 struct Int64_t3736567304 { public: // System.Int64 System.Int64::m_value int64_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int64_t3736567304, ___m_value_0)); } inline int64_t get_m_value_0() const { return ___m_value_0; } inline int64_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int64_t value) { ___m_value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT64_T3736567304_H #ifndef INTPTR_T_H #define INTPTR_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTPTR_T_H #ifndef UINT32_T2560061978_H #define UINT32_T2560061978_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.UInt32 struct UInt32_t2560061978 { public: // System.UInt32 System.UInt32::m_value uint32_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(UInt32_t2560061978, ___m_value_0)); } inline uint32_t get_m_value_0() const { return ___m_value_0; } inline uint32_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(uint32_t value) { ___m_value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UINT32_T2560061978_H #ifndef VOID_T1185182177_H #define VOID_T1185182177_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void struct Void_t1185182177 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VOID_T1185182177_H #ifndef HASH128_T2357739769_H #define HASH128_T2357739769_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Hash128 struct Hash128_t2357739769 { public: // System.UInt32 UnityEngine.Hash128::m_u32_0 uint32_t ___m_u32_0_0; // System.UInt32 UnityEngine.Hash128::m_u32_1 uint32_t ___m_u32_1_1; // System.UInt32 UnityEngine.Hash128::m_u32_2 uint32_t ___m_u32_2_2; // System.UInt32 UnityEngine.Hash128::m_u32_3 uint32_t ___m_u32_3_3; public: inline static int32_t get_offset_of_m_u32_0_0() { return static_cast<int32_t>(offsetof(Hash128_t2357739769, ___m_u32_0_0)); } inline uint32_t get_m_u32_0_0() const { return ___m_u32_0_0; } inline uint32_t* get_address_of_m_u32_0_0() { return &___m_u32_0_0; } inline void set_m_u32_0_0(uint32_t value) { ___m_u32_0_0 = value; } inline static int32_t get_offset_of_m_u32_1_1() { return static_cast<int32_t>(offsetof(Hash128_t2357739769, ___m_u32_1_1)); } inline uint32_t get_m_u32_1_1() const { return ___m_u32_1_1; } inline uint32_t* get_address_of_m_u32_1_1() { return &___m_u32_1_1; } inline void set_m_u32_1_1(uint32_t value) { ___m_u32_1_1 = value; } inline static int32_t get_offset_of_m_u32_2_2() { return static_cast<int32_t>(offsetof(Hash128_t2357739769, ___m_u32_2_2)); } inline uint32_t get_m_u32_2_2() const { return ___m_u32_2_2; } inline uint32_t* get_address_of_m_u32_2_2() { return &___m_u32_2_2; } inline void set_m_u32_2_2(uint32_t value) { ___m_u32_2_2 = value; } inline static int32_t get_offset_of_m_u32_3_3() { return static_cast<int32_t>(offsetof(Hash128_t2357739769, ___m_u32_3_3)); } inline uint32_t get_m_u32_3_3() const { return ___m_u32_3_3; } inline uint32_t* get_address_of_m_u32_3_3() { return &___m_u32_3_3; } inline void set_m_u32_3_3(uint32_t value) { ___m_u32_3_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // HASH128_T2357739769_H #ifndef WWW_T3688466362_H #define WWW_T3688466362_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.WWW struct WWW_t3688466362 : public CustomYieldInstruction_t1895667560 { public: // UnityEngine.Networking.UnityWebRequest UnityEngine.WWW::_uwr UnityWebRequest_t463507806 * ____uwr_0; // UnityEngine.AssetBundle UnityEngine.WWW::_assetBundle AssetBundle_t1153907252 * ____assetBundle_1; public: inline static int32_t get_offset_of__uwr_0() { return static_cast<int32_t>(offsetof(WWW_t3688466362, ____uwr_0)); } inline UnityWebRequest_t463507806 * get__uwr_0() const { return ____uwr_0; } inline UnityWebRequest_t463507806 ** get_address_of__uwr_0() { return &____uwr_0; } inline void set__uwr_0(UnityWebRequest_t463507806 * value) { ____uwr_0 = value; Il2CppCodeGenWriteBarrier((&____uwr_0), value); } inline static int32_t get_offset_of__assetBundle_1() { return static_cast<int32_t>(offsetof(WWW_t3688466362, ____assetBundle_1)); } inline AssetBundle_t1153907252 * get__assetBundle_1() const { return ____assetBundle_1; } inline AssetBundle_t1153907252 ** get_address_of__assetBundle_1() { return &____assetBundle_1; } inline void set__assetBundle_1(AssetBundle_t1153907252 * value) { ____assetBundle_1 = value; Il2CppCodeGenWriteBarrier((&____assetBundle_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // WWW_T3688466362_H #ifndef STRINGCOMPARISON_T3657712135_H #define STRINGCOMPARISON_T3657712135_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.StringComparison struct StringComparison_t3657712135 { public: // System.Int32 System.StringComparison::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(StringComparison_t3657712135, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STRINGCOMPARISON_T3657712135_H #ifndef ASYNCOPERATION_T1445031843_H #define ASYNCOPERATION_T1445031843_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.AsyncOperation struct AsyncOperation_t1445031843 : public YieldInstruction_t403091072 { public: // System.IntPtr UnityEngine.AsyncOperation::m_Ptr intptr_t ___m_Ptr_0; // System.Action`1<UnityEngine.AsyncOperation> UnityEngine.AsyncOperation::m_completeCallback Action_1_t1617499438 * ___m_completeCallback_1; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(AsyncOperation_t1445031843, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } inline static int32_t get_offset_of_m_completeCallback_1() { return static_cast<int32_t>(offsetof(AsyncOperation_t1445031843, ___m_completeCallback_1)); } inline Action_1_t1617499438 * get_m_completeCallback_1() const { return ___m_completeCallback_1; } inline Action_1_t1617499438 ** get_address_of_m_completeCallback_1() { return &___m_completeCallback_1; } inline void set_m_completeCallback_1(Action_1_t1617499438 * value) { ___m_completeCallback_1 = value; Il2CppCodeGenWriteBarrier((&___m_completeCallback_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.AsyncOperation struct AsyncOperation_t1445031843_marshaled_pinvoke : public YieldInstruction_t403091072_marshaled_pinvoke { intptr_t ___m_Ptr_0; Il2CppMethodPointer ___m_completeCallback_1; }; // Native definition for COM marshalling of UnityEngine.AsyncOperation struct AsyncOperation_t1445031843_marshaled_com : public YieldInstruction_t403091072_marshaled_com { intptr_t ___m_Ptr_0; Il2CppMethodPointer ___m_completeCallback_1; }; #endif // ASYNCOPERATION_T1445031843_H #ifndef CACHEDASSETBUNDLE_T2205819908_H #define CACHEDASSETBUNDLE_T2205819908_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.CachedAssetBundle struct CachedAssetBundle_t2205819908 { public: // System.String UnityEngine.CachedAssetBundle::m_Name String_t* ___m_Name_0; // UnityEngine.Hash128 UnityEngine.CachedAssetBundle::m_Hash Hash128_t2357739769 ___m_Hash_1; public: inline static int32_t get_offset_of_m_Name_0() { return static_cast<int32_t>(offsetof(CachedAssetBundle_t2205819908, ___m_Name_0)); } inline String_t* get_m_Name_0() const { return ___m_Name_0; } inline String_t** get_address_of_m_Name_0() { return &___m_Name_0; } inline void set_m_Name_0(String_t* value) { ___m_Name_0 = value; Il2CppCodeGenWriteBarrier((&___m_Name_0), value); } inline static int32_t get_offset_of_m_Hash_1() { return static_cast<int32_t>(offsetof(CachedAssetBundle_t2205819908, ___m_Hash_1)); } inline Hash128_t2357739769 get_m_Hash_1() const { return ___m_Hash_1; } inline Hash128_t2357739769 * get_address_of_m_Hash_1() { return &___m_Hash_1; } inline void set_m_Hash_1(Hash128_t2357739769 value) { ___m_Hash_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.CachedAssetBundle struct CachedAssetBundle_t2205819908_marshaled_pinvoke { char* ___m_Name_0; Hash128_t2357739769 ___m_Hash_1; }; // Native definition for COM marshalling of UnityEngine.CachedAssetBundle struct CachedAssetBundle_t2205819908_marshaled_com { Il2CppChar* ___m_Name_0; Hash128_t2357739769 ___m_Hash_1; }; #endif // CACHEDASSETBUNDLE_T2205819908_H #ifndef CERTIFICATEHANDLER_T2739891000_H #define CERTIFICATEHANDLER_T2739891000_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Networking.CertificateHandler struct CertificateHandler_t2739891000 : public RuntimeObject { public: // System.IntPtr UnityEngine.Networking.CertificateHandler::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(CertificateHandler_t2739891000, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Networking.CertificateHandler struct CertificateHandler_t2739891000_marshaled_pinvoke { intptr_t ___m_Ptr_0; }; // Native definition for COM marshalling of UnityEngine.Networking.CertificateHandler struct CertificateHandler_t2739891000_marshaled_com { intptr_t ___m_Ptr_0; }; #endif // CERTIFICATEHANDLER_T2739891000_H #ifndef DOWNLOADHANDLER_T2937767557_H #define DOWNLOADHANDLER_T2937767557_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Networking.DownloadHandler struct DownloadHandler_t2937767557 : public RuntimeObject { public: // System.IntPtr UnityEngine.Networking.DownloadHandler::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(DownloadHandler_t2937767557, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Networking.DownloadHandler struct DownloadHandler_t2937767557_marshaled_pinvoke { intptr_t ___m_Ptr_0; }; // Native definition for COM marshalling of UnityEngine.Networking.DownloadHandler struct DownloadHandler_t2937767557_marshaled_com { intptr_t ___m_Ptr_0; }; #endif // DOWNLOADHANDLER_T2937767557_H #ifndef UPLOADHANDLER_T2993558019_H #define UPLOADHANDLER_T2993558019_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Networking.UploadHandler struct UploadHandler_t2993558019 : public RuntimeObject { public: // System.IntPtr UnityEngine.Networking.UploadHandler::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(UploadHandler_t2993558019, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Networking.UploadHandler struct UploadHandler_t2993558019_marshaled_pinvoke { intptr_t ___m_Ptr_0; }; // Native definition for COM marshalling of UnityEngine.Networking.UploadHandler struct UploadHandler_t2993558019_marshaled_com { intptr_t ___m_Ptr_0; }; #endif // UPLOADHANDLER_T2993558019_H #ifndef OBJECT_T631007953_H #define OBJECT_T631007953_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Object struct Object_t631007953 : public RuntimeObject { public: // System.IntPtr UnityEngine.Object::m_CachedPtr intptr_t ___m_CachedPtr_0; public: inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_t631007953, ___m_CachedPtr_0)); } inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; } inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; } inline void set_m_CachedPtr_0(intptr_t value) { ___m_CachedPtr_0 = value; } }; struct Object_t631007953_StaticFields { public: // System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1; public: inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_t631007953_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); } inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; } inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; } inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value) { ___OffsetOfInstanceIDInCPlusPlusObject_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Object struct Object_t631007953_marshaled_pinvoke { intptr_t ___m_CachedPtr_0; }; // Native definition for COM marshalling of UnityEngine.Object struct Object_t631007953_marshaled_com { intptr_t ___m_CachedPtr_0; }; #endif // OBJECT_T631007953_H #ifndef ASSETBUNDLE_T1153907252_H #define ASSETBUNDLE_T1153907252_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.AssetBundle struct AssetBundle_t1153907252 : public Object_t631007953 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASSETBUNDLE_T1153907252_H #ifndef DOWNLOADHANDLERASSETBUNDLE_T197128434_H #define DOWNLOADHANDLERASSETBUNDLE_T197128434_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Networking.DownloadHandlerAssetBundle struct DownloadHandlerAssetBundle_t197128434 : public DownloadHandler_t2937767557 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Networking.DownloadHandlerAssetBundle struct DownloadHandlerAssetBundle_t197128434_marshaled_pinvoke : public DownloadHandler_t2937767557_marshaled_pinvoke { }; // Native definition for COM marshalling of UnityEngine.Networking.DownloadHandlerAssetBundle struct DownloadHandlerAssetBundle_t197128434_marshaled_com : public DownloadHandler_t2937767557_marshaled_com { }; #endif // DOWNLOADHANDLERASSETBUNDLE_T197128434_H #ifndef UNITYWEBREQUEST_T463507806_H #define UNITYWEBREQUEST_T463507806_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Networking.UnityWebRequest struct UnityWebRequest_t463507806 : public RuntimeObject { public: // System.IntPtr UnityEngine.Networking.UnityWebRequest::m_Ptr intptr_t ___m_Ptr_0; // UnityEngine.Networking.DownloadHandler UnityEngine.Networking.UnityWebRequest::m_DownloadHandler DownloadHandler_t2937767557 * ___m_DownloadHandler_1; // UnityEngine.Networking.UploadHandler UnityEngine.Networking.UnityWebRequest::m_UploadHandler UploadHandler_t2993558019 * ___m_UploadHandler_2; // UnityEngine.Networking.CertificateHandler UnityEngine.Networking.UnityWebRequest::m_CertificateHandler CertificateHandler_t2739891000 * ___m_CertificateHandler_3; // System.Uri UnityEngine.Networking.UnityWebRequest::m_Uri Uri_t100236324 * ___m_Uri_4; // System.Boolean UnityEngine.Networking.UnityWebRequest::<disposeCertificateHandlerOnDispose>k__BackingField bool ___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5; // System.Boolean UnityEngine.Networking.UnityWebRequest::<disposeDownloadHandlerOnDispose>k__BackingField bool ___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6; // System.Boolean UnityEngine.Networking.UnityWebRequest::<disposeUploadHandlerOnDispose>k__BackingField bool ___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } inline static int32_t get_offset_of_m_DownloadHandler_1() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___m_DownloadHandler_1)); } inline DownloadHandler_t2937767557 * get_m_DownloadHandler_1() const { return ___m_DownloadHandler_1; } inline DownloadHandler_t2937767557 ** get_address_of_m_DownloadHandler_1() { return &___m_DownloadHandler_1; } inline void set_m_DownloadHandler_1(DownloadHandler_t2937767557 * value) { ___m_DownloadHandler_1 = value; Il2CppCodeGenWriteBarrier((&___m_DownloadHandler_1), value); } inline static int32_t get_offset_of_m_UploadHandler_2() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___m_UploadHandler_2)); } inline UploadHandler_t2993558019 * get_m_UploadHandler_2() const { return ___m_UploadHandler_2; } inline UploadHandler_t2993558019 ** get_address_of_m_UploadHandler_2() { return &___m_UploadHandler_2; } inline void set_m_UploadHandler_2(UploadHandler_t2993558019 * value) { ___m_UploadHandler_2 = value; Il2CppCodeGenWriteBarrier((&___m_UploadHandler_2), value); } inline static int32_t get_offset_of_m_CertificateHandler_3() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___m_CertificateHandler_3)); } inline CertificateHandler_t2739891000 * get_m_CertificateHandler_3() const { return ___m_CertificateHandler_3; } inline CertificateHandler_t2739891000 ** get_address_of_m_CertificateHandler_3() { return &___m_CertificateHandler_3; } inline void set_m_CertificateHandler_3(CertificateHandler_t2739891000 * value) { ___m_CertificateHandler_3 = value; Il2CppCodeGenWriteBarrier((&___m_CertificateHandler_3), value); } inline static int32_t get_offset_of_m_Uri_4() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___m_Uri_4)); } inline Uri_t100236324 * get_m_Uri_4() const { return ___m_Uri_4; } inline Uri_t100236324 ** get_address_of_m_Uri_4() { return &___m_Uri_4; } inline void set_m_Uri_4(Uri_t100236324 * value) { ___m_Uri_4 = value; Il2CppCodeGenWriteBarrier((&___m_Uri_4), value); } inline static int32_t get_offset_of_U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5)); } inline bool get_U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5() const { return ___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5; } inline bool* get_address_of_U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5() { return &___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5; } inline void set_U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5(bool value) { ___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5 = value; } inline static int32_t get_offset_of_U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6)); } inline bool get_U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6() const { return ___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6; } inline bool* get_address_of_U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6() { return &___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6; } inline void set_U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6(bool value) { ___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6 = value; } inline static int32_t get_offset_of_U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7)); } inline bool get_U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7() const { return ___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7; } inline bool* get_address_of_U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7() { return &___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7; } inline void set_U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7(bool value) { ___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Networking.UnityWebRequest struct UnityWebRequest_t463507806_marshaled_pinvoke { intptr_t ___m_Ptr_0; DownloadHandler_t2937767557_marshaled_pinvoke ___m_DownloadHandler_1; UploadHandler_t2993558019_marshaled_pinvoke ___m_UploadHandler_2; CertificateHandler_t2739891000_marshaled_pinvoke ___m_CertificateHandler_3; Uri_t100236324 * ___m_Uri_4; int32_t ___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5; int32_t ___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6; int32_t ___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7; }; // Native definition for COM marshalling of UnityEngine.Networking.UnityWebRequest struct UnityWebRequest_t463507806_marshaled_com { intptr_t ___m_Ptr_0; DownloadHandler_t2937767557_marshaled_com* ___m_DownloadHandler_1; UploadHandler_t2993558019_marshaled_com* ___m_UploadHandler_2; CertificateHandler_t2739891000_marshaled_com* ___m_CertificateHandler_3; Uri_t100236324 * ___m_Uri_4; int32_t ___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5; int32_t ___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6; int32_t ___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7; }; #endif // UNITYWEBREQUEST_T463507806_H #ifndef UNITYWEBREQUESTASYNCOPERATION_T3852015985_H #define UNITYWEBREQUESTASYNCOPERATION_T3852015985_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Networking.UnityWebRequestAsyncOperation struct UnityWebRequestAsyncOperation_t3852015985 : public AsyncOperation_t1445031843 { public: // UnityEngine.Networking.UnityWebRequest UnityEngine.Networking.UnityWebRequestAsyncOperation::<webRequest>k__BackingField UnityWebRequest_t463507806 * ___U3CwebRequestU3Ek__BackingField_2; public: inline static int32_t get_offset_of_U3CwebRequestU3Ek__BackingField_2() { return static_cast<int32_t>(offsetof(UnityWebRequestAsyncOperation_t3852015985, ___U3CwebRequestU3Ek__BackingField_2)); } inline UnityWebRequest_t463507806 * get_U3CwebRequestU3Ek__BackingField_2() const { return ___U3CwebRequestU3Ek__BackingField_2; } inline UnityWebRequest_t463507806 ** get_address_of_U3CwebRequestU3Ek__BackingField_2() { return &___U3CwebRequestU3Ek__BackingField_2; } inline void set_U3CwebRequestU3Ek__BackingField_2(UnityWebRequest_t463507806 * value) { ___U3CwebRequestU3Ek__BackingField_2 = value; Il2CppCodeGenWriteBarrier((&___U3CwebRequestU3Ek__BackingField_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Networking.UnityWebRequestAsyncOperation struct UnityWebRequestAsyncOperation_t3852015985_marshaled_pinvoke : public AsyncOperation_t1445031843_marshaled_pinvoke { UnityWebRequest_t463507806_marshaled_pinvoke* ___U3CwebRequestU3Ek__BackingField_2; }; // Native definition for COM marshalling of UnityEngine.Networking.UnityWebRequestAsyncOperation struct UnityWebRequestAsyncOperation_t3852015985_marshaled_com : public AsyncOperation_t1445031843_marshaled_com { UnityWebRequest_t463507806_marshaled_com* ___U3CwebRequestU3Ek__BackingField_2; }; #endif // UNITYWEBREQUESTASYNCOPERATION_T3852015985_H // System.Byte[] struct ByteU5BU5D_t4116647657 : public RuntimeArray { public: ALIGN_FIELD (8) uint8_t m_Items[1]; public: inline uint8_t GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline uint8_t* GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, uint8_t value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline uint8_t GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline uint8_t* GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, uint8_t value) { m_Items[index] = value; } }; // System.Void UnityEngine.CustomYieldInstruction::.ctor() extern "C" IL2CPP_METHOD_ATTR void CustomYieldInstruction__ctor_m3408208142 (CustomYieldInstruction_t1895667560 * __this, const RuntimeMethod* method); // UnityEngine.Networking.UnityWebRequest UnityEngine.Networking.UnityWebRequest::Get(System.String) extern "C" IL2CPP_METHOD_ATTR UnityWebRequest_t463507806 * UnityWebRequest_Get_m996521828 (RuntimeObject * __this /* static, unused */, String_t* p0, const RuntimeMethod* method); // UnityEngine.Networking.UnityWebRequestAsyncOperation UnityEngine.Networking.UnityWebRequest::SendWebRequest() extern "C" IL2CPP_METHOD_ATTR UnityWebRequestAsyncOperation_t3852015985 * UnityWebRequest_SendWebRequest_m489860187 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method); // UnityEngine.Networking.UnityWebRequest UnityEngine.Networking.UnityWebRequest::Post(System.String,UnityEngine.WWWForm) extern "C" IL2CPP_METHOD_ATTR UnityWebRequest_t463507806 * UnityWebRequest_Post_m4193475377 (RuntimeObject * __this /* static, unused */, String_t* p0, WWWForm_t4064702195 * p1, const RuntimeMethod* method); // System.Void UnityEngine.Networking.UnityWebRequest::set_chunkedTransfer(System.Boolean) extern "C" IL2CPP_METHOD_ATTR void UnityWebRequest_set_chunkedTransfer_m1735705240 (UnityWebRequest_t463507806 * __this, bool p0, const RuntimeMethod* method); // System.Void UnityEngine.CachedAssetBundle::.ctor(System.String,UnityEngine.Hash128) extern "C" IL2CPP_METHOD_ATTR void CachedAssetBundle__ctor_m1886503626 (CachedAssetBundle_t2205819908 * __this, String_t* p0, Hash128_t2357739769 p1, const RuntimeMethod* method); // UnityEngine.Networking.UnityWebRequest UnityEngine.Networking.UnityWebRequestAssetBundle::GetAssetBundle(System.String,UnityEngine.CachedAssetBundle,System.UInt32) extern "C" IL2CPP_METHOD_ATTR UnityWebRequest_t463507806 * UnityWebRequestAssetBundle_GetAssetBundle_m1528696577 (RuntimeObject * __this /* static, unused */, String_t* p0, CachedAssetBundle_t2205819908 p1, uint32_t p2, const RuntimeMethod* method); // System.String UnityEngine.Networking.UnityWebRequest::EscapeURL(System.String,System.Text.Encoding) extern "C" IL2CPP_METHOD_ATTR String_t* UnityWebRequest_EscapeURL_m1351912812 (RuntimeObject * __this /* static, unused */, String_t* p0, Encoding_t1523322056 * p1, const RuntimeMethod* method); // UnityEngine.WWW UnityEngine.WWW::LoadFromCacheOrDownload(System.String,System.Int32,System.UInt32) extern "C" IL2CPP_METHOD_ATTR WWW_t3688466362 * WWW_LoadFromCacheOrDownload_m3958223827 (RuntimeObject * __this /* static, unused */, String_t* ___url0, int32_t ___version1, uint32_t ___crc2, const RuntimeMethod* method); // System.Void UnityEngine.Hash128::.ctor(System.UInt32,System.UInt32,System.UInt32,System.UInt32) extern "C" IL2CPP_METHOD_ATTR void Hash128__ctor_m2348731757 (Hash128_t2357739769 * __this, uint32_t p0, uint32_t p1, uint32_t p2, uint32_t p3, const RuntimeMethod* method); // UnityEngine.WWW UnityEngine.WWW::LoadFromCacheOrDownload(System.String,UnityEngine.Hash128,System.UInt32) extern "C" IL2CPP_METHOD_ATTR WWW_t3688466362 * WWW_LoadFromCacheOrDownload_m4247140216 (RuntimeObject * __this /* static, unused */, String_t* ___url0, Hash128_t2357739769 ___hash1, uint32_t ___crc2, const RuntimeMethod* method); // System.Void UnityEngine.WWW::.ctor(System.String,System.String,UnityEngine.Hash128,System.UInt32) extern "C" IL2CPP_METHOD_ATTR void WWW__ctor_m3488013117 (WWW_t3688466362 * __this, String_t* ___url0, String_t* ___name1, Hash128_t2357739769 ___hash2, uint32_t ___crc3, const RuntimeMethod* method); // System.Boolean UnityEngine.Object::op_Equality(UnityEngine.Object,UnityEngine.Object) extern "C" IL2CPP_METHOD_ATTR bool Object_op_Equality_m1810815630 (RuntimeObject * __this /* static, unused */, Object_t631007953 * p0, Object_t631007953 * p1, const RuntimeMethod* method); // System.Boolean UnityEngine.WWW::WaitUntilDoneIfPossible() extern "C" IL2CPP_METHOD_ATTR bool WWW_WaitUntilDoneIfPossible_m2855479680 (WWW_t3688466362 * __this, const RuntimeMethod* method); // System.Boolean UnityEngine.Networking.UnityWebRequest::get_isNetworkError() extern "C" IL2CPP_METHOD_ATTR bool UnityWebRequest_get_isNetworkError_m1231611882 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method); // UnityEngine.Networking.DownloadHandler UnityEngine.Networking.UnityWebRequest::get_downloadHandler() extern "C" IL2CPP_METHOD_ATTR DownloadHandler_t2937767557 * UnityWebRequest_get_downloadHandler_m534911913 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method); // UnityEngine.AssetBundle UnityEngine.Networking.DownloadHandlerAssetBundle::get_assetBundle() extern "C" IL2CPP_METHOD_ATTR AssetBundle_t1153907252 * DownloadHandlerAssetBundle_get_assetBundle_m3640693480 (DownloadHandlerAssetBundle_t197128434 * __this, const RuntimeMethod* method); // System.Byte[] UnityEngine.WWW::get_bytes() extern "C" IL2CPP_METHOD_ATTR ByteU5BU5D_t4116647657* WWW_get_bytes_m3061182897 (WWW_t3688466362 * __this, const RuntimeMethod* method); // UnityEngine.AssetBundle UnityEngine.AssetBundle::LoadFromMemory(System.Byte[]) extern "C" IL2CPP_METHOD_ATTR AssetBundle_t1153907252 * AssetBundle_LoadFromMemory_m336091660 (RuntimeObject * __this /* static, unused */, ByteU5BU5D_t4116647657* p0, const RuntimeMethod* method); // System.Byte[] UnityEngine.Networking.DownloadHandler::get_data() extern "C" IL2CPP_METHOD_ATTR ByteU5BU5D_t4116647657* DownloadHandler_get_data_m1669096410 (DownloadHandler_t2937767557 * __this, const RuntimeMethod* method); // System.Boolean UnityEngine.Networking.UnityWebRequest::get_isDone() extern "C" IL2CPP_METHOD_ATTR bool UnityWebRequest_get_isDone_m1752128881 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method); // System.String UnityEngine.Networking.UnityWebRequest::get_error() extern "C" IL2CPP_METHOD_ATTR String_t* UnityWebRequest_get_error_m1613086199 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method); // System.Int64 UnityEngine.Networking.UnityWebRequest::get_responseCode() extern "C" IL2CPP_METHOD_ATTR int64_t UnityWebRequest_get_responseCode_m1090830473 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method); // System.String UnityEngine.WWW::GetStatusCodeName(System.Int64) extern "C" IL2CPP_METHOD_ATTR String_t* WWW_GetStatusCodeName_m3580893459 (WWW_t3688466362 * __this, int64_t ___statusCode0, const RuntimeMethod* method); // System.String System.String::Format(System.String,System.Object,System.Object) extern "C" IL2CPP_METHOD_ATTR String_t* String_Format_m2556382932 (RuntimeObject * __this /* static, unused */, String_t* p0, RuntimeObject * p1, RuntimeObject * p2, const RuntimeMethod* method); // System.String UnityEngine.Networking.DownloadHandler::get_text() extern "C" IL2CPP_METHOD_ATTR String_t* DownloadHandler_get_text_m2427232382 (DownloadHandler_t2937767557 * __this, const RuntimeMethod* method); // System.String UnityEngine.Networking.UnityWebRequest::get_url() extern "C" IL2CPP_METHOD_ATTR String_t* UnityWebRequest_get_url_m2568598920 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method); // System.Void UnityEngine.Networking.UnityWebRequest::Dispose() extern "C" IL2CPP_METHOD_ATTR void UnityWebRequest_Dispose_m3261105905 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method); // System.String UnityEngine.WWW::get_url() extern "C" IL2CPP_METHOD_ATTR String_t* WWW_get_url_m3672399347 (WWW_t3688466362 * __this, const RuntimeMethod* method); // System.Boolean System.String::StartsWith(System.String,System.StringComparison) extern "C" IL2CPP_METHOD_ATTR bool String_StartsWith_m2640722675 (String_t* __this, String_t* p0, int32_t p1, const RuntimeMethod* method); // System.Void UnityEngine.Debug::LogError(System.Object) extern "C" IL2CPP_METHOD_ATTR void Debug_LogError_m2850623458 (RuntimeObject * __this /* static, unused */, RuntimeObject * p0, const RuntimeMethod* method); #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityEngine.WWW::.ctor(System.String) extern "C" IL2CPP_METHOD_ATTR void WWW__ctor_m2915079343 (WWW_t3688466362 * __this, String_t* ___url0, const RuntimeMethod* method) { { CustomYieldInstruction__ctor_m3408208142(__this, /*hidden argument*/NULL); String_t* L_0 = ___url0; UnityWebRequest_t463507806 * L_1 = UnityWebRequest_Get_m996521828(NULL /*static, unused*/, L_0, /*hidden argument*/NULL); __this->set__uwr_0(L_1); UnityWebRequest_t463507806 * L_2 = __this->get__uwr_0(); NullCheck(L_2); UnityWebRequest_SendWebRequest_m489860187(L_2, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.WWW::.ctor(System.String,UnityEngine.WWWForm) extern "C" IL2CPP_METHOD_ATTR void WWW__ctor_m1562165 (WWW_t3688466362 * __this, String_t* ___url0, WWWForm_t4064702195 * ___form1, const RuntimeMethod* method) { { CustomYieldInstruction__ctor_m3408208142(__this, /*hidden argument*/NULL); String_t* L_0 = ___url0; WWWForm_t4064702195 * L_1 = ___form1; UnityWebRequest_t463507806 * L_2 = UnityWebRequest_Post_m4193475377(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); __this->set__uwr_0(L_2); UnityWebRequest_t463507806 * L_3 = __this->get__uwr_0(); NullCheck(L_3); UnityWebRequest_set_chunkedTransfer_m1735705240(L_3, (bool)0, /*hidden argument*/NULL); UnityWebRequest_t463507806 * L_4 = __this->get__uwr_0(); NullCheck(L_4); UnityWebRequest_SendWebRequest_m489860187(L_4, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.WWW::.ctor(System.String,System.String,UnityEngine.Hash128,System.UInt32) extern "C" IL2CPP_METHOD_ATTR void WWW__ctor_m3488013117 (WWW_t3688466362 * __this, String_t* ___url0, String_t* ___name1, Hash128_t2357739769 ___hash2, uint32_t ___crc3, const RuntimeMethod* method) { { CustomYieldInstruction__ctor_m3408208142(__this, /*hidden argument*/NULL); String_t* L_0 = ___url0; String_t* L_1 = ___name1; Hash128_t2357739769 L_2 = ___hash2; CachedAssetBundle_t2205819908 L_3; memset(&L_3, 0, sizeof(L_3)); CachedAssetBundle__ctor_m1886503626((&L_3), L_1, L_2, /*hidden argument*/NULL); uint32_t L_4 = ___crc3; UnityWebRequest_t463507806 * L_5 = UnityWebRequestAssetBundle_GetAssetBundle_m1528696577(NULL /*static, unused*/, L_0, L_3, L_4, /*hidden argument*/NULL); __this->set__uwr_0(L_5); UnityWebRequest_t463507806 * L_6 = __this->get__uwr_0(); NullCheck(L_6); UnityWebRequest_SendWebRequest_m489860187(L_6, /*hidden argument*/NULL); return; } } // System.String UnityEngine.WWW::EscapeURL(System.String,System.Text.Encoding) extern "C" IL2CPP_METHOD_ATTR String_t* WWW_EscapeURL_m2044390713 (RuntimeObject * __this /* static, unused */, String_t* ___s0, Encoding_t1523322056 * ___e1, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = ___s0; Encoding_t1523322056 * L_1 = ___e1; String_t* L_2 = UnityWebRequest_EscapeURL_m1351912812(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_000e; } IL_000e: { String_t* L_3 = V_0; return L_3; } } // UnityEngine.WWW UnityEngine.WWW::LoadFromCacheOrDownload(System.String,System.Int32) extern "C" IL2CPP_METHOD_ATTR WWW_t3688466362 * WWW_LoadFromCacheOrDownload_m1915063972 (RuntimeObject * __this /* static, unused */, String_t* ___url0, int32_t ___version1, const RuntimeMethod* method) { WWW_t3688466362 * V_0 = NULL; { String_t* L_0 = ___url0; int32_t L_1 = ___version1; WWW_t3688466362 * L_2 = WWW_LoadFromCacheOrDownload_m3958223827(NULL /*static, unused*/, L_0, L_1, 0, /*hidden argument*/NULL); V_0 = L_2; goto IL_000f; } IL_000f: { WWW_t3688466362 * L_3 = V_0; return L_3; } } // UnityEngine.WWW UnityEngine.WWW::LoadFromCacheOrDownload(System.String,System.Int32,System.UInt32) extern "C" IL2CPP_METHOD_ATTR WWW_t3688466362 * WWW_LoadFromCacheOrDownload_m3958223827 (RuntimeObject * __this /* static, unused */, String_t* ___url0, int32_t ___version1, uint32_t ___crc2, const RuntimeMethod* method) { Hash128_t2357739769 V_0; memset(&V_0, 0, sizeof(V_0)); WWW_t3688466362 * V_1 = NULL; { int32_t L_0 = ___version1; Hash128__ctor_m2348731757((Hash128_t2357739769 *)(&V_0), 0, 0, 0, L_0, /*hidden argument*/NULL); String_t* L_1 = ___url0; Hash128_t2357739769 L_2 = V_0; uint32_t L_3 = ___crc2; WWW_t3688466362 * L_4 = WWW_LoadFromCacheOrDownload_m4247140216(NULL /*static, unused*/, L_1, L_2, L_3, /*hidden argument*/NULL); V_1 = L_4; goto IL_001a; } IL_001a: { WWW_t3688466362 * L_5 = V_1; return L_5; } } // UnityEngine.WWW UnityEngine.WWW::LoadFromCacheOrDownload(System.String,UnityEngine.Hash128,System.UInt32) extern "C" IL2CPP_METHOD_ATTR WWW_t3688466362 * WWW_LoadFromCacheOrDownload_m4247140216 (RuntimeObject * __this /* static, unused */, String_t* ___url0, Hash128_t2357739769 ___hash1, uint32_t ___crc2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WWW_LoadFromCacheOrDownload_m4247140216_MetadataUsageId); s_Il2CppMethodInitialized = true; } WWW_t3688466362 * V_0 = NULL; { String_t* L_0 = ___url0; Hash128_t2357739769 L_1 = ___hash1; uint32_t L_2 = ___crc2; WWW_t3688466362 * L_3 = (WWW_t3688466362 *)il2cpp_codegen_object_new(WWW_t3688466362_il2cpp_TypeInfo_var); WWW__ctor_m3488013117(L_3, L_0, _stringLiteral757602046, L_1, L_2, /*hidden argument*/NULL); V_0 = L_3; goto IL_0014; } IL_0014: { WWW_t3688466362 * L_4 = V_0; return L_4; } } // UnityEngine.AssetBundle UnityEngine.WWW::get_assetBundle() extern "C" IL2CPP_METHOD_ATTR AssetBundle_t1153907252 * WWW_get_assetBundle_m3753667806 (WWW_t3688466362 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WWW_get_assetBundle_m3753667806_MetadataUsageId); s_Il2CppMethodInitialized = true; } AssetBundle_t1153907252 * V_0 = NULL; DownloadHandlerAssetBundle_t197128434 * V_1 = NULL; ByteU5BU5D_t4116647657* V_2 = NULL; { AssetBundle_t1153907252 * L_0 = __this->get__assetBundle_1(); IL2CPP_RUNTIME_CLASS_INIT(Object_t631007953_il2cpp_TypeInfo_var); bool L_1 = Object_op_Equality_m1810815630(NULL /*static, unused*/, L_0, (Object_t631007953 *)NULL, /*hidden argument*/NULL); if (!L_1) { goto IL_0087; } } { bool L_2 = WWW_WaitUntilDoneIfPossible_m2855479680(__this, /*hidden argument*/NULL); if (L_2) { goto IL_0025; } } { V_0 = (AssetBundle_t1153907252 *)NULL; goto IL_0093; } IL_0025: { UnityWebRequest_t463507806 * L_3 = __this->get__uwr_0(); NullCheck(L_3); bool L_4 = UnityWebRequest_get_isNetworkError_m1231611882(L_3, /*hidden argument*/NULL); if (!L_4) { goto IL_003c; } } { V_0 = (AssetBundle_t1153907252 *)NULL; goto IL_0093; } IL_003c: { UnityWebRequest_t463507806 * L_5 = __this->get__uwr_0(); NullCheck(L_5); DownloadHandler_t2937767557 * L_6 = UnityWebRequest_get_downloadHandler_m534911913(L_5, /*hidden argument*/NULL); V_1 = ((DownloadHandlerAssetBundle_t197128434 *)IsInstSealed((RuntimeObject*)L_6, DownloadHandlerAssetBundle_t197128434_il2cpp_TypeInfo_var)); DownloadHandlerAssetBundle_t197128434 * L_7 = V_1; if (!L_7) { goto IL_0064; } } { DownloadHandlerAssetBundle_t197128434 * L_8 = V_1; NullCheck(L_8); AssetBundle_t1153907252 * L_9 = DownloadHandlerAssetBundle_get_assetBundle_m3640693480(L_8, /*hidden argument*/NULL); __this->set__assetBundle_1(L_9); goto IL_0086; } IL_0064: { ByteU5BU5D_t4116647657* L_10 = WWW_get_bytes_m3061182897(__this, /*hidden argument*/NULL); V_2 = L_10; ByteU5BU5D_t4116647657* L_11 = V_2; if (L_11) { goto IL_0079; } } { V_0 = (AssetBundle_t1153907252 *)NULL; goto IL_0093; } IL_0079: { ByteU5BU5D_t4116647657* L_12 = V_2; AssetBundle_t1153907252 * L_13 = AssetBundle_LoadFromMemory_m336091660(NULL /*static, unused*/, L_12, /*hidden argument*/NULL); __this->set__assetBundle_1(L_13); } IL_0086: { } IL_0087: { AssetBundle_t1153907252 * L_14 = __this->get__assetBundle_1(); V_0 = L_14; goto IL_0093; } IL_0093: { AssetBundle_t1153907252 * L_15 = V_0; return L_15; } } // System.Byte[] UnityEngine.WWW::get_bytes() extern "C" IL2CPP_METHOD_ATTR ByteU5BU5D_t4116647657* WWW_get_bytes_m3061182897 (WWW_t3688466362 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WWW_get_bytes_m3061182897_MetadataUsageId); s_Il2CppMethodInitialized = true; } ByteU5BU5D_t4116647657* V_0 = NULL; DownloadHandler_t2937767557 * V_1 = NULL; { bool L_0 = WWW_WaitUntilDoneIfPossible_m2855479680(__this, /*hidden argument*/NULL); if (L_0) { goto IL_0018; } } { ByteU5BU5D_t4116647657* L_1 = (ByteU5BU5D_t4116647657*)SZArrayNew(ByteU5BU5D_t4116647657_il2cpp_TypeInfo_var, (uint32_t)0); V_0 = L_1; goto IL_005e; } IL_0018: { UnityWebRequest_t463507806 * L_2 = __this->get__uwr_0(); NullCheck(L_2); bool L_3 = UnityWebRequest_get_isNetworkError_m1231611882(L_2, /*hidden argument*/NULL); if (!L_3) { goto IL_0034; } } { ByteU5BU5D_t4116647657* L_4 = (ByteU5BU5D_t4116647657*)SZArrayNew(ByteU5BU5D_t4116647657_il2cpp_TypeInfo_var, (uint32_t)0); V_0 = L_4; goto IL_005e; } IL_0034: { UnityWebRequest_t463507806 * L_5 = __this->get__uwr_0(); NullCheck(L_5); DownloadHandler_t2937767557 * L_6 = UnityWebRequest_get_downloadHandler_m534911913(L_5, /*hidden argument*/NULL); V_1 = L_6; DownloadHandler_t2937767557 * L_7 = V_1; if (L_7) { goto IL_0052; } } { ByteU5BU5D_t4116647657* L_8 = (ByteU5BU5D_t4116647657*)SZArrayNew(ByteU5BU5D_t4116647657_il2cpp_TypeInfo_var, (uint32_t)0); V_0 = L_8; goto IL_005e; } IL_0052: { DownloadHandler_t2937767557 * L_9 = V_1; NullCheck(L_9); ByteU5BU5D_t4116647657* L_10 = DownloadHandler_get_data_m1669096410(L_9, /*hidden argument*/NULL); V_0 = L_10; goto IL_005e; } IL_005e: { ByteU5BU5D_t4116647657* L_11 = V_0; return L_11; } } // System.String UnityEngine.WWW::get_error() extern "C" IL2CPP_METHOD_ATTR String_t* WWW_get_error_m3055313367 (WWW_t3688466362 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WWW_get_error_m3055313367_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; { UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0(); NullCheck(L_0); bool L_1 = UnityWebRequest_get_isDone_m1752128881(L_0, /*hidden argument*/NULL); if (L_1) { goto IL_0018; } } { V_0 = (String_t*)NULL; goto IL_0087; } IL_0018: { UnityWebRequest_t463507806 * L_2 = __this->get__uwr_0(); NullCheck(L_2); bool L_3 = UnityWebRequest_get_isNetworkError_m1231611882(L_2, /*hidden argument*/NULL); if (!L_3) { goto IL_0039; } } { UnityWebRequest_t463507806 * L_4 = __this->get__uwr_0(); NullCheck(L_4); String_t* L_5 = UnityWebRequest_get_error_m1613086199(L_4, /*hidden argument*/NULL); V_0 = L_5; goto IL_0087; } IL_0039: { UnityWebRequest_t463507806 * L_6 = __this->get__uwr_0(); NullCheck(L_6); int64_t L_7 = UnityWebRequest_get_responseCode_m1090830473(L_6, /*hidden argument*/NULL); if ((((int64_t)L_7) < ((int64_t)(((int64_t)((int64_t)((int32_t)400))))))) { goto IL_0080; } } { UnityWebRequest_t463507806 * L_8 = __this->get__uwr_0(); NullCheck(L_8); int64_t L_9 = UnityWebRequest_get_responseCode_m1090830473(L_8, /*hidden argument*/NULL); int64_t L_10 = L_9; RuntimeObject * L_11 = Box(Int64_t3736567304_il2cpp_TypeInfo_var, &L_10); UnityWebRequest_t463507806 * L_12 = __this->get__uwr_0(); NullCheck(L_12); int64_t L_13 = UnityWebRequest_get_responseCode_m1090830473(L_12, /*hidden argument*/NULL); String_t* L_14 = WWW_GetStatusCodeName_m3580893459(__this, L_13, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_15 = String_Format_m2556382932(NULL /*static, unused*/, _stringLiteral380657706, L_11, L_14, /*hidden argument*/NULL); V_0 = L_15; goto IL_0087; } IL_0080: { V_0 = (String_t*)NULL; goto IL_0087; } IL_0087: { String_t* L_16 = V_0; return L_16; } } // System.Boolean UnityEngine.WWW::get_isDone() extern "C" IL2CPP_METHOD_ATTR bool WWW_get_isDone_m3426350689 (WWW_t3688466362 * __this, const RuntimeMethod* method) { bool V_0 = false; { UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0(); NullCheck(L_0); bool L_1 = UnityWebRequest_get_isDone_m1752128881(L_0, /*hidden argument*/NULL); V_0 = L_1; goto IL_0012; } IL_0012: { bool L_2 = V_0; return L_2; } } // System.String UnityEngine.WWW::get_text() extern "C" IL2CPP_METHOD_ATTR String_t* WWW_get_text_m898164367 (WWW_t3688466362 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WWW_get_text_m898164367_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; DownloadHandler_t2937767557 * V_1 = NULL; { bool L_0 = WWW_WaitUntilDoneIfPossible_m2855479680(__this, /*hidden argument*/NULL); if (L_0) { goto IL_0017; } } { V_0 = _stringLiteral757602046; goto IL_005b; } IL_0017: { UnityWebRequest_t463507806 * L_1 = __this->get__uwr_0(); NullCheck(L_1); bool L_2 = UnityWebRequest_get_isNetworkError_m1231611882(L_1, /*hidden argument*/NULL); if (!L_2) { goto IL_0032; } } { V_0 = _stringLiteral757602046; goto IL_005b; } IL_0032: { UnityWebRequest_t463507806 * L_3 = __this->get__uwr_0(); NullCheck(L_3); DownloadHandler_t2937767557 * L_4 = UnityWebRequest_get_downloadHandler_m534911913(L_3, /*hidden argument*/NULL); V_1 = L_4; DownloadHandler_t2937767557 * L_5 = V_1; if (L_5) { goto IL_004f; } } { V_0 = _stringLiteral757602046; goto IL_005b; } IL_004f: { DownloadHandler_t2937767557 * L_6 = V_1; NullCheck(L_6); String_t* L_7 = DownloadHandler_get_text_m2427232382(L_6, /*hidden argument*/NULL); V_0 = L_7; goto IL_005b; } IL_005b: { String_t* L_8 = V_0; return L_8; } } // System.String UnityEngine.WWW::get_url() extern "C" IL2CPP_METHOD_ATTR String_t* WWW_get_url_m3672399347 (WWW_t3688466362 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0(); NullCheck(L_0); String_t* L_1 = UnityWebRequest_get_url_m2568598920(L_0, /*hidden argument*/NULL); V_0 = L_1; goto IL_0012; } IL_0012: { String_t* L_2 = V_0; return L_2; } } // System.Boolean UnityEngine.WWW::get_keepWaiting() extern "C" IL2CPP_METHOD_ATTR bool WWW_get_keepWaiting_m1438015190 (WWW_t3688466362 * __this, const RuntimeMethod* method) { bool V_0 = false; { UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0(); NullCheck(L_0); bool L_1 = UnityWebRequest_get_isDone_m1752128881(L_0, /*hidden argument*/NULL); V_0 = (bool)((((int32_t)L_1) == ((int32_t)0))? 1 : 0); goto IL_0015; } IL_0015: { bool L_2 = V_0; return L_2; } } // System.Void UnityEngine.WWW::Dispose() extern "C" IL2CPP_METHOD_ATTR void WWW_Dispose_m2256148703 (WWW_t3688466362 * __this, const RuntimeMethod* method) { { UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0(); NullCheck(L_0); UnityWebRequest_Dispose_m3261105905(L_0, /*hidden argument*/NULL); return; } } // System.Boolean UnityEngine.WWW::WaitUntilDoneIfPossible() extern "C" IL2CPP_METHOD_ATTR bool WWW_WaitUntilDoneIfPossible_m2855479680 (WWW_t3688466362 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WWW_WaitUntilDoneIfPossible_m2855479680_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; { UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0(); NullCheck(L_0); bool L_1 = UnityWebRequest_get_isDone_m1752128881(L_0, /*hidden argument*/NULL); if (!L_1) { goto IL_0018; } } { V_0 = (bool)1; goto IL_005f; } IL_0018: { String_t* L_2 = WWW_get_url_m3672399347(__this, /*hidden argument*/NULL); NullCheck(L_2); bool L_3 = String_StartsWith_m2640722675(L_2, _stringLiteral4054833267, 5, /*hidden argument*/NULL); if (!L_3) { goto IL_004d; } } { goto IL_0036; } IL_0034: { } IL_0036: { UnityWebRequest_t463507806 * L_4 = __this->get__uwr_0(); NullCheck(L_4); bool L_5 = UnityWebRequest_get_isDone_m1752128881(L_4, /*hidden argument*/NULL); if (!L_5) { goto IL_0034; } } { V_0 = (bool)1; goto IL_005f; } IL_004d: { IL2CPP_RUNTIME_CLASS_INIT(Debug_t3317548046_il2cpp_TypeInfo_var); Debug_LogError_m2850623458(NULL /*static, unused*/, _stringLiteral1973828197, /*hidden argument*/NULL); V_0 = (bool)0; goto IL_005f; } IL_005f: { bool L_6 = V_0; return L_6; } } // System.String UnityEngine.WWW::GetStatusCodeName(System.Int64) extern "C" IL2CPP_METHOD_ATTR String_t* WWW_GetStatusCodeName_m3580893459 (WWW_t3688466362 * __this, int64_t ___statusCode0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WWW_GetStatusCodeName_m3580893459_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; { int64_t L_0 = ___statusCode0; if ((((int64_t)L_0) < ((int64_t)(((int64_t)((int64_t)((int32_t)400))))))) { goto IL_006b; } } { int64_t L_1 = ___statusCode0; if ((((int64_t)L_1) > ((int64_t)(((int64_t)((int64_t)((int32_t)416))))))) { goto IL_006b; } } { int64_t L_2 = ___statusCode0; switch ((((int32_t)((int32_t)((int64_t)il2cpp_codegen_subtract((int64_t)L_2, (int64_t)(((int64_t)((int64_t)((int32_t)400)))))))))) { case 0: { goto IL_01d9; } case 1: { goto IL_01e4; } case 2: { goto IL_01ef; } case 3: { goto IL_01fa; } case 4: { goto IL_0205; } case 5: { goto IL_0210; } case 6: { goto IL_021b; } case 7: { goto IL_0226; } case 8: { goto IL_0231; } case 9: { goto IL_023c; } case 10: { goto IL_0247; } case 11: { goto IL_0252; } case 12: { goto IL_025d; } case 13: { goto IL_0268; } case 14: { goto IL_0273; } case 15: { goto IL_027e; } case 16: { goto IL_0289; } } } IL_006b: { int64_t L_3 = ___statusCode0; if ((((int64_t)L_3) < ((int64_t)(((int64_t)((int64_t)((int32_t)200))))))) { goto IL_00ad; } } { int64_t L_4 = ___statusCode0; if ((((int64_t)L_4) > ((int64_t)(((int64_t)((int64_t)((int32_t)206))))))) { goto IL_00ad; } } { int64_t L_5 = ___statusCode0; switch ((((int32_t)((int32_t)((int64_t)il2cpp_codegen_subtract((int64_t)L_5, (int64_t)(((int64_t)((int64_t)((int32_t)200)))))))))) { case 0: { goto IL_013f; } case 1: { goto IL_014a; } case 2: { goto IL_0155; } case 3: { goto IL_0160; } case 4: { goto IL_016b; } case 5: { goto IL_0176; } case 6: { goto IL_0181; } } } IL_00ad: { int64_t L_6 = ___statusCode0; if ((((int64_t)L_6) < ((int64_t)(((int64_t)((int64_t)((int32_t)300))))))) { goto IL_00f3; } } { int64_t L_7 = ___statusCode0; if ((((int64_t)L_7) > ((int64_t)(((int64_t)((int64_t)((int32_t)307))))))) { goto IL_00f3; } } { int64_t L_8 = ___statusCode0; switch ((((int32_t)((int32_t)((int64_t)il2cpp_codegen_subtract((int64_t)L_8, (int64_t)(((int64_t)((int64_t)((int32_t)300)))))))))) { case 0: { goto IL_018c; } case 1: { goto IL_0197; } case 2: { goto IL_01a2; } case 3: { goto IL_01ad; } case 4: { goto IL_01b8; } case 5: { goto IL_01c3; } case 6: { goto IL_00f3; } case 7: { goto IL_01ce; } } } IL_00f3: { int64_t L_9 = ___statusCode0; if ((((int64_t)L_9) < ((int64_t)(((int64_t)((int64_t)((int32_t)500))))))) { goto IL_0131; } } { int64_t L_10 = ___statusCode0; if ((((int64_t)L_10) > ((int64_t)(((int64_t)((int64_t)((int32_t)505))))))) { goto IL_0131; } } { int64_t L_11 = ___statusCode0; switch ((((int32_t)((int32_t)((int64_t)il2cpp_codegen_subtract((int64_t)L_11, (int64_t)(((int64_t)((int64_t)((int32_t)500)))))))))) { case 0: { goto IL_029f; } case 1: { goto IL_02aa; } case 2: { goto IL_02b5; } case 3: { goto IL_02c0; } case 4: { goto IL_02cb; } case 5: { goto IL_02d6; } } } IL_0131: { int64_t L_12 = ___statusCode0; if ((((int64_t)L_12) == ((int64_t)(((int64_t)((int64_t)((int32_t)41))))))) { goto IL_0294; } } { goto IL_02e1; } IL_013f: { V_0 = _stringLiteral3457136609; goto IL_02ec; } IL_014a: { V_0 = _stringLiteral3911804090; goto IL_02ec; } IL_0155: { V_0 = _stringLiteral2487325543; goto IL_02ec; } IL_0160: { V_0 = _stringLiteral3860885797; goto IL_02ec; } IL_016b: { V_0 = _stringLiteral3476706848; goto IL_02ec; } IL_0176: { V_0 = _stringLiteral560819067; goto IL_02ec; } IL_0181: { V_0 = _stringLiteral2030167956; goto IL_02ec; } IL_018c: { V_0 = _stringLiteral1814237603; goto IL_02ec; } IL_0197: { V_0 = _stringLiteral4140321389; goto IL_02ec; } IL_01a2: { V_0 = _stringLiteral2002596717; goto IL_02ec; } IL_01ad: { V_0 = _stringLiteral1659593328; goto IL_02ec; } IL_01b8: { V_0 = _stringLiteral4277434149; goto IL_02ec; } IL_01c3: { V_0 = _stringLiteral3090824594; goto IL_02ec; } IL_01ce: { V_0 = _stringLiteral3842069051; goto IL_02ec; } IL_01d9: { V_0 = _stringLiteral4233297459; goto IL_02ec; } IL_01e4: { V_0 = _stringLiteral3545044340; goto IL_02ec; } IL_01ef: { V_0 = _stringLiteral573727993; goto IL_02ec; } IL_01fa: { V_0 = _stringLiteral2117271536; goto IL_02ec; } IL_0205: { V_0 = _stringLiteral2178748878; goto IL_02ec; } IL_0210: { V_0 = _stringLiteral106317971; goto IL_02ec; } IL_021b: { V_0 = _stringLiteral461727106; goto IL_02ec; } IL_0226: { V_0 = _stringLiteral1542497020; goto IL_02ec; } IL_0231: { V_0 = _stringLiteral2343474426; goto IL_02ec; } IL_023c: { V_0 = _stringLiteral1138636386; goto IL_02ec; } IL_0247: { V_0 = _stringLiteral2791739693; goto IL_02ec; } IL_0252: { V_0 = _stringLiteral1091611732; goto IL_02ec; } IL_025d: { V_0 = _stringLiteral356324127; goto IL_02ec; } IL_0268: { V_0 = _stringLiteral624401215; goto IL_02ec; } IL_0273: { V_0 = _stringLiteral1073086928; goto IL_02ec; } IL_027e: { V_0 = _stringLiteral1060465165; goto IL_02ec; } IL_0289: { V_0 = _stringLiteral3739562776; goto IL_02ec; } IL_0294: { V_0 = _stringLiteral3244775435; goto IL_02ec; } IL_029f: { V_0 = _stringLiteral3899005722; goto IL_02ec; } IL_02aa: { V_0 = _stringLiteral4002396095; goto IL_02ec; } IL_02b5: { V_0 = _stringLiteral3604523934; goto IL_02ec; } IL_02c0: { V_0 = _stringLiteral2201204884; goto IL_02ec; } IL_02cb: { V_0 = _stringLiteral3363965078; goto IL_02ec; } IL_02d6: { V_0 = _stringLiteral858510039; goto IL_02ec; } IL_02e1: { V_0 = _stringLiteral757602046; goto IL_02ec; } IL_02ec: { String_t* L_13 = V_0; return L_13; } } #ifdef __clang__ #pragma clang diagnostic pop #endif
33.346503
250
0.798754
sashohadz