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
109
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
48.5k
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
78970d4524a752d6f4374359c1e412bed994e97f
805
cpp
C++
test/SeeDeviceAddress.cpp
genevea/TankController
18c47c54737800cca09525d907c8ddf4f6e36750
[ "MIT" ]
null
null
null
test/SeeDeviceAddress.cpp
genevea/TankController
18c47c54737800cca09525d907c8ddf4f6e36750
[ "MIT" ]
1
2021-05-10T05:41:39.000Z
2021-05-10T05:41:39.000Z
test/SeeDeviceAddress.cpp
genevea/TankController
18c47c54737800cca09525d907c8ddf4f6e36750
[ "MIT" ]
null
null
null
#include "SeeDeviceAddress.h" #include <Arduino.h> #include <ArduinoUnitTests.h> #include "Keypad_TC.h" #include "LiquidCrystal_TC.h" #include "TankControllerLib.h" unittest(testOutput) { TankControllerLib* tc = TankControllerLib::instance(); LiquidCrystal_TC* display = LiquidCrystal_TC::instance(); assertEqual("MainMenu", tc->stateName()); SeeDeviceAddress* test = new SeeDeviceAddress(tc); tc->setNextState(test, true); assertEqual("SeeDeviceAddress", tc->stateName()); // Test the output tc->loop(); assertEqual("192.168.001.002 ", display->getLines().at(0)); assertEqual("90A2:DA00:0000 ", display->getLines().at(1)); // Return to mainMenu Keypad_TC::instance()->_getPuppet()->push_back('D'); tc->loop(); assertEqual("MainMenu", tc->stateName()); } unittest_main()
27.758621
61
0.710559
genevea
789752e9399a02405a1da70f1958f3491dd7c602
545
cpp
C++
Easy Challenges/Ciel and A-B.cpp
Akashverma247/Coding_Library
09c28a71c7ba5b2f192bb8ef26b2d0a41905f011
[ "MIT" ]
null
null
null
Easy Challenges/Ciel and A-B.cpp
Akashverma247/Coding_Library
09c28a71c7ba5b2f192bb8ef26b2d0a41905f011
[ "MIT" ]
null
null
null
Easy Challenges/Ciel and A-B.cpp
Akashverma247/Coding_Library
09c28a71c7ba5b2f192bb8ef26b2d0a41905f011
[ "MIT" ]
null
null
null
/* In Ciel's restaurant, a waiter is training. Since the waiter isn't good at arithmetic, sometimes he gives guests wrong change. Ciel gives him a simple problem. What is A-B (A minus B) ? Surprisingly, his answer is wrong. To be more precise, his answer has exactly one wrong digit. Can you imagine this? Can you make the same mistake in this problem? */ #include<bits/stdc++.h> using namespace std; int main(){ int n,m; cin>>n>>m; int k=n-m; if(k%10!=9){ k++; } else{ k--; } cout<<k<<endl; }
25.952381
185
0.638532
Akashverma247
7898e79d60d92ba5b556054923231de1c9141dca
790
cpp
C++
cpp/src/exercise/e0100/e0098.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0100/e0098.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0100/e0098.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
// https://leetcode-cn.com/problems/validate-binary-search-tree/ #include "extern.h" class S0098 { bool leftFirst(TreeNode* root, vector<int>& vec) { if (root->left && !leftFirst(root->left, vec)) return false; if (!vec.empty() && vec.back() >= root->val) return false; vec.push_back(root->val); if (root->right && !leftFirst(root->right, vec)) return false; return true; } public: bool isValidBST(TreeNode* root) { if (!root) return true; vector<int> vec; return leftFirst(root, vec); } }; TEST(e0100, e0098) { TreeNode* root; root = new TreeNode("[2,1,3]"); ASSERT_TRUE(S0098().isValidBST(root)); root = new TreeNode("[5,1,4,null,null,3,6]"); ASSERT_FALSE(S0098().isValidBST(root)); }
28.214286
70
0.6
ajz34
78990cb7b401b12c5bb8983ba059e6734fa46a4a
5,974
cpp
C++
src/utils/Blob.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
2
2020-11-25T17:45:58.000Z
2021-12-21T02:01:16.000Z
src/utils/Blob.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
null
null
null
src/utils/Blob.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
1
2021-10-11T19:54:05.000Z
2021-10-11T19:54:05.000Z
#include <cstring> #include <iomanip> #include <stdexcept> #include <utility> #include "utils/Blob.hpp" #include "utils/little_endian.hpp" #include "utils/memory.hpp" Blob::Blob(void *ptr, const std::size_t len, const hxhim_data_t type, const bool clean) : ptr(ptr), len(len), type(type), clean(clean) {} Blob::Blob(const std::size_t len, const void *ptr, const hxhim_data_t type) : ptr(::alloc(len)), len(len), type(type), clean(true) { memcpy(this->ptr, ptr, len); } Blob::Blob(const std::string &str, const hxhim_data_t type) : Blob((char *) str.data(), str.size(), type) {} Blob::Blob(Blob &rhs) : Blob(rhs.ptr, rhs.len, rhs.type, false) {} Blob::Blob(Blob &&rhs) : Blob(rhs.ptr, rhs.len, rhs.type, rhs.clean) { rhs.clear(); } Blob::~Blob() { Blob::dealloc(); } Blob &Blob::operator=(Blob &rhs) { if (this != &rhs) { Blob::dealloc(); // handle existing data // this becomes a reference to rhs ptr = rhs.ptr; len = rhs.len; type = rhs.type; clean = false; } return *this; } Blob &Blob::operator=(Blob &&rhs) { if (this != &rhs) { Blob::dealloc(); // handle existing data ptr = rhs.ptr; len = rhs.len; type = rhs.type; clean = rhs.clean; rhs.clean = false; rhs.clear(); } return *this; } bool Blob::operator==(const Blob &rhs) const { return ((type == rhs.type) && (len == rhs.len) && ((ptr == rhs.ptr) || (memcmp(ptr, rhs.ptr, rhs.len) == 0))); } bool Blob::operator!=(const Blob &rhs) const { return !(*this == rhs); } hxhim_data_t Blob::set_type(const hxhim_data_t new_type) { const hxhim_data_t old_type = type; type = new_type; return old_type; } bool Blob::set_clean(bool new_clean) { const bool old_clean = clean; clean = new_clean; return old_clean; } void Blob::clear() { ptr = nullptr; len = 0; type = hxhim_data_t::HXHIM_DATA_INVALID; clean = false; } void Blob::dealloc() { if (clean) { ::dealloc(ptr); } clear(); } // read to a blob of memory // the blob argument is assumed to be defined and large enough to fit the data // (length is not known) char *Blob::pack(char *&dst, const bool include_type) const { if (!dst || !ptr) { return nullptr; } little_endian::encode(dst, len); dst += sizeof(len); memcpy(dst, ptr, len); dst += len; if (include_type) { little_endian::encode(dst, type); dst += sizeof(type); } return dst; } std::size_t Blob::pack_size(const bool include_type) const { return pack_size(len, include_type); } std::size_t Blob::pack_size(const std::size_t len, const bool include_type) { return len + sizeof(len) + (include_type?sizeof(type):0); } // read from a blob of memory // (length is not known) char *Blob::unpack(char *&src, const bool include_type, const bool copy) { if (!src) { throw std::runtime_error("unable to unpack blob"); } little_endian::decode(len, src); src += sizeof(len); if ((clean = copy)) { ptr = alloc(len); memcpy(ptr, src, len); } else { ptr = src; } src += len; if (include_type) { little_endian::decode(type, src); src += sizeof(type); } return src; } // pack the ptr address and length char *Blob::pack_ref(char *&dst, const bool include_type) const { if (!dst) { return nullptr; } memcpy(dst, &ptr, sizeof(ptr)); dst += sizeof(ptr); little_endian::encode(dst, len); dst += sizeof(len); if (include_type) { little_endian::encode(dst, type); dst += sizeof(type); } return dst; } std::size_t Blob::pack_ref_size(const bool include_type) const { return sizeof(ptr) + sizeof(len) + (include_type?sizeof(type):0); } char *Blob::unpack_ref(char *&src, const bool include_type) { if (!src) { return nullptr; } memcpy(&ptr, src, sizeof(ptr)); src += sizeof(ptr); little_endian::decode(len, src); src += sizeof(len); if (include_type) { little_endian::decode(type, src); src += sizeof(type); } clean = false; return src; } /** * get * Get values from a Blob in one function * Caller does not own pointer extracted from Blob * * @param addr Address of variable to copy ptr into (optional) * @param length how long the item stored in this Blob is (optional) * @param datatype the type of data pointed to by addr */ void Blob::get(void **addr, std::size_t *length, hxhim_data_t *datatype) const { if (addr) { *addr = ptr; } if (length) { *length = len; } if (datatype) { *datatype = type; } } void *Blob::data() const { return ptr; } std::size_t Blob::size() const { return len; } hxhim_data_t Blob::data_type() const { return type; } bool Blob::will_clean() const { return clean; } Blob::operator std::string() const { return std::string((char *) ptr, len); } std::ostream &operator<<(std::ostream &stream, const Blob &blob) { stream << "[" << blob.ptr << ", " << blob.len << ", "; if (blob.type <= hxhim_data_t::HXHIM_DATA_MAX_KNOWN) { stream << HXHIM_DATA_STR[blob.type]; } else { stream << "Unknown Type (" << blob.type << ")"; } return stream << ", " << std::boolalpha << blob.clean << "]"; } Blob ReferenceBlob(void *ptr, const std::size_t len, const hxhim_data_t type) { return Blob(ptr, len, type, false); } Blob RealBlob(void *ptr, const std::size_t len, const hxhim_data_t type) { return std::move(Blob(ptr, len, type, true)); } Blob RealBlob(const std::size_t len, const void *ptr, const hxhim_data_t type) { return std::move(Blob(len, ptr, type)); }
20.888112
87
0.58085
hpc
789cfa59cc193d3548d4d62cf96743b9fa99e656
7,664
cpp
C++
src/XPTools/ConvertObj3DS.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
71
2015-12-15T19:32:27.000Z
2022-02-25T04:46:01.000Z
src/XPTools/ConvertObj3DS.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
19
2016-07-09T19:08:15.000Z
2021-07-29T10:30:20.000Z
src/XPTools/ConvertObj3DS.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
42
2015-12-14T19:13:02.000Z
2022-03-01T15:15:03.000Z
/* * Copyright (c) 2004, Laminar Research. * * 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. * */ // // Another 3DS lib can be found at: http://c3ds.sourceforge.net/ // #include "ConvertObj3DS.h" #include "ObjUtils.h" #include <lib3ds/file.h> #include <lib3ds/vector.h> #include <lib3ds/matrix.h> #include <lib3ds/material.h> #include <lib3ds/mesh.h> bool ReadObj3DS(const char * inFilePath, XObj& obj, bool inReversePoly) { obj.texture = "no_texture"; Lib3dsFile * f=lib3ds_file_load(inFilePath); obj.cmds.clear(); XObjCmd lodCmd; lodCmd.cmdID = attr_LOD; lodCmd.cmdType = type_Attr; lodCmd.attributes.resize(2); bool success = false; if (f) { map<string, Lib3dsMaterial*> materials; for (Lib3dsMaterial * material = f->materials; material ; material = material->next) { materials.insert(pair<string,Lib3dsMaterial*>(material->name, material)); } lib3ds_file_eval(f,0.0); // I think this sets the time of a specified motion sequence. // We could iterate the nodes on the file, they would reference the meshes by name and we'd fetch // them. We would then apply the node's matrix and pivot point, as follows: // mesh=lib3ds_file_mesh_by_name(f, node->name); // Lib3dsMatrix N,M,X; // lib3ds_matrix_copy(N, node->matrix); // lib3ds_matrix_translate_xyz(N, -d->pivot[0], -d->pivot[1], -d->pivot[2]); // lib3ds_matrix_copy(M, mesh->matrix); // lib3ds_matrix_inv(M); // lib3ds_matrix_mul(X,N,M); // Iterate across all of the meshes in the 3DS file. for (Lib3dsMesh * mesh = f->meshes; mesh; mesh = mesh->next) { if (sscanf(mesh->name,"LOD %f/%f",&lodCmd.attributes[0], &lodCmd.attributes[1])==2) { obj.cmds.push_back(lodCmd); } // Transform each point by the matrix... for (int pp=0; pp<mesh->points; ++pp) { Lib3dsVector c; lib3ds_vector_transform(c,mesh->matrix, mesh->pointL[pp].pos); mesh->pointL[pp].pos[0] = c[0]; mesh->pointL[pp].pos[1] = c[1]; mesh->pointL[pp].pos[2] = c[2]; } // 3DS is made entirely of triangles...de-index each face and emit it. for (int p=0; p<mesh->faces; ++p) { float s_offset = 0.0; float t_offset = 0.0; float s_scale = 1.0; float t_scale = 1.0; Lib3dsFace *face=&mesh->faceL[p]; if (materials.find(face->material) != materials.end()) { Lib3dsMaterial * material = materials[face->material]; s_offset = material->texture1_map.offset[0]; t_offset = material->texture1_map.offset[1]; s_scale = material->texture1_map.scale[0]; t_scale = material->texture1_map.scale[1]; } vec_tex vv; XObjCmd cmd; cmd.cmdType = type_Poly; cmd.cmdID = obj_Tri; if (mesh->texelL) { vv.st[0] = s_offset + s_scale * mesh->texelL[face->points[0]][0]; vv.st[1] = t_offset + t_scale * mesh->texelL[face->points[0]][1]; } else vv.st[0] = vv.st[1] = 0.0; vv.v[0] = mesh->pointL[face->points[0]].pos[0]; vv.v[1] = mesh->pointL[face->points[0]].pos[1]; vv.v[2] = mesh->pointL[face->points[0]].pos[2]; cmd.st.push_back(vv); if (mesh->texelL) { vv.st[0] = s_offset + s_scale * mesh->texelL[face->points[1]][0]; vv.st[1] = t_offset + t_scale * mesh->texelL[face->points[1]][1]; } else vv.st[0] = vv.st[1] = 0.0; vv.v[0] = mesh->pointL[face->points[1]].pos[0]; vv.v[1] = mesh->pointL[face->points[1]].pos[1]; vv.v[2] = mesh->pointL[face->points[1]].pos[2]; cmd.st.push_back(vv); if (mesh->texelL) { vv.st[0] = s_offset + s_scale * mesh->texelL[face->points[2]][0]; vv.st[1] = t_offset + t_scale * mesh->texelL[face->points[2]][1]; } else vv.st[0] = vv.st[1] = 0.0; vv.v[0] = mesh->pointL[face->points[2]].pos[0]; vv.v[1] = mesh->pointL[face->points[2]].pos[1]; vv.v[2] = mesh->pointL[face->points[2]].pos[2]; cmd.st.push_back(vv); if (inReversePoly) ChangePolyCmdCW(cmd); obj.cmds.push_back(cmd); } } lib3ds_file_free(f); success = true; } return success; } void pool_get(ObjPointPool * pool, int idx, float xyz[3], float st[2]) { float * p = pool->get(idx); xyz[0] = p[0]; xyz[1] = p[1]; xyz[2] = p[2]; st [0] = p[3]; st [1] = p[4]; } int pool_accumulate(ObjPointPool * pool, const float xyz[3], const float st[2]) { float d[5]; d[0] = xyz[0]; d[1] = xyz[1]; d[2] = xyz[2]; d[3] = st [0]; d[4] = st [1]; return pool->accumulate(d); } bool WriteObj3DS(const char * inFilePath, const XObj& inObj, bool inReversePoly) { ObjPointPool pool; pool.clear(5); bool success = false; Lib3dsFile * file = lib3ds_file_new(); if (!file) return false; Lib3dsMesh * mesh; vector<int> p1, p2, p3; static char meshName[256]; sprintf(meshName,"Unnamed"); XObj obj; DecomposeObj(inObj, obj, 3); for(vector<XObjCmd>::iterator cmd = obj.cmds.begin(); cmd != obj.cmds.end(); ++cmd) { switch(cmd->cmdType) { case type_Attr: switch(cmd->cmdID) { case attr_LOD: if (!p1.empty()) { mesh = lib3ds_mesh_new(meshName); lib3ds_mesh_new_point_list(mesh, pool.count()); lib3ds_mesh_new_texel_list(mesh, pool.count()); lib3ds_mesh_new_face_list(mesh, p1.size()); for (int i = 0; i < pool.count(); ++i) pool_get(&pool,i,mesh->pointL[i].pos,mesh->texelL[i]); for (int p = 0; p < p1.size(); ++p) { mesh->faceL[p].points[0] = p1[p]; mesh->faceL[p].points[1] = p2[p]; mesh->faceL[p].points[2] = p3[p]; } lib3ds_file_insert_mesh(file, mesh); pool.clear(5); p1.clear(); p2.clear(); p3.clear(); } sprintf(meshName,"LOD %f/%f\n",cmd->attributes[0], cmd->attributes[1]); break; } break; case type_Poly: if (inReversePoly) ChangePolyCmdCW(*cmd); switch(cmd->cmdID) { case obj_Tri: p1.push_back(pool_accumulate(&pool,cmd->st[0].v, cmd->st[0].st)); p2.push_back(pool_accumulate(&pool,cmd->st[1].v, cmd->st[1].st)); p3.push_back(pool_accumulate(&pool,cmd->st[2].v, cmd->st[2].st)); break; } break; } } if (!p1.empty()) { mesh = lib3ds_mesh_new(meshName); lib3ds_mesh_new_point_list(mesh, pool.count()); lib3ds_mesh_new_texel_list(mesh, pool.count()); lib3ds_mesh_new_face_list(mesh, p1.size()); for (int i = 0; i < pool.count(); ++i) pool_get(&pool,i,mesh->pointL[i].pos,mesh->texelL[i]); for (int p = 0; p < p1.size(); ++p) { mesh->faceL[p].points[0] = p1[p]; mesh->faceL[p].points[1] = p2[p]; mesh->faceL[p].points[2] = p3[p]; } lib3ds_file_insert_mesh(file, mesh); } success = lib3ds_file_save(file, inFilePath); lib3ds_file_free(file); return success; }
29.590734
99
0.635569
rromanchuk
789d80e2e0142611c4c8d2abe5fd9c9c05a19060
4,542
cpp
C++
frontends/p4/typeChecking/syntacticEquivalence.cpp
DTharun/p4lang
d83d078f95ae2eaf054955fb645fa4d4a7e54847
[ "Apache-2.0" ]
27
2018-06-30T13:01:40.000Z
2022-01-28T09:07:21.000Z
frontends/p4/typeChecking/syntacticEquivalence.cpp
DTharun/p4lang
d83d078f95ae2eaf054955fb645fa4d4a7e54847
[ "Apache-2.0" ]
8
2018-06-01T11:19:02.000Z
2018-06-09T13:09:15.000Z
frontends/p4/typeChecking/syntacticEquivalence.cpp
DTharun/p4lang
d83d078f95ae2eaf054955fb645fa4d4a7e54847
[ "Apache-2.0" ]
6
2019-02-24T11:20:22.000Z
2021-05-25T17:21:07.000Z
/* Copyright 2016 VMware, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "syntacticEquivalence.h" namespace P4 { bool SameExpression::sameType(const IR::Type* left, const IR::Type* right) const { auto lt = typeMap->getType(left, true); auto rt = typeMap->getType(right, true); return TypeMap::equivalent(lt, rt); } bool SameExpression::sameExpressions(const IR::Vector<IR::Expression>* left, const IR::Vector<IR::Expression>* right) const { if (left->size() != right->size()) return false; for (unsigned i = 0; i < left->size(); i++) if (!sameExpression(left->at(i), right->at(i))) return false; return true; } bool SameExpression::sameExpression(const IR::Expression* left, const IR::Expression* right) const { CHECK_NULL(left); CHECK_NULL(right); if (left->node_type_name() != right->node_type_name()) return false; if (left->is<IR::Operation_Unary>()) { auto lu = left->to<IR::Operation_Unary>(); auto ru = right->to<IR::Operation_Unary>(); if (left->is<IR::Member>()) { auto lm = left->to<IR::Member>(); auto rm = right->to<IR::Member>(); if (lm->member != rm->member) return false; } else if (left->is<IR::Cast>()) { auto lc = left->to<IR::Cast>(); auto rc = right->to<IR::Cast>(); if (!sameType(lc->type, rc->type)) return false; } return sameExpression(lu->expr, ru->expr); } else if (left->is<IR::Operation_Binary>()) { auto lb = left->to<IR::Operation_Binary>(); auto rb = right->to<IR::Operation_Binary>(); return sameExpression(lb->left, rb->left) && sameExpression(lb->right, rb->right); } else if (left->is<IR::Operation_Ternary>()) { auto lt = left->to<IR::Operation_Ternary>(); auto rt = right->to<IR::Operation_Ternary>(); return sameExpression(lt->e0, rt->e0) && sameExpression(lt->e1, rt->e1) && sameExpression(lt->e2, rt->e2); } else if (left->is<IR::Constant>()) { return left->to<IR::Constant>()->value == right->to<IR::Constant>()->value; } else if (left->is<IR::Literal>()) { return *left == *right; } else if (left->is<IR::PathExpression>()) { auto ld = refMap->getDeclaration(left->to<IR::PathExpression>()->path, true); auto rd = refMap->getDeclaration(right->to<IR::PathExpression>()->path, true); return ld == rd; } else if (left->is<IR::TypeNameExpression>()) { auto ld = refMap->getDeclaration(left->to<IR::TypeNameExpression>()->typeName->path, true); auto rd = refMap->getDeclaration(right->to<IR::TypeNameExpression>()->typeName->path, true); return ld == rd; } else if (left->is<IR::ListExpression>()) { auto ll = left->to<IR::ListExpression>(); auto rl = right->to<IR::ListExpression>(); return sameExpressions(&ll->components, &rl->components); } else if (left->is<IR::MethodCallExpression>()) { auto lm = left->to<IR::MethodCallExpression>(); auto rm = right->to<IR::MethodCallExpression>(); if (!sameExpression(lm->method, rm->method)) return false; if (lm->typeArguments->size() != rm->typeArguments->size()) return false; for (unsigned i = 0; i < lm->typeArguments->size(); i++) if (!sameType(lm->typeArguments->at(i), rm->typeArguments->at(i))) return false; return sameExpressions(lm->arguments, rm->arguments); } else if (left->is<IR::ConstructorCallExpression>()) { auto lc = left->to<IR::ConstructorCallExpression>(); auto rc = right->to<IR::ConstructorCallExpression>(); if (!sameType(lc->constructedType, rc->constructedType)) return false; return sameExpressions(lc->arguments, rc->arguments); } else { BUG("%1%: Unexpected expression", left); } } } // namespace P4
42.849057
100
0.60502
DTharun
a191d05341c14819ccb1b24f8319b73074ed6fba
322
hpp
C++
source/luaquicks.hpp
Pika-Software/gmsv_network
037ddbaf5b9c29e9e2bbfdc0db45a51dfbe03733
[ "MIT" ]
2
2021-12-25T17:59:38.000Z
2021-12-25T17:59:45.000Z
source/luaquicks.hpp
Pika-Software/gmsv_network
037ddbaf5b9c29e9e2bbfdc0db45a51dfbe03733
[ "MIT" ]
1
2021-12-26T13:51:58.000Z
2021-12-26T19:03:02.000Z
source/luaquicks.hpp
Pika-Software/gmsv_network
037ddbaf5b9c29e9e2bbfdc0db45a51dfbe03733
[ "MIT" ]
null
null
null
#ifndef GMNETWORK_LUAQUICKS_H #define GMNETWORK_LUAQUICKS_H #ifdef SYSTEM_WINDOWS #pragma once #endif #include "main.hpp" namespace GmNetwork::LuaQuicks { bool PushHookCall(GarrysMod::Lua::ILuaInterface* LUA, const char* eventName); bool RunHookCall(GarrysMod::Lua::ILuaInterface* LUA, int argC, int retC); } #endif
21.466667
78
0.785714
Pika-Software
a19800bcc0d8a25160214e357dda16db5c68465f
5,429
cpp
C++
src/LCDController.cpp
danielmcmillan/CharLCD
c367b1fcf03306c1d11cd9b24785518ae019b762
[ "BSD-2-Clause" ]
null
null
null
src/LCDController.cpp
danielmcmillan/CharLCD
c367b1fcf03306c1d11cd9b24785518ae019b762
[ "BSD-2-Clause" ]
null
null
null
src/LCDController.cpp
danielmcmillan/CharLCD
c367b1fcf03306c1d11cd9b24785518ae019b762
[ "BSD-2-Clause" ]
null
null
null
#include "LCDController.h" #include <algorithm> #include <iterator> #include <cassert> #include <lcd.h> namespace CharLCD { const LCDController::BufferChar LCDController::emptyChar = {false, {' '}}; LCDController::LCDController(LCDBackend lcd) : lcd(std::move(lcd)), numRows(lcd.getRows()), numCols(lcd.getCols()) { state = { true, 1024, -1, -1, {}, {} }; state.displayChars.resize(numRows * numCols, ' '); displayBuffer.resize(numRows * numCols, emptyChar); this->lcd.power(true); this->lcd.clear(); this->lcd.backlightPower(true); } void LCDController::power(bool on) { if (state.power != on) { state.power = on; lcd.power(on); lcd.backlightBrightness(on ? state.brightness : 0); } } void LCDController::brightness(int brightness) { state.brightness = brightness; if (state.power) { lcd.backlightBrightness(brightness); } } void LCDController::drawString(const std::string &string, Location location, TextAlignment alignment) { if (location.row < 0 || location.row >= numRows) { return; } // Get range of columns to draw the string within int startCol = 0; switch (alignment) { case TextAlignment::left: startCol = location.col; break; case TextAlignment::right: startCol = location.col - (string.size() - 1); break; case TextAlignment::center: startCol = location.col - ((string.size() - 1) / 2); break; } // Write each character of the string to display buffer for (int i = 0; i < string.size(); ++i) { int col = i + startCol; // Check column is on the screen if (col < 0 || col >= numCols) { continue; } int index = indexForLocation({location.row, col}); displayBuffer[index] = {false, string[i]}; } } void LCDController::drawSymbol(const Symbol &symbol, Location location) { BufferChar bc = {true}; bc.symbol = symbol; displayBuffer[indexForLocation(location)] = bc; } void LCDController::clear() { std::fill(displayBuffer.begin(), displayBuffer.end(), emptyChar); } void LCDController::update() { // New screen character data std::vector<uint8_t> displayChars(displayBuffer.size()); std::vector<Symbol> customChars; for (int i = 0; i < displayBuffer.size(); ++i) { const BufferChar &bufferChar = displayBuffer[i]; if (bufferChar.custom) { // For symbol, need to reference a custom character std::vector<Symbol>::iterator it = std::find(customChars.begin(), customChars.end(), bufferChar.symbol); if (it != customChars.end()) { // Symbol already exists in customChars displayChars[i] = std::distance(customChars.begin(), it); } else if (customChars.size() < 8) { // Add new symbol displayChars[i] = customChars.size(); customChars.push_back(bufferChar.symbol); } else { // No room for the symbol displayChars[i] = ' '; } } else { // Store normal characters directly displayChars[i] = bufferChar.rawChar; } } writeToDisplay(displayChars, customChars); } unsigned LCDController::indexForLocation(Location location) { return location.row * numCols + location.col; } void LCDController::writeToDisplay(const std::vector<uint8_t> &displayChars, const std::vector<Symbol> &customChars) { assert(customChars.size() <= 8); // Write the custom characters for (int i = 0; i < customChars.size(); ++i) { if (customChars[i] != state.customChars[i]) { lcd.defineChar(i, customChars[i]); state.customChars[i] = customChars[i]; } } // Write the screen contents for (int row = 0; row < numRows; ++row) { for (int col = 0; col < numCols; ++col) { int index = indexForLocation({row, col}); // Check whether an update is needed at this location if (displayChars[index] != state.displayChars[index]) { // Check whether the cursor needs to be moved if (state.cursorCol != col || state.cursorRow != row) { lcd.moveCursor(row, col); } lcd.writeChar(displayChars[index]); // Cursor moves to the right after writing state.cursorCol = col + 1; state.cursorRow = row; } } } state.displayChars = displayChars; } }
30.846591
120
0.500829
danielmcmillan
a199aca4f640c384880747da1b343f44f12d37ac
710
hpp
C++
modules/control/include/toffy/web/sensor2dGroupController.hpp
voxel-dot-at/toffy
e9f14b186cf57225ad9eae99f227f894f0e5f940
[ "Apache-2.0" ]
null
null
null
modules/control/include/toffy/web/sensor2dGroupController.hpp
voxel-dot-at/toffy
e9f14b186cf57225ad9eae99f227f894f0e5f940
[ "Apache-2.0" ]
null
null
null
modules/control/include/toffy/web/sensor2dGroupController.hpp
voxel-dot-at/toffy
e9f14b186cf57225ad9eae99f227f894f0e5f940
[ "Apache-2.0" ]
null
null
null
#pragma once #include <toffy/web/filterController.hpp> #include <toffy/web/requestAction.hpp> namespace toffy { namespace control { /** * @brief Extended controller to handle multiples sensor2d filter at the same time * @ingroup Control * * Apply the Action on all 2d filters declared in the filterBanks */ class Sensor2dGroupController : public FilterController { std::vector<toffy::Filter *> _filterList; public: Sensor2dGroupController() {} Sensor2dGroupController(std::vector<toffy::Filter *> vec) : _filterList(vec) {} virtual ~Sensor2dGroupController() {} virtual bool doAction(Action &action, std::string &log); private: }; } // namespace controller } // namespace toffy
23.666667
83
0.733803
voxel-dot-at
a19bc512eaa8cc87ff46dc61866b9755863c94c2
812
cpp
C++
codeforces/C - NN and the Optical Illusion/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/C - NN and the Optical Illusion/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/C - NN and the Optical Illusion/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Jan/13/2019 21:08 * solution_verdict: Accepted language: GNU C++14 * run_time: 31 ms memory_used: 0 KB * problem: https://codeforces.com/contest/1100/problem/C ****************************************************************************************/ #include<bits/stdc++.h> using namespace std; int t,tc; double n,R,r; const double pi=acos(-1.0); int main() { cin>>n>>R; double ang=pi/n; r=(R*sin(ang))/(1-sin(ang)); cout<<setprecision(12)<<fixed<<r<<endl; return 0; }
42.736842
111
0.348522
kzvd4729
a19be4ff220efe907f6f0d9edce3293d50cbede5
26,684
cpp
C++
Code/Engine/DebugGui/DebugGuiHelper.cpp
WarzesProject/Micro3DRPG
36604d51d5dd640836cad77995abbfecfe4bdccc
[ "MIT" ]
3
2020-05-12T04:36:38.000Z
2021-04-04T07:21:44.000Z
Code/Engine/DebugGui/DebugGuiHelper.cpp
WarzesProject/Micro3DRPG
36604d51d5dd640836cad77995abbfecfe4bdccc
[ "MIT" ]
null
null
null
Code/Engine/DebugGui/DebugGuiHelper.cpp
WarzesProject/Micro3DRPG
36604d51d5dd640836cad77995abbfecfe4bdccc
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "DebugGui/DebugGuiHelper.h" #include "Core/Math/Transform.h" #include "Core/Math/EulerAngles.h" #include "Resource/Scene/SceneNode.h" #include "Resource/Scene/SceneResource.h" #include "Resource/Scene/Item/Camera/CameraSceneItem.h" #include "Resource/Scene/Item/Mesh/SkeletonMeshSceneItem.h" #include "Resource/Skeleton/SkeletonResourceManager.h" #include "Resource/Skeleton/SkeletonResource.h" #include "Resource/CompositorWorkspace/CompositorWorkspaceInstance.h" #include "IRendererRuntime.h" #include <ImGuizmo/ImGuizmo.h> #include <imgui/imgui.h> // Disable warnings in external headers, we can't fix them PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(4201) // warning C4201: nonstandard extension used: nameless struct/union PRAGMA_WARNING_DISABLE_MSVC(4464) // warning C4464: relative include path contains '..' #include <glm/gtc/type_ptr.hpp> PRAGMA_WARNING_POP // Disable warnings in external headers, we can't fix them PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(4365) // warning C4365: 'argument': conversion from 'long' to 'unsigned int', signed/unsigned mismatch PRAGMA_WARNING_DISABLE_MSVC(5026) // warning C5026: 'std::_Generic_error_category': move constructor was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(5027) // warning C5027: 'std::_Generic_error_category': move assignment operator was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(4571) // warning C4571: Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught PRAGMA_WARNING_DISABLE_MSVC(4625) // warning C4625: 'std::codecvt_base': copy constructor was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(4626) // warning C4626: 'std::codecvt<char16_t,char,_Mbstatet>': assignment operator was implicitly defined as deleted PRAGMA_WARNING_DISABLE_MSVC(4668) // warning C4668: '_M_HYBRID_X86_ARM64' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' PRAGMA_WARNING_DISABLE_MSVC(4774) // warning C4774: 'sprintf_s' : format string expected in argument 3 is not a string literal #include <string> #include <unordered_set> PRAGMA_WARNING_POP //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] namespace { namespace detail { //[-------------------------------------------------------] //[ Global definitions ] //[-------------------------------------------------------] static const ImVec4 GREEN_COLOR(0.0f, 1.0f, 0.0f, 1.0f); static const ImVec4 YELLOW_COLOR(1.0f, 1.0f, 0.0f, 1.0f); static const ImVec4 RED_COLOR(1.0f, 0.0f, 0.0f, 1.0f); //[-------------------------------------------------------] //[ Global functions ] //[-------------------------------------------------------] [[nodiscard]] bool objectSpaceToScreenSpacePosition(const glm::vec3& objectSpacePosition, const glm::mat4& objectSpaceToClipSpaceMatrix, ImVec2& screenSpacePosition) { glm::vec4 position = objectSpaceToClipSpaceMatrix * glm::vec4(objectSpacePosition, 1.0f); const bool inFront = (position.z >= 0.0f); position *= 0.5f / position.w; position += glm::vec4(0.5f, 0.5f, 0.0f, 0.0f); position.y = 1.0f - position.y; const ImGuiIO& imGuiIO = ImGui::GetIO(); position.x *= imGuiIO.DisplaySize.x; position.y *= imGuiIO.DisplaySize.y; screenSpacePosition = ImVec2(position.x, position.y); // In front of camera? return inFront; } void draw3DLine(const glm::mat4& objectSpaceToClipSpaceMatrix, const glm::vec3& objectSpaceStartPosition, const glm::vec3& objectSpaceEndPosition, const ImColor& color, float thickness, ImDrawList& imDrawList) { // TODO(co) Add near plane clip ImVec2 screenSpaceStartPosition; ImVec2 screenSpaceEndPosition; const bool screenSpaceStartPositionVisible = objectSpaceToScreenSpacePosition(objectSpaceStartPosition, objectSpaceToClipSpaceMatrix, screenSpaceStartPosition); const bool screenSpaceEndPositionVisible = objectSpaceToScreenSpacePosition(objectSpaceEndPosition, objectSpaceToClipSpaceMatrix, screenSpaceEndPosition); if (screenSpaceStartPositionVisible || screenSpaceEndPositionVisible) { imDrawList.AddLine(screenSpaceStartPosition, screenSpaceEndPosition, color, thickness); } } // Basing on https://stackoverflow.com/a/33390058 const char* stringFormatCommas(uint64_t number, char* output) { char* outputBackup = output; // Backup pointer for return char buffer[100]; snprintf(buffer, 100, "%I64d", number); size_t c = 2 - (strlen(buffer) % 3); for (const char* p = buffer; 0 != *p; ++p) { *output++ = *p; if (1 == c) { *output++ = '.'; } c = (c + 1) % 3; } *--output = 0; return outputBackup; } //[-------------------------------------------------------] //[ Anonymous detail namespace ] //[-------------------------------------------------------] } // detail } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace RendererRuntime { //[-------------------------------------------------------] //[ Private static data ] //[-------------------------------------------------------] uint32_t DebugGuiHelper::mDrawTextCounter = 0; //[-------------------------------------------------------] //[ Public static methods ] //[-------------------------------------------------------] void DebugGuiHelper::drawText(const char* text, float x, float y, bool drawBackground) { if (!drawBackground) { ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(1.0f, 0.0f, 0.0f, 0.0f)); } ImGui::Begin(("RendererRuntime::DebugGuiManager::drawText_" + std::to_string(mDrawTextCounter)).c_str(), nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoFocusOnAppearing); ImGui::Text("%s", text); ImGui::SetWindowPos(ImVec2(x, y)); ImGui::End(); if (!drawBackground) { ImGui::PopStyleColor(); } ++mDrawTextCounter; } void DebugGuiHelper::drawGizmo(const CameraSceneItem& cameraSceneItem, GizmoSettings& gizmoSettings, Transform& transform) { // Setup ImGuizmo if (ImGui::RadioButton("Translate", gizmoSettings.currentGizmoOperation == GizmoOperation::TRANSLATE)) { gizmoSettings.currentGizmoOperation = GizmoOperation::TRANSLATE; } ImGui::SameLine(); if (ImGui::RadioButton("Rotate", gizmoSettings.currentGizmoOperation == GizmoOperation::ROTATE)) { gizmoSettings.currentGizmoOperation = GizmoOperation::ROTATE; } ImGui::SameLine(); if (ImGui::RadioButton("Scale", gizmoSettings.currentGizmoOperation == GizmoOperation::SCALE)) { gizmoSettings.currentGizmoOperation = GizmoOperation::SCALE; } { // Show and edit rotation quaternion using Euler angles in degree glm::vec3 eulerAngles = glm::degrees(EulerAngles::matrixToEuler(glm::mat3_cast(transform.rotation))); { // TODO(co) We're using a 64 bit position, ImGui can only process 32 bit floating point values glm::vec3 position = transform.position; ImGui::InputFloat3("Tr", glm::value_ptr(position), "%.3f"); transform.position = position; } ImGui::InputFloat3("Rt", glm::value_ptr(eulerAngles), "%.3f"); ImGui::InputFloat3("Sc", glm::value_ptr(transform.scale), "%.3f"); transform.rotation = EulerAngles::eulerToQuaternion(glm::radians(eulerAngles)); } if (gizmoSettings.currentGizmoOperation != GizmoOperation::SCALE) { if (ImGui::RadioButton("Local", gizmoSettings.currentGizmoMode == GizmoMode::LOCAL)) { gizmoSettings.currentGizmoMode = GizmoMode::LOCAL; } ImGui::SameLine(); if (ImGui::RadioButton("World", gizmoSettings.currentGizmoMode == GizmoMode::WORLD)) { gizmoSettings.currentGizmoMode = GizmoMode::WORLD; } } ImGui::Checkbox("", &gizmoSettings.useSnap); ImGui::SameLine(); switch (gizmoSettings.currentGizmoOperation) { case GizmoOperation::TRANSLATE: ImGui::InputFloat3("Snap", &gizmoSettings.snap[0]); break; case GizmoOperation::ROTATE: ImGui::InputFloat("Angle Snap", &gizmoSettings.snap[0]); break; case GizmoOperation::SCALE: ImGui::InputFloat("Scale Snap", &gizmoSettings.snap[0]); break; } { // Let ImGuizmo do its thing glm::mat4 matrix; transform.position -= cameraSceneItem.getWorldSpaceCameraPosition(); // Camera relative rendering transform.getAsMatrix(matrix); ImGuizmo::OPERATION operation = static_cast<ImGuizmo::OPERATION>(gizmoSettings.currentGizmoOperation); ImGuizmo::MODE mode = (operation == ImGuizmo::SCALE) ? ImGuizmo::LOCAL : static_cast<ImGuizmo::MODE>(gizmoSettings.currentGizmoMode); const ImGuiIO& imGuiIO = ImGui::GetIO(); ImGuizmo::SetRect(0, 0, imGuiIO.DisplaySize.x, imGuiIO.DisplaySize.y); ImGuizmo::Manipulate(glm::value_ptr(cameraSceneItem.getCameraRelativeWorldSpaceToViewSpaceMatrix()), glm::value_ptr(cameraSceneItem.getViewSpaceToClipSpaceMatrix(static_cast<float>(imGuiIO.DisplaySize.x) / imGuiIO.DisplaySize.y)), operation, mode, glm::value_ptr(matrix), nullptr, gizmoSettings.useSnap ? &gizmoSettings.snap[0] : nullptr); transform = Transform(matrix); transform.position += cameraSceneItem.getWorldSpaceCameraPosition(); // Camera relative rendering } } void DebugGuiHelper::drawSkeleton(const CameraSceneItem& cameraSceneItem, const SkeletonMeshSceneItem& skeletonMeshSceneItem) { // Get skeleton resource instance const SkeletonResource* skeletonResource = skeletonMeshSceneItem.getSceneResource().getRendererRuntime().getSkeletonResourceManager().tryGetById(skeletonMeshSceneItem.getSkeletonResourceId()); if (nullptr != skeletonResource) { // Get transform data glm::mat4 objectSpaceToWorldSpace; { Transform transform = skeletonMeshSceneItem.getParentSceneNodeSafe().getGlobalTransform(); transform.position -= cameraSceneItem.getWorldSpaceCameraPosition(); // Camera relative rendering transform.getAsMatrix(objectSpaceToWorldSpace); } const ImGuiIO& imGuiIO = ImGui::GetIO(); const glm::mat4 objectSpaceToClipSpaceMatrix = cameraSceneItem.getViewSpaceToClipSpaceMatrix(static_cast<float>(imGuiIO.DisplaySize.x) / imGuiIO.DisplaySize.y) * cameraSceneItem.getCameraRelativeWorldSpaceToViewSpaceMatrix() * objectSpaceToWorldSpace; // Get skeleton data const uint8_t numberOfBones = skeletonResource->getNumberOfBones(); const uint8_t* boneParentIndices = skeletonResource->getBoneParentIndices(); const glm::mat4* globalBoneMatrices = skeletonResource->getGlobalBoneMatrices(); // Draw skeleton hierarchy as lines // -> Update ImGui style to not have a visible round border ImGui::PushStyleColor(ImGuiCol_WindowBg, 0); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ImGui::SetNextWindowSize(ImGui::GetIO().DisplaySize, ImGuiCond_FirstUseEver); if (ImGui::Begin("skeleton", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus)) { static const ImColor WHITE_COLOR(255, 255, 255); ImDrawList* imDrawList = ImGui::GetWindowDrawList(); ImVec2 parentBonePosition; ImVec2 bonePosition; for (uint8_t boneIndex = 1; boneIndex < numberOfBones; ++boneIndex) { ::detail::draw3DLine(objectSpaceToClipSpaceMatrix, globalBoneMatrices[boneParentIndices[boneIndex]][3], globalBoneMatrices[boneIndex][3], WHITE_COLOR, 6.0f, *imDrawList); } } ImGui::End(); ImGui::PopStyleVar(); ImGui::PopStyleColor(); } } void DebugGuiHelper::drawGrid(const CameraSceneItem& cameraSceneItem, float cellSize, float yPosition) { ImGui::SetNextWindowSize(ImGui::GetIO().DisplaySize, ImGuiCond_FirstUseEver); if (ImGui::Begin("grid", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus)) { const int32_t NUMBER_OF_LINES_PER_DIRECTION = 10; static const ImColor GREY_COLOR(0.5f, 0.5f, 0.5f, 1.0f); ImDrawList* imDrawList = ImGui::GetWindowDrawList(); const ImGuiIO& imGuiIO = ImGui::GetIO(); const glm::mat4 objectSpaceToClipSpaceMatrix = cameraSceneItem.getViewSpaceToClipSpaceMatrix(static_cast<float>(imGuiIO.DisplaySize.x) / imGuiIO.DisplaySize.y) * cameraSceneItem.getCameraRelativeWorldSpaceToViewSpaceMatrix(); // Keep the grid fixed at the 64 bit world space position of the camera and take camera relative rendering into account const glm::dvec3& cameraPosition = cameraSceneItem.getParentSceneNodeSafe().getTransform().position; const glm::dvec3& worldSpaceCameraPosition = cameraSceneItem.getWorldSpaceCameraPosition(); const glm::vec3 centerPosition(Math::makeMultipleOf(cameraPosition.x, cellSize) - worldSpaceCameraPosition.x, yPosition - worldSpaceCameraPosition.y, Math::makeMultipleOf(cameraPosition.z, cellSize) - worldSpaceCameraPosition.z); // Lines along z axis for (int32_t z = -NUMBER_OF_LINES_PER_DIRECTION; z <= NUMBER_OF_LINES_PER_DIRECTION; ++z) { const float thickness = (0 == z || NUMBER_OF_LINES_PER_DIRECTION == std::abs(z)) ? 4.0f : 1.0f; ::detail::draw3DLine(objectSpaceToClipSpaceMatrix, centerPosition + glm::vec3(-NUMBER_OF_LINES_PER_DIRECTION * cellSize, 0.0f, z * cellSize), centerPosition + glm::vec3(NUMBER_OF_LINES_PER_DIRECTION * cellSize, 0.0f, z * cellSize), GREY_COLOR, thickness, *imDrawList); } // Lines along x axis for (int32_t x = -NUMBER_OF_LINES_PER_DIRECTION; x <= NUMBER_OF_LINES_PER_DIRECTION; ++x) { const float thickness = (0 == x || NUMBER_OF_LINES_PER_DIRECTION == std::abs(x)) ? 4.0f : 1.0f; ::detail::draw3DLine(objectSpaceToClipSpaceMatrix, centerPosition + glm::vec3(x * cellSize, 0.0f, -NUMBER_OF_LINES_PER_DIRECTION * cellSize), centerPosition + glm::vec3(x * cellSize, 0.0f, NUMBER_OF_LINES_PER_DIRECTION * cellSize), GREY_COLOR, thickness, *imDrawList); } } ImGui::End(); } //[-------------------------------------------------------] //[ Private static methods ] //[-------------------------------------------------------] void DebugGuiHelper::drawMetricsWindow(bool& open, CompositorWorkspaceInstance* compositorWorkspaceInstance) { if (ImGui::Begin("Metrics", &open)) { // Frames per second (FPS) const float framesPerSecond = ImGui::GetIO().Framerate; ImVec4 color = ::detail::GREEN_COLOR; if (framesPerSecond < 60.0f) { color = ::detail::RED_COLOR; } else if (framesPerSecond < 90.0f) { // HTC Vive refresh rate: 90 Hz (11.11 ms per frame), everything below isn't OK color = ::detail::YELLOW_COLOR; } ImGui::PushStyleColor(ImGuiCol_Text, color); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / framesPerSecond, framesPerSecond); ImGui::PopStyleColor(); // Optional compositor workspace instance metrics if (nullptr != compositorWorkspaceInstance) { char temporary[128] = {}; // Please note that one renderable manager can be inside multiple render queue index ranges // -> Since this metrics debugging code isn't performance critical we're using already available data to extract the // information we want to display instead of letting the core system gather additional data it doesn't need to work size_t numberOfRenderables = 0; std::unordered_set<const RenderableManager*> processedRenderableManager; for (const CompositorWorkspaceInstance::RenderQueueIndexRange& renderQueueIndexRanges : compositorWorkspaceInstance->getRenderQueueIndexRanges()) { for (const RenderableManager* renderableManager : renderQueueIndexRanges.renderableManagers) { if (processedRenderableManager.find(renderableManager) == processedRenderableManager.cend()) { processedRenderableManager.insert(renderableManager); numberOfRenderables += renderableManager->getRenderables().size(); } } } ImGui::Text("Rendered renderable managers %s", ::detail::stringFormatCommas(static_cast<uint64_t>(processedRenderableManager.size()), temporary)); ImGui::Text("Rendered renderables %s", ::detail::stringFormatCommas(static_cast<uint64_t>(numberOfRenderables), temporary)); // Command buffer metrics const Renderer::CommandBuffer& commandBuffer = compositorWorkspaceInstance->getCommandBuffer(); #ifdef RENDERER_STATISTICS const uint32_t numberOfCommands = commandBuffer.getNumberOfCommands(); #else uint32_t numberOfCommands = 0; { const uint8_t* commandPacketBuffer = commandBuffer.getCommandPacketBuffer(); Renderer::ConstCommandPacket constCommandPacket = commandPacketBuffer; while (nullptr != constCommandPacket) { // Count command packet ++numberOfCommands; { // Next command const uint32_t nextCommandPacketByteIndex = Renderer::CommandPacketHelper::getNextCommandPacketByteIndex(constCommandPacket); constCommandPacket = (~0u != nextCommandPacketByteIndex) ? &commandPacketBuffer[nextCommandPacketByteIndex] : nullptr; } } } #endif if (ImGui::TreeNode("EmittedCommands", "Emitted commands: %s", ::detail::stringFormatCommas(numberOfCommands, temporary))) { // Loop through all commands and count them uint32_t numberOfCommandFunctions[Renderer::CommandDispatchFunctionIndex::NumberOfFunctions] = {}; const uint8_t* commandPacketBuffer = commandBuffer.getCommandPacketBuffer(); Renderer::ConstCommandPacket constCommandPacket = commandPacketBuffer; while (nullptr != constCommandPacket) { // Count command packet ++numberOfCommandFunctions[Renderer::CommandPacketHelper::loadCommandDispatchFunctionIndex(constCommandPacket)]; { // Next command const uint32_t nextCommandPacketByteIndex = Renderer::CommandPacketHelper::getNextCommandPacketByteIndex(constCommandPacket); constCommandPacket = (~0u != nextCommandPacketByteIndex) ? &commandPacketBuffer[nextCommandPacketByteIndex] : nullptr; } } // Print the number of emitted command functions static constexpr const char* commandFunction[Renderer::CommandDispatchFunctionIndex::NumberOfFunctions] = { // Command buffer "ExecuteCommandBuffer", // Graphics "SetGraphicsRootSignature", "SetGraphicsPipelineState", "SetGraphicsResourceGroup", "SetGraphicsVertexArray", "SetGraphicsViewports", "SetGraphicsScissorRectangles", "SetGraphicsRenderTarget", "ClearGraphics", "DrawGraphics", "DrawIndexedGraphics", // Compute "SetComputeRootSignature", "SetComputePipelineState", "SetComputeResourceGroup", "DispatchCompute", // Resource "SetTextureMinimumMaximumMipmapIndex", "ResolveMultisampleFramebuffer", "CopyResource", "GenerateMipmaps", // Query "ResetQueryPool", "BeginQuery", "EndQuery", "WriteTimestampQuery", // Debug "SetDebugMarker", "BeginDebugEvent", "EndDebugEvent" }; for (uint32_t i = 0; i < Renderer::CommandDispatchFunctionIndex::NumberOfFunctions; ++i) { ImGui::Text("%s: %s", commandFunction[i], ::detail::stringFormatCommas(numberOfCommandFunctions[i], temporary)); } ImGui::TreePop(); } // Renderer and pipeline statistics #ifdef RENDERER_STATISTICS { // Renderer statistics const Renderer::Statistics& statistics = static_cast<const Renderer::IRenderer&>(compositorWorkspaceInstance->getRendererRuntime().getRenderer()).getStatistics(); if (ImGui::TreeNode("RendererResources", "Renderer resources: %s", ::detail::stringFormatCommas(statistics.getNumberOfCurrentResources(), temporary))) { ImGui::Text("Root signatures: %s", ::detail::stringFormatCommas(statistics.currentNumberOfRootSignatures.load(), temporary)); ImGui::Text("Resource groups: %s", ::detail::stringFormatCommas(statistics.currentNumberOfResourceGroups.load(), temporary)); ImGui::Text("Graphics programs: %s", ::detail::stringFormatCommas(statistics.currentNumberOfGraphicsPrograms.load(), temporary)); ImGui::Text("Vertex arrays: %s", ::detail::stringFormatCommas(statistics.currentNumberOfVertexArrays.load(), temporary)); ImGui::Text("Render passes: %s", ::detail::stringFormatCommas(statistics.currentNumberOfRenderPasses.load(), temporary)); ImGui::Text("Query pools: %s", ::detail::stringFormatCommas(statistics.currentNumberOfQueryPools.load(), temporary)); ImGui::Text("Swap chains: %s", ::detail::stringFormatCommas(statistics.currentNumberOfSwapChains.load(), temporary)); ImGui::Text("Framebuffers: %s", ::detail::stringFormatCommas(statistics.currentNumberOfFramebuffers.load(), temporary)); ImGui::Text("Index buffers: %s", ::detail::stringFormatCommas(statistics.currentNumberOfIndexBuffers.load(), temporary)); ImGui::Text("Vertex buffers: %s", ::detail::stringFormatCommas(statistics.currentNumberOfVertexBuffers.load(), temporary)); ImGui::Text("Texture buffers: %s", ::detail::stringFormatCommas(statistics.currentNumberOfTextureBuffers.load(), temporary)); ImGui::Text("Structured buffers: %s", ::detail::stringFormatCommas(statistics.currentNumberOfStructuredBuffers.load(), temporary)); ImGui::Text("Indirect buffers: %s", ::detail::stringFormatCommas(statistics.currentNumberOfIndirectBuffers.load(), temporary)); ImGui::Text("Uniform buffers: %s", ::detail::stringFormatCommas(statistics.currentNumberOfUniformBuffers.load(), temporary)); ImGui::Text("1D textures: %s", ::detail::stringFormatCommas(statistics.currentNumberOfTexture1Ds.load(), temporary)); ImGui::Text("1D texture arrays: %s", ::detail::stringFormatCommas(statistics.currentNumberOfTexture1DArrays.load(), temporary)); ImGui::Text("2D textures: %s", ::detail::stringFormatCommas(statistics.currentNumberOfTexture2Ds.load(), temporary)); ImGui::Text("2D texture arrays: %s", ::detail::stringFormatCommas(statistics.currentNumberOfTexture2DArrays.load(), temporary)); ImGui::Text("3D textures: %s", ::detail::stringFormatCommas(statistics.currentNumberOfTexture3Ds.load(), temporary)); ImGui::Text("Cubes textures: %s", ::detail::stringFormatCommas(statistics.currentNumberOfTextureCubes.load(), temporary)); ImGui::Text("Graphics pipeline states: %s", ::detail::stringFormatCommas(statistics.currentNumberOfGraphicsPipelineStates.load(), temporary)); ImGui::Text("Compute pipeline states: %s", ::detail::stringFormatCommas(statistics.currentNumberOfComputePipelineStates.load(), temporary)); ImGui::Text("Sampler states: %s", ::detail::stringFormatCommas(statistics.currentNumberOfSamplerStates.load(), temporary)); ImGui::Text("Vertex shaders: %s", ::detail::stringFormatCommas(statistics.currentNumberOfVertexShaders.load(), temporary)); ImGui::Text("Tessellation control shaders: %s", ::detail::stringFormatCommas(statistics.currentNumberOfTessellationControlShaders.load(), temporary)); ImGui::Text("Tessellation evaluation shaders: %s", ::detail::stringFormatCommas(statistics.currentNumberOfTessellationEvaluationShaders.load(), temporary)); ImGui::Text("Geometry shaders: %s", ::detail::stringFormatCommas(statistics.currentNumberOfGeometryShaders.load(), temporary)); ImGui::Text("Fragment shaders: %s", ::detail::stringFormatCommas(statistics.currentNumberOfFragmentShaders.load(), temporary)); ImGui::Text("Compute shaders: %s", ::detail::stringFormatCommas(statistics.currentNumberOfComputeShaders.load(), temporary)); ImGui::TreePop(); } } // Pipeline statistics if (ImGui::TreeNode("PipelineStatistics", "Pipeline statistics")) { const Renderer::PipelineStatisticsQueryResult& pipelineStatisticsQueryResult = compositorWorkspaceInstance->getPipelineStatisticsQueryResult(); ImGui::Text("Input assembler vertices: %s", ::detail::stringFormatCommas(pipelineStatisticsQueryResult.numberOfInputAssemblerVertices, temporary)); ImGui::Text("Input assembler primitives: %s", ::detail::stringFormatCommas(pipelineStatisticsQueryResult.numberOfInputAssemblerPrimitives, temporary)); ImGui::Text("Vertex shader invocations: %s", ::detail::stringFormatCommas(pipelineStatisticsQueryResult.numberOfVertexShaderInvocations, temporary)); ImGui::Text("Geometry shader invocations: %s", ::detail::stringFormatCommas(pipelineStatisticsQueryResult.numberOfGeometryShaderInvocations, temporary)); ImGui::Text("Geometry shader output primitives: %s", ::detail::stringFormatCommas(pipelineStatisticsQueryResult.numberOfGeometryShaderOutputPrimitives, temporary)); ImGui::Text("Clipping input primitives: %s", ::detail::stringFormatCommas(pipelineStatisticsQueryResult.numberOfClippingInputPrimitives, temporary)); ImGui::Text("Clipping output primitives: %s", ::detail::stringFormatCommas(pipelineStatisticsQueryResult.numberOfClippingOutputPrimitives, temporary)); ImGui::Text("Fragment shader invocations: %s", ::detail::stringFormatCommas(pipelineStatisticsQueryResult.numberOfFragmentShaderInvocations, temporary)); ImGui::Text("Tessellation control shader invocations: %s", ::detail::stringFormatCommas(pipelineStatisticsQueryResult.numberOfTessellationControlShaderInvocations, temporary)); ImGui::Text("Tessellation evaluation shader invocations: %s", ::detail::stringFormatCommas(pipelineStatisticsQueryResult.numberOfTessellationEvaluationShaderInvocations, temporary)); ImGui::Text("Compute shader invocations: %s", ::detail::stringFormatCommas(pipelineStatisticsQueryResult.numberOfComputeShaderInvocations, temporary)); ImGui::TreePop(); } #endif } } ImGui::End(); } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // RendererRuntime
54.016194
434
0.713386
WarzesProject
a19cb47ca3651bc3e5c42cda2c7ac04a291ef15e
18,124
cpp
C++
src/webview/webpage.cpp
bubapl/QupZilla
3555a92eaf864fb00cce0c325c4afef582bd2024
[ "BSD-3-Clause" ]
1
2017-05-21T15:31:02.000Z
2017-05-21T15:31:02.000Z
src/webview/webpage.cpp
bubapl/QupZilla
3555a92eaf864fb00cce0c325c4afef582bd2024
[ "BSD-3-Clause" ]
null
null
null
src/webview/webpage.cpp
bubapl/QupZilla
3555a92eaf864fb00cce0c325c4afef582bd2024
[ "BSD-3-Clause" ]
null
null
null
/* ============================================================ * QupZilla - WebKit based browser * Copyright (C) 2010-2012 David Rosca <nowrep@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ============================================================ */ #include "webpage.h" #include "webview.h" #include "tabwidget.h" #include "qupzilla.h" #include "downloadmanager.h" #include "webpluginfactory.h" #include "mainapplication.h" #include "ui_jsconfirm.h" #include "ui_jsalert.h" #include "ui_jsprompt.h" #include "widget.h" #include "globalfunctions.h" #include "pluginproxy.h" #include "speeddial.h" QString WebPage::UserAgent = ""; QString WebPage::m_lastUploadLocation = QDir::homePath(); WebPage::WebPage(WebView* parent, QupZilla* mainClass) : QWebPage(parent) , p_QupZilla(mainClass) , m_view(parent) , m_speedDial(mApp->plugins()->speedDial()) , m_fileWatcher(0) , m_runningLoop(0) , m_blockAlerts(false) , m_secureStatus(false) // , m_isOpeningNextWindowAsNewTab(false) { setForwardUnsupportedContent(true); setPluginFactory(new WebPluginFactory(this)); history()->setMaximumItemCount(20); connect(this, SIGNAL(unsupportedContent(QNetworkReply*)), this, SLOT(handleUnsupportedContent(QNetworkReply*))); // connect(this, SIGNAL(loadStarted()), this, SLOT(loadingStarted())); connect(this, SIGNAL(loadProgress(int)), this, SLOT(progress(int))); connect(this, SIGNAL(loadFinished(bool)), this, SLOT(finished())); connect(m_view, SIGNAL(urlChanged(QUrl)), this, SLOT(urlChanged(QUrl))); connect(mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addJavaScriptObject())); connect(this, SIGNAL(printRequested(QWebFrame*)), this, SLOT(printFrame(QWebFrame*))); m_runningLoop = 0; } void WebPage::scheduleAdjustPage() { if (m_view->isLoading()) { m_adjustingScheduled = true; } else { mainFrame()->setZoomFactor(mainFrame()->zoomFactor() + 1); mainFrame()->setZoomFactor(mainFrame()->zoomFactor() - 1); } } void WebPage::urlChanged(const QUrl &url) { Q_UNUSED(url) m_adBlockedEntries.clear(); m_blockAlerts = false; } void WebPage::progress(int prog) { Q_UNUSED(prog) bool secStatus = sslCertificate().isValid(); if (secStatus != m_secureStatus) { m_secureStatus = secStatus; emit privacyChanged(sslCertificate().isValid()); } } void WebPage::finished() { progress(100); if (m_adjustingScheduled) { m_adjustingScheduled = false; mainFrame()->setZoomFactor(mainFrame()->zoomFactor() + 1); mainFrame()->setZoomFactor(mainFrame()->zoomFactor() - 1); } if (mainFrame()->url().scheme() == "file") { if (!m_fileWatcher) { m_fileWatcher = new QFileSystemWatcher(this); connect(m_fileWatcher, SIGNAL(fileChanged(QString)), this, SLOT(watchedFileChanged(QString))); } QString filePath = mainFrame()->url().toLocalFile(); if (!m_fileWatcher->files().contains(filePath)) { m_fileWatcher->addPath(filePath); } } else if (m_fileWatcher) { m_fileWatcher->removePaths(m_fileWatcher->files()); } QTimer::singleShot(100, this, SLOT(cleanBlockedObjects())); } void WebPage::watchedFileChanged(const QString &file) { if (mainFrame()->url().toLocalFile() == file) { triggerAction(QWebPage::Reload); } } void WebPage::printFrame(QWebFrame* frame) { p_QupZilla->printPage(frame); } //void WebPage::loadingStarted() //{ // m_adBlockedEntries.clear(); // m_blockAlerts = false; // m_SslCert.clear(); //} void WebPage::addJavaScriptObject() { if (mainFrame()->url().toString() != "qupzilla:speeddial") { return; } mainFrame()->addToJavaScriptWindowObject("speeddial", m_speedDial); m_speedDial->addWebFrame(mainFrame()); } void WebPage::handleUnsupportedContent(QNetworkReply* reply) { if (!reply) { return; } QUrl url = reply->url(); switch (reply->error()) { case QNetworkReply::NoError: if (reply->header(QNetworkRequest::ContentTypeHeader).isValid()) { DownloadManager* dManager = mApp->downManager(); dManager->handleUnsupportedContent(reply, this); return; } break; case QNetworkReply::ProtocolUnknownError: qDebug() << url << "ProtocolUnknowError"; QDesktopServices::openUrl(url); return; break; default: break; } qDebug() << "WebPage::UnsupportedContent error" << reply->errorString(); } void WebPage::setSSLCertificate(const QSslCertificate &cert) { // if (cert != m_SslCert) -- crashing on linux :-| m_SslCert = cert; } QSslCertificate WebPage::sslCertificate() { if (mainFrame()->url().scheme() == "https" && m_SslCert.subjectInfo(QSslCertificate::CommonName).remove("*").contains(QRegExp(mainFrame()->url().host()))) { return m_SslCert; } else { return QSslCertificate(); } } bool WebPage::acceptNavigationRequest(QWebFrame* frame, const QNetworkRequest &request, NavigationType type) { m_lastRequest = request; m_lastRequestType = type; QString scheme = request.url().scheme(); if (scheme == "mailto" || scheme == "ftp") { QDesktopServices::openUrl(request.url()); return false; } if (type == QWebPage::NavigationTypeFormResubmitted) { bool result = javaScriptConfirm(frame, tr("To show this page, QupZilla must resend request which do it again \n" "(like searching on making an shoping, which has been already done.)")); if (!result) { return false; } } bool accept = QWebPage::acceptNavigationRequest(frame, request, type); return accept; } void WebPage::populateNetworkRequest(QNetworkRequest &request) { WebPage* pagePointer = this; WebView* webViewPointer = m_view; QVariant variant = qVariantFromValue((void*) pagePointer); request.setAttribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100), variant); request.setAttribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 101), m_lastRequestType); variant = qVariantFromValue((void*) webViewPointer); request.setAttribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 102), variant); } QWebPage* WebPage::createWindow(QWebPage::WebWindowType type) { // if (m_isOpeningNextWindowAsNewTab) // return 0; // m_isOpeningNextWindowAsNewTab = false; // qDebug() << type; // QWebView* view = new QWebView(); // view->show(); // return view->page(); Q_UNUSED(type); int index = p_QupZilla->tabWidget()->addView(QUrl(), TabWidget::CleanSelectedPage); return p_QupZilla->weView(index)->page(); } void WebPage::addAdBlockRule(const QString &filter, const QUrl &url) { AdBlockedEntry entry; entry.rule = filter; entry.url = url; if (!m_adBlockedEntries.contains(entry)) { m_adBlockedEntries.append(entry); } } void WebPage::cleanBlockedObjects() { QStringList findingStrings; foreach(AdBlockedEntry entry, m_adBlockedEntries) { if (entry.url.toString().endsWith(".js")) { continue; } findingStrings.append(entry.url.toString()); QUrl mainFrameUrl = mainFrame()->url(); if (entry.url.scheme() == mainFrameUrl.scheme() && entry.url.host() == mainFrameUrl.host()) { //May be relative url QString relativeUrl = qz_makeRelativeUrl(mainFrameUrl, entry.url).toString(); findingStrings.append(relativeUrl); if (relativeUrl.startsWith("/")) { findingStrings.append(relativeUrl.right(relativeUrl.size() - 1)); } } } QWebElement docElement = mainFrame()->documentElement(); QWebElementCollection elements; foreach(QString s, findingStrings) elements.append(docElement.findAll("*[src=\"" + s + "\"]")); foreach(QWebElement element, elements) element.setAttribute("style", "display:none;"); } QString WebPage::userAgentForUrl(const QUrl &url) const { if (UserAgent.isEmpty()) { UserAgent = QWebPage::userAgentForUrl(url); #ifdef Q_WS_MAC #ifdef __i386__ || __x86_64__ UserAgent.replace("PPC Mac OS X", "Intel Mac OS X"); #endif #endif } return UserAgent; } bool WebPage::extension(Extension extension, const ExtensionOption* option, ExtensionReturn* output) { if (extension == ChooseMultipleFilesExtension) { return QWebPage::extension(extension, option, output); } const ErrorPageExtensionOption* exOption = static_cast<const QWebPage::ErrorPageExtensionOption*>(option); ErrorPageExtensionReturn* exReturn = static_cast<QWebPage::ErrorPageExtensionReturn*>(output); WebPage* erPage = qobject_cast<WebPage*>(exOption->frame->page()); QString errorString; if (exOption->domain == QWebPage::QtNetwork) { switch (exOption->error) { case QNetworkReply::ConnectionRefusedError: errorString = tr("Server refused the connection"); break; case QNetworkReply::RemoteHostClosedError: errorString = tr("Server closed the connection"); break; case QNetworkReply::HostNotFoundError: errorString = tr("Server not found"); break; case QNetworkReply::TimeoutError: errorString = tr("Connection timed out"); break; case QNetworkReply::SslHandshakeFailedError: errorString = tr("Untrusted connection"); break; case QNetworkReply::TemporaryNetworkFailureError: errorString = tr("Temporary network failure"); break; case QNetworkReply::ProxyConnectionRefusedError: errorString = tr("Proxy connection refused"); break; case QNetworkReply::ProxyNotFoundError: errorString = tr("Proxy host name not found"); break; case QNetworkReply::ProxyTimeoutError: errorString = tr("Proxy connection timed out"); break; case QNetworkReply::ProxyAuthenticationRequiredError: errorString = tr("Proxy authentication required"); break; case QNetworkReply::ContentNotFoundError: errorString = tr("Content not found"); break; case QNetworkReply::ContentAccessDenied: if (exOption->errorString.startsWith("AdBlockRule")) { if (exOption->frame != erPage->mainFrame()) { //Content in <iframe> QWebElement docElement = erPage->mainFrame()->documentElement(); QWebElementCollection elements; elements.append(docElement.findAll("iframe")); foreach(QWebElement element, elements) { QString src = element.attribute("src"); if (exOption->url.toString().contains(src)) { element.setAttribute("style", "display:none;"); } } return false; } else { //The whole page is blocked QString rule = exOption->errorString; rule.remove("AdBlockRule:"); QFile file(":/html/adblockPage.html"); file.open(QFile::ReadOnly); QString errString = file.readAll(); errString.replace("%TITLE%", tr("AdBlocked Content")); errString.replace("%IMAGE%", "qrc:html/adblock_big.png"); errString.replace("%FAVICON%", "qrc:html/adblock_big.png"); errString.replace("%RULE%", tr("Blocked by rule <i>%1</i>").arg(rule)); exReturn->baseUrl = exOption->url.toString(); exReturn->content = errString.toUtf8(); return true; } } errorString = tr("Content Access Denied"); break; default: qDebug() << "Content error: " << exOption->errorString; return false; } } else if (exOption->domain == QWebPage::Http) { errorString = tr("Error code %1").arg(exOption->error); } else if (exOption->domain == QWebPage::WebKit) { return false; // Downloads } QString loadedUrl = exOption->url.toString(); exReturn->baseUrl = loadedUrl; QFile file(":/html/errorPage.html"); file.open(QFile::ReadOnly); QString errString = file.readAll(); errString.replace("%TITLE%", tr("Failed loading page")); errString.replace("%IMAGE%", qz_pixmapToByteArray(MainApplication::style()->standardIcon(QStyle::SP_MessageBoxWarning).pixmap(45, 45))); errString.replace("%FAVICON%", qz_pixmapToByteArray(MainApplication::style()->standardIcon(QStyle::SP_MessageBoxWarning).pixmap(16, 16))); errString.replace("%BOX-BORDER%", "qrc:html/box-border.png"); errString.replace("%HEADING%", errorString); errString.replace("%HEADING2%", tr("QupZilla can't load page from %1.").arg(QUrl(loadedUrl).host())); errString.replace("%LI-1%", tr("Check the address for typing errors such as <b>ww.</b>example.com instead of <b>www.</b>example.com")); errString.replace("%LI-2%", tr("If you are unable to load any pages, check your computer's network connection.")); errString.replace("%LI-3%", tr("If your computer or network is protected by a firewall or proxy, make sure that QupZilla is permitted to access the Web.")); errString.replace("%TRY-AGAIN%", tr("Try Again")); exReturn->content = errString.toUtf8(); return true; } bool WebPage::javaScriptPrompt(QWebFrame* originatingFrame, const QString &msg, const QString &defaultValue, QString* result) { WebView* _view = qobject_cast<WebView*>(originatingFrame->page()->view()); ResizableFrame* widget = new ResizableFrame(_view->webTab()); widget->setObjectName("jsFrame"); Ui_jsPrompt* ui = new Ui_jsPrompt(); ui->setupUi(widget); ui->message->setText(msg); ui->lineEdit->setText(defaultValue); ui->lineEdit->setFocus(); widget->resize(originatingFrame->page()->viewportSize()); widget->show(); connect(_view, SIGNAL(viewportResized(QSize)), widget, SLOT(slotResize(QSize))); connect(ui->lineEdit, SIGNAL(returnPressed()), ui->buttonBox->button(QDialogButtonBox::Ok), SLOT(animateClick())); QEventLoop eLoop; m_runningLoop = &eLoop; connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton*)), &eLoop, SLOT(quit())); if (eLoop.exec() == 1) { return result; } m_runningLoop = 0; QString x = ui->lineEdit->text(); bool _result = ui->buttonBox->clickedButtonRole() == QDialogButtonBox::AcceptRole; *result = x; delete widget; _view->setFocus(); return _result; } bool WebPage::javaScriptConfirm(QWebFrame* originatingFrame, const QString &msg) { WebView* _view = qobject_cast<WebView*>(originatingFrame->page()->view()); ResizableFrame* widget = new ResizableFrame(_view->webTab()); widget->setObjectName("jsFrame"); Ui_jsConfirm* ui = new Ui_jsConfirm(); ui->setupUi(widget); ui->message->setText(msg); ui->buttonBox->button(QDialogButtonBox::Ok)->setFocus(); widget->resize(originatingFrame->page()->viewportSize()); widget->show(); connect(_view, SIGNAL(viewportResized(QSize)), widget, SLOT(slotResize(QSize))); QEventLoop eLoop; m_runningLoop = &eLoop; connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton*)), &eLoop, SLOT(quit())); if (eLoop.exec() == 1) { return false; } m_runningLoop = 0; bool result = ui->buttonBox->clickedButtonRole() == QDialogButtonBox::AcceptRole; delete widget; _view->setFocus(); return result; } void WebPage::javaScriptAlert(QWebFrame* originatingFrame, const QString &msg) { if (m_blockAlerts) { return; } WebView* _view = qobject_cast<WebView*>(originatingFrame->page()->view()); ResizableFrame* widget = new ResizableFrame(_view->webTab()); widget->setObjectName("jsFrame"); Ui_jsAlert* ui = new Ui_jsAlert(); ui->setupUi(widget); ui->message->setText(msg); ui->buttonBox->button(QDialogButtonBox::Ok)->setFocus(); widget->resize(originatingFrame->page()->viewportSize()); widget->show(); connect(_view, SIGNAL(viewportResized(QSize)), widget, SLOT(slotResize(QSize))); QEventLoop eLoop; m_runningLoop = &eLoop; connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton*)), &eLoop, SLOT(quit())); if (eLoop.exec() == 1) { return; } m_runningLoop = 0; m_blockAlerts = ui->preventAlerts->isChecked(); delete widget; _view->setFocus(); } QString WebPage::chooseFile(QWebFrame* originatingFrame, const QString &oldFile) { QString suggFileName; if (oldFile.isEmpty()) { suggFileName = m_lastUploadLocation; } else { suggFileName = oldFile; } QString fileName = QFileDialog::getOpenFileName(originatingFrame->page()->view(), tr("Choose file..."), suggFileName); if (!fileName.isEmpty()) { m_lastUploadLocation = fileName; } return fileName; } void WebPage::disconnectObjects() { disconnect(this); } WebPage::~WebPage() { if (m_runningLoop) { m_runningLoop->exit(1); } }
33.133455
160
0.640422
bubapl
a19f31700ba3ce48e8f7e139dc6fdf8a5d925b47
244
cpp
C++
control-flow/return.cpp
punithpatil/csci1300-recitation-notes
b6ad687e56bc58ff808e5786e7381d125089beeb
[ "MIT" ]
2
2019-04-11T16:41:42.000Z
2019-11-19T22:07:57.000Z
control-flow/return.cpp
punithpatil/csci1300-recitation-notes
b6ad687e56bc58ff808e5786e7381d125089beeb
[ "MIT" ]
null
null
null
control-flow/return.cpp
punithpatil/csci1300-recitation-notes
b6ad687e56bc58ff808e5786e7381d125089beeb
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int function1(int a){ return a + 1; return a+2; cout<<"hello"; } int main(){ int result; result = function1(7); cout<<result<<endl; return 0; }
11.619048
26
0.516393
punithpatil
a1a05d13cb589d78a1a077645873a3b35f369c56
2,680
hpp
C++
include/ghex/device/cuda/runtime.hpp
GridTools/GHEX
1adce924c02cf0553d2ceed69f7dc37e39c7013d
[ "BSD-3-Clause" ]
9
2020-01-30T08:12:40.000Z
2022-01-17T11:18:07.000Z
include/ghex/device/cuda/runtime.hpp
ghex-org/GHEX
6eb91410d5c01d36a70f0eb106c1f065df3cee9f
[ "BSD-3-Clause" ]
50
2019-12-19T13:25:56.000Z
2021-09-16T13:57:36.000Z
include/ghex/device/cuda/runtime.hpp
ghex-org/GHEX
6eb91410d5c01d36a70f0eb106c1f065df3cee9f
[ "BSD-3-Clause" ]
10
2019-12-10T15:31:36.000Z
2021-07-04T19:31:28.000Z
/* * GridTools * * Copyright (c) 2014-2021, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause * */ #pragma once #ifdef __HIP_PLATFORM_HCC__ #include <hip/hip_runtime.h> #include <ghex/device/cuda/undef_cuda_macros.hpp> /* GridTools cuda -> hip translations */ #define cudaDeviceProp hipDeviceProp_t #define cudaDeviceSynchronize hipDeviceSynchronize #define cudaErrorInvalidValue hipErrorInvalidValue #define cudaError_t hipError_t #define cudaEventCreate hipEventCreate #define cudaEventDestroy hipEventDestroy #define cudaEventElapsedTime hipEventElapsedTime #define cudaEventRecord hipEventRecord #define cudaEventSynchronize hipEventSynchronize #define cudaEvent_t hipEvent_t #define cudaFree hipFree #define cudaFreeHost hipFreeHost #define cudaGetDevice hipGetDevice #define cudaGetDeviceCount hipGetDeviceCount #define cudaGetDeviceProperties hipGetDeviceProperties #define cudaGetErrorName hipGetErrorName #define cudaGetErrorString hipGetErrorString #define cudaGetLastError hipGetLastError #define cudaMalloc hipMalloc #define cudaMallocHost hipMallocHost #define cudaMallocManaged hipMallocManaged #define cudaMemAttachGlobal hipMemAttachGlobal #define cudaMemcpy hipMemcpy #define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost #define cudaMemcpyHostToDevice hipMemcpyHostToDevice #define cudaMemoryTypeDevice hipMemoryTypeDevice #define cudaPointerAttributes hipPointerAttribute_t #define cudaPointerGetAttributes hipPointerGetAttributes #define cudaSetDevice hipSetDevice #define cudaStreamCreate hipStreamCreate #define cudaStreamDestroy hipStreamDestroy #define cudaStreamSynchronize hipStreamSynchronize #define cudaStream_t hipStream_t #define cudaSuccess hipSuccess /* additional cuda -> hip translations */ #define cudaEventCreateWithFlags hipEventCreateWithFlags #define cudaEventDisableTiming hipEventDisableTiming #define cudaEventInterprocess hipEventInterprocess #define cudaEventQuery hipEventQuery #define cudaIpcCloseMemHandle hipIpcCloseMemHandle #define cudaIpcEventHandle_t hipIpcEventHandle_t #define cudaIpcGetEventHandle hipIpcGetEventHandle #define cudaIpcGetMemHandle hipIpcGetMemHandle #define cudaIpcMemHandle_t hipIpcMemHandle_t #define cudaIpcMemLazyEnablePeerAccess hipIpcMemLazyEnablePeerAccess #define cudaIpcOpenEventHandle hipIpcOpenEventHandle #define cudaIpcOpenMemHandle hipIpcOpenMemHandle #define cudaMemcpyAsync hipMemcpyAsync #define cudaStreamCreateWithFlags hipStreamCreateWithFlags #define cudaStreamNonBlocking hipStreamNonBlocking #else /* __HIP_PLATFORM_HCC__ */ #include <cuda_runtime.h> #endif /* __HIP_PLATFORM_HCC__ */
35.263158
68
0.873507
GridTools
a1a161930ab97e58a54ad1f09a7f427a03e1c6fb
392
cpp
C++
cpp/541-550/Output Contest Matches.cpp
KaiyuWei/leetcode
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
[ "MIT" ]
150
2015-04-04T06:53:49.000Z
2022-03-21T13:32:08.000Z
cpp/541-550/Output Contest Matches.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
1
2015-04-13T15:15:40.000Z
2015-04-21T20:23:16.000Z
cpp/541-550/Output Contest Matches.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
64
2015-06-30T08:00:07.000Z
2022-01-01T16:44:14.000Z
class Solution { public: string findContestMatch(int n) { vector<string> m(n); for (int i = 0; i < n; i++) { m[i] = to_string(i + 1); } while (n > 1) { for (int i = 0; i < n / 2; i++) { m[i] = "(" + m[i] + "," + m[n - 1 - i] + ")"; } n /= 2; } return m[0]; } };
20.631579
61
0.306122
KaiyuWei
a1a1e7c0aab8bd2c65f33f1d8d6e581472223f44
951
cpp
C++
DSA/Building a linked list.cpp
lixk28/Assignment
1128d041a111063be0dba1699ebcf4aa8a74e49c
[ "MIT" ]
null
null
null
DSA/Building a linked list.cpp
lixk28/Assignment
1128d041a111063be0dba1699ebcf4aa8a74e49c
[ "MIT" ]
null
null
null
DSA/Building a linked list.cpp
lixk28/Assignment
1128d041a111063be0dba1699ebcf4aa8a74e49c
[ "MIT" ]
null
null
null
#include <iostream> #define JUST_CHECK using namespace std; typedef string T; struct Node { //data members T data; Node *next; //constructors Node() { next = NULL;}; Node(T item, Node *add_on = NULL) { data = item; next = add_on; }; }; Node *foo() { Node *temp1 = new Node("Programming", NULL); Node *temp2 = new Node("is", NULL); Node *temp3 = new Node("fun", NULL); temp1->next = temp2; temp2->next = temp3; return temp1; } void Destroy(Node *head) { while(head != NULL) { Node *temp = head; head = head->next; delete temp; } } int main() { Node *list = foo(); #ifdef JUST_CHECK Node *temp = list; while(temp != NULL) { cout << temp->data << " "; temp = temp->next; } #endif Destroy(list); return 0; }
16.684211
49
0.477392
lixk28
a1a2c0ae4c87d618f814a7e0686b4723833b7e36
2,243
cpp
C++
src/zorbatypes/rchandle.cpp
jsoniq/jsoniq
f7af29417f809d64d1f0b2622d880bc4d87f2e42
[ "Apache-2.0" ]
94
2015-01-18T09:40:36.000Z
2022-03-02T21:14:55.000Z
src/zorbatypes/rchandle.cpp
jsoniq/jsoniq
f7af29417f809d64d1f0b2622d880bc4d87f2e42
[ "Apache-2.0" ]
72
2015-01-05T22:00:31.000Z
2021-07-17T11:35:03.000Z
src/zorbatypes/rchandle.cpp
jsoniq/jsoniq
f7af29417f809d64d1f0b2622d880bc4d87f2e42
[ "Apache-2.0" ]
27
2015-01-18T20:20:54.000Z
2020-11-01T18:01:07.000Z
/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "stdafx.h" #include "zorbatypes/rchandle.h" #include "zorbaserialization/archiver.h" #include "diagnostics/assert.h" namespace zorba { /******************************************************************************* Base class for reference counted objects Any class wishing to take advantage of automatic reference counting must inherit from this class. rcobject encapsulates the reference count, as well as functions for incrementing and decrementing the count. It also contains code for destroying a value when it is no longer in use, i.e., when its reference count becomes 0. ********************************************************************************/ SERIALIZABLE_CLASS_VERSIONS(SyncedRCObject) SERIALIZABLE_CLASS_VERSIONS_2(SimpleRCObject, TYPE_SimpleRCObject) /******************************************************************************* ********************************************************************************/ void SyncedRCObject::serialize(::zorba::serialization::Archiver& ar) { ZORBA_ASSERT(false); if (!ar.is_serializing_out()) theRefCount = 0; } /******************************************************************************* ********************************************************************************/ void SimpleRCObject::serialize(::zorba::serialization::Archiver& ar) { ZORBA_ASSERT(false); if (!ar.is_serializing_out()) theRefCount = 0; } size_t SimpleRCObject::alloc_size() const { return 0; } size_t SimpleRCObject::dynamic_size() const { return sizeof( *this ); } } /* namespace zorba */ /* vim:set et sw=2 ts=2: */
26.081395
81
0.579581
jsoniq
a1a4841562c5a2eb83898c6398460f7fcd04d0d8
1,895
hpp
C++
include/SSVOpenHexagon/Core/Steam.hpp
duck-37/SSVOpenHexagon
f4af15149de5c9d3b843cbfe2abcd9b68a9876d1
[ "AFL-3.0" ]
409
2015-01-03T00:08:16.000Z
2021-11-29T05:42:06.000Z
include/SSVOpenHexagon/Core/Steam.hpp
duck-37/SSVOpenHexagon
f4af15149de5c9d3b843cbfe2abcd9b68a9876d1
[ "AFL-3.0" ]
185
2015-01-03T14:52:31.000Z
2021-11-19T20:58:48.000Z
include/SSVOpenHexagon/Core/Steam.hpp
duck-37/SSVOpenHexagon
f4af15149de5c9d3b843cbfe2abcd9b68a9876d1
[ "AFL-3.0" ]
74
2015-01-12T19:08:54.000Z
2021-11-22T23:43:59.000Z
// Copyright (c) 2013-2020 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: https://opensource.org/licenses/AFL-3.0 #pragma once #include "SSVOpenHexagon/Utils/UniquePtr.hpp" #include <cstdint> #include <functional> #include <optional> #include <string_view> #include <string> namespace hg::Steam { class steam_manager { private: class steam_manager_impl; Utils::UniquePtr<steam_manager_impl> _impl; [[nodiscard]] const steam_manager_impl& impl() const noexcept; [[nodiscard]] steam_manager_impl& impl() noexcept; public: explicit steam_manager(); ~steam_manager(); steam_manager(const steam_manager&) = delete; steam_manager& operator=(const steam_manager&) = delete; steam_manager(steam_manager&&) = delete; steam_manager& operator=(steam_manager&&) = delete; [[nodiscard]] bool is_initialized() const noexcept; bool request_stats_and_achievements(); bool run_callbacks(); bool store_stats(); bool unlock_achievement(std::string_view name); bool set_rich_presence_in_menu(); bool set_rich_presence_in_game(std::string_view level_name_format, std::string_view difficulty_mult_format, std::string_view time_format); bool set_and_store_stat(std::string_view name, int data); [[nodiscard]] bool get_achievement(bool* out, std::string_view name); [[nodiscard]] bool get_stat(int* out, std::string_view name); bool update_hardcoded_achievements(); void for_workshop_pack_folders( const std::function<void(const std::string&)>& f) const; bool request_encrypted_app_ticket(); [[nodiscard]] bool got_encrypted_app_ticket_response() const noexcept; [[nodiscard]] bool got_encrypted_app_ticket() const noexcept; [[nodiscard]] std::optional<std::uint64_t> get_ticket_steam_id() const noexcept; }; } // namespace hg::Steam
27.071429
79
0.727704
duck-37
a1abc358146106cb6d96b49c93e31e3c15904ba9
7,748
cpp
C++
dc/src/v20180410/model/DirectConnectTunnelRoute.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
dc/src/v20180410/model/DirectConnectTunnelRoute.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
dc/src/v20180410/model/DirectConnectTunnelRoute.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * 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/dc/v20180410/model/DirectConnectTunnelRoute.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Dc::V20180410::Model; using namespace std; DirectConnectTunnelRoute::DirectConnectTunnelRoute() : m_routeIdHasBeenSet(false), m_destinationCidrBlockHasBeenSet(false), m_routeTypeHasBeenSet(false), m_statusHasBeenSet(false), m_aSPathHasBeenSet(false), m_nextHopHasBeenSet(false) { } CoreInternalOutcome DirectConnectTunnelRoute::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("RouteId") && !value["RouteId"].IsNull()) { if (!value["RouteId"].IsString()) { return CoreInternalOutcome(Core::Error("response `DirectConnectTunnelRoute.RouteId` IsString=false incorrectly").SetRequestId(requestId)); } m_routeId = string(value["RouteId"].GetString()); m_routeIdHasBeenSet = true; } if (value.HasMember("DestinationCidrBlock") && !value["DestinationCidrBlock"].IsNull()) { if (!value["DestinationCidrBlock"].IsString()) { return CoreInternalOutcome(Core::Error("response `DirectConnectTunnelRoute.DestinationCidrBlock` IsString=false incorrectly").SetRequestId(requestId)); } m_destinationCidrBlock = string(value["DestinationCidrBlock"].GetString()); m_destinationCidrBlockHasBeenSet = true; } if (value.HasMember("RouteType") && !value["RouteType"].IsNull()) { if (!value["RouteType"].IsString()) { return CoreInternalOutcome(Core::Error("response `DirectConnectTunnelRoute.RouteType` IsString=false incorrectly").SetRequestId(requestId)); } m_routeType = string(value["RouteType"].GetString()); m_routeTypeHasBeenSet = true; } if (value.HasMember("Status") && !value["Status"].IsNull()) { if (!value["Status"].IsString()) { return CoreInternalOutcome(Core::Error("response `DirectConnectTunnelRoute.Status` IsString=false incorrectly").SetRequestId(requestId)); } m_status = string(value["Status"].GetString()); m_statusHasBeenSet = true; } if (value.HasMember("ASPath") && !value["ASPath"].IsNull()) { if (!value["ASPath"].IsArray()) return CoreInternalOutcome(Core::Error("response `DirectConnectTunnelRoute.ASPath` is not array type")); const rapidjson::Value &tmpValue = value["ASPath"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { m_aSPath.push_back((*itr).GetString()); } m_aSPathHasBeenSet = true; } if (value.HasMember("NextHop") && !value["NextHop"].IsNull()) { if (!value["NextHop"].IsString()) { return CoreInternalOutcome(Core::Error("response `DirectConnectTunnelRoute.NextHop` IsString=false incorrectly").SetRequestId(requestId)); } m_nextHop = string(value["NextHop"].GetString()); m_nextHopHasBeenSet = true; } return CoreInternalOutcome(true); } void DirectConnectTunnelRoute::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_routeIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RouteId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_routeId.c_str(), allocator).Move(), allocator); } if (m_destinationCidrBlockHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DestinationCidrBlock"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_destinationCidrBlock.c_str(), allocator).Move(), allocator); } if (m_routeTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RouteType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_routeType.c_str(), allocator).Move(), allocator); } if (m_statusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Status"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_status.c_str(), allocator).Move(), allocator); } if (m_aSPathHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ASPath"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_aSPath.begin(); itr != m_aSPath.end(); ++itr) { value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_nextHopHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "NextHop"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_nextHop.c_str(), allocator).Move(), allocator); } } string DirectConnectTunnelRoute::GetRouteId() const { return m_routeId; } void DirectConnectTunnelRoute::SetRouteId(const string& _routeId) { m_routeId = _routeId; m_routeIdHasBeenSet = true; } bool DirectConnectTunnelRoute::RouteIdHasBeenSet() const { return m_routeIdHasBeenSet; } string DirectConnectTunnelRoute::GetDestinationCidrBlock() const { return m_destinationCidrBlock; } void DirectConnectTunnelRoute::SetDestinationCidrBlock(const string& _destinationCidrBlock) { m_destinationCidrBlock = _destinationCidrBlock; m_destinationCidrBlockHasBeenSet = true; } bool DirectConnectTunnelRoute::DestinationCidrBlockHasBeenSet() const { return m_destinationCidrBlockHasBeenSet; } string DirectConnectTunnelRoute::GetRouteType() const { return m_routeType; } void DirectConnectTunnelRoute::SetRouteType(const string& _routeType) { m_routeType = _routeType; m_routeTypeHasBeenSet = true; } bool DirectConnectTunnelRoute::RouteTypeHasBeenSet() const { return m_routeTypeHasBeenSet; } string DirectConnectTunnelRoute::GetStatus() const { return m_status; } void DirectConnectTunnelRoute::SetStatus(const string& _status) { m_status = _status; m_statusHasBeenSet = true; } bool DirectConnectTunnelRoute::StatusHasBeenSet() const { return m_statusHasBeenSet; } vector<string> DirectConnectTunnelRoute::GetASPath() const { return m_aSPath; } void DirectConnectTunnelRoute::SetASPath(const vector<string>& _aSPath) { m_aSPath = _aSPath; m_aSPathHasBeenSet = true; } bool DirectConnectTunnelRoute::ASPathHasBeenSet() const { return m_aSPathHasBeenSet; } string DirectConnectTunnelRoute::GetNextHop() const { return m_nextHop; } void DirectConnectTunnelRoute::SetNextHop(const string& _nextHop) { m_nextHop = _nextHop; m_nextHopHasBeenSet = true; } bool DirectConnectTunnelRoute::NextHopHasBeenSet() const { return m_nextHopHasBeenSet; }
29.8
163
0.692953
suluner
a1ad6726f38dc872891381e33ce8cac59cf6d3f3
2,160
cpp
C++
aws-cpp-sdk-accessanalyzer/source/model/KmsKeyConfiguration.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-accessanalyzer/source/model/KmsKeyConfiguration.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-accessanalyzer/source/model/KmsKeyConfiguration.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/accessanalyzer/model/KmsKeyConfiguration.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace AccessAnalyzer { namespace Model { KmsKeyConfiguration::KmsKeyConfiguration() : m_grantsHasBeenSet(false), m_keyPoliciesHasBeenSet(false) { } KmsKeyConfiguration::KmsKeyConfiguration(JsonView jsonValue) : m_grantsHasBeenSet(false), m_keyPoliciesHasBeenSet(false) { *this = jsonValue; } KmsKeyConfiguration& KmsKeyConfiguration::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("grants")) { Array<JsonView> grantsJsonList = jsonValue.GetArray("grants"); for(unsigned grantsIndex = 0; grantsIndex < grantsJsonList.GetLength(); ++grantsIndex) { m_grants.push_back(grantsJsonList[grantsIndex].AsObject()); } m_grantsHasBeenSet = true; } if(jsonValue.ValueExists("keyPolicies")) { Aws::Map<Aws::String, JsonView> keyPoliciesJsonMap = jsonValue.GetObject("keyPolicies").GetAllObjects(); for(auto& keyPoliciesItem : keyPoliciesJsonMap) { m_keyPolicies[keyPoliciesItem.first] = keyPoliciesItem.second.AsString(); } m_keyPoliciesHasBeenSet = true; } return *this; } JsonValue KmsKeyConfiguration::Jsonize() const { JsonValue payload; if(m_grantsHasBeenSet) { Array<JsonValue> grantsJsonList(m_grants.size()); for(unsigned grantsIndex = 0; grantsIndex < grantsJsonList.GetLength(); ++grantsIndex) { grantsJsonList[grantsIndex].AsObject(m_grants[grantsIndex].Jsonize()); } payload.WithArray("grants", std::move(grantsJsonList)); } if(m_keyPoliciesHasBeenSet) { JsonValue keyPoliciesJsonMap; for(auto& keyPoliciesItem : m_keyPolicies) { keyPoliciesJsonMap.WithString(keyPoliciesItem.first, keyPoliciesItem.second); } payload.WithObject("keyPolicies", std::move(keyPoliciesJsonMap)); } return payload; } } // namespace Model } // namespace AccessAnalyzer } // namespace Aws
23.736264
108
0.731944
perfectrecall
a1ada5eebf4f4c1f16c54d12c4e5c61dcdee30d0
1,351
cpp
C++
liblumi/sources/Ray.cpp
Rertsyd/LumiRT
d562fd786f769b385bc051e2ea8bcd26162a9dc6
[ "MIT" ]
null
null
null
liblumi/sources/Ray.cpp
Rertsyd/LumiRT
d562fd786f769b385bc051e2ea8bcd26162a9dc6
[ "MIT" ]
null
null
null
liblumi/sources/Ray.cpp
Rertsyd/LumiRT
d562fd786f769b385bc051e2ea8bcd26162a9dc6
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* ,, */ /* `7MMF' db `7MM"""Mq. MMP""MM""YMM */ /* MM MM `MM.P' MM `7 */ /* MM `7MM `7MM `7MMpMMMb.pMMMb. `7MM MM ,M9 MM */ /* MM MM MM MM MM MM MM MMmmdM9 MM */ /* MM , MM MM MM MM MM MM MM YM. MM */ /* MM ,M MM MM MM MM MM MM MM `Mb. MM */ /* .JMMmmmmMMM `Mbod"YML..JMML JMML JMML..JMML..JMML. .JMM. .JMML. */ /* */ /* ************************************************************************** */ #include "Ray.hpp" unsigned Ray::MaxDepth = 5u; Ray::Ray() : Type(Primary), Origin(), Direction() {} void Ray::SetDir(Camera& cam, const uVec2 pxCoord, const uVec2 res) { const Vec2 indent = { cam.ViewPlane.Width / res.x, cam.ViewPlane.Height / res.y }; const Vector vRight = cam.Right * indent.x; const Vector vUp = cam.Up * indent.y; Direction = (cam.ViewPlane.UpLeft + vRight * pxCoord.x - vUp * pxCoord.y - cam.Position).Normalize(); };
39.735294
80
0.350111
Rertsyd
a1adf3bd15e3a7a05636f556764d6340ad66968c
13,482
hh
C++
Mu2eUtilities/inc/RootTreeSampler.hh
sophiemiddleton/Offline
d0c570158c88b7311e758666ab47fafc828f39b0
[ "Apache-2.0" ]
null
null
null
Mu2eUtilities/inc/RootTreeSampler.hh
sophiemiddleton/Offline
d0c570158c88b7311e758666ab47fafc828f39b0
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
Mu2eUtilities/inc/RootTreeSampler.hh
sophiemiddleton/Offline
d0c570158c88b7311e758666ab47fafc828f39b0
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
// A helper class to randomly sample entries read from a collection of // ROOT trees. Input ROOT files are read only once, during the // construction phase, and data are stored in memory. There are two // template arguments: EventRecord and NtupleRecord. They can be the // same type (the default), then a single row of an input tree will be // read per EventRecord. Otherwise EventRecord is expected to be // a std::vector<NtupleRecord>, and we will use two branches from // the input trees: a "main record" branch that corresponds to // NtupleRecord, and a "particle in event (pie)" branch that // stores a single integer, and allows to keep correlations // between particles (NtupleRecord) in an event (EventRecord). // // The fire() method returns one of the stored EventRecord entries. // All the stored entries are sampled with equal probabilities. // // The optional averageNumRecordsToUse parameter controls memory use: // if the number of input records exceeds the parameter, not all // records are stored. Entries to be used are randomly selected at // the initialization time with equal *per-event* probabilities to // make the expected number of stored ntuple records *approximately* // equal to the specified parameter. The approximations should be // good if the average per-event ntuple record multiplicity is not // large. The biases affect how much memory the code uses, but do not // affect physics results. Setting averageNumRecordsToUse<=0 disables // the feature (the default). If the number of inputs is less than // averageNumRecordsToUse, all input records are used. // // See StoppedParticleReactionGun_module.cc and InFlightParticleSampler_module.cc // for examples of use. // // Andrei Gaponenko, 2014, 2015 #ifndef RootTreeSampler_hh #define RootTreeSampler_hh #include <vector> #include "fhiclcpp/ParameterSet.h" #include "CLHEP/Random/RandomEngine.h" #include "CLHEP/Random/RandFlat.h" #include "art/Framework/Services/Registry/ServiceHandle.h" #include "art_root_io/TFileService.h" #include "cetlib_except/exception.h" #include "TTree.h" #include "TFile.h" #include "ConfigTools/inc/ConfigFileLookupPolicy.hh" namespace mu2e { template<class EventRecord, class NtupleRecord=EventRecord> class RootTreeSampler { public: RootTreeSampler(art::RandomNumberGenerator::base_engine_t& engine, const fhicl::ParameterSet& pset); const EventRecord& fire() { return records_.at(randFlat_.fireInt(records_.size())); } typename std::vector<EventRecord>::size_type numRecords() const { return records_.size(); } private: CLHEP::RandFlat randFlat_; std::vector<EventRecord> records_; typedef std::vector<std::string> Strings; long countInputRecords(const art::ServiceHandle<art::TFileService>& tfs, const Strings& files, const std::string& treeName); //---------------------------------------------------------------- struct SingleRecordGetter { RootTreeSampler *parent_; TTree *nt_; TBranch *mrb_; NtupleRecord ntr_; long averageNumRecordsToUse_; double recordUseFraction_; bool hasMore_ = false; Long64_t numTreeEntries_; Long64_t currentEntry_ = 0; Long64_t numUsedNtupleEntries_ = 0; SingleRecordGetter(RootTreeSampler *ts, TTree *tr, TBranch *mainRecordBranch, const fhicl::ParameterSet& pset, double recordUseFraction) : parent_(ts) , nt_(tr) , mrb_(mainRecordBranch) , recordUseFraction_(recordUseFraction) , numTreeEntries_(tr->GetEntries()) { mrb_->SetAddress(&ntr_); } bool hasMoreRecords() { while(currentEntry_ < numTreeEntries_) { if(parent_->randFlat_.fire() < recordUseFraction_) { mrb_->GetEntry(currentEntry_++); ++numUsedNtupleEntries_; return hasMore_ = true; } ++currentEntry_; } return hasMore_ = false; } EventRecord getRecord() const { if(!hasMore_) { throw cet::exception("BUG") <<"RootTreeSampler::SingleRecordGetter(): getRecord() called with no current record.\n"; } return ntr_; } Long64_t numUsedNtupleEntries() const { return numUsedNtupleEntries_; } }; // SingleRecordGetter //---------------------------------------------------------------- struct MultiRecordGetter { RootTreeSampler *parent_; TTree *nt_; TBranch *mrb_; NtupleRecord ntr_; EventRecord evt_; TBranch *pieb_; unsigned particleInEvent_; long averageNumRecordsToUse_; double recordUseFraction_; Long64_t numTreeEntries_; Long64_t currentEntry_; Long64_t numUsedNtupleEntries_; MultiRecordGetter(RootTreeSampler *ts, TTree *tr, TBranch *mainRecordBranch, const fhicl::ParameterSet& pset, double recordUseFraction) : parent_(ts) , nt_(tr) , mrb_(mainRecordBranch) , pieb_(tr->GetBranch(pset.get<std::string>("pieBranchName").c_str())) , particleInEvent_(-1) , recordUseFraction_(recordUseFraction) , numTreeEntries_(tr->GetEntries()) , currentEntry_(0) , numUsedNtupleEntries_(0) { mrb_->SetAddress(&ntr_); if(!pieb_) { throw cet::exception("BADINPUT") <<"RootTreeSampler: Could not get branch \""<<pset.get<std::string>("pieBranchName") <<"\" in tree \""<<nt_->GetName() <<"\"\n"; } pieb_->SetAddress(&particleInEvent_); } bool hasMoreRecords() { evt_.clear(); while(currentEntry_ < numTreeEntries_) { pieb_->GetEntry(currentEntry_); if(particleInEvent_ != 0) { // something went wrong - we should be aligned on the beginning of an event here throw cet::exception("BADINPUT")<<"RootTreeSampler: Error: unexpected particleInEvent!=0"; } const bool use = (parent_->randFlat_.fire() < recordUseFraction_); if(use) { // read the current record mrb_->GetEntry(currentEntry_); evt_.emplace_back(ntr_); ++numUsedNtupleEntries_; } // go through the rest of records from this event for(++currentEntry_; currentEntry_ < numTreeEntries_; ++currentEntry_) { pieb_->GetEntry(currentEntry_); if(particleInEvent_ == 0) { // that's the first record from the next even. // the current event is complete if(use) { return true; } else { break; // We did not use that event. Go to the next one in the outer loop. } } if(use) { mrb_->GetEntry(currentEntry_); evt_.emplace_back(ntr_); ++numUsedNtupleEntries_; } } } return false; } EventRecord getRecord() const { if(evt_.empty()) { throw cet::exception("BUG") <<"RootTreeSampler::SingleRecordGetter(): " <<"getRecord() called with no current record.\n"; } return evt_; } Long64_t numUsedNtupleEntries() const { return numUsedNtupleEntries_; } }; // MultiRecordGetter //---------------------------------------------------------------- }; } //================================================================ namespace mu2e { template<class EventRecord, class NtupleRecord> RootTreeSampler<EventRecord, NtupleRecord>:: RootTreeSampler(art::RandomNumberGenerator::base_engine_t& engine, const fhicl::ParameterSet& pset) : randFlat_(engine) { const auto inputFiles(pset.get<std::vector<std::string> >("inputFiles")); const auto treeName(pset.get<std::string>("treeName")); const long averageNumRecordsToUse(pset.get<long>("averageNumRecordsToUse", 0)); int verbosityLevel = pset.get<int>("verbosityLevel", 0); if(inputFiles.empty()) { throw cet::exception("BADCONFIG")<<"Error: no inputFiles"; } art::ServiceHandle<art::TFileService> tfs; double recordUseFraction = 1.; if(averageNumRecordsToUse > 0) { const long totalRecords = countInputRecords(tfs, inputFiles, treeName); if(averageNumRecordsToUse < totalRecords) { recordUseFraction = averageNumRecordsToUse/double(totalRecords); if(verbosityLevel > 0) { std::cout<<"RootTreeSampler: recordUseFraction = "<<recordUseFraction <<" for the requested average = "<<averageNumRecordsToUse <<" and total number of input records = "<<totalRecords <<std::endl; } } else { if(verbosityLevel > 0) { std::cout<<"RootTreeSampler: forcing recordUseFraction=1 " <<": the requested number = "<<averageNumRecordsToUse <<" exceeds the number of available inputs = "<<totalRecords <<std::endl; } } } //---------------------------------------------------------------- // Load the records for(const auto& fn : inputFiles) { const std::string resolvedFileName = ConfigFileLookupPolicy()(fn); TFile *infile = tfs->make<TFile>(resolvedFileName.c_str(), "READ"); TTree *nt = dynamic_cast<TTree*>(infile->Get(treeName.c_str())); if(!nt) { throw cet::exception("BADINPUT")<<"RootTreeSampler: Could not get tree \""<<treeName <<"\" from file \""<<infile->GetName() <<"\"\n"; } //---------------------------------------------------------------- // A rudimentary check that the input ntuple is consistent with the data structure const auto branchName(pset.get<std::string>("branchName")); TBranch *bb = nt->GetBranch(branchName.c_str()); if(!bb) { throw cet::exception("BADINPUT")<<"RootTreeSampler: Could not get branch \""<<branchName <<"\" in tree \""<<treeName <<"\" from file \""<<infile->GetName() <<"\"\n"; } if(unsigned(bb->GetNleaves()) != NtupleRecord::numBranchLeaves()) { throw cet::exception("BADINPUT")<<"RootTreeSampler: wrong number of leaves: expect " <<NtupleRecord::numBranchLeaves()<<", but branch \""<<branchName <<"\", tree \""<<treeName <<"\" in file \""<<infile->GetName() <<"\" has "<<bb->GetNleaves() <<"\n"; } //---------------------------------------------------------------- const Long64_t nTreeEntries = nt->GetEntries(); std::cout<<"RootTreeSampler: reading "<<nTreeEntries <<" entries. Tree "<<treeName <<", file "<<infile->GetName() <<std::endl; // If the average per-event ntuple record multiplicity is large, // this will over-allocate the memory. records_.reserve(records_.size() // Add "mean + 3sigma": do not re-allocate in most cases. + recordUseFraction*nTreeEntries + 3*recordUseFraction*sqrt(double(nTreeEntries))); typename std::conditional <std::is_same<EventRecord,NtupleRecord>::value, SingleRecordGetter, MultiRecordGetter>::type egt(this, nt, bb, pset, recordUseFraction); while(egt.hasMoreRecords()) { records_.push_back(egt.getRecord()); } if(verbosityLevel > 0) { std::cout<<"RootTreeSampler: stored "<<records_.size() <<" event entries. Used "<<egt.numUsedNtupleEntries() <<" ntuple entries." <<std::endl; } } // for(inputFiles) } // Constructor //================================================================ template<class EventRecord, class NtupleRecord> long RootTreeSampler<EventRecord, NtupleRecord>::countInputRecords(const art::ServiceHandle<art::TFileService>& tfs, const Strings& inputFiles, const std::string& treeName) { long res=0; for(const auto& fn : inputFiles) { const std::string resolvedFileName = ConfigFileLookupPolicy()(fn); TFile *infile = tfs->make<TFile>(resolvedFileName.c_str(), "READ"); TTree *nt = dynamic_cast<TTree*>(infile->Get(treeName.c_str())); if(!nt) { throw cet::exception("BADINPUT")<<"Could not get tree \""<<treeName <<"\" from file \""<<infile->GetName() <<"\"\n"; } const Long64_t nTreeEntries = nt->GetEntries(); res += nTreeEntries; } return res; } //================================================================ } #endif /* RootTreeSampler_hh */
35.952
118
0.564605
sophiemiddleton
a1afc12bec8fb6c671eec5e36724fc69d537d493
542
cpp
C++
MGAME.cpp
trehanarsh/Codechef-Solutions
8bfd91531138a62aebcc2dffce3ad8e6a296db28
[ "MIT" ]
null
null
null
MGAME.cpp
trehanarsh/Codechef-Solutions
8bfd91531138a62aebcc2dffce3ad8e6a296db28
[ "MIT" ]
null
null
null
MGAME.cpp
trehanarsh/Codechef-Solutions
8bfd91531138a62aebcc2dffce3ad8e6a296db28
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long #define MOD 1000000007 #define print(A,n) for(ll i=0;i<n;++i)cout<<A[i]<<' ';cout<<endl; #define take(A,n) for(ll i=0;i<n;++i)cin>>A[i]; // for(auto& it : m) void fastio(){ios_base::sync_with_stdio(false);cin.tie(NULL);} int main() { fastio(); ll int t; cin>>t; while(t--) { ll int n,p; cin>>n>>p; ll int x=n/2- ( (n&1)?0:1 ); ll int ans= (p-x)*(p-x) + (p-n)*(p-x) + (p-n)*(p-n); if(n==1||n==2)ans=p*p*p; cout<<ans<<endl; } }
19.357143
65
0.527675
trehanarsh
a1b33557aac8576ea9835fce819cecdf76ab0cae
34,003
hpp
C++
include/UnityEngine/AndroidJNI.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/UnityEngine/AndroidJNI.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/UnityEngine/AndroidJNI.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.jvalue #include "UnityEngine/jvalue.hpp" // Completed includes // Type namespace: UnityEngine namespace UnityEngine { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: UnityEngine.AndroidJNI // [NativeHeaderAttribute] Offset: DB8804 // [NativeConditionalAttribute] Offset: DB8804 // [StaticAccessorAttribute] Offset: DB8804 class AndroidJNI : public ::Il2CppObject { public: // Creating value type constructor for type: AndroidJNI AndroidJNI() noexcept {} // static public System.Int32 AttachCurrentThread() // Offset: 0x2355758 static int AttachCurrentThread(); // static public System.Int32 DetachCurrentThread() // Offset: 0x235578C static int DetachCurrentThread(); // static public System.Int32 GetVersion() // Offset: 0x23557C0 static int GetVersion(); // static public System.IntPtr FindClass(System.String name) // Offset: 0x23557F4 static System::IntPtr FindClass(::Il2CppString* name); // static public System.IntPtr FromReflectedMethod(System.IntPtr refMethod) // Offset: 0x2355834 static System::IntPtr FromReflectedMethod(System::IntPtr refMethod); // static public System.IntPtr FromReflectedField(System.IntPtr refField) // Offset: 0x2355874 static System::IntPtr FromReflectedField(System::IntPtr refField); // static public System.IntPtr ToReflectedMethod(System.IntPtr clazz, System.IntPtr methodID, System.Boolean isStatic) // Offset: 0x23558B4 static System::IntPtr ToReflectedMethod(System::IntPtr clazz, System::IntPtr methodID, bool isStatic); // static public System.IntPtr ToReflectedField(System.IntPtr clazz, System.IntPtr fieldID, System.Boolean isStatic) // Offset: 0x235590C static System::IntPtr ToReflectedField(System::IntPtr clazz, System::IntPtr fieldID, bool isStatic); // static public System.IntPtr GetSuperclass(System.IntPtr clazz) // Offset: 0x2355964 static System::IntPtr GetSuperclass(System::IntPtr clazz); // static public System.Boolean IsAssignableFrom(System.IntPtr clazz1, System.IntPtr clazz2) // Offset: 0x23559A4 static bool IsAssignableFrom(System::IntPtr clazz1, System::IntPtr clazz2); // static public System.Int32 Throw(System.IntPtr obj) // Offset: 0x23559F4 static int Throw(System::IntPtr obj); // static public System.Int32 ThrowNew(System.IntPtr clazz, System.String message) // Offset: 0x2355A34 static int ThrowNew(System::IntPtr clazz, ::Il2CppString* message); // static public System.IntPtr ExceptionOccurred() // Offset: 0x2355A84 static System::IntPtr ExceptionOccurred(); // static public System.Void ExceptionDescribe() // Offset: 0x2355AB8 static void ExceptionDescribe(); // static public System.Void ExceptionClear() // Offset: 0x2355AEC static void ExceptionClear(); // static public System.Void FatalError(System.String message) // Offset: 0x2355B20 static void FatalError(::Il2CppString* message); // static public System.Int32 PushLocalFrame(System.Int32 capacity) // Offset: 0x2355B60 static int PushLocalFrame(int capacity); // static public System.IntPtr PopLocalFrame(System.IntPtr ptr) // Offset: 0x2355BA0 static System::IntPtr PopLocalFrame(System::IntPtr ptr); // static public System.IntPtr NewGlobalRef(System.IntPtr obj) // Offset: 0x2355BE0 static System::IntPtr NewGlobalRef(System::IntPtr obj); // static public System.Void DeleteGlobalRef(System.IntPtr obj) // Offset: 0x2355C20 static void DeleteGlobalRef(System::IntPtr obj); // static public System.IntPtr NewWeakGlobalRef(System.IntPtr obj) // Offset: 0x2355C60 static System::IntPtr NewWeakGlobalRef(System::IntPtr obj); // static public System.Void DeleteWeakGlobalRef(System.IntPtr obj) // Offset: 0x2355CA0 static void DeleteWeakGlobalRef(System::IntPtr obj); // static public System.IntPtr NewLocalRef(System.IntPtr obj) // Offset: 0x2355CE0 static System::IntPtr NewLocalRef(System::IntPtr obj); // static public System.Void DeleteLocalRef(System.IntPtr obj) // Offset: 0x2355D20 static void DeleteLocalRef(System::IntPtr obj); // static public System.Boolean IsSameObject(System.IntPtr obj1, System.IntPtr obj2) // Offset: 0x2355D60 static bool IsSameObject(System::IntPtr obj1, System::IntPtr obj2); // static public System.Int32 EnsureLocalCapacity(System.Int32 capacity) // Offset: 0x2355DB0 static int EnsureLocalCapacity(int capacity); // static public System.IntPtr AllocObject(System.IntPtr clazz) // Offset: 0x2355DF0 static System::IntPtr AllocObject(System::IntPtr clazz); // static public System.IntPtr NewObject(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2355E30 static System::IntPtr NewObject(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.IntPtr GetObjectClass(System.IntPtr obj) // Offset: 0x2355E88 static System::IntPtr GetObjectClass(System::IntPtr obj); // static public System.Boolean IsInstanceOf(System.IntPtr obj, System.IntPtr clazz) // Offset: 0x2355EC8 static bool IsInstanceOf(System::IntPtr obj, System::IntPtr clazz); // static public System.IntPtr GetMethodID(System.IntPtr clazz, System.String name, System.String sig) // Offset: 0x2355F18 static System::IntPtr GetMethodID(System::IntPtr clazz, ::Il2CppString* name, ::Il2CppString* sig); // static public System.IntPtr GetFieldID(System.IntPtr clazz, System.String name, System.String sig) // Offset: 0x2355F70 static System::IntPtr GetFieldID(System::IntPtr clazz, ::Il2CppString* name, ::Il2CppString* sig); // static public System.IntPtr GetStaticMethodID(System.IntPtr clazz, System.String name, System.String sig) // Offset: 0x2355FC8 static System::IntPtr GetStaticMethodID(System::IntPtr clazz, ::Il2CppString* name, ::Il2CppString* sig); // static public System.IntPtr GetStaticFieldID(System.IntPtr clazz, System.String name, System.String sig) // Offset: 0x2356020 static System::IntPtr GetStaticFieldID(System::IntPtr clazz, ::Il2CppString* name, ::Il2CppString* sig); // static public System.IntPtr NewString(System.String chars) // Offset: 0x2356078 static System::IntPtr NewString(::Il2CppString* chars); // static private System.IntPtr NewStringFromStr(System.String chars) // Offset: 0x23560B8 static System::IntPtr NewStringFromStr(::Il2CppString* chars); // static public System.IntPtr NewString(System.Char[] chars) // Offset: 0x23560F8 static System::IntPtr NewString(::Array<::Il2CppChar>* chars); // static public System.IntPtr NewStringUTF(System.String bytes) // Offset: 0x2356138 static System::IntPtr NewStringUTF(::Il2CppString* bytes); // static public System.String GetStringChars(System.IntPtr str) // Offset: 0x2356178 static ::Il2CppString* GetStringChars(System::IntPtr str); // static public System.Int32 GetStringLength(System.IntPtr str) // Offset: 0x23561B8 static int GetStringLength(System::IntPtr str); // static public System.Int32 GetStringUTFLength(System.IntPtr str) // Offset: 0x23561F8 static int GetStringUTFLength(System::IntPtr str); // static public System.String GetStringUTFChars(System.IntPtr str) // Offset: 0x2356238 static ::Il2CppString* GetStringUTFChars(System::IntPtr str); // static public System.String CallStringMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356278 static ::Il2CppString* CallStringMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.IntPtr CallObjectMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x23562D0 static System::IntPtr CallObjectMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Int32 CallIntMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356328 static int CallIntMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Boolean CallBooleanMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356380 static bool CallBooleanMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Int16 CallShortMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x23563D8 static int16_t CallShortMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Byte CallByteMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356430 static uint8_t CallByteMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.SByte CallSByteMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356488 static int8_t CallSByteMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Char CallCharMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x23564E0 static ::Il2CppChar CallCharMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Single CallFloatMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356538 static float CallFloatMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Double CallDoubleMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356590 static double CallDoubleMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Int64 CallLongMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x23565E8 static int64_t CallLongMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Void CallVoidMethod(System.IntPtr obj, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356640 static void CallVoidMethod(System::IntPtr obj, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.String GetStringField(System.IntPtr obj, System.IntPtr fieldID) // Offset: 0x2356698 static ::Il2CppString* GetStringField(System::IntPtr obj, System::IntPtr fieldID); // static public System.IntPtr GetObjectField(System.IntPtr obj, System.IntPtr fieldID) // Offset: 0x23566E8 static System::IntPtr GetObjectField(System::IntPtr obj, System::IntPtr fieldID); // static public System.Boolean GetBooleanField(System.IntPtr obj, System.IntPtr fieldID) // Offset: 0x2356738 static bool GetBooleanField(System::IntPtr obj, System::IntPtr fieldID); // static public System.Byte GetByteField(System.IntPtr obj, System.IntPtr fieldID) // Offset: 0x2356788 static uint8_t GetByteField(System::IntPtr obj, System::IntPtr fieldID); // static public System.SByte GetSByteField(System.IntPtr obj, System.IntPtr fieldID) // Offset: 0x23567D8 static int8_t GetSByteField(System::IntPtr obj, System::IntPtr fieldID); // static public System.Char GetCharField(System.IntPtr obj, System.IntPtr fieldID) // Offset: 0x2356828 static ::Il2CppChar GetCharField(System::IntPtr obj, System::IntPtr fieldID); // static public System.Int16 GetShortField(System.IntPtr obj, System.IntPtr fieldID) // Offset: 0x2356878 static int16_t GetShortField(System::IntPtr obj, System::IntPtr fieldID); // static public System.Int32 GetIntField(System.IntPtr obj, System.IntPtr fieldID) // Offset: 0x23568C8 static int GetIntField(System::IntPtr obj, System::IntPtr fieldID); // static public System.Int64 GetLongField(System.IntPtr obj, System.IntPtr fieldID) // Offset: 0x2356918 static int64_t GetLongField(System::IntPtr obj, System::IntPtr fieldID); // static public System.Single GetFloatField(System.IntPtr obj, System.IntPtr fieldID) // Offset: 0x2356968 static float GetFloatField(System::IntPtr obj, System::IntPtr fieldID); // static public System.Double GetDoubleField(System.IntPtr obj, System.IntPtr fieldID) // Offset: 0x23569B8 static double GetDoubleField(System::IntPtr obj, System::IntPtr fieldID); // static public System.Void SetStringField(System.IntPtr obj, System.IntPtr fieldID, System.String val) // Offset: 0x2356A08 static void SetStringField(System::IntPtr obj, System::IntPtr fieldID, ::Il2CppString* val); // static public System.Void SetObjectField(System.IntPtr obj, System.IntPtr fieldID, System.IntPtr val) // Offset: 0x2356A60 static void SetObjectField(System::IntPtr obj, System::IntPtr fieldID, System::IntPtr val); // static public System.Void SetBooleanField(System.IntPtr obj, System.IntPtr fieldID, System.Boolean val) // Offset: 0x2356AB8 static void SetBooleanField(System::IntPtr obj, System::IntPtr fieldID, bool val); // static public System.Void SetByteField(System.IntPtr obj, System.IntPtr fieldID, System.Byte val) // Offset: 0x2356B10 static void SetByteField(System::IntPtr obj, System::IntPtr fieldID, uint8_t val); // static public System.Void SetSByteField(System.IntPtr obj, System.IntPtr fieldID, System.SByte val) // Offset: 0x2356B68 static void SetSByteField(System::IntPtr obj, System::IntPtr fieldID, int8_t val); // static public System.Void SetCharField(System.IntPtr obj, System.IntPtr fieldID, System.Char val) // Offset: 0x2356BC0 static void SetCharField(System::IntPtr obj, System::IntPtr fieldID, ::Il2CppChar val); // static public System.Void SetShortField(System.IntPtr obj, System.IntPtr fieldID, System.Int16 val) // Offset: 0x2356C18 static void SetShortField(System::IntPtr obj, System::IntPtr fieldID, int16_t val); // static public System.Void SetIntField(System.IntPtr obj, System.IntPtr fieldID, System.Int32 val) // Offset: 0x2356C70 static void SetIntField(System::IntPtr obj, System::IntPtr fieldID, int val); // static public System.Void SetLongField(System.IntPtr obj, System.IntPtr fieldID, System.Int64 val) // Offset: 0x2356CC8 static void SetLongField(System::IntPtr obj, System::IntPtr fieldID, int64_t val); // static public System.Void SetFloatField(System.IntPtr obj, System.IntPtr fieldID, System.Single val) // Offset: 0x2356D20 static void SetFloatField(System::IntPtr obj, System::IntPtr fieldID, float val); // static public System.Void SetDoubleField(System.IntPtr obj, System.IntPtr fieldID, System.Double val) // Offset: 0x2356D80 static void SetDoubleField(System::IntPtr obj, System::IntPtr fieldID, double val); // static public System.String CallStaticStringMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356DE0 static ::Il2CppString* CallStaticStringMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.IntPtr CallStaticObjectMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356E38 static System::IntPtr CallStaticObjectMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Int32 CallStaticIntMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356E90 static int CallStaticIntMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Boolean CallStaticBooleanMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356EE8 static bool CallStaticBooleanMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Int16 CallStaticShortMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356F40 static int16_t CallStaticShortMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Byte CallStaticByteMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356F98 static uint8_t CallStaticByteMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.SByte CallStaticSByteMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2356FF0 static int8_t CallStaticSByteMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Char CallStaticCharMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2357048 static ::Il2CppChar CallStaticCharMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Single CallStaticFloatMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x23570A0 static float CallStaticFloatMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Double CallStaticDoubleMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x23570F8 static double CallStaticDoubleMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Int64 CallStaticLongMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x2357150 static int64_t CallStaticLongMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.Void CallStaticVoidMethod(System.IntPtr clazz, System.IntPtr methodID, UnityEngine.jvalue[] args) // Offset: 0x23571A8 static void CallStaticVoidMethod(System::IntPtr clazz, System::IntPtr methodID, ::Array<UnityEngine::jvalue>* args); // static public System.String GetStaticStringField(System.IntPtr clazz, System.IntPtr fieldID) // Offset: 0x2357200 static ::Il2CppString* GetStaticStringField(System::IntPtr clazz, System::IntPtr fieldID); // static public System.IntPtr GetStaticObjectField(System.IntPtr clazz, System.IntPtr fieldID) // Offset: 0x2357250 static System::IntPtr GetStaticObjectField(System::IntPtr clazz, System::IntPtr fieldID); // static public System.Boolean GetStaticBooleanField(System.IntPtr clazz, System.IntPtr fieldID) // Offset: 0x23572A0 static bool GetStaticBooleanField(System::IntPtr clazz, System::IntPtr fieldID); // static public System.Byte GetStaticByteField(System.IntPtr clazz, System.IntPtr fieldID) // Offset: 0x23572F0 static uint8_t GetStaticByteField(System::IntPtr clazz, System::IntPtr fieldID); // static public System.SByte GetStaticSByteField(System.IntPtr clazz, System.IntPtr fieldID) // Offset: 0x2357340 static int8_t GetStaticSByteField(System::IntPtr clazz, System::IntPtr fieldID); // static public System.Char GetStaticCharField(System.IntPtr clazz, System.IntPtr fieldID) // Offset: 0x2357390 static ::Il2CppChar GetStaticCharField(System::IntPtr clazz, System::IntPtr fieldID); // static public System.Int16 GetStaticShortField(System.IntPtr clazz, System.IntPtr fieldID) // Offset: 0x23573E0 static int16_t GetStaticShortField(System::IntPtr clazz, System::IntPtr fieldID); // static public System.Int32 GetStaticIntField(System.IntPtr clazz, System.IntPtr fieldID) // Offset: 0x2357430 static int GetStaticIntField(System::IntPtr clazz, System::IntPtr fieldID); // static public System.Int64 GetStaticLongField(System.IntPtr clazz, System.IntPtr fieldID) // Offset: 0x2357480 static int64_t GetStaticLongField(System::IntPtr clazz, System::IntPtr fieldID); // static public System.Single GetStaticFloatField(System.IntPtr clazz, System.IntPtr fieldID) // Offset: 0x23574D0 static float GetStaticFloatField(System::IntPtr clazz, System::IntPtr fieldID); // static public System.Double GetStaticDoubleField(System.IntPtr clazz, System.IntPtr fieldID) // Offset: 0x2357520 static double GetStaticDoubleField(System::IntPtr clazz, System::IntPtr fieldID); // static public System.Void SetStaticStringField(System.IntPtr clazz, System.IntPtr fieldID, System.String val) // Offset: 0x2357570 static void SetStaticStringField(System::IntPtr clazz, System::IntPtr fieldID, ::Il2CppString* val); // static public System.Void SetStaticObjectField(System.IntPtr clazz, System.IntPtr fieldID, System.IntPtr val) // Offset: 0x23575C8 static void SetStaticObjectField(System::IntPtr clazz, System::IntPtr fieldID, System::IntPtr val); // static public System.Void SetStaticBooleanField(System.IntPtr clazz, System.IntPtr fieldID, System.Boolean val) // Offset: 0x2357620 static void SetStaticBooleanField(System::IntPtr clazz, System::IntPtr fieldID, bool val); // static public System.Void SetStaticByteField(System.IntPtr clazz, System.IntPtr fieldID, System.Byte val) // Offset: 0x2357678 static void SetStaticByteField(System::IntPtr clazz, System::IntPtr fieldID, uint8_t val); // static public System.Void SetStaticSByteField(System.IntPtr clazz, System.IntPtr fieldID, System.SByte val) // Offset: 0x23576D0 static void SetStaticSByteField(System::IntPtr clazz, System::IntPtr fieldID, int8_t val); // static public System.Void SetStaticCharField(System.IntPtr clazz, System.IntPtr fieldID, System.Char val) // Offset: 0x2357728 static void SetStaticCharField(System::IntPtr clazz, System::IntPtr fieldID, ::Il2CppChar val); // static public System.Void SetStaticShortField(System.IntPtr clazz, System.IntPtr fieldID, System.Int16 val) // Offset: 0x2357780 static void SetStaticShortField(System::IntPtr clazz, System::IntPtr fieldID, int16_t val); // static public System.Void SetStaticIntField(System.IntPtr clazz, System.IntPtr fieldID, System.Int32 val) // Offset: 0x23577D8 static void SetStaticIntField(System::IntPtr clazz, System::IntPtr fieldID, int val); // static public System.Void SetStaticLongField(System.IntPtr clazz, System.IntPtr fieldID, System.Int64 val) // Offset: 0x2357830 static void SetStaticLongField(System::IntPtr clazz, System::IntPtr fieldID, int64_t val); // static public System.Void SetStaticFloatField(System.IntPtr clazz, System.IntPtr fieldID, System.Single val) // Offset: 0x2357888 static void SetStaticFloatField(System::IntPtr clazz, System::IntPtr fieldID, float val); // static public System.Void SetStaticDoubleField(System.IntPtr clazz, System.IntPtr fieldID, System.Double val) // Offset: 0x23578E8 static void SetStaticDoubleField(System::IntPtr clazz, System::IntPtr fieldID, double val); // static public System.IntPtr ToBooleanArray(System.Boolean[] array) // Offset: 0x2357948 static System::IntPtr ToBooleanArray(::Array<bool>* array); // static public System.IntPtr ToByteArray(System.Byte[] array) // Offset: 0x2357988 static System::IntPtr ToByteArray(::Array<uint8_t>* array); // static public System.IntPtr ToSByteArray(System.SByte[] array) // Offset: 0x23579C8 static System::IntPtr ToSByteArray(::Array<int8_t>* array); // static public System.IntPtr ToCharArray(System.Char[] array) // Offset: 0x2357A08 static System::IntPtr ToCharArray(::Array<::Il2CppChar>* array); // static public System.IntPtr ToShortArray(System.Int16[] array) // Offset: 0x2357A48 static System::IntPtr ToShortArray(::Array<int16_t>* array); // static public System.IntPtr ToIntArray(System.Int32[] array) // Offset: 0x2357A88 static System::IntPtr ToIntArray(::Array<int>* array); // static public System.IntPtr ToLongArray(System.Int64[] array) // Offset: 0x2357AC8 static System::IntPtr ToLongArray(::Array<int64_t>* array); // static public System.IntPtr ToFloatArray(System.Single[] array) // Offset: 0x2357B08 static System::IntPtr ToFloatArray(::Array<float>* array); // static public System.IntPtr ToDoubleArray(System.Double[] array) // Offset: 0x2357B48 static System::IntPtr ToDoubleArray(::Array<double>* array); // static public System.IntPtr ToObjectArray(System.IntPtr[] array, System.IntPtr arrayClass) // Offset: 0x2357B88 static System::IntPtr ToObjectArray(::Array<System::IntPtr>* array, System::IntPtr arrayClass); // static public System.IntPtr ToObjectArray(System.IntPtr[] array) // Offset: 0x2357BD8 static System::IntPtr ToObjectArray(::Array<System::IntPtr>* array); // static public System.Boolean[] FromBooleanArray(System.IntPtr array) // Offset: 0x2357C40 static ::Array<bool>* FromBooleanArray(System::IntPtr array); // static public System.Byte[] FromByteArray(System.IntPtr array) // Offset: 0x2357C80 static ::Array<uint8_t>* FromByteArray(System::IntPtr array); // static public System.SByte[] FromSByteArray(System.IntPtr array) // Offset: 0x2357CC0 static ::Array<int8_t>* FromSByteArray(System::IntPtr array); // static public System.Char[] FromCharArray(System.IntPtr array) // Offset: 0x2357D00 static ::Array<::Il2CppChar>* FromCharArray(System::IntPtr array); // static public System.Int16[] FromShortArray(System.IntPtr array) // Offset: 0x2357D40 static ::Array<int16_t>* FromShortArray(System::IntPtr array); // static public System.Int32[] FromIntArray(System.IntPtr array) // Offset: 0x2357D80 static ::Array<int>* FromIntArray(System::IntPtr array); // static public System.Int64[] FromLongArray(System.IntPtr array) // Offset: 0x2357DC0 static ::Array<int64_t>* FromLongArray(System::IntPtr array); // static public System.Single[] FromFloatArray(System.IntPtr array) // Offset: 0x2357E00 static ::Array<float>* FromFloatArray(System::IntPtr array); // static public System.Double[] FromDoubleArray(System.IntPtr array) // Offset: 0x2357E40 static ::Array<double>* FromDoubleArray(System::IntPtr array); // static public System.IntPtr[] FromObjectArray(System.IntPtr array) // Offset: 0x2357E80 static ::Array<System::IntPtr>* FromObjectArray(System::IntPtr array); // static public System.Int32 GetArrayLength(System.IntPtr array) // Offset: 0x2357EC0 static int GetArrayLength(System::IntPtr array); // static public System.IntPtr NewBooleanArray(System.Int32 size) // Offset: 0x2357F00 static System::IntPtr NewBooleanArray(int size); // static public System.IntPtr NewByteArray(System.Int32 size) // Offset: 0x2357F40 static System::IntPtr NewByteArray(int size); // static public System.IntPtr NewSByteArray(System.Int32 size) // Offset: 0x2357F80 static System::IntPtr NewSByteArray(int size); // static public System.IntPtr NewCharArray(System.Int32 size) // Offset: 0x2357FC0 static System::IntPtr NewCharArray(int size); // static public System.IntPtr NewShortArray(System.Int32 size) // Offset: 0x2358000 static System::IntPtr NewShortArray(int size); // static public System.IntPtr NewIntArray(System.Int32 size) // Offset: 0x2358040 static System::IntPtr NewIntArray(int size); // static public System.IntPtr NewLongArray(System.Int32 size) // Offset: 0x2358080 static System::IntPtr NewLongArray(int size); // static public System.IntPtr NewFloatArray(System.Int32 size) // Offset: 0x23580C0 static System::IntPtr NewFloatArray(int size); // static public System.IntPtr NewDoubleArray(System.Int32 size) // Offset: 0x2358100 static System::IntPtr NewDoubleArray(int size); // static public System.IntPtr NewObjectArray(System.Int32 size, System.IntPtr clazz, System.IntPtr obj) // Offset: 0x2358140 static System::IntPtr NewObjectArray(int size, System::IntPtr clazz, System::IntPtr obj); // static public System.Boolean GetBooleanArrayElement(System.IntPtr array, System.Int32 index) // Offset: 0x2358198 static bool GetBooleanArrayElement(System::IntPtr array, int index); // static public System.Byte GetByteArrayElement(System.IntPtr array, System.Int32 index) // Offset: 0x23581E8 static uint8_t GetByteArrayElement(System::IntPtr array, int index); // static public System.SByte GetSByteArrayElement(System.IntPtr array, System.Int32 index) // Offset: 0x2358238 static int8_t GetSByteArrayElement(System::IntPtr array, int index); // static public System.Char GetCharArrayElement(System.IntPtr array, System.Int32 index) // Offset: 0x2358288 static ::Il2CppChar GetCharArrayElement(System::IntPtr array, int index); // static public System.Int16 GetShortArrayElement(System.IntPtr array, System.Int32 index) // Offset: 0x23582D8 static int16_t GetShortArrayElement(System::IntPtr array, int index); // static public System.Int32 GetIntArrayElement(System.IntPtr array, System.Int32 index) // Offset: 0x2358328 static int GetIntArrayElement(System::IntPtr array, int index); // static public System.Int64 GetLongArrayElement(System.IntPtr array, System.Int32 index) // Offset: 0x2358378 static int64_t GetLongArrayElement(System::IntPtr array, int index); // static public System.Single GetFloatArrayElement(System.IntPtr array, System.Int32 index) // Offset: 0x23583C8 static float GetFloatArrayElement(System::IntPtr array, int index); // static public System.Double GetDoubleArrayElement(System.IntPtr array, System.Int32 index) // Offset: 0x2358418 static double GetDoubleArrayElement(System::IntPtr array, int index); // static public System.IntPtr GetObjectArrayElement(System.IntPtr array, System.Int32 index) // Offset: 0x2358468 static System::IntPtr GetObjectArrayElement(System::IntPtr array, int index); // static public System.Void SetBooleanArrayElement(System.IntPtr array, System.Int32 index, System.Byte val) // Offset: 0x23584B8 static void SetBooleanArrayElement(System::IntPtr array, int index, uint8_t val); // static public System.Void SetBooleanArrayElement(System.IntPtr array, System.Int32 index, System.Boolean val) // Offset: 0x2358514 static void SetBooleanArrayElement(System::IntPtr array, int index, bool val); // static public System.Void SetByteArrayElement(System.IntPtr array, System.Int32 index, System.SByte val) // Offset: 0x235856C static void SetByteArrayElement(System::IntPtr array, int index, int8_t val); // static public System.Void SetSByteArrayElement(System.IntPtr array, System.Int32 index, System.SByte val) // Offset: 0x23585C4 static void SetSByteArrayElement(System::IntPtr array, int index, int8_t val); // static public System.Void SetCharArrayElement(System.IntPtr array, System.Int32 index, System.Char val) // Offset: 0x235861C static void SetCharArrayElement(System::IntPtr array, int index, ::Il2CppChar val); // static public System.Void SetShortArrayElement(System.IntPtr array, System.Int32 index, System.Int16 val) // Offset: 0x2358674 static void SetShortArrayElement(System::IntPtr array, int index, int16_t val); // static public System.Void SetIntArrayElement(System.IntPtr array, System.Int32 index, System.Int32 val) // Offset: 0x23586CC static void SetIntArrayElement(System::IntPtr array, int index, int val); // static public System.Void SetLongArrayElement(System.IntPtr array, System.Int32 index, System.Int64 val) // Offset: 0x2358724 static void SetLongArrayElement(System::IntPtr array, int index, int64_t val); // static public System.Void SetFloatArrayElement(System.IntPtr array, System.Int32 index, System.Single val) // Offset: 0x235877C static void SetFloatArrayElement(System::IntPtr array, int index, float val); // static public System.Void SetDoubleArrayElement(System.IntPtr array, System.Int32 index, System.Double val) // Offset: 0x23587DC static void SetDoubleArrayElement(System::IntPtr array, int index, double val); // static public System.Void SetObjectArrayElement(System.IntPtr array, System.Int32 index, System.IntPtr obj) // Offset: 0x235883C static void SetObjectArrayElement(System::IntPtr array, int index, System::IntPtr obj); }; // UnityEngine.AndroidJNI #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(UnityEngine::AndroidJNI*, "UnityEngine", "AndroidJNI");
65.897287
134
0.736141
darknight1050
a1b651f13299bddcad47a84b23b7ef1e5c2a3f46
3,006
cpp
C++
calc.cpp
ShotaIuchi/InfiniteCalculator
70f40f50b2bb7265cfe8fdb2532796f978b61c7d
[ "MIT" ]
null
null
null
calc.cpp
ShotaIuchi/InfiniteCalculator
70f40f50b2bb7265cfe8fdb2532796f978b61c7d
[ "MIT" ]
null
null
null
calc.cpp
ShotaIuchi/InfiniteCalculator
70f40f50b2bb7265cfe8fdb2532796f978b61c7d
[ "MIT" ]
null
null
null
#include "util.hpp" #include "calc.hpp" #include <iostream> namespace ic { std::string calcAddition(std::vector<std::string>& argValue) { std::vector<std::vector<int>> value; for (const std::string v : argValue) { value.push_back(str2vec(rstring(v))); } std::vector<int> anser; int moveUp = 0; for (int i=0;; ++i) { bool isFix = true; int add = moveUp; for (std::vector<int> v : value) { if (i < v.size()) { add += v[i]; isFix = false; } } if (isFix && (add <= 0)) { break; } else { moveUp = add / 10; anser.push_back((add % 10)); } } return rstring(vec2str(anser)); } std::string calcSubtraction(std::string argValue1, std::string argValue2) { std::vector<int> bvalue1 = str2vec(rstring(argValue1)); std::vector<int> bvalue2 = str2vec(rstring(argValue2)); std::vector<int> value1, value2; // value1 >= value2 if (largeLeft(bvalue1, bvalue2)) { value1 = bvalue1; value2 = bvalue2; } else { value1 = bvalue2; value2 = bvalue1; } // calc std::vector<int> anser; int moveDown = 0; for (int i=0;; ++i) { if (i >= value1.size()) { // (value1>=value2)より繰り下がり考慮不要 break; } else { // 減算 int value = value1[i] - moveDown; if (i < value2.size()) { value -= value2[i]; } // 繰り下がり考慮 moveDown = 0; if (value < 0) { moveDown = 1; value += 10; } anser.push_back(value); } } // 頭の0削除 // 1の位は必要なので削除しない for (int i=anser.size()-1; i>=1; --i) { if (anser[i] == 0) { anser.pop_back(); } else { break; } } // 負数考慮 if (largeLeft(bvalue1, bvalue2)) { return rstring(vec2str(anser)); } else { return "-" + rstring(vec2str(anser)); } } std::string calcMultiplication(std::string argValue1, std::string argValue2) { std::vector<int> value1 = str2vec(rstring(argValue1)); std::vector<int> value2 = str2vec(rstring(argValue2)); std::vector<std::string> value; int c = 0; for (int v1 : value1) { int moveUp = 0; std::vector<int> t; // 桁上げ for (int i=0; i<c; ++i) { t.push_back(0); } c++; // 乗算 for (int v2 : value2) { int a = v1 * v2 + moveUp; moveUp = a / 10; t.push_back((a % 10)); } // 終わりに繰り上げ値考慮 // 繰り上げ値の最大は8(9*9の10の位)となるため再度の繰り上げ考慮は不要 if (0 < moveUp) { t.push_back(moveUp); } value.push_back(rstring(vec2str(t))); } return calcAddition(value); } std::string calcDivision(std::string value1, std::string value2) { std::string x; return x; } }
24.241935
78
0.482369
ShotaIuchi
a1b6fa7e08eb99f9d698a63f7d3e5f136e453dce
22,803
cpp
C++
Cpp/acc bridge.cpp
alexfordc/Au
9253f0716fca6aa93d0acc61d45df911bdfb0fe9
[ "MIT" ]
1
2020-04-17T12:25:07.000Z
2020-04-17T12:25:07.000Z
Cpp/acc bridge.cpp
alexfordc/Au
9253f0716fca6aa93d0acc61d45df911bdfb0fe9
[ "MIT" ]
null
null
null
Cpp/acc bridge.cpp
alexfordc/Au
9253f0716fca6aa93d0acc61d45df911bdfb0fe9
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "cpp.h" #include "acc.h" HRESULT AccFind(AccFindCallback& callback, HWND w, Cpp_Acc* aParent, const Cpp_AccParams& ap, eAF2 flags2, out BSTR& errStr); HRESULT AccFromPoint(POINT p, int flags, int specWnd, out Cpp_Acc& aResult); HRESULT AccNavigate(Cpp_Acc aFrom, STR navig, out Cpp_Acc& aResult); HRESULT AccGetProp(Cpp_Acc a, WCHAR what, out BSTR& sResult); namespace { #pragma region marshal //Used for marshaling 'find AO' (IPA_AccFind) parameters when calling the get_accHelpTopic hook function. //A flat variable-size memory structure (strings follow the fixed-size part). struct MarshalParams_AccFind { struct _FlatStr { int offs, len; }; MarshalParams_Header hdr; int hwnd; //not HWND, because it must be of same size in 32 and 64 bit process eAF2 flags2; private: //these are the same as Cpp_AccParams, except is used int instead of STR. Cannot use STR because its size can be 32 or 64 bit. _FlatStr _role, _name, _prop; eAF _flags; int _skip; WCHAR _resultProp; LPWSTR _SetString(STR s, int len, LPWSTR dest, out _FlatStr& r) { if(!s) { r.len = r.offs = 0; return dest; } memcpy(dest, s, len * 2); dest[len] = 0; r.offs = (int)(dest - (STR)this); r.len = len; return dest + len + 1; } STR _GetString(_FlatStr r, out int& len) { len = r.len; if(!r.offs) return null; return (STR)this + r.offs; } public: static int CalcMemSize(const Cpp_AccParams& ap) { return sizeof(MarshalParams_AccFind) + (ap.roleLength + ap.nameLength + ap.propLength + 3) * 2; } void Marshal(HWND w, const Cpp_AccParams& ap, eAF2 flags2_) { hwnd = (int)(LPARAM)w; flags2 = flags2_; auto s = (LPWSTR)(this + 1); s = _SetString(ap.role, ap.roleLength, s, out _role); s = _SetString(ap.name, ap.nameLength, s, out _name); s = _SetString(ap.prop, ap.propLength, s, out _prop); _flags = ap.flags; _skip = ap.skip; _resultProp = ap.resultProp; } void Unmarshal(out Cpp_AccParams& ap) { ap.role = _GetString(_role, out ap.roleLength); ap.name = _GetString(_name, out ap.nameLength); ap.prop = _GetString(_prop, out ap.propLength); ap.flags = _flags; ap.skip = _skip; ap.resultProp = _resultProp; } }; static long s_accMarshalWrapperCount; //static CSimpleArray<IUnknown*> s_accMarshalWrappers; //static concurrency::critical_section s_cs1; //Workaround for Firefox bug in TEXT AOs in multi-process mode. class AccessibleMarshalWrapper : public IAccessible { IAccessible* _a; public: bool ignoreQI; AccessibleMarshalWrapper(IAccessible* a) { _a = a;//SHOULDDO: try to addref/release, maybe it will solve the WindowFromAccessibleObject problem for LINK in drag&dropped FF tab window ignoreQI = true; InterlockedIncrement(&s_accMarshalWrapperCount); //concurrency::critical_section::scoped_lock sl(s_cs1); //s_accMarshalWrappers.Add(this); } ~AccessibleMarshalWrapper() { InterlockedDecrement(&s_accMarshalWrapperCount); //concurrency::critical_section::scoped_lock sl(s_cs1); //s_accMarshalWrappers.Remove(this); } static bool Disconnect() { //This process would crash later when releasing wrappers if this dll is unloaded then. #if true //Don't allow to unload this dll if there are unreleased wrappers. return s_accMarshalWrapperCount == 0; #else //Disconnect unreleased acc wrappers. If fails don't allow to unload this dll. //Does not work as expected. Just increments dll refcount, and then FreeLibraryAndExitThread does not unload it. Later is called Release(). concurrency::critical_section::scoped_lock sl(s_cs1); int n = s_accMarshalWrappers.GetSize(); //PRINTI(n); if(n == 0) return true; bool failed = false; for(int i = 0; i < n; i++) { if(s_accMarshalWrappers[i] == null) continue; int hr = CoDisconnectObject(s_accMarshalWrappers[i], 0); if(hr != 0) { PRINTF(L"CoDisconnectObject, 0x%x", hr); failed = true; break; } s_accMarshalWrappers[i] = null; } if(!failed) s_accMarshalWrappers.RemoveAll(); return !failed; #endif } virtual STDMETHODIMP QueryInterface(REFIID riid, void ** ppvObject) override { if(riid == IID_IAccessible || riid == IID_IUnknown || riid == IID_IDispatch) { _a->AddRef(); *ppvObject = this; return 0; //Firefox bug: TEXT AOs return E_NOINTERFACE for IID_IUnknown, that is why CoMarshalInterface fails. // Also they don't give custom IMarshal, although all other AOs do. } if(ignoreQI) { //don't give IMarshal and other interfaces while in CoMarshalInterface *ppvObject = null; return E_NOINTERFACE; } return _a->QueryInterface(riid, ppvObject); } virtual STDMETHODIMP_(ULONG) AddRef(void) override { return _a->AddRef(); } virtual STDMETHODIMP_(ULONG) Release(void) override { auto r = _a->Release(); //Print((int)r); if(r == 0) delete this; return r; } #pragma region virtual STDMETHODIMP GetTypeInfoCount(UINT * pctinfo) override { return E_NOTIMPL; } virtual STDMETHODIMP GetTypeInfo(UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo) override { return E_NOTIMPL; } virtual STDMETHODIMP GetIDsOfNames(REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId) override { return E_NOTIMPL; } virtual STDMETHODIMP Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr) override { return E_NOTIMPL; } virtual STDMETHODIMP get_accParent(IDispatch ** ppdispParent) override { return _a->get_accParent(ppdispParent); } virtual STDMETHODIMP get_accChildCount(long * pcountChildren) override { return _a->get_accChildCount(pcountChildren); } virtual STDMETHODIMP get_accChild(VARIANT varChild, IDispatch ** ppdispChild) override { return _a->get_accChild(varChild, ppdispChild); } virtual STDMETHODIMP get_accName(VARIANT varChild, BSTR * pszName) override { return _a->get_accName(varChild, pszName); } virtual STDMETHODIMP get_accValue(VARIANT varChild, BSTR * pszValue) override { return _a->get_accValue(varChild, pszValue); } virtual STDMETHODIMP get_accDescription(VARIANT varChild, BSTR * pszDescription) override { return _a->get_accDescription(varChild, pszDescription); } virtual STDMETHODIMP get_accRole(VARIANT varChild, VARIANT * pvarRole) override { return _a->get_accRole(varChild, pvarRole); } virtual STDMETHODIMP get_accState(VARIANT varChild, VARIANT * pvarState) override { return _a->get_accState(varChild, pvarState); } virtual STDMETHODIMP get_accHelp(VARIANT varChild, BSTR * pszHelp) override { return _a->get_accHelp(varChild, pszHelp); } virtual STDMETHODIMP get_accHelpTopic(BSTR * pszHelpFile, VARIANT varChild, long * pidTopic) override { return E_NOTIMPL; } virtual STDMETHODIMP get_accKeyboardShortcut(VARIANT varChild, BSTR * pszKeyboardShortcut) override { return _a->get_accKeyboardShortcut(varChild, pszKeyboardShortcut); } virtual STDMETHODIMP get_accFocus(VARIANT * pvarChild) override { return _a->get_accFocus(pvarChild); } virtual STDMETHODIMP get_accSelection(VARIANT * pvarChildren) override { return _a->get_accSelection(pvarChildren); } virtual STDMETHODIMP get_accDefaultAction(VARIANT varChild, BSTR * pszDefaultAction) override { return _a->get_accDefaultAction(varChild, pszDefaultAction); } virtual STDMETHODIMP accSelect(long flagsSelect, VARIANT varChild) override { return _a->accSelect(flagsSelect, varChild); } virtual STDMETHODIMP accLocation(long * pxLeft, long * pyTop, long * pcxWidth, long * pcyHeight, VARIANT varChild) override { return _a->accLocation(pxLeft, pyTop, pcxWidth, pcyHeight, varChild); } virtual STDMETHODIMP accNavigate(long navDir, VARIANT varStart, VARIANT * pvarEndUpAt) override { return _a->accNavigate(navDir, varStart, pvarEndUpAt); } virtual STDMETHODIMP accHitTest(long xLeft, long yTop, VARIANT * pvarChild) override { return _a->accHitTest(xLeft, yTop, pvarChild); } virtual STDMETHODIMP accDoDefaultAction(VARIANT varChild) override { return _a->accDoDefaultAction(varChild); } virtual STDMETHODIMP put_accName(VARIANT varChild, BSTR szName) override { return _a->put_accName(varChild, szName); } virtual STDMETHODIMP put_accValue(VARIANT varChild, BSTR szValue) override { return _a->put_accValue(varChild, szValue); } #pragma endregion }; //The BSTR returned by our get_accHelpTopic hook contains data of one or more accessible objects (AO). // Each AO data can have IAccessible object data (created by CoMarshalInterface), child element id, level, role. // These flags tell what is in the data. //[Flags] enum class eAccResult { Elem = 1, Role = 4, Level = 8, UsePrevAcc = 0x10, UsePrevLevel = 0x20, }; ENABLE_BITMASK_OPERATORS(eAccResult); bool WriteAccToStream(ref Smart<IStream>& stream, Cpp_Acc a, Cpp_Acc* aPrev = null) { if(stream == null) CreateStreamOnHGlobal(0, true, &stream); eAccResult has = (eAccResult)0; if(aPrev != null) { if(a.acc == aPrev->acc && a.elem != 0) has |= eAccResult::UsePrevAcc; else aPrev->acc = a.acc; if(a.misc.level != 0) has |= a.misc.level == aPrev->misc.level ? eAccResult::UsePrevLevel : eAccResult::Level; aPrev->misc.level = a.misc.level; } else { if(a.misc.level != 0) has |= eAccResult::Level; } if(a.elem != 0) has |= eAccResult::Elem; if(a.misc.role != 0) has |= eAccResult::Role; //problem: with some AO the hook is not called when we try to do something inproc, eg get all props. // They use a custom IMarshal, which redirects to another (not hooked) IAccessible interface. In most cases it is even in another process. // Workaround: don't add InProc flag. With all known such apps it does not make faster anyway. // Known apps: 1. Firefox, when multiprocess not disabled. 2. Some hidden AO in IE. 3. Windows store apps, but we don't use inproc. // Known apps where is custom IMarshal but the hook works: 1. Task Scheduler MMC: controls of other process. // Other workarounds: // Tested, fails: replace CoMarshalInterface with CoGetStandardMarshal/MarshalInterface. Chrome works, Firefox crashes. // Not tested: wrap the AO in our AO (like we do with Java and UIA). Makes no sense, just would make slower. IMarshal* m = null; if(0 == a.acc->QueryInterface(&m)) { m->Release(); a.misc.flags &= ~eAccMiscFlags::InProc; //PRINTS(L"custom IMarshal. Using NotInProc."); } else { a.misc.flags |= eAccMiscFlags::InProc; //PRINTS(L"standard IMarshal."); } if(stream->Write(&has, 1, null)) return false; if(!(has&eAccResult::UsePrevAcc)) { HRESULT hr = CoMarshalInterface(stream, IID_IAccessible, a.acc, MSHCTX_LOCAL, null, MSHLFLAGS_NORMAL); //ao::PrintAcc(a.acc, a.elem); if(hr) { //Firefox bug when multi-process: fails to marshal all TEXT AOs. // Workaround: wrap a.acc into an AccessibleMarshalWrapper and marshal it instead. // Or could detect Firefox multi-process and use NotInProc implicitly. But slower almost 2 times. Also then cannot get HTML attributes etc later. #if true HRESULT hr1 = hr; auto wrap = new AccessibleMarshalWrapper(a.acc); a.acc = wrap; hr = CoMarshalInterface(stream, IID_IAccessible, a.acc, MSHCTX_LOCAL, null, MSHLFLAGS_NORMAL); if(hr == 0) wrap->ignoreQI = false; else delete wrap; //Print((UINT)hr); if(hr) PRINTF(L"failed to marshal AO: 0x%X 0x%X", hr1, hr); #endif //ao::PrintAcc(a.acc, a.elem); } //else Print(L"OK"); if(hr) return false; inproc::s_hookIAcc.Hook(a.acc); } if(!!(has&eAccResult::Elem)) if(stream->Write(&a.elem, 4, null)) return false; if(stream->Write(&a.misc.flags, 1, null)) return false; if(!!(has&eAccResult::Role)) if(stream->Write(&a.misc.role, 1, null)) return false; if(!!(has&eAccResult::Level)) if(stream->Write(&a.misc.level, 2, null)) return false; return true; } #pragma endregion } //namespace namespace inproc { //Called from the hook to find or get AO. //Common for Cpp_AccFind, Cpp_AccFromWindow and other functions that return AO. HRESULT AccFindOrGet(MarshalParams_Header* h, IAccessible* iacc, out BSTR& sResult) { Smart<IStream> stream; auto action = h->action; if(action == InProcAction::IPA_AccNavigate) { auto p = (MarshalParams_AccElem*)h; Cpp_Acc aFrom(iacc, p->elem, h->miscFlags), aResult; HRESULT hr = AccNavigate(aFrom, (STR)(p + 1), out aResult); if(hr) return hr; aResult.SetRole(); if(!WriteAccToStream(ref stream, aResult)) return RPC_E_SERVER_CANTMARSHAL_DATA; if(aResult.acc != iacc) aResult.acc->Release(); } else if(action == InProcAction::IPA_AccFromWindow) { auto p = (MarshalParams_AccFromWindow*)h; Smart<IAccessible> a; HRESULT hr = ao::AccFromWindowSR((HWND)(LPARAM)p->hwnd, p->objid, &a); if(hr) return hr; if(p->flags & 2) { //get name return a->get_accName(ao::VE(), out &sResult); } Cpp_Acc aResult(a, 0); aResult.SetRole(); if(!WriteAccToStream(ref stream, aResult)) return RPC_E_SERVER_CANTMARSHAL_DATA; } else if(action == InProcAction::IPA_AccFromPoint) { auto x = (MarshalParams_AccFromPoint*)h; Cpp_Acc aResult; HRESULT hr = AccFromPoint(x->p, x->flags, x->specWnd, out aResult); if(hr) return hr; if(!WriteAccToStream(ref stream, aResult)) return RPC_E_SERVER_CANTMARSHAL_DATA; } else { //IPA_AccFind Cpp_AccParams ap; auto p = (MarshalParams_AccFind*)h; p->Unmarshal(out ap); HWND w = (HWND)(LPARAM)p->hwnd; eAF2 flags2 = p->flags2; bool findAll = !!(flags2&eAF2::FindAll); auto resultProp = ap.resultProp; HRESULT hr = (HRESULT)eError::NotFound; Cpp_Acc aParent(iacc, 0, h->miscFlags), aPrev; HRESULT hr2 = AccFind( [&hr, &stream, &aPrev, resultProp, findAll, skip = ap.skip, &sResult](Cpp_Acc a) mutable { if(!findAll && skip-- > 0) return eAccFindCallbackResult::Continue; if(resultProp) { if(resultProp != '-') AccGetProp(a, resultProp, out sResult); } else { if(!stream) CreateStreamOnHGlobal(0, true, &stream); DWORD pos = 0; if(findAll) istream::GetPos(stream, out pos); if(!WriteAccToStream(ref stream, a, &aPrev)) { if(!findAll) goto ge; stream->Seek(istream::LI(pos), STREAM_SEEK_SET, null); } } hr = 0; return findAll ? eAccFindCallbackResult::Continue : eAccFindCallbackResult::StopFound; ge: hr = RPC_E_SERVER_CANTMARSHAL_DATA; return eAccFindCallbackResult::StopNotFound; }, w, w ? null : &aParent, ref ap, flags2, out sResult); if(hr2 && hr2 != (HRESULT)eError::NotFound) return hr2; if(hr) return hr; if(resultProp) return 0; } DWORD streamSize, readSize; if(istream::GetPos(stream, out streamSize) && istream::ResetPos(stream)) { sResult = SysAllocStringByteLen(null, streamSize); if(0 == stream->Read(sResult, streamSize, &readSize) && readSize == streamSize) return 0; SysFreeString(sResult); sResult = null; } return RPC_E_SERVER_CANTMARSHAL_DATA; } bool AccDisconnectWrappers() { return AccessibleMarshalWrapper::Disconnect(); } } //namespace inproc namespace outproc { //Reads one AO from results. //When FindAll, the caller must call this in loop, until returns a non-zero. If returns NotFound, there are no more AO to read. //a - receives the AO, elem, etc. When FindAll, the caller must use the same variable for all, because this function uses it as an input parameter too (previous AO). //dontNeedAO - don't need AO. Only release marshal data if need. HRESULT InProcCall::ReadResultAcc(ref Cpp_Acc& a, bool dontNeedAO/* = false*/) { if(!_stream) { _resultSize = _br.ByteLength(); if(_resultSize == 0) return RPC_E_CLIENT_CANTUNMARSHAL_DATA; HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, _resultSize); if(hg == 0) return RPC_E_CLIENT_CANTUNMARSHAL_DATA; LPVOID mem = GlobalLock(hg); memcpy(mem, _br, _resultSize); GlobalUnlock(mem); CreateStreamOnHGlobal(hg, true, &_stream); //Print(_resultSize); } DWORD pos; if(istream::GetPos(_stream, out pos) && pos == _resultSize) return (HRESULT)eError::NotFound; //no more results when FindAll. Fast. eAccResult has=(eAccResult)0; if(0 != _stream->Read(&has, 1, null)) return RPC_E_CLIENT_CANTUNMARSHAL_DATA; if(!(has&eAccResult::UsePrevAcc)) { HRESULT hr; if(dontNeedAO) { //Perf.First(); hr = CoReleaseMarshalData(_stream); //Perf.NW(); //slow, because calls Release in the server process a.acc = null; } else { hr = CoUnmarshalInterface(_stream, IID_IAccessible, (void**)&a.acc); } if(hr) return RPC_E_CLIENT_CANTUNMARSHAL_DATA; } else if(!dontNeedAO) { assert(!!(has&eAccResult::Elem)); a.acc->AddRef(); } if(!(has&eAccResult::Elem)) a.elem = 0; else if(_stream->Read(&a.elem, 4, null)) return RPC_E_CLIENT_CANTUNMARSHAL_DATA; if(_stream->Read(&a.misc.flags, 1, null)) return RPC_E_CLIENT_CANTUNMARSHAL_DATA; if(!(has&eAccResult::Role)) a.misc.role = 0; else if(_stream->Read(&a.misc.role, 1, null)) return RPC_E_CLIENT_CANTUNMARSHAL_DATA; if(!(has&eAccResult::UsePrevLevel)) { if(!(has&eAccResult::Level)) a.misc.level = 0; else if(_stream->Read(&a.misc.level, 2, null)) return RPC_E_CLIENT_CANTUNMARSHAL_DATA; } return 0; } //Gets AO of window (calls AccessibleObjectFromWindow). //flags: // 1 - not inproc. If used this flag, or if failed to inject dll, the returned AO will not be suitable for in-proc search. // 2 - get name instead. Results: aResult = empty, sResult = name. EXPORT HRESULT Cpp_AccFromWindow(DWORD flags, HWND w, DWORD objid, out Cpp_Acc& aResult, out BSTR& sResult) { aResult.Zero(); sResult = null; if(objid == OBJID_JAVA) { auto iacc = AccJavaFromWindow(w); if(iacc == null) return 1; aResult.acc = iacc; aResult.misc.flags = eAccMiscFlags::Java; return 0; } else if(objid == OBJID_UIA) { HRESULT hr = AccUiaFromWindow(w, &aResult.acc); if(hr == 0) aResult.misc.flags = eAccMiscFlags::UIA; return hr; //never mind: inproc. Maybe in the future. } HRESULT R; g1: if(flags & 1) { //not inproc R = ao::AccFromWindowSR(w, objid, &aResult.acc); if(R == 0 && flags & 2) { R = aResult.acc->get_accName(ao::VE(), out &sResult); aResult.acc->Release(); aResult.acc = null; } return R; } //Perf.First(); Cpp_Acc aAgent; if(R = InjectDllAndGetAgent(w, out aAgent.acc)) { switch((eError)R) { case eError::WindowOfThisThread: case eError::UseNotInProc: case eError::Inject: break; default: return R; } flags |= 1; goto g1; } //Perf.Next(); InProcCall c; auto p = (MarshalParams_AccFromWindow*)c.AllocParams(&aAgent, InProcAction::IPA_AccFromWindow, sizeof(MarshalParams_AccFromWindow)); p->hwnd = (int)(LPARAM)w; p->objid = objid; p->flags = flags; if(R = c.Call()) return R; //Perf.Next(); if(flags & 2) sResult = c.DetachResultBSTR(); else R = c.ReadResultAcc(ref aResult); //Perf.NW(); return R; } //Finds a descendant AO of w or aParent. //By default searches in the target process. If flag NotInProc (or if cannot inject), searches from this process (slow); then the returned AO will not be suitable for in-proc search. //w - parent window or 0 (if aParent used). //aParent - parent AO or null (if w used). Must be retrieved in-proc. //ap - AO parameters. //also - if not null, this func calls the callback function for each matching AO. // Need to Release the AO, preferably later, maybe in another thread. // If the callback returns true, it is not called again (unless 'skip' is used), and this function returns 0 (found). // If the callback always returns false, this function returns eError::NotFound. //aResult - receives the found AO (if this function returns 0 (found)). // Need to Release. // If used 'also', it can be the same AO as the callback received the last time. Need to Release both. // It is empty if this func returns not 0 or if used ap.resultProp. //sResult - error string or a property of the found AO. // When this func returns eError::InvalidParameter, it is error string. // When this func returns 0 and used ap.resultProp, it is the property (string, or binary struct); null if '-'. // Else null. EXPORT HRESULT Cpp_AccFind(HWND w, Cpp_Acc* aParent, const Cpp_AccParams& ap, Cpp_AccCallbackT also, out Cpp_Acc& aResult, out BSTR& sResult) { //Perf.First(); aResult.Zero(); sResult = null; bool inProc = !(ap.flags&eAF::NotInProc), findAll = (also != null), useWnd = (aParent == null); eAF2 flags2 = findAll ? eAF2::FindAll : (eAF2)0; HRESULT R; assert(!!w == !aParent); assert(!ap.resultProp || !findAll); if(useWnd) { //If role has prefix "web:" and w is IE, need to find the web browser control at first, because it's in a different process than IE. //We cannot detect IE by window class name. It can be any, because IE-based web browser controls can be used anywhere. //To detect it, we look for an "Internet Explorer_Server" control. //If it is Firefox or Chrome, this makes slightly slower. if(ap.roleLength >= 4 && CMP4(ap.role, L"web:")) { HWND wIES = wnd::FindChildByClassName(w, c_IES, true); if(wIES) { w = wIES; flags2 |= eAF2::InIES; } } } Cpp_Acc aAgent; if(inProc && useWnd) { IAccessible* iagent = null; if(R = InjectDllAndGetAgent(w, out iagent)) { switch((eError)R) { case eError::WindowOfThisThread: case eError::UseNotInProc: case eError::Inject: break; default: return R; } inProc = false; } else { aAgent.acc = iagent; aParent = &aAgent; } //Perf.Next(); } if(inProc) { InProcCall c; auto sizeofParams = MarshalParams_AccFind::CalcMemSize(ref ap); auto p = (MarshalParams_AccFind*)c.AllocParams(aParent, InProcAction::IPA_AccFind, sizeofParams); p->Marshal(useWnd ? w : 0, ref ap, flags2); if(R = c.Call()) { if(R == (HRESULT)eError::InvalidParameter) sResult = c.DetachResultBSTR(); } else if(!findAll) { if(!ap.resultProp) R = c.ReadResultAcc(ref aResult); else if(ap.resultProp != '-') sResult = c.DetachResultBSTR(); } else { Cpp_Acc a; int skip = ap.skip; for(;;) { R = c.ReadResultAcc(ref a); if(R) break; //NotFound when end of stream if(!also(a)) continue; //must Release u.acc, preferably later if(skip-- == 0) { a.acc->AddRef(); aResult = a; break; } } //release the marshal data of remaining AO for(auto k = R; k == 0; ) k = c.ReadResultAcc(ref a, true); } //Perf.Next(); } else { flags2 |= eAF2::NotInProc; bool found = false; R = AccFind( [&found, &aResult, &sResult, &ap, skip = ap.skip, also](Cpp_Acc a) mutable { if(also) { a.acc->AddRef(); //of proxy (fast) if(!also(a)) return eAccFindCallbackResult::Continue; } if(skip-- > 0) return eAccFindCallbackResult::Continue; found = true; if(ap.resultProp) { if(ap.resultProp != '-') AccGetProp(a, ap.resultProp, out sResult); } else { aResult = a; a.acc->AddRef(); } return eAccFindCallbackResult::StopFound; }, w, aParent, ref ap, flags2, out sResult); if(!R && !found) R = (HRESULT)eError::NotFound; } //Perf.NW(); return R; } } //namespace outproc
34.445619
184
0.710784
alexfordc
a1bbcdb67eb60c99e1b459019c6796eb7c9079c4
1,026
hpp
C++
samples/WindowsVulkan/gli/sampler.hpp
dnikolaidis2/optick
9c692bca0d542c768eb02db8f81f44d57f626e55
[ "MIT" ]
1,711
2019-04-15T16:39:00.000Z
2022-03-31T22:06:38.000Z
samples/WindowsVulkan/gli/sampler.hpp
dnikolaidis2/optick
9c692bca0d542c768eb02db8f81f44d57f626e55
[ "MIT" ]
113
2019-12-14T04:28:04.000Z
2021-09-26T18:40:27.000Z
samples/WindowsVulkan/gli/sampler.hpp
dnikolaidis2/optick
9c692bca0d542c768eb02db8f81f44d57f626e55
[ "MIT" ]
172
2019-04-23T05:08:55.000Z
2022-03-31T17:30:35.000Z
/// @brief Include to use wrap modes and the sampler base class. /// @file gli/sampler.hpp #pragma once #include "core/filter.hpp" namespace gli { /// Texture coordinate wrapping mode enum wrap { WRAP_CLAMP_TO_EDGE, WRAP_FIRST = WRAP_CLAMP_TO_EDGE, WRAP_CLAMP_TO_BORDER, WRAP_REPEAT, WRAP_MIRROR_REPEAT, WRAP_MIRROR_CLAMP_TO_EDGE, WRAP_MIRROR_CLAMP_TO_BORDER, WRAP_LAST = WRAP_MIRROR_CLAMP_TO_BORDER }; enum { WRAP_COUNT = WRAP_LAST - WRAP_FIRST + 1 }; /// Evaluate whether the texture coordinate wrapping mode relies on border color inline bool is_border(wrap Wrap) { return Wrap == WRAP_CLAMP_TO_BORDER || Wrap == WRAP_MIRROR_CLAMP_TO_BORDER; } /// Genetic sampler class. class sampler { public: sampler(wrap Wrap, filter Mip, filter Min); virtual ~sampler() = default; protected: typedef float(*wrap_type)(float const & SamplerCoord); wrap_type get_func(wrap WrapMode) const; wrap_type Wrap; filter Mip; filter Min; }; }//namespace gli #include "./core/sampler.inl"
20.117647
81
0.736842
dnikolaidis2
a1bd8ab1dd1325d2463e238f4adaf256adb75913
41,525
cc
C++
tensorflow/core/kernels/sdca_ops.cc
topsun888/tensorflow
bad7c50b9dc9789ad7dd0a62daca40b7269841ed
[ "Apache-2.0" ]
2
2019-07-05T15:17:01.000Z
2020-04-16T07:25:56.000Z
tensorflow/core/kernels/sdca_ops.cc
topsun888/tensorflow
bad7c50b9dc9789ad7dd0a62daca40b7269841ed
[ "Apache-2.0" ]
1
2021-04-12T03:51:59.000Z
2021-04-12T03:51:59.000Z
tensorflow/core/kernels/sdca_ops.cc
topsun888/tensorflow
bad7c50b9dc9789ad7dd0a62daca40b7269841ed
[ "Apache-2.0" ]
5
2018-02-27T00:34:23.000Z
2022-02-28T16:38:08.000Z
/* Copyright 2016 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. ==============================================================================*/ // See docs in ./ops/sdca_ops.cc. #define EIGEN_USE_THREADS #include <stddef.h> #include <atomic> #include <cmath> #include <functional> #include <limits> #include <string> #include <unordered_set> #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/device_base.h" #include "tensorflow/core/framework/kernel_def_builder.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_def_builder.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/hinge-loss.h" #include "tensorflow/core/kernels/logistic-loss.h" #include "tensorflow/core/kernels/smooth-hinge-loss.h" #include "tensorflow/core/kernels/squared-loss.h" #include "tensorflow/core/lib/core/coding.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/core/stringpiece.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/lib/hash/hash.h" #include "tensorflow/core/lib/random/distribution_sampler.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/fingerprint.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/guarded_philox_random.h" #include "tensorflow/core/util/sparse/group_iterator.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" #include "tensorflow/core/util/work_sharder.h" namespace tensorflow { namespace { using UnalignedFloatVector = TTypes<const float>::UnalignedConstVec; using UnalignedInt64Vector = TTypes<const int64>::UnalignedConstVec; // Statistics computed with input (ModelWeights, Example). struct ExampleStatistics { // feature_weights dot feature_values for the example. double wx = 0; // dot product using the previous weights double prev_wx = 0; // sum of squared feature values occurring in the example divided by // L2 * sum(example_weights). double normalized_squared_norm = 0; }; class Regularizations { public: Regularizations(){}; // Initialize() must be called immediately after construction. Status Initialize(OpKernelConstruction* const context) { TF_RETURN_IF_ERROR(context->GetAttr("l1", &symmetric_l1_)); TF_RETURN_IF_ERROR(context->GetAttr("l2", &symmetric_l2_)); shrinkage_ = symmetric_l1_ / symmetric_l2_; return Status::OK(); } // Proximal SDCA shrinking for L1 regularization. double Shrink(const double weight) const { const double shrinked = std::max(std::abs(weight) - shrinkage_, 0.0); if (shrinked > 0.0) { return std::copysign(shrinked, weight); } return 0.0; } // Vectorized float variant of the above. Eigen::Tensor<float, 1, Eigen::RowMajor> EigenShrink( const Eigen::Tensor<float, 1, Eigen::RowMajor> weights) const { // Proximal step on the weights which is sign(w)*|w - shrinkage|+. return weights.sign() * ((weights.abs() - weights.constant(shrinkage_)) .cwiseMax(weights.constant(0.0))); } float symmetric_l2() const { return symmetric_l2_; } private: float symmetric_l1_ = 0; float symmetric_l2_ = 0; // L1 divided by L2, pre-computed for use during weight shrinking. double shrinkage_ = 0; TF_DISALLOW_COPY_AND_ASSIGN(Regularizations); }; class ModelWeights; // Struct describing a single example. class Example { public: // Compute dot product between weights, and example feature values. This // method also computes the normalized example norm used in SDCA update. const ExampleStatistics ComputeWxAndWeightedExampleNorm( const int num_loss_partitions, const ModelWeights& model_weights, const Regularizations& regularization) const; float example_label() const { return example_label_; } float example_weight() const { return example_weight_; } double squared_norm() const { return squared_norm_; } // Sparse features associated with the example. // Indices and Values are the associated feature index, and values. Values // can be optionally absent, in which we case we implicitly assume a value of // 1.0f. struct SparseFeatures { std::unique_ptr<UnalignedInt64Vector> indices; std::unique_ptr<UnalignedFloatVector> values; // nullptr encodes optional. }; // A dense vector which is a row-slice of the underlying matrix. struct DenseVector { // Returns a row slice from the matrix. Eigen::TensorMap<Eigen::Tensor<const float, 1, Eigen::RowMajor>> row() const { // TensorMap to a row slice of the matrix. return Eigen::TensorMap<Eigen::Tensor<const float, 1, Eigen::RowMajor>>( data_matrix.data() + row_index * data_matrix.dimension(1), data_matrix.dimension(1)); } const TTypes<float>::ConstMatrix data_matrix; const int64 row_index; }; private: std::vector<SparseFeatures> sparse_features_; std::vector<std::unique_ptr<DenseVector>> dense_vectors_; float example_label_ = 0; float example_weight_ = 0; double squared_norm_ = 0; // sum squared norm of the features. // Examples fills Example in a multi-threaded way. friend class Examples; // ModelWeights use each example for model update w += \alpha * x_{i}; friend class ModelWeights; }; // Weights related to features. For example, say you have two sets of sparse // features i.e. age bracket and country, then FeatureWeightsDenseStorage hold // the parameters for it. We keep track of the original weight passed in and the // delta weight which the optimizer learns in each call to the optimizer. class FeatureWeightsDenseStorage { public: FeatureWeightsDenseStorage(const TTypes<const float>::Vec nominals, TTypes<float>::Vec deltas) : nominals_(nominals), deltas_(deltas) {} // Check if a feature index is with-in the bounds. bool IndexValid(const int64 index) const { return index >= 0 && index < deltas_.size(); } // Nominals here are the original weight vector. TTypes<const float>::Vec nominals() const { return nominals_; } // Delta weights durining mini-batch updates. TTypes<float>::Vec deltas() const { return deltas_; } // Nominal value at a particular feature index. float nominals(const int64 index) const { return nominals_(index); } // Delta value at a particular feature index. float deltas(const int64 index) const { return deltas_(index); } // Updates delta weights based on active dense features in the example and // the corresponding dual residual. void UpdateDenseDeltaWeights(const Eigen::ThreadPoolDevice& device, const Example::DenseVector& dense_vector, const double normalized_bounded_dual_delta) { deltas_.device(device) = deltas_ + dense_vector.row() * deltas_.constant(normalized_bounded_dual_delta); } private: // The nominal value of the weight for a feature (indexed by its id). const TTypes<const float>::Vec nominals_; // The accumulated delta weight for a feature (indexed by its id). TTypes<float>::Vec deltas_; }; // Similar to FeatureWeightsDenseStorage, but the underlying weights are stored // a hash map. class FeatureWeightsSparseStorage { public: FeatureWeightsSparseStorage(const TTypes<const int64>::Vec indices, const TTypes<const float>::Vec nominals, TTypes<float>::Vec deltas) : nominals_(nominals), deltas_(deltas) { // Create a map from sparse index to the dense index of the underlying // storage. for (int j = 0; j < indices.size(); ++j) { indices_to_id_[indices(j)] = j; } } // Check if a feature index exists. bool IndexValid(const int64 index) const { return indices_to_id_.find(index) != indices_to_id_.end(); } // Nominal value at a particular feature index. float nominals(const int64 index) const { auto it = indices_to_id_.find(index); return nominals_(it->second); } // Delta weights durining mini-batch updates. float deltas(const int64 index) const { auto it = indices_to_id_.find(index); return deltas_(it->second); } // Updates delta weights based on active sparse features in the example and // the corresponding dual residual. void UpdateSparseDeltaWeights(const Eigen::ThreadPoolDevice& device, const Example::SparseFeatures& sparse_features, const double normalized_bounded_dual_delta) { for (int64 k = 0; k < sparse_features.indices->size(); ++k) { const double feature_value = sparse_features.values == nullptr ? 1.0 : (*sparse_features.values)(k); auto it = indices_to_id_.find((*sparse_features.indices)(k)); deltas_(it->second) += feature_value * normalized_bounded_dual_delta; } } private: // The nominal value of the weight for a feature (indexed by its id). const TTypes<const float>::Vec nominals_; // The accumulated delta weight for a feature (indexed by its id). TTypes<float>::Vec deltas_; // Map from feature index to an index to the dense vector. std::unordered_map<int64, int64> indices_to_id_; }; // Weights in the model, wraps both current weights, and the delta weights // for both sparse and dense features. class ModelWeights { public: ModelWeights() {} bool SparseIndexValid(const int col, const int64 index) const { return sparse_weights_[col].IndexValid(index); } bool DenseIndexValid(const int col, const int64 index) const { return dense_weights_[col].IndexValid(index); } // Go through all the features present in the example, and update the // weights based on the dual delta. void UpdateDeltaWeights(const Eigen::ThreadPoolDevice& device, const Example& example, const double normalized_bounded_dual_delta) { // Sparse weights. for (size_t j = 0; j < sparse_weights_.size(); ++j) { sparse_weights_[j].UpdateSparseDeltaWeights( device, example.sparse_features_[j], normalized_bounded_dual_delta); } // Dense weights. for (size_t j = 0; j < dense_weights_.size(); ++j) { dense_weights_[j].UpdateDenseDeltaWeights( device, *example.dense_vectors_[j], normalized_bounded_dual_delta); } } Status Initialize(OpKernelContext* const context) { OpInputList sparse_indices_inputs; TF_RETURN_IF_ERROR( context->input_list("sparse_indices", &sparse_indices_inputs)); OpInputList sparse_weights_inputs; TF_RETURN_IF_ERROR( context->input_list("sparse_weights", &sparse_weights_inputs)); OpInputList dense_weights_inputs; TF_RETURN_IF_ERROR( context->input_list("dense_weights", &dense_weights_inputs)); OpOutputList sparse_weights_outputs; TF_RETURN_IF_ERROR(context->output_list("out_delta_sparse_weights", &sparse_weights_outputs)); OpOutputList dense_weights_outputs; TF_RETURN_IF_ERROR(context->output_list("out_delta_dense_weights", &dense_weights_outputs)); for (int i = 0; i < sparse_weights_inputs.size(); ++i) { Tensor* delta_t; sparse_weights_outputs.allocate(i, sparse_weights_inputs[i].shape(), &delta_t); auto deltas = delta_t->flat<float>(); deltas.setZero(); sparse_weights_.emplace_back(FeatureWeightsSparseStorage{ sparse_indices_inputs[i].flat<int64>(), sparse_weights_inputs[i].flat<float>(), deltas}); } // Reads in the weights, and allocates and initializes the delta weights. const auto intialize_weights = [&]( const OpInputList& weight_inputs, OpOutputList* const weight_outputs, std::vector<FeatureWeightsDenseStorage>* const feature_weights) { for (int i = 0; i < weight_inputs.size(); ++i) { Tensor* delta_t; weight_outputs->allocate(i, weight_inputs[i].shape(), &delta_t); auto deltas = delta_t->flat<float>(); deltas.setZero(); feature_weights->emplace_back( FeatureWeightsDenseStorage{weight_inputs[i].flat<float>(), deltas}); } }; intialize_weights(dense_weights_inputs, &dense_weights_outputs, &dense_weights_); return Status::OK(); } const std::vector<FeatureWeightsSparseStorage>& sparse_weights() const { return sparse_weights_; } const std::vector<FeatureWeightsDenseStorage>& dense_weights() const { return dense_weights_; } private: std::vector<FeatureWeightsSparseStorage> sparse_weights_; std::vector<FeatureWeightsDenseStorage> dense_weights_; TF_DISALLOW_COPY_AND_ASSIGN(ModelWeights); }; // Computes the example statistics for given example, and model. Defined here // as we need definition of ModelWeights and Regularizations. const ExampleStatistics Example::ComputeWxAndWeightedExampleNorm( const int num_loss_partitions, const ModelWeights& model_weights, const Regularizations& regularization) const { ExampleStatistics result; result.normalized_squared_norm = squared_norm_ / regularization.symmetric_l2(); // Compute the w \dot x and prev_w \dot x. // Sparse features contribution. for (size_t j = 0; j < sparse_features_.size(); ++j) { const Example::SparseFeatures& sparse_features = sparse_features_[j]; const FeatureWeightsSparseStorage& sparse_weights = model_weights.sparse_weights()[j]; for (int64 k = 0; k < sparse_features.indices->size(); ++k) { const int64 feature_index = (*sparse_features.indices)(k); const double feature_value = sparse_features.values == nullptr ? 1.0 : (*sparse_features.values)(k); const double feature_weight = sparse_weights.nominals(feature_index) + sparse_weights.deltas(feature_index) * num_loss_partitions; result.prev_wx += feature_value * regularization.Shrink(sparse_weights.nominals(feature_index)); result.wx += feature_value * regularization.Shrink(feature_weight); } } // Dense features contribution. for (size_t j = 0; j < dense_vectors_.size(); ++j) { const Example::DenseVector& dense_vector = *dense_vectors_[j]; const FeatureWeightsDenseStorage& dense_weights = model_weights.dense_weights()[j]; const Eigen::Tensor<float, 1, Eigen::RowMajor> feature_weights = dense_weights.nominals() + dense_weights.deltas() * dense_weights.deltas().constant(num_loss_partitions); const Eigen::Tensor<float, 0, Eigen::RowMajor> prev_prediction = (dense_vector.row() * regularization.EigenShrink(dense_weights.nominals())) .sum(); const Eigen::Tensor<float, 0, Eigen::RowMajor> prediction = (dense_vector.row() * regularization.EigenShrink(feature_weights)) .sum(); result.prev_wx += prev_prediction(); result.wx += prediction(); } return result; } // Examples contains all the training examples that SDCA uses for a mini-batch. class Examples { public: Examples() {} // Returns the Example at |example_index|. const Example& example(const int example_index) const { return examples_.at(example_index); } int sampled_index(const int id, const bool adaptative) const { if (adaptative) return sampled_index_[id]; return id; } void SampleAdaptativeProbabilities( const int num_loss_partitions, const Regularizations& regularization, const ModelWeights& model_weights, const TTypes<float>::Matrix example_state_data, const std::unique_ptr<DualLossUpdater>& loss_updater) { // Compute the probabilities for (int example_id = 0; example_id < num_examples(); ++example_id) { const Example& example = examples_[example_id]; const double example_weight = example.example_weight(); float label = example.example_label(); const Status conversion_status = loss_updater->ConvertLabel(&label); const ExampleStatistics example_statistics = example.ComputeWxAndWeightedExampleNorm( num_loss_partitions, model_weights, regularization); const double kappa = example_state_data(example_id, 0) + loss_updater->PrimalLossDerivative( example_statistics.wx, label, example_weight); probabilities_[example_id] = example_weight * sqrt(examples_[example_id].squared_norm_ + regularization.symmetric_l2() * loss_updater->SmoothnessConstant()) * std::abs(kappa); } // Sample the index random::DistributionSampler sampler(probabilities_); GuardedPhiloxRandom generator; generator.Init(0, 0); auto local_gen = generator.ReserveSamples32(num_examples()); random::SimplePhilox random(&local_gen); std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> dis(0, 1); // We use a decay of 10: the probability of an example is divided by 10 // once that example is picked. A good approximation of that is to only // keep a picked example with probability (1 / 10) ^ k where k is the // number of times we already picked that example. We add a num_retries // to avoid taking too long to sample. We then fill the sampled_index with // unseen examples sorted by probabilities. int id = 0; int num_retries = 0; while (id < num_examples() && num_retries < num_examples()) { int picked_id = sampler.Sample(&random); if (dis(gen) > std::pow(0.1, sampled_count_[picked_id])) { num_retries++; continue; } sampled_count_[picked_id]++; sampled_index_[id++] = picked_id; } std::vector<std::pair<int, float>> examples_not_seen; examples_not_seen.reserve(num_examples()); for (int i = 0; i < num_examples(); ++i) { if (sampled_count_[i] == 0) examples_not_seen.emplace_back(sampled_index_[i], probabilities_[i]); } std::sort( examples_not_seen.begin(), examples_not_seen.end(), [](const std::pair<int, float>& lhs, const std::pair<int, float>& rhs) { return lhs.second > rhs.second; }); for (int i = id; i < num_examples(); ++i) { sampled_count_[i] = examples_not_seen[i - id].first; } } int num_examples() const { return examples_.size(); } int num_features() const { return num_features_; } // Initialize() must be called immediately after construction. // TODO(sibyl-Aix6ihai): Refactor/shorten this function. Status Initialize(OpKernelContext* const context, const ModelWeights& weights, int num_sparse_features, int num_sparse_features_with_values, int num_dense_features); private: // Reads the input tensors, and builds the internal representation for sparse // features per example. This function modifies the |examples| passed in // to build the sparse representations. static Status CreateSparseFeatureRepresentation( const DeviceBase::CpuWorkerThreads& worker_threads, int num_examples, int num_sparse_features, const ModelWeights& weights, const OpInputList& sparse_example_indices_inputs, const OpInputList& sparse_feature_indices_inputs, const OpInputList& sparse_feature_values_inputs, std::vector<Example>* const examples); // Reads the input tensors, and builds the internal representation for dense // features per example. This function modifies the |examples| passed in // to build the sparse representations. static Status CreateDenseFeatureRepresentation( const DeviceBase::CpuWorkerThreads& worker_threads, int num_examples, int num_dense_features, const ModelWeights& weights, const OpInputList& dense_features_inputs, std::vector<Example>* const examples); // Computes squared example norm per example i.e |x|^2. This function modifies // the |examples| passed in and adds the squared norm per example. static void ComputeSquaredNormPerExample( const DeviceBase::CpuWorkerThreads& worker_threads, int num_examples, int num_sparse_features, int num_dense_features, std::vector<Example>* const examples); // All examples in the batch. std::vector<Example> examples_; // Adaptative sampling variables std::vector<float> probabilities_; std::vector<int> sampled_index_; std::vector<int> sampled_count_; int num_features_ = 0; TF_DISALLOW_COPY_AND_ASSIGN(Examples); }; Status Examples::Initialize(OpKernelContext* const context, const ModelWeights& weights, const int num_sparse_features, const int num_sparse_features_with_values, const int num_dense_features) { num_features_ = num_sparse_features + num_dense_features; OpInputList sparse_example_indices_inputs; TF_RETURN_IF_ERROR(context->input_list("sparse_example_indices", &sparse_example_indices_inputs)); OpInputList sparse_feature_indices_inputs; TF_RETURN_IF_ERROR(context->input_list("sparse_feature_indices", &sparse_feature_indices_inputs)); OpInputList sparse_feature_values_inputs; if (num_sparse_features_with_values > 0) { TF_RETURN_IF_ERROR(context->input_list("sparse_feature_values", &sparse_feature_values_inputs)); } const Tensor* example_weights_t; TF_RETURN_IF_ERROR(context->input("example_weights", &example_weights_t)); auto example_weights = example_weights_t->flat<float>(); if (example_weights.size() >= std::numeric_limits<int>::max()) { return errors::InvalidArgument(strings::Printf( "Too many examples in a mini-batch: %ld > %d", example_weights.size(), std::numeric_limits<int>::max())); } // The static_cast here is safe since num_examples can be at max an int. const int num_examples = static_cast<int>(example_weights.size()); const Tensor* example_labels_t; TF_RETURN_IF_ERROR(context->input("example_labels", &example_labels_t)); auto example_labels = example_labels_t->flat<float>(); OpInputList dense_features_inputs; TF_RETURN_IF_ERROR( context->input_list("dense_features", &dense_features_inputs)); examples_.clear(); examples_.resize(num_examples); probabilities_.resize(num_examples); sampled_index_.resize(num_examples); sampled_count_.resize(num_examples); for (int example_id = 0; example_id < num_examples; ++example_id) { Example* const example = &examples_[example_id]; example->sparse_features_.resize(num_sparse_features); example->dense_vectors_.resize(num_dense_features); example->example_weight_ = example_weights(example_id); example->example_label_ = example_labels(example_id); } const DeviceBase::CpuWorkerThreads& worker_threads = *context->device()->tensorflow_cpu_worker_threads(); TF_RETURN_IF_ERROR(CreateSparseFeatureRepresentation( worker_threads, num_examples, num_sparse_features, weights, sparse_example_indices_inputs, sparse_feature_indices_inputs, sparse_feature_values_inputs, &examples_)); TF_RETURN_IF_ERROR(CreateDenseFeatureRepresentation( worker_threads, num_examples, num_dense_features, weights, dense_features_inputs, &examples_)); ComputeSquaredNormPerExample(worker_threads, num_examples, num_sparse_features, num_dense_features, &examples_); return Status::OK(); } Status Examples::CreateSparseFeatureRepresentation( const DeviceBase::CpuWorkerThreads& worker_threads, const int num_examples, const int num_sparse_features, const ModelWeights& weights, const OpInputList& sparse_example_indices_inputs, const OpInputList& sparse_feature_indices_inputs, const OpInputList& sparse_feature_values_inputs, std::vector<Example>* const examples) { mutex mu; Status result GUARDED_BY(mu); auto parse_partition = [&](const int64 begin, const int64 end) { // The static_cast here is safe since begin and end can be at most // num_examples which is an int. for (int i = static_cast<int>(begin); i < end; ++i) { auto example_indices = sparse_example_indices_inputs[i].template flat<int64>(); auto feature_indices = sparse_feature_indices_inputs[i].template flat<int64>(); // Parse features for each example. Features for a particular example // are at the offsets (start_id, end_id] int start_id = -1; int end_id = 0; for (int example_id = 0; example_id < num_examples; ++example_id) { start_id = end_id; while (end_id < example_indices.size() && example_indices(end_id) == example_id) { ++end_id; } Example::SparseFeatures* const sparse_features = &(*examples)[example_id].sparse_features_[i]; if (start_id < example_indices.size() && example_indices(start_id) == example_id) { sparse_features->indices.reset(new UnalignedInt64Vector( &(feature_indices(start_id)), end_id - start_id)); if (sparse_feature_values_inputs.size() > i) { auto feature_weights = sparse_feature_values_inputs[i].flat<float>(); sparse_features->values.reset(new UnalignedFloatVector( &(feature_weights(start_id)), end_id - start_id)); } // If features are non empty. if (end_id - start_id > 0) { // TODO(sibyl-Aix6ihai): Write this efficiently using vectorized // operations from eigen. for (int64 k = 0; k < sparse_features->indices->size(); ++k) { const int64 feature_index = (*sparse_features->indices)(k); if (!weights.SparseIndexValid(i, feature_index)) { mutex_lock l(mu); result = errors::InvalidArgument( "Found sparse feature indices out of valid range: ", (*sparse_features->indices)(k)); return; } } } } else { // Add a Tensor that has size 0. sparse_features->indices.reset( new UnalignedInt64Vector(&(feature_indices(0)), 0)); // If values exist for this feature group. if (sparse_feature_values_inputs.size() > i) { auto feature_weights = sparse_feature_values_inputs[i].flat<float>(); sparse_features->values.reset( new UnalignedFloatVector(&(feature_weights(0)), 0)); } } } } }; // For each column, the cost of parsing it is O(num_examples). We use // num_examples here, as empirically Shard() creates the right amount of // threads based on the problem size. // TODO(sibyl-Aix6ihai): Tune this as a function of dataset size. const int64 kCostPerUnit = num_examples; Shard(worker_threads.num_threads, worker_threads.workers, num_sparse_features, kCostPerUnit, parse_partition); return result; } Status Examples::CreateDenseFeatureRepresentation( const DeviceBase::CpuWorkerThreads& worker_threads, const int num_examples, const int num_dense_features, const ModelWeights& weights, const OpInputList& dense_features_inputs, std::vector<Example>* const examples) { mutex mu; Status result GUARDED_BY(mu); auto parse_partition = [&](const int64 begin, const int64 end) { // The static_cast here is safe since begin and end can be at most // num_examples which is an int. for (int i = static_cast<int>(begin); i < end; ++i) { auto dense_features = dense_features_inputs[i].template matrix<float>(); for (int example_id = 0; example_id < num_examples; ++example_id) { (*examples)[example_id].dense_vectors_[i].reset( new Example::DenseVector{dense_features, example_id}); } if (!weights.DenseIndexValid(i, dense_features.dimension(1) - 1)) { mutex_lock l(mu); result = errors::InvalidArgument( "More dense features than we have parameters for: ", dense_features.dimension(1)); return; } } }; // TODO(sibyl-Aix6ihai): Tune this as a function of dataset size. const int64 kCostPerUnit = num_examples; Shard(worker_threads.num_threads, worker_threads.workers, num_dense_features, kCostPerUnit, parse_partition); return result; } void Examples::ComputeSquaredNormPerExample( const DeviceBase::CpuWorkerThreads& worker_threads, const int num_examples, const int num_sparse_features, const int num_dense_features, std::vector<Example>* const examples) { // Compute norm of examples. auto compute_example_norm = [&](const int64 begin, const int64 end) { // The static_cast here is safe since begin and end can be at most // num_examples which is an int. for (int example_id = static_cast<int>(begin); example_id < end; ++example_id) { double squared_norm = 0; Example* const example = &(*examples)[example_id]; for (int j = 0; j < num_sparse_features; ++j) { const Example::SparseFeatures& sparse_features = example->sparse_features_[j]; if (sparse_features.values) { const Eigen::Tensor<float, 0, Eigen::RowMajor> sn = sparse_features.values->square().sum(); squared_norm += sn(); } else { squared_norm += sparse_features.indices->size(); } } for (int j = 0; j < num_dense_features; ++j) { const Eigen::Tensor<float, 0, Eigen::RowMajor> sn = example->dense_vectors_[j]->row().square().sum(); squared_norm += sn(); } example->squared_norm_ = squared_norm; } }; // TODO(sibyl-Aix6ihai): Compute the cost optimally. const int64 kCostPerUnit = num_dense_features + num_sparse_features; Shard(worker_threads.num_threads, worker_threads.workers, num_examples, kCostPerUnit, compute_example_norm); } struct ComputeOptions { ComputeOptions(OpKernelConstruction* const context) { string loss_type; OP_REQUIRES_OK(context, context->GetAttr("loss_type", &loss_type)); if (loss_type == "logistic_loss") { loss_updater.reset(new LogisticLossUpdater); } else if (loss_type == "squared_loss") { loss_updater.reset(new SquaredLossUpdater); } else if (loss_type == "hinge_loss") { loss_updater.reset(new HingeLossUpdater); } else if (loss_type == "smooth_hinge_loss") { loss_updater.reset(new SmoothHingeLossUpdater); } else { OP_REQUIRES(context, false, errors::InvalidArgument( "Unsupported loss type: ", loss_type)); } OP_REQUIRES_OK(context, context->GetAttr("adaptative", &adaptative)); OP_REQUIRES_OK( context, context->GetAttr("num_sparse_features", &num_sparse_features)); OP_REQUIRES_OK(context, context->GetAttr("num_sparse_features_with_values", &num_sparse_features_with_values)); OP_REQUIRES_OK(context, context->GetAttr("num_dense_features", &num_dense_features)); OP_REQUIRES( context, num_sparse_features + num_dense_features > 0, errors::InvalidArgument("Requires at least one feature to train.")); OP_REQUIRES(context, static_cast<int64>(num_sparse_features) + static_cast<int64>(num_dense_features) <= std::numeric_limits<int>::max(), errors::InvalidArgument( strings::Printf("Too many feature groups: %lld > %d", static_cast<int64>(num_sparse_features) + static_cast<int64>(num_dense_features), std::numeric_limits<int>::max()))); OP_REQUIRES_OK( context, context->GetAttr("num_loss_partitions", &num_loss_partitions)); OP_REQUIRES_OK(context, context->GetAttr("num_inner_iterations", &num_inner_iterations)); OP_REQUIRES_OK(context, regularizations.Initialize(context)); } std::unique_ptr<DualLossUpdater> loss_updater; int num_sparse_features = 0; int num_sparse_features_with_values = 0; int num_dense_features = 0; int num_inner_iterations = 0; int num_loss_partitions = 0; bool adaptative = false; Regularizations regularizations; }; void DoCompute(const ComputeOptions& options, OpKernelContext* const context) { ModelWeights model_weights; OP_REQUIRES_OK(context, model_weights.Initialize(context)); Examples examples; OP_REQUIRES_OK( context, examples.Initialize(context, model_weights, options.num_sparse_features, options.num_sparse_features_with_values, options.num_dense_features)); const Tensor* example_state_data_t; OP_REQUIRES_OK(context, context->input("example_state_data", &example_state_data_t)); TensorShape expected_example_state_shape({examples.num_examples(), 4}); OP_REQUIRES(context, example_state_data_t->shape() == expected_example_state_shape, errors::InvalidArgument( "Expected shape ", expected_example_state_shape.DebugString(), " for example_state_data, got ", example_state_data_t->shape().DebugString())); Tensor mutable_example_state_data_t(*example_state_data_t); auto example_state_data = mutable_example_state_data_t.matrix<float>(); context->set_output("out_example_state_data", mutable_example_state_data_t); if (options.adaptative) { examples.SampleAdaptativeProbabilities( options.num_loss_partitions, options.regularizations, model_weights, example_state_data, options.loss_updater); } mutex mu; Status train_step_status GUARDED_BY(mu); std::atomic<std::int64_t> atomic_index(-1); auto train_step = [&](const int64 begin, const int64 end) { // The static_cast here is safe since begin and end can be at most // num_examples which is an int. for (int id = static_cast<int>(begin); id < end; ++id) { const int64 example_index = examples.sampled_index(++atomic_index, options.adaptative); const Example& example = examples.example(example_index); const float dual = example_state_data(example_index, 0); const float example_weight = example.example_weight(); float example_label = example.example_label(); const Status conversion_status = options.loss_updater->ConvertLabel(&example_label); if (!conversion_status.ok()) { mutex_lock l(mu); train_step_status = conversion_status; // Return from this worker thread - the calling thread is // responsible for checking context status and returning on error. return; } // Compute wx, example norm weighted by regularization, dual loss, // primal loss. const ExampleStatistics example_statistics = example.ComputeWxAndWeightedExampleNorm(options.num_loss_partitions, model_weights, options.regularizations); const double new_dual = options.loss_updater->ComputeUpdatedDual( options.num_loss_partitions, example_label, example_weight, dual, example_statistics.wx, example_statistics.normalized_squared_norm); // Compute new weights. const double normalized_bounded_dual_delta = (new_dual - dual) * example_weight / options.regularizations.symmetric_l2(); model_weights.UpdateDeltaWeights(context->eigen_cpu_device(), example, normalized_bounded_dual_delta); // Update example data. example_state_data(example_index, 0) = new_dual; example_state_data(example_index, 1) = options.loss_updater->ComputePrimalLoss( example_statistics.prev_wx, example_label, example_weight); example_state_data(example_index, 2) = options.loss_updater->ComputeDualLoss(dual, example_label, example_weight); example_state_data(example_index, 3) = example_weight; } }; // TODO(sibyl-Aix6ihai): Tune this properly based on sparsity of the data, // number of cpus, and cost per example. const int64 kCostPerUnit = examples.num_features(); const DeviceBase::CpuWorkerThreads& worker_threads = *context->device()->tensorflow_cpu_worker_threads(); Shard(worker_threads.num_threads, worker_threads.workers, examples.num_examples(), kCostPerUnit, train_step); OP_REQUIRES_OK(context, train_step_status); } } // namespace class SdcaOptimizer : public OpKernel { public: explicit SdcaOptimizer(OpKernelConstruction* const context) : OpKernel(context), options_(context) {} void Compute(OpKernelContext* const context) override { DoCompute(options_, context); } private: // TODO(sibyl-Aix6ihai): We could use the type-constraint on loss_type, and // template the entire class to avoid the virtual table lookup penalty in // the inner loop. ComputeOptions options_; }; REGISTER_KERNEL_BUILDER(Name("SdcaOptimizer").Device(DEVICE_CPU), SdcaOptimizer); class SdcaShrinkL1 : public OpKernel { public: explicit SdcaShrinkL1(OpKernelConstruction* const context) : OpKernel(context) { OP_REQUIRES_OK(context, regularizations_.Initialize(context)); } void Compute(OpKernelContext* const context) override { OpMutableInputList weights_inputs; OP_REQUIRES_OK(context, context->mutable_input_list("weights", &weights_inputs)); auto do_work = [&](const int64 begin, const int64 end) { for (int i = begin; i < end; ++i) { auto prox_w = weights_inputs.at(i, /*lock_held=*/true).flat<float>(); prox_w.device(context->eigen_cpu_device()) = regularizations_.EigenShrink(prox_w); } }; if (weights_inputs.size() > 0) { int64 num_weights = 0; for (int i = 0; i < weights_inputs.size(); ++i) { num_weights += weights_inputs.at(i, /*lock_held=*/true).NumElements(); } // TODO(sibyl-Aix6ihai): Tune this value. const int64 kCostPerUnit = (num_weights * 50) / weights_inputs.size(); const DeviceBase::CpuWorkerThreads& worker_threads = *context->device()->tensorflow_cpu_worker_threads(); Shard(worker_threads.num_threads, worker_threads.workers, weights_inputs.size(), kCostPerUnit, do_work); } } private: Regularizations regularizations_; }; REGISTER_KERNEL_BUILDER(Name("SdcaShrinkL1").Device(DEVICE_CPU), SdcaShrinkL1); // Computes platform independent, compact and unique (with very high // probability) representation of an example id. It shouldn't be put in // persistent storage, as its implementation may change in the future. // // The current probability of at least one collision for 1B example_ids is // approximately 10^-11 (ie 2^60 / 2^97). class SdcaFprint : public OpKernel { public: explicit SdcaFprint(OpKernelConstruction* const context) : OpKernel(context) {} void Compute(OpKernelContext* const context) override { const Tensor& input = context->input(0); Tensor* out; OP_REQUIRES_OK(context, context->allocate_output(0, input.shape(), &out)); const auto in_values = input.flat<string>(); auto out_values = out->flat<string>(); for (int64 i = 0; i < in_values.size(); ++i) { out_values(i) = Fp128ToBinaryString(Fingerprint128(in_values(i))); } } private: // Returns a 12 character binary string of the fprint. // We use 12 of the 16 fingerprint bytes to save memory, in particular in // string implementations that use a short string optimization. static string Fp128ToBinaryString(const Fprint128& fprint) { string result; core::PutFixed64(&result, fprint.low64); core::PutFixed32(&result, fprint.high64); return result; } }; REGISTER_KERNEL_BUILDER(Name("SdcaFprint").Device(DEVICE_CPU), SdcaFprint); } // namespace tensorflow
40.710784
80
0.684359
topsun888
a1bec3d4f239995a579afb417f9b2fe91b778649
3,385
cpp
C++
src/Native/libcryptonight/xmrig/Mem_unix.cpp
lurchinms/miningcore-2
1ab7d1ce1b3dd3c28e35348e0b701fd5b5e264b1
[ "MIT" ]
28
2018-05-24T06:35:38.000Z
2021-11-29T17:18:32.000Z
src/Native/libcryptonight/xmrig/Mem_unix.cpp
lurchinms/miningcore-2
1ab7d1ce1b3dd3c28e35348e0b701fd5b5e264b1
[ "MIT" ]
19
2019-03-30T23:23:02.000Z
2021-12-19T09:12:00.000Z
src/Native/libcryptonight/xmrig/Mem_unix.cpp
lurchinms/miningcore-2
1ab7d1ce1b3dd3c28e35348e0b701fd5b5e264b1
[ "MIT" ]
37
2021-03-19T02:56:14.000Z
2022-03-19T16:42:51.000Z
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018 Lee Clagett <https://github.com/vtnerd> * Copyright 2018-2019 SChernykh <https://github.com/SChernykh> * Copyright 2016-2019 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <sys/mman.h> #include "common/utils/mm_malloc.h" #include "common/xmrig.h" #include "crypto/CryptoNight.h" #include "Mem.h" void Mem::init(bool enabled) { m_enabled = enabled; } void Mem::allocate(MemInfo &info, bool enabled) { info.hugePages = 0; if (!enabled) { info.memory = static_cast<uint8_t*>(_mm_malloc(info.size, 4096)); return; } # if defined(__APPLE__) info.memory = static_cast<uint8_t*>(mmap(0, info.size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, VM_FLAGS_SUPERPAGE_SIZE_2MB, 0)); # elif defined(__FreeBSD__) info.memory = static_cast<uint8_t*>(mmap(0, info.size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_ALIGNED_SUPER | MAP_PREFAULT_READ, -1, 0)); # else info.memory = static_cast<uint8_t*>(mmap(0, info.size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_POPULATE, 0, 0)); # endif if (info.memory == MAP_FAILED) { return allocate(info, false);; } info.hugePages = info.pages; if (madvise(info.memory, info.size, MADV_RANDOM | MADV_WILLNEED) != 0) { //LOG_ERR("madvise failed"); } if (mlock(info.memory, info.size) == 0) { m_flags |= Lock; } } void Mem::release(MemInfo &info) { if (info.hugePages) { if (m_flags & Lock) { munlock(info.memory, info.size); } munmap(info.memory, info.size); } else { _mm_free(info.memory); } } void *Mem::allocateExecutableMemory(size_t size) { # if defined(__APPLE__) return mmap(0, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0); # else return mmap(0, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); # endif } void Mem::protectExecutableMemory(void *p, size_t size) { mprotect(p, size, PROT_READ | PROT_EXEC); } void Mem::flushInstructionCache(void *p, size_t size) { # ifndef __FreeBSD__ __builtin___clear_cache(reinterpret_cast<char*>(p), reinterpret_cast<char*>(p) + size); # endif }
29.692982
160
0.675923
lurchinms
a1c007235c0d50e8f8f47ee48bac963fe11a28b7
5,054
cpp
C++
MLP.cpp
LiliamPumpernickel/DAMIS
51369f27ad907b21548bccd6ad184e2e2858e707
[ "Apache-2.0" ]
1
2018-05-13T11:42:44.000Z
2018-05-13T11:42:44.000Z
MLP.cpp
LiliamPumpernickel/DAMIS
51369f27ad907b21548bccd6ad184e2e2858e707
[ "Apache-2.0" ]
null
null
null
MLP.cpp
LiliamPumpernickel/DAMIS
51369f27ad907b21548bccd6ad184e2e2858e707
[ "Apache-2.0" ]
1
2018-05-01T16:53:27.000Z
2018-05-01T16:53:27.000Z
#include "MLP.h" MLP::MLP() { //ctor } MLP::MLP(int h1pNo, int h2pNo, double qtty, int maxIter, bool validationMethod) { //no of neurons in hidden layer HiddenNeuronNo1 = h1pNo; HiddenNeuronNo2 = h2pNo; // param = qtty; // this->dL = dL; //learning // this->dT = dT; //testing // this->decay = wDecay; this->maxIter = maxIter; this->kFoldValidation = validationMethod; alglib::mlpcreatetrainercls(X.getObjectAt(0).getFeatureCount(), X.getClassCount(), trn); //qtt of input features, number of classes to be produced double wstep = 0.000; mlpsetdecay(trn, 0.001); // by default we set moderate weight decay mlpsetcond(trn, wstep, this->maxIter); // * we choose iterations limit as stopping condition (another condition - step size - is zero, which means than this condition is not active) if ((HiddenNeuronNo1 > 0) && (HiddenNeuronNo2 > 0)) alglib::mlpcreatec2(X.getObjectAt(0).getFeatureCount(), HiddenNeuronNo1, HiddenNeuronNo2, X.getClassCount(), network); //create nn network with noofinput features, 2 hidden layers, noofclasses (and sore to network variable) if ((HiddenNeuronNo1 > 0) && (HiddenNeuronNo2 == 0)) alglib::mlpcreatec1(X.getObjectAt(0).getFeatureCount(), HiddenNeuronNo1, X.getClassCount(), network); //create nn network with no of input features, 1 hidden layer, noofclasses (and sore to network variable) if ((HiddenNeuronNo1 == 0) && (HiddenNeuronNo2 == 0)) alglib::mlpcreatec0(X.getObjectAt(0).getFeatureCount(), X.getClassCount(), network); //create nn network with no of input features, 0 hidden layer, noofclasses (and sore to network variable) ///HiddenNeuronNo2 must be non zero inline void MLP::determineKfoldValidation(double qtty) { if (this->kFoldValidation == true) //do kfold validation { ClusterizationMethods::initializeData(); alglib::mlpsetdataset(trn, ClusterizationMethods::learnSet, ClusterizationMethods::learnObjQtty); //attach learning data to data set alglib::mlpkfoldcv(trn, network, 1, int(qtty), rep); } else { ClusterizationMethods::initializeData(qtty, 100 - qtty); alglib::mlpsetdataset(trn, ClusterizationMethods::learnSet, ClusterizationMethods::learnObjQtty); //attach learning data to data set alglib::mlptrainnetwork(trn, network, 1, rep); // train network NRestarts=1, network is trained from random initial state. With NRestarts=0, network is trained without randomization (original state is used as initial point). alglib::integer_1d_array Subset; Subset.setlength(10); alglib::mlpallerrorssubset(network, testSet, testObjQtty, Subset, -1, repp); } } //ctor // now get network error // do not calculate cross-validation since it validates the topology of the network } MLP::~MLP() { //dtor } ObjectMatrix MLP::getProjection() { //int cols = X.getClassCount(); int featureCount = X.getObjectAt(0).getFeatureCount(); int objCount = X.getObjectCount(); initializeYMatrix(objCount, featureCount + X.getClassCount()); alglib::real_1d_array tmpYObj; alglib::real_1d_array tmpXObj; tmpYObj.setlength(featureCount); tmpXObj.setlength(X.getClassCount()); DataObject tempObj; for (int objIndex = 0; objIndex < objCount; objIndex++) { inline void MLP::updateDataObjectsWithFeatures(DataObject &tempObj, int objIndex, int featureCount, alglib::real_1d_array &tmpYObj) { tempObj = X.getObjectAt(objIndex); for (int ft = 0; ft < featureCount; ft++) { double feature = tempObj.getFeatureAt(ft); tmpYObj(ft) = feature; Y.updateDataObject(objIndex, ft, feature); } } alglib::mlpprocess(network, tmpYObj, tmpXObj); inline void UpdateDataObjectsWithMaxProbability(alglib::real_1d_array &tmpXObj, int objIndex, int featureCount, DataObject &tempObj) { double max_probability = tmpXObj(0); int indx = 0; for (int j = 0; j < X.getClassCount(); j++) { Y.updateDataObject(objIndex, j + featureCount, tmpXObj(j)); if (max_probability < tmpXObj(j)) { max_probability = tmpXObj(j); indx = j; } } if (tempObj.getClassLabel() != -1) Y.updateDataObjectClass(objIndex, tempObj.getClassLabel()); else Y.updateDataObjectClass(objIndex, indx); } } std::vector <std::string > probabilities; probabilities.reserve(0); for (int i = 0; i < X.getClassCount(); i++) probabilities.push_back("probClass" + X.getStringClassAttributes().at(i)); Y.addAtributes(probabilities); Y.setPrintClass(X.getStringClassAttributes()); return Y; } double MLP::getStress() { if (this->kFoldValidation) { return rep.avgrelerror; } else { return repp.avgrelerror; } //} /* * Rep.RelCLSError - fraction of misclassified cases. * Rep.AvgCE - acerage cross-entropy * Rep.RMSError - root-mean-square error * Rep.AvgError - average error * Rep.AvgRelError - average relative error */ return rep.rmserror; }
32.606452
231
0.688959
LiliamPumpernickel
a1c302d58f1e3dc8a35f60aed12a52fac38b7b90
26,438
cpp
C++
MovementSimulation.cpp
Cloudfare/123123123123123
879954a3f628f2173ab221070e1d9bf119304ff7
[ "Apache-2.0" ]
null
null
null
MovementSimulation.cpp
Cloudfare/123123123123123
879954a3f628f2173ab221070e1d9bf119304ff7
[ "Apache-2.0" ]
null
null
null
MovementSimulation.cpp
Cloudfare/123123123123123
879954a3f628f2173ab221070e1d9bf119304ff7
[ "Apache-2.0" ]
null
null
null
#include "sdk.h" #include "MovementSimulation.h" #include "Math.h" /* RebuildGameMovement::RebuildGameMovement(void) { } void RebuildGameMovement::SetAbsOrigin(CBaseEntity *player, const Vector &vec) { if (player && player->GetMoveType() == MOVETYPE_WALK) { trace_t pm; TracePlayerBBox(vec, vec, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, pm, player); if (pm.startsolid || pm.allsolid || pm.fraction != 1.0f) { //player will get stuck, lets not? return; } } player->SetOrigin(vec); } int RebuildGameMovement::ClipVelocity(Vector &in, Vector &normal, Vector &out, float overbounce) { float backoff; float change; float angle; int i, blocked; angle = normal[2]; blocked = 0x00; // Assume unblocked. if (angle > 0) // If the plane that is blocking us has a positive z component, then assume it's a floor. blocked |= 0x01; // if (!angle) // If the plane has no Z, it is vertical (wall/step) blocked |= 0x02; // // Determine how far along plane to slide based on incoming direction. backoff = DotProduct(in, normal) * overbounce; for (i = 0; i<3; i++) { change = normal[i] * backoff; out[i] = in[i] - change; } // iterate once to make sure we aren't still moving through the plane float adjust = DotProduct(out, normal); if (adjust < 0.0f) { out -= (normal * adjust); // Msg( "Adjustment = %lf\n", adjust ); } // Return blocking flags. return blocked; } int RebuildGameMovement::TryPlayerMove(CBaseEntity *player, Vector *pFirstDest, trace_t *pFirstTrace) { Vector planes[5]; numbumps[player->GetIndex()] = 4; // Bump up to four times blocked[player->GetIndex()] = 0; // Assume not blocked numplanes[player->GetIndex()] = 0; // and not sliding along any planes original_velocity[player->GetIndex()] = player->GetVelocity(); // Store original velocity primal_velocity[player->GetIndex()] = player->GetVelocity(); allFraction[player->GetIndex()] = 0; time_left[player->GetIndex()] = g_pGlobals->frametime; // Total time for this movement operation. new_velocity[player->GetIndex()].Init(); for (bumpcount[player->GetIndex()] = 0; bumpcount[player->GetIndex()] < numbumps[player->GetIndex()]; bumpcount[player->GetIndex()]++) { if (player->GetVelocity().Length() == 0.0) break; // Assume we can move all the way from the current origin to the // end point. VectorMA(player->GetOrigin(), time_left[player->GetIndex()], player->GetVelocity(), end[player->GetIndex()]); // See if we can make it from origin to end point. if (true) { // If their velocity Z is 0, then we can avoid an extra trace here during WalkMove. if (pFirstDest && end[player->GetIndex()] == *pFirstDest) pm[player->GetIndex()] = *pFirstTrace; else { TracePlayerBBox(player->GetOrigin(), end[player->GetIndex()], MASK_PLAYERSOLID, 8, pm[player->GetIndex()], player); } } else { TracePlayerBBox(player->GetOrigin(), end[player->GetIndex()], MASK_PLAYERSOLID, 8, pm[player->GetIndex()], player); } allFraction[player->GetIndex()] += pm[player->GetIndex()].fraction; // If we started in a solid object, or we were in solid space // the whole way, zero out our velocity and return that we // are blocked by floor and wall. if (pm[player->GetIndex()].allsolid) { // entity is trapped in another solid player->GetVelocity() = vec3_origin[player->GetIndex()]; return 4; } // If we moved some portion of the total distance, then // copy the end position into the pmove.origin and // zero the plane counter. if (pm[player->GetIndex()].fraction > 0) { if (numbumps[player->GetIndex()] > 0 && pm[player->GetIndex()].fraction == 1) { // There's a precision issue with terrain tracing that can cause a swept box to successfully trace // when the end position is stuck in the triangle. Re-run the test with an uswept box to catch that // case until the bug is fixed. // If we detect getting stuck, don't allow the movement trace_t stuck; TracePlayerBBox(pm[player->GetIndex()].endpos, pm[player->GetIndex()].endpos, MASK_PLAYERSOLID, 8, stuck, player); if (stuck.startsolid || stuck.fraction != 1.0f) { //Msg( "Player will become stuck!!!\n" ); player->GetVelocity() = vec3_origin[player->GetIndex()]; break; } } // actually covered some distance SetAbsOrigin(player, pm[player->GetIndex()].endpos); original_velocity[player->GetIndex()] = player->GetVelocity(); numplanes[player->GetIndex()] = 0; } // If we covered the entire distance, we are done // and can return. if (pm[player->GetIndex()].fraction == 1) { break; // moved the entire distance } // If the plane we hit has a high z component in the normal, then // it's probably a floor if (pm[player->GetIndex()].plane.normal[2] > 0.7) { blocked[player->GetIndex()] |= 1; // floor } // If the plane has a zero z component in the normal, then it's a // step or wall if (!pm[player->GetIndex()].plane.normal[2]) { blocked[player->GetIndex()] |= 2; // step / wall } // Reduce amount of m_flFrameTime left by total time left * fraction // that we covered. time_left[player->GetIndex()] -= time_left[player->GetIndex()] * pm[player->GetIndex()].fraction; // Did we run out of planes to clip against? if (numplanes[player->GetIndex()] >= 5) { // this shouldn't really happen // Stop our movement if so. player->GetVelocity() = vec3_origin[player->GetIndex()]; //Con_DPrintf("Too many planes 4\n"); break; } // Set up next clipping plane planes[numplanes[player->GetIndex()]] = pm[player->GetIndex()].plane.normal; numplanes[player->GetIndex()]++; // modify original_velocity so it parallels all of the clip planes // // reflect player velocity // Only give this a try for first impact plane because you can get yourself stuck in an acute corner by jumping in place // and pressing forward and nobody was really using this bounce/reflection feature anyway... if (numplanes[player->GetIndex()] == 1 && player->GetFlags() & FL_ONGROUND) { for (i[player->GetIndex()] = 0; i[player->GetIndex()] < numplanes[player->GetIndex()]; i[player->GetIndex()]++) { if (planes[i[player->GetIndex()]][2] > 0.7) { // floor or slope ClipVelocity(original_velocity[player->GetIndex()], planes[i[player->GetIndex()]], new_velocity[player->GetIndex()], 1); original_velocity[player->GetIndex()] = new_velocity[player->GetIndex()]; } else { ClipVelocity(original_velocity[player->GetIndex()], planes[i[player->GetIndex()]], new_velocity[player->GetIndex()], 1.0 + g_pCvar->FindVar("sv_bounce")->GetValue() * (1 - player->GetFriction())); } } player->GetVelocity() = new_velocity[player->GetIndex()]; original_velocity[player->GetIndex()] = new_velocity[player->GetIndex()]; } else { for (i[player->GetIndex()] = 0; i[player->GetIndex()] < numplanes[player->GetIndex()]; i[player->GetIndex()]++) { for (j[player->GetIndex()] = 0; j[player->GetIndex()]<numplanes[player->GetIndex()]; j[player->GetIndex()]++) if (j[player->GetIndex()] != i[player->GetIndex()]) { // Are we now moving against this plane? if (DotProduct(player->GetVelocity(), planes[j[player->GetIndex()]]) < 0) break; // not ok } if (j[player->GetIndex()] == numplanes[player->GetIndex()]) // Didn't have to clip, so we're ok break; } // Did we go all the way through plane set if (i[player->GetIndex()] != numplanes[player->GetIndex()]) { // go along this plane // pmove.velocity is set in clipping call, no need to set again. ; } else { // go along the crease if (numplanes[player->GetIndex()] != 2) { player->GetVelocity() = vec3_origin[player->GetIndex()]; break; } CrossProduct(planes[0], planes[1], dir[player->GetIndex()]); dir[player->GetIndex()].NormalizeInPlace(); d[player->GetIndex()] = DotProduct(dir[player->GetIndex()], player->GetVelocity()); VectorMultiply(dir[player->GetIndex()], d[player->GetIndex()], player->GetVelocity()); } // // if original velocity is against the original velocity, stop dead // to avoid tiny occilations in sloping corners // d[player->GetIndex()] = DotProduct(player->GetVelocity(), primal_velocity[player->GetIndex()]); if (d[player->GetIndex()] <= 0) { //Con_DPrintf("Back\n"); player->GetVelocity() = vec3_origin[player->GetIndex()]; break; } } } if (allFraction == 0) { player->GetVelocity() = vec3_origin[player->GetIndex()]; } // Check if they slammed into a wall float fSlamVol = 0.0f; float fLateralStoppingAmount = primal_velocity[player->GetIndex()].Length2D() - player->GetVelocity().Length2D(); if (fLateralStoppingAmount > 580.f * 2.0f) { fSlamVol = 1.0f; } else if (fLateralStoppingAmount > 580.f) { fSlamVol = 0.85f; } return blocked[player->GetIndex()]; } void RebuildGameMovement::Accelerate(CBaseEntity *player, Vector &wishdir, float wishspeed, float accel) { // See if we are changing direction a bit currentspeed[player->GetIndex()] = DotProduct(player->GetVelocity(), wishdir); // Reduce wishspeed by the amount of veer. addspeed[player->GetIndex()] = wishspeed - currentspeed[player->GetIndex()]; // If not going to add any speed, done. if (addspeed[player->GetIndex()] <= 0) return; // Determine amount of accleration. accelspeed[player->GetIndex()] = accel * g_pGlobals->frametime * wishspeed * player->GetFriction(); // Cap at addspeed if (accelspeed[player->GetIndex()] > addspeed[player->GetIndex()]) accelspeed[player->GetIndex()] = addspeed[player->GetIndex()]; // Adjust velocity. for (i[player->GetIndex()] = 0; i[player->GetIndex()]<3; i[player->GetIndex()]++) { player->GetVelocity()[i[player->GetIndex()]] += accelspeed[player->GetIndex()] * wishdir[i[player->GetIndex()]]; } } void RebuildGameMovement::AirAccelerate(CBaseEntity *player, Vector &wishdir, float wishspeed, float accel) { wishspd[player->GetIndex()] = wishspeed; // Cap speed if (wishspd[player->GetIndex()] > 30.f) wishspd[player->GetIndex()] = 30.f; // Determine veer amount currentspeed[player->GetIndex()] = DotProduct(player->GetVelocity(), wishdir); // See how much to add addspeed[player->GetIndex()] = wishspd[player->GetIndex()] - currentspeed[player->GetIndex()]; // If not adding any, done. if (addspeed <= 0) return; // Determine acceleration speed after acceleration accelspeed[player->GetIndex()] = accel * wishspeed * g_pGlobals->frametime * player->GetFriction(); // Cap it if (accelspeed[player->GetIndex()] > addspeed[player->GetIndex()]) accelspeed[player->GetIndex()] = addspeed[player->GetIndex()]; // Adjust pmove vel. for (i[player->GetIndex()] = 0; i[player->GetIndex()]<3; i[player->GetIndex()]++) { player->GetVelocity()[i[player->GetIndex()]] += accelspeed[player->GetIndex()] * wishdir[i[player->GetIndex()]]; g_pMoveHelper->SetHost(reinterpret_cast<CBaseEntity*>(player)); g_pMoveHelper->m_outWishVel[i[player->GetIndex()]] += accelspeed[player->GetIndex()] * wishdir[i[player->GetIndex()]]; } } void RebuildGameMovement::AirMove(CBaseEntity *player) { csFuncs->aechseVektor(player->getEyeAechse(), (float*)&forward[player->GetIndex()], (float*)&right[player->GetIndex()], (float*)&up[player->GetIndex()]); // Determine movement angles // Copy movement amounts g_pMoveHelper->SetHost(player); fmove[player->GetIndex()] = g_pMoveHelper->m_flForwardMove; smove[player->GetIndex()] = g_pMoveHelper->m_flSideMove; // Zero out z components of movement vectors forward[player->GetIndex()][2] = 0; right[player->GetIndex()][2] = 0; csFuncs->normaleAechse(forward[player->GetIndex()]); // Normalize remainder of vectors csFuncs->normaleAechse(right[player->GetIndex()]); // for (i[player->GetIndex()] = 0; i[player->GetIndex()]<2; i[player->GetIndex()]++) // Determine x and y parts of velocity wishvel[player->GetIndex()][i[player->GetIndex()]] = forward[player->GetIndex()][i[player->GetIndex()]] * fmove[player->GetIndex()] + right[player->GetIndex()][i[player->GetIndex()]] * smove[player->GetIndex()]; wishvel[player->GetIndex()][2] = 0; // Zero out z part of velocity wishdir[player->GetIndex()] = wishvel[player->GetIndex()]; // Determine maginitude of speed of move wishspeed[player->GetIndex()] = VectorNormalize(wishdir[player->GetIndex()]); // // clamp to server defined max speed // if (wishspeed != 0 && (wishspeed[player->GetIndex()] > player->GetMaxSpeed())) { VectorMultiply(wishvel[player->GetIndex()], player->GetMaxSpeed() / wishspeed[player->GetIndex()], wishvel[player->GetIndex()]); wishspeed[player->GetIndex()] = player->GetMaxSpeed(); } AirAccelerate(player, wishdir[player->GetIndex()], wishspeed[player->GetIndex()], g_pCvar->FindVar("sv_airaccelerate")->GetValue()); // Add in any base velocity to the current velocity. VectorAdd(player->GetVelocity(), player->GetVelocity(), player->GetVelocity()); trace_t trace; TryPlayerMove(player, &dest[player->GetIndex()], &trace); // Now pull the base velocity back out. Base velocity is set if you are on a moving object, like a conveyor (or maybe another monster?) VectorSubtract(player->GetVelocity(), player->GetVelocity(), player->GetVelocity()); } void RebuildGameMovement::StepMove(CBaseEntity *player, Vector &vecDestination, trace_t &trace) { Vector vecEndPos; vecEndPos = vecDestination; // Try sliding forward both on ground and up 16 pixels // take the move that goes farthest Vector vecPos, vecVel; vecPos = player->GetOrigin(); vecVel = player->GetVelocity(); // Slide move down. TryPlayerMove(player, &vecEndPos, &trace); // Down results. Vector vecDownPos, vecDownVel; vecDownPos = player->GetOrigin(); vecDownVel = player->GetVelocity(); // Reset original values. SetAbsOrigin(player, vecPos); player->GetVelocity() = vecVel; // Move up a stair height. vecEndPos = player->GetOrigin(); vecEndPos.z += player->GetStepSize() + 0.03125; TracePlayerBBox(player->GetOrigin(), vecEndPos, MASK_PLAYERSOLID, 8, trace, player); if (!trace.startsolid && !trace.allsolid) { SetAbsOrigin(player, trace.endpos); } TryPlayerMove(player, &dest[player->GetIndex()], &trace); // Move down a stair (attempt to). vecEndPos = player->GetOrigin(); vecEndPos.z -= player->GetStepSize() + 0.03125; TracePlayerBBox(player->GetOrigin(), vecEndPos, MASK_PLAYERSOLID, 8, trace, player); // If we are not on the ground any more then use the original movement attempt. if (trace.plane.normal[2] < 0.7) { SetAbsOrigin(player, vecDownPos); player->GetVelocity() = vecDownVel; float flStepDist = player->GetOrigin().z - vecPos.z; if (flStepDist > 0.0f) { g_pMoveHelper->SetHost(player); g_pMoveHelper->m_outStepHeight += flStepDist; g_pMoveHelper->SetHost(nullptr); } return; } // If the trace ended up in empty space, copy the end over to the origin. if (!trace.startsolid && !trace.allsolid) { player->SetOrigin(trace.endpos); } // Copy this origin to up. Vector vecUpPos; vecUpPos = player->GetOrigin(); // decide which one went farther float flDownDist = (vecDownPos.x - vecPos.x) * (vecDownPos.x - vecPos.x) + (vecDownPos.y- vecPos.y) * (vecDownPos.y - vecPos.y); float flUpDist = (vecUpPos.x - vecPos.x) * (vecUpPos.x - vecPos.x) + (vecUpPos.y - vecPos.y) * (vecUpPos.y - vecPos.y); if (flDownDist > flUpDist) { SetAbsOrigin(player, vecDownPos); player->GetVelocity() = vecDownVel; } else { // copy z value from slide move player->GetVelocity() = vecDownVel; } float flStepDist = player->GetOrigin().z - vecPos.z; if (flStepDist > 0) { g_pMoveHelper->SetHost(player); g_pMoveHelper->m_outStepHeight += flStepDist; g_pMoveHelper->SetHost(nullptr); } } void RebuildGameMovement::TracePlayerBBox(const Vector &start, const Vector &end, unsigned int fMask, int collisionGroup, trace_t& pm, CBaseEntity *player) { Ray_t ray; CTraceFilter filter; filter.pSkip = reinterpret_cast<void*>(player); ray.Init(start, end, player->GetCollision()->VecMins(), player->GetCollision()->VecMaxs()); g_pEngineTrace->TraceRay(ray, fMask, &filter, &pm); } void RebuildGameMovement::WalkMove(CBaseEntity *player) { Math::AngleVectors(player->GetEyeAngles(), forward[player->GetIndex()],right[player->GetIndex()], up[player->GetIndex()]); // Determine movement angles // Copy movement amounts g_pMoveHelper->SetHost(player); fmove[player->GetIndex()] = g_pMoveHelper->m_flForwardMove; smove[player->GetIndex()] = g_pMoveHelper->m_flSideMove; g_pMoveHelper->SetHost(nullptr); if (forward[player->GetIndex()][2] != 0) { forward[player->GetIndex()][2] = 0; VectorNormalize(forward[player->GetIndex()]); } if (right[player->GetIndex()][2] != 0) { right[player->GetIndex()][2] = 0; VectorNormalize(right[player->GetIndex()]); } for (i[player->GetIndex()] = 0; i[player->GetIndex()]<2; i[player->GetIndex()]++) // Determine x and y parts of velocity wishvel[player->GetIndex()][i[player->GetIndex()]] = forward[player->GetIndex()][i[player->GetIndex()]] * fmove[player->GetIndex()] + right[player->GetIndex()][i[player->GetIndex()]] * smove[player->GetIndex()]; wishvel[player->GetIndex()][2] = 0; // Zero out z part of velocity wishdir[player->GetIndex()] = wishvel[player->GetIndex()]; // Determine maginitude of speed of move wishspeed[player->GetIndex()] = VectorNormalize(wishdir[player->GetIndex()]); // // Clamp to server defined max speed // g_pMoveHelper->SetHost(player); if ((wishspeed[player->GetIndex()] != 0.0f) && (wishspeed[player->GetIndex()] > g_pMoveHelper->m_flMaxSpeed)) { VectorMultiply(wishvel[player->GetIndex()], player->GetMaxSpeed() / wishspeed[player->GetIndex()], wishvel[player->GetIndex()]); wishspeed[player->GetIndex()] = player->GetMaxSpeed(); } g_pMoveHelper->SetHost(nullptr); // Set pmove velocity player->GetVelocity()[2] = 0; Accelerate(player, wishdir[player->GetIndex()], wishspeed[player->GetIndex()], g_pCvar->FindVar("sv_accelerate")->GetValue()); player->GetVelocity()[2] = 0; // Add in any base velocity to the current velocity. VectorAdd(player->GetVelocity(), player->GetVelocity(), player->GetVelocity()); spd[player->GetIndex()] = player->GetVelocity().Length(); if (spd[player->GetIndex()] < 1.0f) { //player->GetVelocity().clearVekt(); player->SetVelocity(Vector(0, 0, 0)); // Now pull the base velocity back out. Base velocity is set if you are on a moving object, like a conveyor (or maybe another monster?) VectorSubtract(player->GetVelocity(), player->GetVelocity(), player->GetVelocity()); return; } // first try just moving to the destination dest[player->GetIndex()][0] = player->GetOrigin()[0] + player->GetVelocity()[0] * g_pGlobals->frametime; dest[player->GetIndex()][1] = player->GetOrigin()[1] + player->GetVelocity()[1] * g_pGlobals->frametime; dest[player->GetIndex()][2] = player->GetOrigin()[2]; // first try moving directly to the next spot TracePlayerBBox(player->GetOrigin(), dest[player->GetIndex()], MASK_PLAYERSOLID, 8, pm[player->GetIndex()], player); // If we made it all the way, then copy trace end as new player position. g_pMoveHelper->SetHost(player); g_pMoveHelper->m_outWishVel += wishdir[player->GetIndex()] * wishspeed[player->GetIndex()]; g_pMoveHelper->SetHost(nullptr); if (pm[player->GetIndex()].fraction == 1) { player->SetOrigin(pm[player->GetIndex()].endpos); // Now pull the base velocity back out. Base velocity is set if you are on a moving object, like a conveyor (or maybe another monster?) VectorSubtract(player->GetVelocity(), player->GetVelocity(), player->GetVelocity()); //tayOnGround(); //needed? return; } // Don't walk up stairs if not on ground. if (!(player->GetFlags() & FL_ONGROUND)) { // Now pull the base velocity back out. Base velocity is set if you are on a moving object, like a conveyor (or maybe another monster?) VectorSubtract(player->GetVelocity(), player->GetVelocity(), player->GetVelocity()); return; } StepMove(player, dest[player->GetIndex()], pm[player->GetIndex()]); // Now pull the base velocity back out. Base velocity is set if you are on a moving object, like a conveyor (or maybe another monster?) VectorSubtract(player->GetVelocity(), player->GetVelocity(), player->GetVelocity()); } void RebuildGameMovement::FinishGravity(CBaseEntity *player) { float ent_gravity; ent_gravity = g_pCvar->FindVar("sv_gravity")->GetValue(); // Get the correct velocity for the end of the dt player->GetVelocity()[2] -= (ent_gravity * g_pCvar->FindVar("sv_gravity")->GetValue() * g_pGlobals->frametime * 0.5); CheckVelocity(player); } void RebuildGameMovement::FullWalkMove(CBaseEntity *player) { StartGravity(player); // Fricion is handled before we add in any base velocity. That way, if we are on a conveyor, // we don't slow when standing still, relative to the conveyor. if (player->GetFlags() & FL_ONGROUND) { player->GetVelocity()[2] = 0.0; Friction(player); } // Make sure velocity is valid. CheckVelocity(player); if (player->GetFlags() & FL_ONGROUND) { WalkMove(player); } else { AirMove(player); // Take into account movement when in air. } // Make sure velocity is valid. CheckVelocity(player); // Add any remaining gravitational component. FinishGravity(player); // If we are on ground, no downward velocity. if (player->GetFlags() & FL_ONGROUND) { player->GetVelocity()[2] = 0; } CheckFalling(player); } void RebuildGameMovement::Friction(CBaseEntity *player) { // Calculate speed speed[player->GetIndex()] = player->GetVelocity().Length(); // If too slow, return if (speed[player->GetIndex()] < 0.1f) { return; } drop[player->GetIndex()] = 0; // apply ground friction if (player->GetFlags() & FL_ONGROUND) // On an entity that is the ground { friction[player->GetIndex()] = g_pCvar->FindVar("sv_friction")->GetValue() * player->GetFriction(); // Bleed off some speed, but if we have less than the bleed // threshold, bleed the threshold amount. control[player->GetIndex()] = (speed[player->GetIndex()] < g_pCvar->FindVar("sv_stopspeed")->GetValue()) ? g_pCvar->FindVar("sv_stopspeed")->GetValue() : speed[player->GetIndex()]; // Add the amount to the drop amount. drop[player->GetIndex()] += control[player->GetIndex()] * friction[player->GetIndex()] * g_pGlobals->frametime; } // scale the velocity newspeed[player->GetIndex()] = speed[player->GetIndex()] - drop[player->GetIndex()]; if (newspeed[player->GetIndex()] < 0) newspeed[player->GetIndex()] = 0; if (newspeed[player->GetIndex()] != speed[player->GetIndex()]) { // Determine proportion of old speed we are using. newspeed[player->GetIndex()] /= speed[player->GetIndex()]; // Adjust velocity according to proportion. VectorMultiply(player->GetVelocity(), newspeed[player->GetIndex()], player->GetVelocity()); } player->GetVelocity() -= (1.f - newspeed[player->GetIndex()]) * player->GetVelocity(); } void RebuildGameMovement::CheckFalling(CBaseEntity *player) { // this function really deals with landing, not falling, so early out otherwise if (player->GetFallVelocity() <= 0) return; if (!player->GetHealth() && player->GetFallVelocity() >= 303.0f) { bool bAlive = true; float fvol = 0.5; // // They hit the ground. // if (player->GetVelocity().z < 0.0f) { // Player landed on a descending object. Subtract the velocity of the ground entity. player->SetFallVelocity(max(0.1f, player->GetFallVelocity() + player->GetVelocity().z)); } if (player->GetFallVelocity() > 526.5f) { fvol = 1.0; } else if (player->GetFallVelocity() > 526.5f / 2) { fvol = 0.85; } else if (player->GetFallVelocity() < 173) { fvol = 0; } } // let any subclasses know that the player has landed and how hard // // Clear the fall velocity so the impact doesn't happen again. // player->SetFallVelocity(0); } const int nanmask = 255 << 23; #define IS_NAN(x) (((*(int *)&x)&nanmask)==nanmask) void RebuildGameMovement::CheckVelocity(CBaseEntity *player) { Vector org = player->GetOrigin(); for (i[player->GetIndex()] = 0; i[player->GetIndex()] < 3; i[player->GetIndex()]++) { // See if it's bogus. if (IS_NAN(player->GetVelocity()[i[player->GetIndex()]])) { player->GetVelocity()[i[player->GetIndex()]] = 0; } if (IS_NAN(org[i[player->GetIndex()]])) { org[i[player->GetIndex()]] = 0; player->SetOrigin(org); } // Bound it. if (player->GetVelocity()[i[player->GetIndex()]] > g_pCvar->FindVar("sv_maxvelocity")->GetValue()) { player->GetVelocity()[i[player->GetIndex()]] = g_pCvar->FindVar("sv_maxvelocity")->GetValue(); } else if (player->GetVelocity()[i[player->GetIndex()]] < -g_pCvar->FindVar("sv_maxvelocity")->GetValue()) { player->GetVelocity()[i[player->GetIndex()]] = -g_pCvar->FindVar("sv_maxvelocity")->GetValue(); } } } void RebuildGameMovement::StartGravity(CBaseEntity *player) { if (!player || !player->GetHealth()) return; Vector pVel = player->GetVelocity(); pVel[2] -= (g_pCvar->FindVar("sv_gravity")->GetValue() * 0.5f * g_pGlobals->interval_per_tick); pVel[2] += (player->GetVelocity()[2] * g_pGlobals->interval_per_tick); player->GetVelocity() = pVel; Vector tmp = player->GetVelocity(); tmp[2] = 0.f; player->GetVelocity() = tmp; }*/
33.982005
214
0.656858
Cloudfare
a1c5bac75a004b2e082a00463bb0ccdd41ecd65c
3,960
hpp
C++
external/ipopt/include/coin/IpTimedTask.hpp
l03ie/Gernby
dabe9d71ab1f7ee4fc4118ccce9b331ebcd801ca
[ "MIT" ]
9
2020-07-09T06:40:31.000Z
2022-03-28T02:50:21.000Z
external/ipopt/include/coin/IpTimedTask.hpp
iambluefred/Test_9
dabe9d71ab1f7ee4fc4118ccce9b331ebcd801ca
[ "MIT" ]
1
2021-07-27T01:42:57.000Z
2021-07-27T06:40:48.000Z
external/ipopt/include/coin/IpTimedTask.hpp
iambluefred/Test_9
dabe9d71ab1f7ee4fc4118ccce9b331ebcd801ca
[ "MIT" ]
5
2020-12-01T01:41:12.000Z
2022-01-04T01:21:49.000Z
// Copyright (C) 2006, 2009 International Business Machines and others. // All Rights Reserved. // This code is published under the Eclipse Public License. // // $Id: IpTimedTask.hpp 1861 2010-12-21 21:34:47Z andreasw $ // // Authors: Andreas Waechter IBM 2005-09-19 #ifndef __IPTIMEDTASK_HPP__ #define __IPTIMEDTASK_HPP__ #include "IpUtils.hpp" namespace Ipopt { /** This class is used to collect timing information for a * particular task. */ class TimedTask { public: /**@name Constructors/Destructors */ //@{ /** Default constructor. */ TimedTask() : total_cputime_(0.), total_systime_(0.), total_walltime_(0.), start_called_(false), end_called_(true) {} /** Default destructor */ ~TimedTask() {} //@} /** Method for resetting time to zero. */ void Reset() { total_cputime_ = 0.; total_systime_ = 0.; total_walltime_ = 0.; start_called_ = false; end_called_ = true; } /** Method that is called before execution of the task. */ void Start() { DBG_ASSERT(end_called_); DBG_ASSERT(!start_called_); end_called_ = false; start_called_ = true; start_cputime_ = CpuTime(); start_systime_ = SysTime(); start_walltime_ = WallclockTime(); } /** Method that is called after execution of the task. */ void End() { DBG_ASSERT(!end_called_); DBG_ASSERT(start_called_); end_called_ = true; start_called_ = false; total_cputime_ += CpuTime() - start_cputime_; total_systime_ += SysTime() - start_systime_; total_walltime_ += WallclockTime() - start_walltime_; } /** Method that is called after execution of the task for which * timing might have been started. This only updates the timing * if the timing has indeed been conducted. This is useful to * stop timing after catching exceptions. */ void EndIfStarted() { if (start_called_) { end_called_ = true; start_called_ = false; total_cputime_ += CpuTime() - start_cputime_; total_systime_ += SysTime() - start_systime_; total_walltime_ += WallclockTime() - start_walltime_; } DBG_ASSERT(end_called_); } /** Method returning total CPU time spend for task so far. */ Number TotalCpuTime() const { DBG_ASSERT(end_called_); return total_cputime_; } /** Method returning total system time spend for task so far. */ Number TotalSysTime() const { DBG_ASSERT(end_called_); return total_systime_; } /** Method returning total wall clock time spend for task so far. */ Number TotalWallclockTime() const { DBG_ASSERT(end_called_); return total_walltime_; } private: /**@name Default Compiler Generated Methods (Hidden to avoid * implicit creation/calling). These methods are not * implemented and we do not want the compiler to implement them * for us, so we declare them private and do not define * them. This ensures that they will not be implicitly * created/called. */ //@{ /** Copy Constructor */ TimedTask(const TimedTask&); /** Overloaded Equals Operator */ void operator=(const TimedTask&); //@} /** CPU time at beginning of task. */ Number start_cputime_; /** Total CPU time for task measured so far. */ Number total_cputime_; /** System time at beginning of task. */ Number start_systime_; /** Total system time for task measured so far. */ Number total_systime_; /** Wall clock time at beginning of task. */ Number start_walltime_; /** Total wall clock time for task measured so far. */ Number total_walltime_; /** @name fields for debugging */ //@{ bool start_called_; bool end_called_; //@} }; } // namespace Ipopt #endif
26.938776
72
0.630303
l03ie
a1c9f2968f8753cf27b57506628b1574cfde4c93
709
cpp
C++
src/TransportProtocol.cpp
daank94/simpleNW
b5c7d0d999b1b42bf0f45ad28629d6ce29e1c6c8
[ "MIT" ]
2
2015-09-16T23:20:50.000Z
2017-09-04T09:06:17.000Z
src/TransportProtocol.cpp
daank94/simpleNW
b5c7d0d999b1b42bf0f45ad28629d6ce29e1c6c8
[ "MIT" ]
null
null
null
src/TransportProtocol.cpp
daank94/simpleNW
b5c7d0d999b1b42bf0f45ad28629d6ce29e1c6c8
[ "MIT" ]
1
2021-04-11T10:27:51.000Z
2021-04-11T10:27:51.000Z
#include <TransportProtocol.hpp> TransportProtocol::TransportProtocol(transpprtcl protocol) { this->protocol_ = protocol; } namespace IPV4 { TransportProtocol DEFAULT() { return TransportProtocol(TransportProtocol::ipv4_default); } TransportProtocol TCP() { return TransportProtocol(TransportProtocol::ipv4_tcp); } TransportProtocol UDP() { return TransportProtocol(TransportProtocol::ipv4_udp); } } namespace IPV6 { TransportProtocol DEFAULT() { return TransportProtocol(TransportProtocol::ipv6_default); } TransportProtocol TCP() { return TransportProtocol(TransportProtocol::ipv6_tcp); } TransportProtocol UDP() { return TransportProtocol(TransportProtocol::ipv6_udp); } }
20.257143
60
0.777151
daank94
a1d195e24459bad67eb369b8c6f7609f19a6c484
6,832
cpp
C++
Modules/Graphics/Core/Sources/Methane/Graphics/RenderContextBase.cpp
navono/MethaneKit
5cf55dcbbc23392f5c06b178570c7c32b6368ca7
[ "Apache-2.0" ]
null
null
null
Modules/Graphics/Core/Sources/Methane/Graphics/RenderContextBase.cpp
navono/MethaneKit
5cf55dcbbc23392f5c06b178570c7c32b6368ca7
[ "Apache-2.0" ]
null
null
null
Modules/Graphics/Core/Sources/Methane/Graphics/RenderContextBase.cpp
navono/MethaneKit
5cf55dcbbc23392f5c06b178570c7c32b6368ca7
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** Copyright 2019-2020 Evgeny Gorodetskiy 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. ******************************************************************************* FILE: Methane/Graphics/RenderContextBase.cpp Base implementation of the render context interface. ******************************************************************************/ #include "RenderContextBase.h" #include "DeviceBase.h" #include <Methane/Graphics/TypeFormatters.hpp> #include <Methane/Graphics/CommandKit.h> #include <Methane/Checks.hpp> #include <Methane/Instrumentation.h> namespace Methane::Graphics { RenderContextBase::RenderContextBase(DeviceBase& device, tf::Executor& parallel_executor, const Settings& settings) : ContextBase(device, parallel_executor, Type::Render) , m_settings(settings) { META_FUNCTION_TASK(); META_CHECK_ARG_DESCR(m_settings.color_format, !IsSrgbColorSpace(m_settings.color_format), "render context can not use color formats with sRGB gamma correction due to modern swap-chain flip model limitations"); } void RenderContextBase::WaitForGpu(WaitFor wait_for) { META_FUNCTION_TASK(); ContextBase::WaitForGpu(wait_for); switch (wait_for) { case WaitFor::RenderComplete: WaitForGpuRenderComplete(); break; case WaitFor::FramePresented: WaitForGpuFramePresented(); break; case WaitFor::ResourcesUploaded: break; // Handled in ContextBase::WaitForGpu default: META_UNEXPECTED_ARG(wait_for); } } void RenderContextBase::WaitForGpuRenderComplete() { META_FUNCTION_TASK(); META_SCOPE_TIMER("RenderContextDX::WaitForGpu::RenderComplete"); OnGpuWaitStart(WaitFor::RenderComplete); GetRenderFence().FlushOnCpu(); GetUploadCommandKit().GetFence().FlushOnCpu(); OnGpuWaitComplete(WaitFor::RenderComplete); } void RenderContextBase::WaitForGpuFramePresented() { META_FUNCTION_TASK(); META_SCOPE_TIMER("RenderContextDX::WaitForGpu::FramePresented"); OnGpuWaitStart(WaitFor::FramePresented); GetCurrentFrameFence().WaitOnCpu(); OnGpuWaitComplete(WaitFor::FramePresented); } void RenderContextBase::Resize(const FrameSize& frame_size) { META_FUNCTION_TASK(); META_LOG("Render context '{}' RESIZE from {} to {}", GetName(), m_settings.frame_size, frame_size); m_settings.frame_size = frame_size; } void RenderContextBase::Present() { META_FUNCTION_TASK(); META_LOG("Render context '{}' PRESENT frame {}", GetName(), m_frame_buffer_index); m_fps_counter.OnCpuFrameReadyToPresent(); } void RenderContextBase::OnCpuPresentComplete(bool signal_frame_fence) { META_FUNCTION_TASK(); if (signal_frame_fence) { // Schedule a signal command in the queue for a currently finished frame GetCurrentFrameFence().Signal(); } META_CPU_FRAME_DELIMITER(m_frame_buffer_index, m_frame_index); META_LOG("Render context '{}' PRESENT COMPLETE frame {}", GetName(), m_frame_buffer_index); m_fps_counter.OnCpuFramePresented(); } Fence& RenderContextBase::GetCurrentFrameFence() const { META_FUNCTION_TASK(); return GetRenderCommandKit().GetFence(m_frame_buffer_index + 1); } Fence& RenderContextBase::GetRenderFence() const { META_FUNCTION_TASK(); return GetRenderCommandKit().GetFence(0U); } void RenderContextBase::ResetWithSettings(const Settings& settings) { META_FUNCTION_TASK(); META_LOG("Render context '{}' RESET with new settings", GetName()); WaitForGpu(WaitFor::RenderComplete); Ptr<DeviceBase> device_ptr = GetDeviceBase().GetDevicePtr(); m_settings = settings; Release(); Initialize(*device_ptr, true); } void RenderContextBase::Initialize(DeviceBase& device, bool deferred_heap_allocation, bool is_callback_emitted) { META_FUNCTION_TASK(); ContextBase::Initialize(device, deferred_heap_allocation, false); m_frame_index = 0U; if (is_callback_emitted) { Emit(&IContextCallback::OnContextInitialized, *this); } } bool RenderContextBase::UploadResources() { META_FUNCTION_TASK(); if (!ContextBase::UploadResources()) return false; // Render commands will wait for resources uploading completion in upload queue GetUploadCommandKit().GetFence().FlushOnGpu(GetRenderCommandKit().GetQueue()); return true; } void RenderContextBase::OnGpuWaitStart(WaitFor wait_for) { META_FUNCTION_TASK(); if (wait_for == WaitFor::FramePresented) { m_fps_counter.OnGpuFramePresentWait(); } ContextBase::OnGpuWaitStart(wait_for); } void RenderContextBase::OnGpuWaitComplete(WaitFor wait_for) { META_FUNCTION_TASK(); if (wait_for == WaitFor::FramePresented) { m_fps_counter.OnGpuFramePresented(); m_is_frame_buffer_in_use = false; PerformRequestedAction(); } else { ContextBase::OnGpuWaitComplete(wait_for); } } void RenderContextBase::UpdateFrameBufferIndex() { m_frame_buffer_index = GetNextFrameBufferIndex(); m_frame_index++; m_is_frame_buffer_in_use = true; } uint32_t RenderContextBase::GetNextFrameBufferIndex() { return (m_frame_buffer_index + 1) % m_settings.frame_buffers_count; } bool RenderContextBase::SetVSyncEnabled(bool vsync_enabled) { META_FUNCTION_TASK(); if (m_settings.vsync_enabled == vsync_enabled) return false; m_settings.vsync_enabled = vsync_enabled; return true; } bool RenderContextBase::SetFrameBuffersCount(uint32_t frame_buffers_count) { META_FUNCTION_TASK(); frame_buffers_count = std::min(std::max(2U, frame_buffers_count), 10U); if (m_settings.frame_buffers_count == frame_buffers_count) return false; Settings new_settings = m_settings; new_settings.frame_buffers_count = frame_buffers_count; ResetWithSettings(new_settings); return true; } bool RenderContextBase::SetFullScreen(bool is_full_screen) { META_FUNCTION_TASK(); if (m_settings.is_full_screen == is_full_screen) return false; // No need to reset context for switching to full-screen // Application window state is kept in sync with context by the user code and handles window resizing m_settings.is_full_screen = is_full_screen; return true; } } // namespace Methane::Graphics
28.705882
144
0.71692
navono
a1d1f1449ae01bb17e1b40601bfa38220798e9d4
42,450
cpp
C++
src/lib/foundations/finite_fields/finite_field.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-10-27T15:18:28.000Z
2022-02-09T11:13:07.000Z
src/lib/foundations/finite_fields/finite_field.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
4
2019-12-09T11:49:11.000Z
2020-07-30T17:34:45.000Z
src/lib/foundations/finite_fields/finite_field.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-06-10T20:05:30.000Z
2020-12-18T04:59:19.000Z
// finite_field.cpp // // Anton Betten // // started: October 23, 2002 #include "foundations.h" using namespace std; namespace orbiter { namespace foundations { int nb_calls_to_finite_field_init = 0; finite_field::finite_field() { f_has_table = FALSE; T = NULL; Iwo = NULL; //std::string symbol_for_print; polynomial = NULL; //std::string label; //std::string label_tex; //std::override_poly; //std::string my_poly; //std::symbol_for_print; f_is_prime_field = FALSE; q = 0; p = 0; e = 0; alpha = 0; log10_of_q = 1; f_print_as_exponentials = TRUE; nb_calls_to_mult_matrix_matrix = 0; nb_calls_to_PG_element_rank_modified = 0; nb_calls_to_PG_element_unrank_modified = 0; my_nb_calls_to_elliptic_curve_addition = 0; nb_times_mult = 0; nb_times_add = 0; } finite_field::~finite_field() { //print_call_stats(cout); //cout << "destroying tables" << endl; //cout << "destroying add_table" << endl; if (T) { FREE_OBJECT(T); } if (Iwo) { FREE_OBJECT(Iwo); } if (polynomial) { FREE_char(polynomial); } } void finite_field::print_call_stats(std::ostream &ost) { cout << "finite_field::print_call_stats" << endl; cout << "nb_calls_to_mult_matrix_matrix=" << nb_calls_to_mult_matrix_matrix << endl; cout << "nb_calls_to_PG_element_rank_modified=" << nb_calls_to_PG_element_rank_modified << endl; cout << "nb_calls_to_PG_element_unrank_modified=" << nb_calls_to_PG_element_unrank_modified << endl; } int &finite_field::nb_calls_to_elliptic_curve_addition() { return my_nb_calls_to_elliptic_curve_addition; } void finite_field::init(finite_field_description *Descr, int verbose_level) { int f_v = (verbose_level >= 1); if (f_v) { cout << "finite_field::init" << endl; } if (!Descr->f_q) { cout << "finite_field::init !Descr->f_q" << endl; exit(1); } if (Descr->f_override_polynomial) { if (f_v) { cout << "finite_field::init override_polynomial=" << Descr->override_polynomial << endl; cout << "finite_field::init before init_override_polynomial" << endl; } init_override_polynomial(Descr->q, Descr->override_polynomial, Descr->f_without_tables, verbose_level - 1); if (f_v) { cout << "finite_field::init after init_override_polynomial" << endl; } } else { if (f_v) { cout << "finite_field::init before finite_field_init" << endl; } finite_field_init(Descr->q, Descr->f_without_tables, verbose_level - 1); if (f_v) { cout << "finite_field::init after finite_field_init" << endl; } } if (f_v) { cout << "finite_field::init done" << endl; } } void finite_field::finite_field_init(int q, int f_without_tables, int verbose_level) { int f_v = (verbose_level >= 1); string poly; number_theory_domain NT; if (f_v) { cout << "finite_field::finite_field_init q=" << q << " verbose_level = " << verbose_level << endl; } nb_calls_to_finite_field_init++; finite_field::q = q; NT.factor_prime_power(q, p, e); set_default_symbol_for_print(); if (e > 1) { f_is_prime_field = FALSE; algebra_global Algebra; poly.assign(Algebra.get_primitive_polynomial(p, e, verbose_level)); if (f_v) { cout << "finite_field::finite_field_init q=" << q << " before init_override_polynomial poly = " << poly << endl; } init_override_polynomial(q, poly, f_without_tables, verbose_level); if (f_v) { cout << "finite_field::finite_field_init q=" << q << " after init_override_polynomial" << endl; } } else { f_is_prime_field = TRUE; poly.assign(""); if (f_v) { cout << "finite_field::finite_field_init q=" << q << " before init_override_polynomial poly = " << poly << endl; } init_override_polynomial(q, poly, f_without_tables, verbose_level); if (f_v) { cout << "finite_field::finite_field_init q=" << q << " after init_override_polynomial" << endl; } } char str[1000]; sprintf(str, "GF_%d", q); label.assign(str); sprintf(str, "{\\mathbb F}_{%d}", q); label_tex.assign(str); if (f_v) { cout << "finite_field::finite_field_init done" << endl; } } void finite_field::init_implementation(int f_without_tables, int verbose_level) { int f_v = (verbose_level >= 1); string poly; number_theory_domain NT; if (f_v) { cout << "finite_field::init_implementation" << endl; } if (f_without_tables) { if (f_v) { cout << "finite_field::init_implementation implementation without field tables" << endl; } f_has_table = FALSE; Iwo = NEW_OBJECT(finite_field_implementation_wo_tables); if (f_v) { cout << "finite_field::init_implementation before Iwo->init" << endl; } Iwo->init(this, verbose_level); if (f_v) { cout << "finite_field::init_implementation after Iwo->init" << endl; } } else { if (f_v) { cout << "finite_field::init_implementation implementation with field tables" << endl; } T = NEW_OBJECT(finite_field_implementation_by_tables); if (f_v) { cout << "finite_field::init_implementation before T->init" << endl; } T->init(this, verbose_level); if (f_v) { cout << "finite_field::init_implementation after T->init" << endl; } f_has_table = TRUE; } if (f_v) { cout << "finite_field::init_implementation done" << endl; } } void finite_field::set_default_symbol_for_print() { if (q == 4) { init_symbol_for_print("\\omega"); } else if (q == 8) { init_symbol_for_print("\\gamma"); } else if (q == 16) { init_symbol_for_print("\\delta"); } else if (q == 32) { init_symbol_for_print("\\eta"); } else if (q == 64) { init_symbol_for_print("\\epsilon"); } else if (q == 128) { init_symbol_for_print("\\zeta"); } else { init_symbol_for_print("\\alpha"); } } void finite_field::init_symbol_for_print(const char *symbol) { symbol_for_print.assign(symbol); } void finite_field::init_override_polynomial(int q, std::string &poly, int f_without_tables, int verbose_level) { int f_v = (verbose_level >= 1); int f_vv = (verbose_level >= 2); int l; number_theory_domain NT; if (f_v) { cout << "finite_field::init_override_polynomial " "q=" << q << " verbose_level = " << verbose_level << endl; } override_poly.assign(poly); finite_field::q = q; NT.factor_prime_power(q, p, e); if (f_v) { cout << "finite_field::init_override_polynomial p=" << p << endl; cout << "finite_field::init_override_polynomial e=" << e << endl; } //init_symbol_for_print("\\alpha"); log10_of_q = NT.int_log10(q); set_default_symbol_for_print(); if (e > 1) { f_is_prime_field = FALSE; algebra_global Algebra; if (poly.length() == 0) { my_poly.assign(Algebra.get_primitive_polynomial(p, e, verbose_level)); } else { my_poly.assign(poly); if (f_vv) { cout << "finite_field::init_override_polynomial, " "using polynomial " << my_poly << endl; } } if (f_v) { cout << "finite_field::init_override_polynomial " "using poly " << my_poly << endl; } } else { f_is_prime_field = TRUE; } if (f_v) { cout << "finite_field::init_override_polynomial " "GF(" << q << ") = GF(" << p << "^" << e << ")"; if (e > 1) { cout << ", polynomial = "; print_minimum_polynomial(p, my_poly.c_str()); cout << " = " << my_poly << endl; } else { cout << endl; } } l = my_poly.length(); polynomial = NEW_char(l + 1); strcpy(polynomial, my_poly.c_str()); char str[1000]; sprintf(str, "GF_%d", q); label.assign(str); label.append("_poly"); label.append(override_poly); sprintf(str, "{\\mathbb F}_{%d,", q); label_tex.assign(str); label_tex.append(override_poly); label_tex.append("}"); if (f_v) { cout << "finite_field::init_override_polynomial before init_implementation" << endl; } init_implementation(f_without_tables, verbose_level - 1); if (f_v) { cout << "finite_field::init_override_polynomial after init_implementation" << endl; } if (f_vv) { cout << "finite_field::init_override_polynomial " "finished" << endl; } } int finite_field::has_quadratic_subfield() { #if 0 if (!f_has_table) { cout << "finite_field::has_quadratic_subfield !f_has_table" << endl; exit(1); } return T->has_quadratic_subfield(); #else if ((e % 2) == 0) { return TRUE; } else { return FALSE; } #endif } int finite_field::belongs_to_quadratic_subfield(int a) { if ((e % 2) != 0) { cout << "finite_field::belongs_to_quadratic_subfield does not have a quadratic subfield" << endl; exit(1); } if (!f_has_table) { cout << "finite_field::belongs_to_quadratic_subfield !f_has_table" << endl; exit(1); } return T->belongs_to_quadratic_subfield(a); } long int finite_field::compute_subfield_polynomial(int order_subfield, int f_latex, std::ostream &ost, int verbose_level) { int f_v = (verbose_level >= 1); int f_vv = (verbose_level >= 2); int p1, e1, q1, i, j, jj, subgroup_index; number_theory_domain NT; if (f_v) { cout << "finite_field::compute_subfield_polynomial " "for subfield of order " << order_subfield << endl; } NT.factor_prime_power(order_subfield, p1, e1); if (p1 != p) { cout << "finite_field::compute_subfield_polynomial " "the subfield must have the same characteristic" << endl; exit(1); } if ((e % e1)) { cout << "finite_field::compute_subfield_polynomial " "is not a subfield" << endl; exit(1); } finite_field GFp; GFp.finite_field_init(p, FALSE /* f_without_tables */, 0); unipoly_domain FX(&GFp); unipoly_object m; FX.create_object_by_rank_string(m, polynomial, 0/*verbose_level*/); unipoly_domain Fq(&GFp, m, verbose_level - 1); int *M; int *K; int *base_cols; int rk, kernel_m, kernel_n; long int a; geometry_global Gg; M = NEW_int(e * (e1 + 1)); Orbiter->Int_vec.zero(M, e * (e1 + 1)); K = NEW_int(e); base_cols = NEW_int(e); q1 = NT.i_power_j(p, e1); subgroup_index = (q - 1) / (q1 - 1); if (f_v) { cout << "finite_field::compute_subfield_polynomial " "subfield " << p << "^" << e1 << " : subgroup_index = " << subgroup_index << endl; } for (i = 0; i <= e1; i++) { j = i * subgroup_index; jj = alpha_power(j); Gg.AG_element_unrank(p, M + i, e1 + 1, e, jj); { unipoly_object elt; Fq.create_object_by_rank(elt, jj, __FILE__, __LINE__, 0 /*verbose_level*/); if (f_v) { cout << i << " : " << j << " : " << jj << " : "; Fq.print_object(elt, cout); cout << endl; } Fq.delete_object(elt); } } if (f_latex) { ost << "$$" << endl; ost << "\\begin{array}{|c|c|c|c|}" << endl; ost << "\\hline" << endl; ost << "i & i\\cdot d & \\alpha^{id} & \\mbox{vector} \\\\" << endl; ost << "\\hline" << endl; int h; for (i = 0; i <= e1; i++) { ost << i; ost << " & "; j = i * subgroup_index; ost << j; ost << " & "; jj = alpha_power(j); ost << jj; ost << " & "; ost << "("; for (h = e - 1; h >= 0; h--) { ost << M[h * (e1 + 1) + i]; if (h) { ost << ","; } } ost << ")"; ost << "\\\\" << endl; //Gg.AG_element_unrank(p, M + i, e1 + 1, e, jj); } ost << "\\hline" << endl; ost << "\\end{array}" << endl; ost << "$$" << endl; } if (f_v) { cout << "finite_field::compute_subfield_polynomial M=" << endl; Orbiter->Int_vec.print_integer_matrix_width(cout, M, e, e1 + 1, e1 + 1, GFp.log10_of_q); } rk = GFp.Gauss_simple(M, e, e1 + 1, base_cols, 0/*verbose_level*/); if (f_vv) { cout << "finite_field::compute_subfield_polynomial after Gauss=" << endl; Orbiter->Int_vec.print_integer_matrix_width(cout, M, e, e1 + 1, e1 + 1, GFp.log10_of_q); cout << "rk=" << rk << endl; } if (rk != e1) { cout << "finite_field::compute_subfield_polynomial fatal: rk != e1" << endl; cout << "rk=" << rk << endl; exit(1); } GFp.matrix_get_kernel(M, e, e1 + 1, base_cols, rk, kernel_m, kernel_n, K, 0 /* verbose_level */); if (f_vv) { cout << "kernel_m=" << kernel_m << endl; cout << "kernel_n=" << kernel_n << endl; } if (kernel_n != 1) { cout << "kernel_n != 1" << endl; exit(1); } if (K[e1] == 0) { cout << "K[e1] == 0" << endl; exit(1); } if (K[e1] != 1) { a = GFp.inverse(K[e1]); for (i = 0; i < e1 + 1; i++) { K[i] = GFp.mult(a, K[i]); } } if (f_latex) { ost << "Left nullspace generated by:\\\\" << endl; ost << "$$" << endl; Orbiter->Int_vec.print(ost, K, e1 + 1); ost << "$$" << endl; } if (f_vv) { cout << "finite_field::compute_subfield_polynomial the relation is " << endl; Orbiter->Int_vec.print(cout, K, e1 + 1); cout << endl; } a = Gg.AG_element_rank(p, K, 1, e1 + 1); if (f_v) { unipoly_object elt; FX.create_object_by_rank(elt, a, __FILE__, __LINE__, verbose_level); cout << "finite_field::compute_subfield_polynomial " "subfield of order " << NT.i_power_j(p, e1) << " : " << a << " = "; Fq.print_object(elt, cout); cout << endl; Fq.delete_object(elt); } FREE_int(M); FREE_int(K); FREE_int(base_cols); return a; } void finite_field::compute_subfields(int verbose_level) { int f_v = (verbose_level >= 1); //int f_vv = (verbose_level >= 2); int e1; number_theory_domain NT; if (f_v) { cout << "finite_field::compute_subfields" << endl; } cout << "subfields of F_{" << q << "}:" << endl; finite_field GFp; GFp.finite_field_init(p, FALSE /* f_without_tables */, 0); unipoly_domain FX(&GFp); unipoly_object m; FX.create_object_by_rank_string(m, polynomial, 0 /*verbose_level*/); unipoly_domain Fq(&GFp, m, verbose_level - 1); //Fq.print_object(m, cout); for (e1 = 2; e1 < e; e1++) { if ((e % e1) == 0) { int poly; poly = compute_subfield_polynomial( NT.i_power_j(p, e1), FALSE, cout, verbose_level); { unipoly_object elt; FX.create_object_by_rank(elt, poly, __FILE__, __LINE__, verbose_level); cout << "subfield of order " << NT.i_power_j(p, e1) << " : " << poly << " = "; Fq.print_object(elt, cout); cout << endl; Fq.delete_object(elt); } } } FX.delete_object(m); } int finite_field::find_primitive_element(int verbose_level) { int f_v = (verbose_level >= 1); int i, ord; if (f_v) { cout << "finite_field::find_primitive_element" << endl; } for (i = 2; i < q; i++) { ord = compute_order_of_element(i, 0 /*verbose_level - 3*/); if (f_v) { cout << "finite_field::find_primitive_element the order of " << i << " is " << ord << endl; } if (ord == q - 1) { break; } } if (i == q) { cout << "finite_field::find_primitive_element could not find a primitive element" << endl; exit(1); } if (f_v) { cout << "finite_field::find_primitive_element done" << endl; } return i; } int finite_field::compute_order_of_element(int elt, int verbose_level) { int f_v = (verbose_level >= 1); int f_vv = (verbose_level >= 2); int i, k; if (f_v) { cout << "finite_field::compute_order_of_element " "q=" << q << " p=" << p << " e=" << e << " elt=" << elt << endl; } finite_field GFp; GFp.finite_field_init(p, FALSE /* f_without_tables */, 0); unipoly_domain FX(&GFp); unipoly_object m; FX.create_object_by_rank_string(m, polynomial, verbose_level - 2); if (f_vv) { cout << "m="; FX.print_object(m, cout); cout << endl; } { unipoly_domain Fq(&GFp, m, verbose_level - 1); unipoly_object a, c, Alpha; Fq.create_object_by_rank(Alpha, elt, __FILE__, __LINE__, verbose_level); Fq.create_object_by_rank(a, elt, __FILE__, __LINE__, verbose_level); Fq.create_object_by_rank(c, 1, __FILE__, __LINE__, verbose_level); for (i = 1; i < q; i++) { if (f_vv) { cout << "i=" << i << endl; } k = Fq.rank(a); if (f_vv) { cout << "a="; Fq.print_object(a, cout); cout << " has rank " << k << endl; } if (k < 0 || k >= q) { cout << "finite_field::compute_order_of_element error: k = " << k << endl; } if (k == 1) { break; } Fq.mult(a, Alpha, c, verbose_level - 1); Fq.assign(c, a, verbose_level - 2); } Fq.delete_object(Alpha); Fq.delete_object(a); Fq.delete_object(c); } FX.delete_object(m); if (f_v) { cout << "finite_field::compute_order_of_element done " "q=" << q << " p=" << p << " e=" << e << " order of " << elt << " is " << i << endl; } return i; } int *finite_field::private_add_table() { if (!f_has_table) { cout << "finite_field::private_add_table !f_has_table" << endl; exit(1); } return T->private_add_table(); } int *finite_field::private_mult_table() { if (!f_has_table) { cout << "finite_field::private_mult_table !f_has_table" << endl; exit(1); } return T->private_mult_table(); } int finite_field::zero() { return 0; } int finite_field::one() { return 1; } int finite_field::minus_one() { return negate(1); } int finite_field::is_zero(int i) { if (i == 0) { return TRUE; } else { return FALSE; } } int finite_field::is_one(int i) { if (i == 1) { return TRUE; } else { return FALSE; } } int finite_field::mult(int i, int j) { return mult_verbose(i, j, 0); } int finite_field::mult_verbose(int i, int j, int verbose_level) { int f_v = (verbose_level >= 1); int c; if (f_v) { cout << "finite_field_by_tables::mult_verbose" << endl; } nb_times_mult++; //cout << "finite_field::mult_verbose i=" << i << " j=" << j << endl; if (i < 0 || i >= q) { cout << "finite_field_by_tables::mult_verbose i = " << i << endl; exit(1); } if (j < 0 || j >= q) { cout << "finite_field_by_tables::mult_verbose j = " << j << endl; exit(1); } if (f_has_table) { if (f_v) { cout << "finite_field_by_tables::mult_verbose with table" << endl; } c = T->mult_verbose(i, j, verbose_level); } else { if (Iwo == NULL) { cout << "finite_field_by_tables::mult_verbose !f_has_table && Iwo == NULL" << endl; exit(1); } c = Iwo->mult(i, j, verbose_level); } return c; } int finite_field::a_over_b(int a, int b) { int bv, c; if (b == 0) { cout << "finite_field::a_over_b b == 0" << endl; exit(1); } bv = inverse(b); c = mult(a, bv); return c; } int finite_field::mult3(int a1, int a2, int a3) { int x; x = mult(a1, a2); x = mult(x, a3); return x; } int finite_field::product3(int a1, int a2, int a3) { int x; x = mult(a1, a2); x = mult(x, a3); return x; } int finite_field::mult4(int a1, int a2, int a3, int a4) { int x; x = mult(a1, a2); x = mult(x, a3); x = mult(x, a4); return x; } int finite_field::mult5(int a1, int a2, int a3, int a4, int a5) { int x; x = mult(a1, a2); x = mult(x, a3); x = mult(x, a4); x = mult(x, a5); return x; } int finite_field::mult6(int a1, int a2, int a3, int a4, int a5, int a6) { int x; x = mult(a1, a2); x = mult(x, a3); x = mult(x, a4); x = mult(x, a5); x = mult(x, a6); return x; } int finite_field::product4(int a1, int a2, int a3, int a4) { int x; x = mult(a1, a2); x = mult(x, a3); x = mult(x, a4); return x; } int finite_field::product5(int a1, int a2, int a3, int a4, int a5) { int x; x = mult(a1, a2); x = mult(x, a3); x = mult(x, a4); x = mult(x, a5); return x; } int finite_field::product_n(int *a, int n) { int x, i; if (n == 0) { return 1; } x = a[0]; for (i = 1; i < n; i++) { x = mult(x, a[i]); } return x; } int finite_field::square(int a) { return mult(a, a); } int finite_field::twice(int a) { int two; two = 2 % p; return mult(two, a); } int finite_field::four_times(int a) { int four; four = 4 % p; return mult(four, a); } int finite_field::Z_embedding(int k) { int a; a = k % p; return a; } int finite_field::add(int i, int j) { geometry_global Gg; int verbose_level = 0; int f_v = (verbose_level >= 1); int c; nb_times_add++; if (!f_has_table) { cout << "finite_field::add !f_has_table" << endl; exit(1); } if (f_has_table) { if (f_v) { cout << "finite_field_by_tables::add with table" << endl; } c = T->add(i, j); } else { if (Iwo == NULL) { cout << "finite_field_by_tables::add !f_has_table && Iwo == NULL" << endl; exit(1); } c = Iwo->add(i, j, verbose_level); } return c; } int finite_field::add3(int i1, int i2, int i3) { int x; x = add(i1, i2); x = add(x, i3); return x; } int finite_field::add4(int i1, int i2, int i3, int i4) { int x; x = add(i1, i2); x = add(x, i3); x = add(x, i4); return x; } int finite_field::add5(int i1, int i2, int i3, int i4, int i5) { int x; x = add(i1, i2); x = add(x, i3); x = add(x, i4); x = add(x, i5); return x; } int finite_field::add6(int i1, int i2, int i3, int i4, int i5, int i6) { int x; x = add(i1, i2); x = add(x, i3); x = add(x, i4); x = add(x, i5); x = add(x, i6); return x; } int finite_field::add7(int i1, int i2, int i3, int i4, int i5, int i6, int i7) { int x; x = add(i1, i2); x = add(x, i3); x = add(x, i4); x = add(x, i5); x = add(x, i6); x = add(x, i7); return x; } int finite_field::add8(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8) { int x; x = add(i1, i2); x = add(x, i3); x = add(x, i4); x = add(x, i5); x = add(x, i6); x = add(x, i7); x = add(x, i8); return x; } int finite_field::negate(int i) { int verbose_level = 0; int f_v = (verbose_level >= 1); int c; if (i < 0 || i >= q) { cout << "finite_field::negate i = " << i << endl; exit(1); } if (f_has_table) { if (f_v) { cout << "finite_field_by_tables::negate with table" << endl; } c = T->negate(i); } else { if (Iwo == NULL) { cout << "finite_field_by_tables::negate !f_has_table && Iwo == NULL" << endl; exit(1); } c = Iwo->negate(i, verbose_level); } return c; } int finite_field::inverse(int i) { int c; int verbose_level = 0; int f_v = (verbose_level >= 1); if (f_has_table) { if (f_v) { cout << "finite_field_by_tables::inverse with table" << endl; } c = T->inverse(i); } else { if (Iwo == NULL) { cout << "finite_field_by_tables::inverse !f_has_table && Iwo == NULL" << endl; exit(1); } c = Iwo->inverse(i, verbose_level); } return c; } int finite_field::power(int a, int n) // computes a^n { return power_verbose(a, n, 0); } int finite_field::power_verbose(int a, int n, int verbose_level) // computes a^n { int f_v = (verbose_level >= 1); int b, c; if (f_v) { cout << "finite_field::power_verbose a=" << a << " n=" << n << endl; } b = a; c = 1; while (n) { if (f_v) { cout << "finite_field::power_verbose n=" << n << " a=" << a << " b=" << b << " c=" << c << endl; } if (n % 2) { //cout << "finite_field::power: mult(" << b << "," << c << ")="; c = mult(b, c); //cout << c << endl; } b = mult_verbose(b, b, verbose_level); n >>= 1; //cout << "finite_field::power: " << b << "^" //<< n << " * " << c << endl; } if (f_v) { cout << "finite_field::power_verbose a=" << a << " n=" << n << " c=" << c << " done" << endl; } return c; } void finite_field::frobenius_power_vec(int *v, int len, int frob_power) { int h; for (h = 0; h < len; h++) { v[h] = frobenius_power(v[h], frob_power); } } void finite_field::frobenius_power_vec_to_vec(int *v_in, int *v_out, int len, int frob_power) { int h; for (h = 0; h < len; h++) { v_out[h] = frobenius_power(v_in[h], frob_power); } } int finite_field::frobenius_power(int a, int frob_power) // computes a^{p^i} { if (!f_has_table) { cout << "finite_field::frobenius_power !f_has_table" << endl; exit(1); } a = T->frobenius_power(a, frob_power); return a; } int finite_field::absolute_trace(int i) { int j, ii = i, t = 0; if (!f_has_table) { cout << "finite_field::absolute_trace !f_has_table" << endl; exit(1); } for (j = 0; j < e; j++) { //ii = power(ii, p); //cout << "absolute_trace() ii = " << ii << " -> "; ii = T->frobenius_image(ii); //cout << ii << endl; t = add(t, ii); } if (ii != i) { cout << "finite_field::absolute_trace ii != i" << endl; cout << "i=" << i << endl; cout << "ii=" << ii << endl; ii = i; for (j = 0; j < e; j++) { ii = T->frobenius_image(ii); cout << "j=" << j << " ii=" << ii << endl; } exit(1); } return t; } int finite_field::absolute_norm(int i) { int j, ii = i, t = 1; if (!f_has_table) { cout << "finite_field::absolute_norm !f_has_table" << endl; exit(1); } for (j = 0; j < e; j++) { //ii = power(ii, p); //cout << "absolute_trace ii = " << ii << " -> "; ii = T->frobenius_image(ii); //cout << ii << endl; t = mult(t, ii); } if (ii != i) { cout << "finite_field::absolute_norm ii != i" << endl; exit(1); } return t; } int finite_field::alpha_power(int i) { if (!f_has_table) { cout << "finite_field::alpha_power !f_has_table" << endl; exit(1); } return T->alpha_power(i); } int finite_field::log_alpha(int i) { if (!f_has_table) { cout << "finite_field::log_alpha !f_has_table" << endl; exit(1); } return T->log_alpha(i); } int finite_field::multiplicative_order(int a) { int l, g, order; number_theory_domain NT; if (a == 0) { cout << "finite_field::multiplicative_order a == 0" << endl; exit(1); } l = log_alpha(a); g = NT.gcd_lint(l, q - 1); order = (q - 1) / g; return order; } void finite_field::all_square_roots(int a, int &nb_roots, int *roots2) { if (a == 0) { nb_roots = 1; roots2[0] = 0; } else { if (p == 2) { // we are in characteristic two nb_roots = 1; roots2[0] = frobenius_power(a, e - 1 /* frob_power */); } else { // we are in characteristic odd int r; r = log_alpha(a); if (ODD(r)) { nb_roots = 0; } else { nb_roots = 2; r >>= 1; roots2[0] = alpha_power(r); roots2[1] = negate(roots2[0]); } } } } int finite_field::square_root(int i, int &root) { int r; r = log_alpha(i); if (ODD(r)) { cout << "finite_field::square_root not a square: " << i << endl; exit(1); //return FALSE; } r >>= 1; root = alpha_power(r); return TRUE; } int finite_field::primitive_root() { return alpha; } int finite_field::N2(int a) { int r; int b, c; r = e >> 1; if (e != 2 * r) { cout << "finite_field::N2 field does not have a " "quadratic subfield" << endl; exit(1); } b = frobenius_power(a, r); c = mult(a, b); return c; } int finite_field::N3(int a) { int r; int b, c; r = e / 3; if (e != 3 * r) { cout << "finite_field::N3 field does not have a " "cubic subfield" << endl; exit(1); } b = frobenius_power(a, r); c = mult(a, b); b = frobenius_power(b, r); c = mult(c, b); return c; } int finite_field::T2(int a) { int r; int b, c; r = e >> 1; if (e != 2 * r) { cout << "finite_field::T2 field does not have a " "quadratic subfield" << endl; exit(1); } b = frobenius_power(a, r); c = add(a, b); return c; } int finite_field::T3(int a) { int r; int b, c; r = e / 3; if (e != 3 * r) { cout << "finite_field::T3 field does not have a " "cubic subfield" << endl; exit(1); } b = frobenius_power(a, r); c = add(a, b); b = frobenius_power(b, r); c = add(c, b); return c; } int finite_field::bar(int a) { int r; int b; r = e >> 1; if (e != 2 * r) { cout << "finite_field::bar field does not have a " "quadratic subfield" << endl; exit(1); } b = frobenius_power(a, r); return b; } void finite_field::abc2xy(int a, int b, int c, int &x, int &y, int verbose_level) // given a, b, c, determine x and y such that // c = a * x^2 + b * y^2 // such elements x and y exist for any choice of a, b, c. { int f_v = (verbose_level >= 1); int xx, yy, cc; if (f_v) { cout << "finite_field::abc2xy q=" << q << " a=" << a << " b=" << b << " c=" << c << endl; } for (x = 0; x < q; x++) { xx = mult(x, x); for (y = 0; y < q; y++) { yy = mult(y, y); cc = add(mult(a, xx), mult(b, yy)); if (cc == c) { if (f_v) { cout << "finite_field::abc2xy q=" << q << " x=" << x << " y=" << y << " done" << endl; } return; } } } cout << "finite_field::abc2xy no solution" << endl; cout << "a=" << a << endl; cout << "b=" << b << endl; cout << "c=" << c << endl; exit(1); } int finite_field::retract(finite_field &subfield, int index, int a, int verbose_level) { int b; retract_int_vec(subfield, index, &a, &b, 1, verbose_level); return b; } void finite_field::retract_int_vec(finite_field &subfield, int index, int *v_in, int *v_out, int len, int verbose_level) { int f_v = (verbose_level >= 1); int a, b, i, j, idx, m, n, k; number_theory_domain NT; if (f_v) { cout << "finite_field::retract_int_vec index=" << index << endl; } n = e / index; m = NT.i_power_j(p, n); if (m != subfield.q) { cout << "finite_field::retract_int_vec subfield " "order does not match" << endl; exit(1); } idx = (q - 1) / (m - 1); if (f_v) { cout << "finite_field::retract_int_vec " "subfield " << p << "^" << n << " = " << n << endl; cout << "idx = " << idx << endl; } for (k = 0; k < len; k++) { a = v_in[k]; if (a == 0) { v_out[k] = 0; continue; } i = log_alpha(a); if (i % idx) { cout << "finite_field::retract_int_vec index=" << index << " k=" << k << " a=" << a << endl; cout << "element does not lie in the subfield" << endl; exit(1); } j = i / idx; b = subfield.alpha_power(j); v_out[k] = b; } if (f_v) { cout << "finite_field::retract_int_vec done" << endl; } } int finite_field::embed(finite_field &subfield, int index, int b, int verbose_level) { int f_v = (verbose_level >= 1); int a, i, j, idx, m, n; number_theory_domain NT; if (f_v) { cout << "finite_field::embed index=" << index << " b=" << b << endl; } if (b == 0) { a = 0; goto finish; } j = subfield.log_alpha(b); n = e / index; m = NT.i_power_j(p, n); if (m != subfield.q) { cout << "finite_field::embed subfield order does not match" << endl; exit(1); } idx = (q - 1) / (m - 1); if (f_v) { cout << "subfield " << p << "^" << n << " = " << n << endl; cout << "idx = " << idx << endl; } i = j * idx; a = alpha_power(i); finish: if (f_v) { cout << "finite_field::embed index=" << index << " b=" << b << " a=" << a << endl; } return a; } void finite_field::subfield_embedding_2dimensional( finite_field &subfield, int *&components, int *&embedding, int *&pair_embedding, int verbose_level) // we think of F as two dimensional vector space over f with basis (1,alpha) // for i,j \in f, with x = i + j * alpha \in F, we have // pair_embedding[i * q + j] = x; // also, // components[x * 2 + 0] = i; // components[x * 2 + 1] = j; // also, for i \in f, embedding[i] is the element in F that corresponds to i // components[Q * 2] // embedding[q] // pair_embedding[q * q] { int f_v = (verbose_level >= 1); int f_vv = (verbose_level >= 1); int alpha, i, j, I, J, x, q, Q; if (f_v) { cout << "finite_field::subfield_embedding_2dimensional" << endl; } Q = finite_field::q; q = subfield.q; components = NEW_int(Q * 2); embedding = NEW_int(q); pair_embedding = NEW_int(q * q); alpha = p; embedding[0] = 0; for (i = 0; i < q * q; i++) { pair_embedding[i] = -1; } for (i = 0; i < Q * 2; i++) { components[i] = -1; } for (i = 1; i < q; i++) { j = embed(subfield, 2, i, verbose_level - 2); embedding[i] = j; } for (i = 0; i < q; i++) { I = embed(subfield, 2, i, verbose_level - 4); if (f_vv) { cout << "i=" << i << " I=" << I << endl; } for (j = 0; j < q; j++) { J = embed(subfield, 2, j, verbose_level - 4); x = add(I, mult(alpha, J)); if (pair_embedding[i * q + j] != -1) { cout << "error" << endl; cout << "element (" << i << "," << j << ") embeds " "as (" << I << "," << J << ") = " << x << endl; exit(1); } pair_embedding[i * q + j] = x; components[x * 2 + 0] = i; components[x * 2 + 1] = j; if (f_vv) { cout << "element (" << i << "," << j << ") embeds " "as (" << I << "," << J << ") = " << x << endl; } } } if (f_vv) { print_embedding(subfield, components, embedding, pair_embedding); } if (f_v) { cout << "finite_field::subfield_embedding_2dimensional " "done" << endl; } } int finite_field::nb_times_mult_called() { return nb_times_mult; } int finite_field::nb_times_add_called() { return nb_times_add; } void finite_field::compute_nth_roots(int *&Nth_roots, int n, int verbose_level) { int f_v = (verbose_level >= 1); int i, idx, beta; if (f_v) { cout << "finite_field::compute_nth_roots" << endl; } if ((q - 1) % n) { cout << "finite_field::compute_nth_roots n does not divide q - 1" << endl; exit(1); } idx = (q - 1) / n; beta = power(alpha, idx); Nth_roots = NEW_int(n); Nth_roots[0] = 1; Nth_roots[1] = beta; for (i = 2; i < n; i++) { Nth_roots[i] = mult(Nth_roots[i - 1], beta); } if (f_v) { cout << "finite_field::compute_nth_roots done" << endl; } } void finite_field::compute_nth_roots_as_polynomials(unipoly_domain *FpX, unipoly_domain *Fq, unipoly_object *&Beta, int n1, int n2, int verbose_level) { int f_v = (verbose_level >= 1); //unipoly_object M; unipoly_object beta; if (f_v) { cout << "finite_field::compute_nth_roots_as_polynomials " << endl; } #if 0 Fp.finite_field_init(p, FALSE /* f_without_tables */, verbose_level - 1); algebra_global Algebra; unipoly_domain FpX(&Fp); FpX.create_object_by_rank_string(M, Algebra.get_primitive_polynomial(p, field_degree, 0), verbose_level - 2); #endif int m, r; int i; longinteger_object Qm1, Index; longinteger_domain D; number_theory_domain NT; m = NT.order_mod_p(q, n1); if (f_v) { cout << "coding_theory_domain::make_cyclic_code order of q mod n is m=" << m << endl; } D.create_qnm1(Qm1, q, m); // q = i_power_j(p, e); // GF(q)=GF(p^e) has n-th roots of unity D.integral_division_by_int(Qm1, n2, Index, r); if (f_v) { cout << "coding_theory_domain::make_cyclic_code Index = " << Index << endl; } int subgroup_index; subgroup_index = Index.as_int(); if (f_v) { cout << "coding_theory_domain::make_cyclic_code subgroup_index = " << subgroup_index << endl; } //b = (q - 1) / n; if (r != 0) { cout << "coding_theory_domain::make_cyclic_code n does not divide q^m-1" << endl; exit(1); } #if 0 if (f_v) { cout << "finite_field::compute_nth_roots_as_polynomials choosing the following irreducible " "and primitive polynomial:" << endl; FpX.print_object(M, cout); cout << endl; } if (f_v) { cout << "finite_field::compute_nth_roots_as_polynomials creating unipoly_domain Fq modulo M" << endl; } //unipoly_domain Fq(this, M, verbose_level); // Fq = Fp[X] modulo factor polynomial M if (f_v) { cout << "finite_field::compute_nth_roots_as_polynomials extension field created" << endl; } #endif Beta = new unipoly_object[n2]; for (i = 0; i < n2; i++) { Fq->create_object_by_rank(Beta[i], 0, __FILE__, __LINE__, verbose_level); } //Fq->create_object_by_rank(c, 0, __FILE__, __LINE__, verbose_level); Fq->create_object_by_rank(beta, p, __FILE__, __LINE__, verbose_level); // the element alpha //Fq->create_object_by_rank(beta_i, 1, __FILE__, __LINE__, verbose_level); if (subgroup_index != 1) { //Fq.power_int(beta, b); if (f_v) { cout << "\\alpha = "; Fq->print_object(beta, cout); cout << endl; } if (f_v) { cout << "finite_field::compute_nth_roots_as_polynomials before Fq->power_int" << endl; } Fq->power_int(beta, subgroup_index, verbose_level - 1); if (f_v) { cout << "\\beta = \\alpha^" << Index << " = "; Fq->print_object(beta, cout); cout << endl; } } else { if (f_v) { cout << "finite_field::compute_nth_roots_as_polynomials subgroup_index is one" << endl; } } for (i = 0; i < n2; i++) { if (f_v) { cout << "finite_field::compute_nth_roots_as_polynomials i=" << i << endl; } if (f_v) { cout << "finite_field::compute_nth_roots_as_polynomials working on root " << i << endl; } if (f_v) { cout << "finite_field::compute_nth_roots_as_polynomials before Fq.assign beta" << endl; } Fq->assign(beta, Beta[i], verbose_level); if (f_v) { cout << "finite_field::compute_nth_roots_as_polynomials before Fq.power_int" << endl; } Fq->power_int(Beta[i], i, verbose_level); } if (f_v) { cout << "finite_field::compute_nth_roots_as_polynomials done" << endl; } } void finite_field::compute_powers(unipoly_domain *Fq, int n, int start_idx, unipoly_object *&Beta, int verbose_level) { int f_v = (verbose_level >= 1); if (f_v) { cout << "finite_field::compute_powers" << endl; } int i; unipoly_object beta; Beta = new unipoly_object[n]; for (i = 0; i < n; i++) { Fq->create_object_by_rank(Beta[i], 0, __FILE__, __LINE__, verbose_level); } Fq->create_object_by_rank(beta, p, __FILE__, __LINE__, verbose_level); // the element alpha if (start_idx != 1) { if (f_v) { cout << "\\alpha = "; Fq->print_object(beta, cout); cout << endl; } if (f_v) { cout << "finite_field::compute_powers before Fq->power_int" << endl; } Fq->power_int(beta, start_idx, verbose_level - 1); if (f_v) { cout << "\\beta = \\alpha^" << start_idx << " = "; Fq->print_object(beta, cout); cout << endl; } } else { if (f_v) { cout << "finite_field::compute_powers subgroup_index is one" << endl; } } for (i = 0; i < n; i++) { if (f_v) { cout << "finite_field::compute_powers i=" << i << endl; } if (f_v) { cout << "finite_field::compute_powers working on root " << i << endl; } if (f_v) { cout << "finite_field::compute_powers before Fq.assign beta" << endl; } Fq->assign(beta, Beta[i], verbose_level); if (f_v) { cout << "finite_field::compute_powers before Fq.power_int" << endl; } Fq->power_int(Beta[i], i, verbose_level); } if (f_v) { cout << "finite_field::compute_powers done" << endl; } } void finite_field::create_irreducible_polynomial(unipoly_domain *Fq, unipoly_object *&Beta, int n, long int *cyclotomic_set, int cylotomic_set_size, unipoly_object *&generator, int verbose_level) { int f_v = (verbose_level >= 1); if (f_v) { cout << "finite_field::create_irreducible_polynomial n=" << n << endl; } if (f_v) { cout << "finite_field::create_irreducible_polynomial before allocating generator etc" << endl; } int degree = cylotomic_set_size; coding_theory_domain Codes; generator = NEW_OBJECTS(unipoly_object, degree + 2); unipoly_object *tmp = NEW_OBJECTS(unipoly_object, degree + 1); unipoly_object *linear_factor = NEW_OBJECTS(unipoly_object, 2); unipoly_object Pc, Pd; int i, j, h, r; // create the polynomial linear_factor = X - a: if (f_v) { cout << "finite_field::create_irreducible_polynomial creating linear_factor = X-a" << endl; } for (i = 0; i < 2; i++) { if (i == 1) { Fq->create_object_by_rank(linear_factor[i], 1, __FILE__, __LINE__, verbose_level); } else { Fq->create_object_by_rank(linear_factor[i], 0, __FILE__, __LINE__, verbose_level); } } for (i = 0; i <= degree; i++) { if (f_v) { cout << "finite_field::create_irreducible_polynomial creating generator[" << i << "]" << endl; } Fq->create_object_by_rank(generator[i], 0, __FILE__, __LINE__, verbose_level); Fq->create_object_by_rank(tmp[i], 0, __FILE__, __LINE__, verbose_level); } if (f_v) { cout << "finite_field::create_irreducible_polynomial creating generator[0]" << endl; } Fq->create_object_by_rank(generator[0], 1, __FILE__, __LINE__, verbose_level); // now coeffs has degree 1 // and generator has degree 0 if (f_v) { cout << "finite_field::create_irreducible_polynomial coeffs:" << endl; Codes.print_polynomial(*Fq, 1, linear_factor); cout << endl; cout << "finite_field::create_irreducible_polynomial generator:" << endl; Codes.print_polynomial(*Fq, 0, generator); cout << endl; } if (f_v) { cout << "finite_field::create_irreducible_polynomial creating Pc" << endl; } Fq->create_object_by_rank(Pc, 0, __FILE__, __LINE__, verbose_level); if (f_v) { cout << "finite_field::create_irreducible_polynomial creating Pd" << endl; } Fq->create_object_by_rank(Pd, 0, __FILE__, __LINE__, verbose_level); r = 0; for (h = 0; h < cylotomic_set_size; h++) { i = cyclotomic_set[h]; if (f_v) { cout << "h=" << h << ", i=" << i << endl; } if (f_v) { cout << "finite_field::create_irreducible_polynomial working on root " << i << endl; } if (f_v) { cout << "finite_field::create_irreducible_polynomial before Fq.assign beta" << endl; } Fq->assign(Beta[i], linear_factor[0], verbose_level); if (f_v) { cout << "finite_field::create_irreducible_polynomial before Fq.negate" << endl; } Fq->negate(linear_factor[0]); if (f_v) { cout << "finite_field::create_irreducible_polynomial root: " << i << " : "; Fq->print_object(linear_factor[0], cout); //cout << " : "; //print_polynomial(Fq, 2, coeffs); cout << endl; } if (f_v) { cout << "finite_field::create_irreducible_polynomial before Fq.assign(generator[j], tmp[j])" << endl; } for (j = 0; j <= r; j++) { Fq->assign(generator[j], tmp[j], verbose_level); } //cout << "tmp:" << endl; //print_polynomial(Fq, r, tmp); //cout << endl; if (f_v) { cout << "finite_field::create_irreducible_polynomial before Fq.assign(tmp[j], generator[j + 1])" << endl; } for (j = 0; j <= r; j++) { Fq->assign(tmp[j], generator[j + 1], verbose_level); } Fq->delete_object(generator[0]); Fq->create_object_by_rank(generator[0], 0, __FILE__, __LINE__, verbose_level); //cout << "generator after shifting up:" << endl; //print_polynomial(Fq, r + 1, generator); //cout << endl; for (j = 0; j <= r; j++) { if (f_v) { cout << "finite_field::create_irreducible_polynomial j=" << j << endl; } if (f_v) { cout << "finite_field::create_irreducible_polynomial before Fq.mult(tmp[j], linear_factor[0], Pc)" << endl; } Fq->mult(tmp[j], linear_factor[0], Pc, verbose_level - 1); if (f_v) { cout << "finite_field::create_irreducible_polynomial before Fq.add()" << endl; } Fq->add(Pc, generator[j], Pd); if (f_v) { cout << "finite_field::create_irreducible_polynomial before Fq.assign()" << endl; } Fq->assign(Pd, generator[j], verbose_level); } r++; if (f_v) { cout << "finite_field::create_irreducible_polynomial r=" << r << endl; } if (f_v) { cout << "finite_field::create_irreducible_polynomial current polynomial: "; Codes.print_polynomial(*Fq, r, generator); cout << endl; } } if (r != degree) { cout << "finite_field::create_irreducible_polynomial r != degree" << endl; exit(1); } if (f_v) { cout << "finite_field::create_irreducible_polynomial The generator polynomial is: "; Codes.print_polynomial(*Fq, r, generator); cout << endl; } if (f_v) { cout << "finite_field::create_irreducible_polynomial done" << endl; } } } }
21.504559
115
0.607044
abetten
a1d2c612df1c9b6816ddfd50b6c2c9e8113b9147
10,991
cpp
C++
BT_engine/BT_CPP_engine.cpp
barbalberto/YARP-BT-modules
5e89e381f6d39bc8561b372dbf3969660cf876c5
[ "BSD-3-Clause" ]
null
null
null
BT_engine/BT_CPP_engine.cpp
barbalberto/YARP-BT-modules
5e89e381f6d39bc8561b372dbf3969660cf876c5
[ "BSD-3-Clause" ]
null
null
null
BT_engine/BT_CPP_engine.cpp
barbalberto/YARP-BT-modules
5e89e381f6d39bc8561b372dbf3969660cf876c5
[ "BSD-3-Clause" ]
null
null
null
#include <yarp/os/Network.h> #include <yarp/os/LogStream.h> #include <yarp/os/RFModule.h> #include <yarp/os/YarpPlugin.h> #include <behaviortree_cpp/bt_factory.h> #include <BT_CPP_leaves/btCpp_common.h> #include <behaviortree_cpp/blackboard.h> // For Groot monitor #include <behaviortree_cpp/loggers/bt_cout_logger.h> #include <behaviortree_cpp/loggers/bt_file_logger.h> #include <behaviortree_cpp/loggers/bt_zmq_publisher.h> #include <behaviortree_cpp/loggers/bt_minitrace_logger.h> using namespace BT; using namespace std; using namespace yarp::os; const string plugin_path_env = "BT_CPP_PLUGIN_DIRS"; static Bottle parsePaths(const std::string& txt) { if (txt.empty()) { return Bottle(); } char slash = NetworkBase::getDirectorySeparator()[0]; char sep = NetworkBase::getPathSeparator()[0]; Bottle result; const char *at = txt.c_str(); int slash_tweak = 0; int len = 0; for (char ch : txt) { if (ch==sep) { result.addString(std::string(at, len-slash_tweak)); at += len+1; len = 0; slash_tweak = 0; continue; } slash_tweak = (ch==slash && len>0)?1:0; len++; } if (len>0) { result.addString(std::string(at, len-slash_tweak)); } return result; } class BT_Engine : public yarp::os::RFModule { private: double period; // We use the BehaviorTreeFactory to register our custom nodes Tree tree; BehaviorTreeFactory factory; std::unique_ptr<MinitraceLogger> logger_minitrace; std::unique_ptr<FileLogger> logger_file; std::unique_ptr<StdCoutLogger> logger_cout; std::unique_ptr<PublisherZMQ> publisher_zmq; public: bool configure(ResourceFinder &rf) override { this->setName("BT_engine"); bool verbose = rf.check("verbose"); period = rf.check("period", Value(0.020)).asDouble(); // // Handle BT description xml file // // get the name of xml file describing the BT. Mandatory string bt_description_name = rf.find("bt_description").asString(); if(bt_description_name == "") { yError() << "Missing <bt_description> parameter"; return false; } // Actually find the file using the ResourceFinder ResourceFinder bt_description_finder; if(rf.check("context")) bt_description_finder.setDefaultContext(rf.find("context").asString().c_str()); if(verbose) { bt_description_finder.setVerbose(); yInfo() << "Searching for file " << bt_description_name << (rf.check("context") ? (string(" in context ") + rf.find("context").asString() + ".") : string(".")); } string bt_description_path = bt_description_finder.findFileByName(bt_description_name); if(bt_description_path == "") { yError() << string("Can't find <") + bt_description_name + "> file."; return false; } yDebug() << bt_description_path; // // Handle list of node libraries // // get the list of shared libraries containing the node classes Value input = rf.find("libraries"); Bottle *libraries_names; if(input.isList()) libraries_names = input.asList(); else libraries_names = new Bottle; // include default libs, always shipped with this executable libraries_names->addString("libBT_CPP_leaves.so"); // Read env variables with path into which search for libraries Bottle paths = parsePaths(NetworkBase::getEnvironment(plugin_path_env.c_str())); if(verbose && paths.size() == 0) { yWarning() << "Environment variable " << plugin_path_env << " is missing, BT plugins may not be found"; } if(verbose) yDebug() << "Looking for node libraries " << libraries_names->toString(); char slash = NetworkBase::getDirectorySeparator()[0]; // Keep track of libraries already found ... loading two times the same one creates issues std::map<string, bool> libFound; // Search all required libraries for(int lib=0; lib<libraries_names->size(); lib++) { string libName = libraries_names->get(lib).toString(); auto it = libFound.find( libName); if (it != libFound.end()) { // lib already found continue; } bool found = false; // search in all known paths for(int path=0; path<paths.size(); path++) { try { string libPath = paths.get(path).asString() + slash + libName; yInfo() << "looking for " << libPath; factory.registerFromPlugin(libPath); found = true; break; } catch(RuntimeError err) { // lib not found yError() << err.what(); } } libFound[libName] = found; if(!found) { yError() << "Cannot find library " << libraries_names->get(lib).toString() << " inside provided paths " << paths.toString() << "\n\tPlease update environment variable " << plugin_path_env << " with the path containing the library."; return false; } } if(!input.isList()) delete libraries_names; // // find parameter file, if any // Property params; // Actually find the file using the ResourceFinder ResourceFinder params_file_finder; string param_file_name= ""; if(rf.check("params_file")) { params_file_finder.setDefaultContext(rf.find("context").asString().c_str()); param_file_name = rf.find("params_file").asString(); if(verbose) { params_file_finder.setVerbose(); yInfo() << "Searching for parameters file " << param_file_name << (rf.check("context") ? (string(" in context ") + rf.find("context").asString() + ".") : string(".")); } string param_file_path = params_file_finder.findFileByName(param_file_name); if(param_file_path == "") { yError() << string("Can't find <") + param_file_name + "> file."; return false; } yDebug() << param_file_path; yDebug() << params_file_finder.toString(); // Fill in a Propety params.fromConfigFile(param_file_path); yDebug() << params.toString(); } // Trees are created at deployment-time (i.e. at run-time, but only once at the beginning). // The currently supported format is XML. // IMPORTANT: when the object "tree" goes out of scope, all the TreeNodes are destroyed yInfo() << "Loading BT from file" << bt_description_path; tree = factory.createTreeFromFile(bt_description_path); // // Make sure to call 'init' function on each node, if present // bool ret{true}; yInfo() << "tree.nodes size is " << tree.nodes.size(); for( auto& node: tree.nodes ) { yInfo() << "Initting " << node->name(); if( auto action_B_node = dynamic_cast<bt_cpp_modules::iBT_CPP_modules*>( node.get() )) { yInfo() << "Calling init for node " << node->name(); if(! action_B_node->initialize(params) ) { ret = false; yError() << node->name() << "failed to initialize. Cannot start the BT engine."; } } } if(!ret) { yError() << "Some nodes failed to initialize. Quitting."; return false; } // Open ZMQ socket for Groot GUI logger_minitrace = make_unique<MinitraceLogger>(tree, "bt_trace.json"); logger_file = make_unique<FileLogger> (tree, "bt_trace.fbl"); logger_cout = make_unique<StdCoutLogger> (tree); publisher_zmq = make_unique<PublisherZMQ>(tree); printTreeRecursively(tree.root_node); // std::this_thread::sleep_for(std::chrono::seconds(2)); for(int i : {1,0}) { NodeStatus status = NodeStatus(i); for(auto node : tree.nodes) { node->setStatus((NodeStatus)i); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } std::cout << "\n\nInitialization succesfull ...\n" << std::endl; return true; } /****************************************************************/ double getPeriod() override { return period; } /****************************************************************/ bool updateModule() override { // To "execute" a Tree you need to "tick" it. // The tick is propagated to the children based on the logic of the tree. // In this case, the entire sequence is executed, because all the children // of the Sequence return SUCCESS. int i{0}; yDebug() << "start running the BT "; std::cout << "\nIteration num " << i++ << "\n"; tree.root_node->executeTick(); return true; } /****************************************************************/ bool respond(const Bottle &command, Bottle &reply) override { } /****************************************************************/ bool interruptModule() override { yDebug() << "Ended with " << toStr(tree.root_node->status()); for( auto& node: tree.nodes ) { yInfo() << "Terminating nodes " << node->name(); if( auto action_B_node = dynamic_cast<bt_cpp_modules::iBT_CPP_modules*>( node.get() )) { yInfo() << "Calling terminate for node " << node->name(); if(! action_B_node->terminate() ) { yError() << node->name() << "Terminate action for node " << node->name() << "ended with error"; } } } return true; } /****************************************************************/ bool close() override { yTrace(); return true; } }; int main(int argc, char *argv[]) { yarp::os::Network init; yarp::os::ResourceFinder rf; rf.configure(argc, argv); BT_Engine engine; return engine.runModule(rf); }
32.614243
167
0.527614
barbalberto
a1d62a722a174170bff62562200a1f3529ec7009
6,598
hh
C++
elements/ethernet/arpquerier.hh
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
1
2021-05-06T07:28:08.000Z
2021-05-06T07:28:08.000Z
elements/ethernet/arpquerier.hh
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
null
null
null
elements/ethernet/arpquerier.hh
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
null
null
null
#ifndef CLICK_ARPQUERIER_HH #define CLICK_ARPQUERIER_HH #include <click/batchelement.hh> #include <click/etheraddress.hh> #include <click/ipaddress.hh> #include <click/sync.hh> #include <click/hashtablemp.hh> #include <click/timer.hh> #include "arptable.hh" CLICK_DECLS /* =c ARPQuerier(IP, ETH, I<keywords>) ARPQuerier(NAME, I<keywords>) =s arp encapsulates IP packets in Ethernet headers found via ARP =d Handles most of the ARP protocol. Argument IP should be this host's IP address, and ETH should be this host's Ethernet address. (In the one-argument form, NAME should be shorthand for both an IP and an Ethernet address; see AddressInfo(n).) Packets arriving on input 0 should be IP packets, and must have their destination address annotations set. If an Ethernet address is already known for the destination, the IP packet is wrapped in an Ethernet header and sent to output 0. Otherwise the IP packet is saved and an ARP query is sent instead. If an ARP response arrives on input 1 for an IP address that we need, the mapping is recorded and any saved IP packets are sent. The ARP reply packets on input 1 should include the Ethernet header. ARPQuerier may have one or two outputs. If it has two, then ARP queries are sent to the second output. ARPQuerier implements special behavior for 0.0.0.0, 255.255.255.255, multicast addresses, and, if specified, any BROADCAST address. Packets addressed to 0.0.0.0 are dropped. Packets for broadcast addresses are forwarded with destination Ethernet address FF-FF-FF-FF-FF-FF. Multicast IP addresses are forwarded to 01-00-5E-xx-yy-zz, where xx-yy-zz are the lower 23 bits of the multicast IP address, as specified in RFC1112. Keyword arguments are: =over 8 =item TABLE Element. Names an ARPTable element that holds this element's corresponding ARP state. By default ARPQuerier creates its own internal ARPTable and uses that. If TABLE is specified, CAPACITY, ENTRY_CAPACITY, ENTRY_PACKET_CAPACITY, and TIMEOUT are ignored. =item CAPACITY Unsigned integer. The maximum number of saved IP packets the table will hold at a time. Default is 2048. =item ENTRY_CAPACITY Unsigned integer. The maximum number of ARP entries the table will hold at a time. Default is 0, which means unlimited. =item ENTRY_PACKET_CAPACITY Unsigned integer. The maximum number of saved packets the table will hold for any given ARP entry at a time. Default is 0, which means unlimited. =item TIMEOUT Amount of time before an ARP entry expires. Defaults to 5 minutes. =item POLL_TIMEOUT Amount of time after which ARPQuerier will start polling for renewal. 0 means don't poll. Defaults to one minute. =item BROADCAST IP address. Local broadcast IP address. Packets sent to this address will be forwarded to Ethernet address FF-FF-FF-FF-FF-FF. Defaults to the local broadcast address that can be extracted from the IP address's corresponding prefix, if any. =item BROADCAST_POLL Boolean. If true, then send broadcast ARP polls (where an entry is about to expire, but hasn't expired yet). The default is to send such polls unicast to the known Ethernet address. Defaults to false. =back =e c :: Classifier(12/0806 20/0002, 12/0800, ...); a :: ARPQuerier(18.26.4.24, 00:00:C0:AE:67:EF); c[0] -> a[1]; c[1] -> ... -> a[0]; a[0] -> ... -> ToDevice(eth0); =n If a host has multiple interfaces, it will need multiple instances of ARPQuerier. ARPQuerier uses packets' destination IP address annotations, and can destroy their next packet annotations. Generated ARP queries have VLAN TCI annotations set from the corresponding input packets. ARPQuerier will send at most 10 queries a second for any IP address. =h ipaddr rw Returns or sets the ARPQuerier's source IP address. =h broadcast r Returns the ARPQuerier's IP broadcast address. =h table r Returns a textual representation of the ARP table. See ARPTable's table handler. =h stats r Returns textual statistics (queries and drops). =h queries r Returns the number of queries sent. =h responses r Returns the number of responses received. =h drops r Returns the number of packets dropped. =h count r Returns the number of entries in the ARP table. =h length r Returns the number of packets stored in the ARP table. =h insert w Add an entry to the ARP table. The input string should have the form "IP ETH". =h delete w Delete an entry from the ARP table. The input string should be an IP address. =h clear w Clear the ARP table. =a ARPTable, ARPResponder, ARPFaker, AddressInfo */ class ARPQuerier : public BatchElement { public: ARPQuerier() CLICK_COLD; ~ARPQuerier() CLICK_COLD; const char *class_name() const override { return "ARPQuerier"; } const char *port_count() const override { return "2/1-2"; } const char *processing() const override { return PUSH; } const char *flow_code() const override { return "xy/x"; } // click-undead should consider all paths live (not just "xy/x"): const char *flags() const { return "L2"; } void *cast(const char *name); int configure(Vector<String> &, ErrorHandler *) CLICK_COLD; int live_reconfigure(Vector<String> &, ErrorHandler *); bool can_live_reconfigure() const { return true; } int initialize(ErrorHandler *errh) CLICK_COLD; void add_handlers() CLICK_COLD; void cleanup(CleanupStage stage) CLICK_COLD; void take_state(Element *e, ErrorHandler *errh); void push(int port, Packet *p) override; #if HAVE_BATCH void push_batch(int port, PacketBatch *batch) override; #endif private: ARPTable *_arpt; EtherAddress _my_en; IPAddress _my_ip; IPAddress _my_bcast_ip; uint32_t _poll_timeout_j; int _broadcast_poll; bool _have_cache; // statistics atomic_uint32_t _arp_queries; atomic_uint32_t _drops; atomic_uint32_t _arp_responses; atomic_uint32_t _broadcasts; bool _my_arpt; bool _zero_warned; void send_query_for(const Packet *p, bool ether_dhost_valid); Packet* handle_ip(Packet *p, bool response = false); void handle_response(Packet *p); static void expire_hook(Timer *, void *); static String read_table(Element *, void *); static String read_table_xml(Element *, void *); static String read_handler(Element *, void *) CLICK_COLD; static int write_handler(const String &, Element *, void *, ErrorHandler *) CLICK_COLD; enum { h_table, h_table_xml, h_stats, h_insert, h_delete, h_clear, h_count, h_length }; per_thread<AgingTable<IPAddress,EtherAddress> > _cache; }; CLICK_ENDDECLS #endif
27.839662
91
0.745681
BorisPis
a1e19ea439ce2ef2af0c1f016a0b003d33b99ae9
1,856
cp
C++
11926.cp
JazzikPeng/UVa_Algorithm_CPP
5de29ebc44ae8dd94b767fd5815309e5eaa7c8bf
[ "MIT" ]
null
null
null
11926.cp
JazzikPeng/UVa_Algorithm_CPP
5de29ebc44ae8dd94b767fd5815309e5eaa7c8bf
[ "MIT" ]
null
null
null
11926.cp
JazzikPeng/UVa_Algorithm_CPP
5de29ebc44ae8dd94b767fd5815309e5eaa7c8bf
[ "MIT" ]
null
null
null
//Zhejian Peng #include <cstdio> #include <bitset> #include <iostream> using namespace std; bitset<2000005> bs; /*The class template bitset represents a fixed-size sequence of N bits. Bitsets can be manipulated by standard logic operators and converted to and from strings and integers. */ int main() { int n, m, s, e, itv; bool conflict; while (cin>>n>>m) { if(n==0 && m==0) break; conflict = false; for (int i = 0; i < n; i++) { cin>>s>>e; if (!conflict) { for (int i = 2 * s + 1; i <= 2 * e; i++) { if (bs[i]) { conflict = true; break; } bs.set(i);//sets bits to true or given value } } } for (int i = 0; i < m; i++) { cin>>s>>e>>itv; if (!conflict) { while (1) { for (int i = 2 * s + 1; i <= 2 * e; i++) { if (bs[i]) { conflict = true; break; } bs.set(i); } s += itv; e += itv; if (s > 1000000 && e > 1000000) break; else if (e > 1000000) e = 1000000; } } } if (conflict) cout<<"CONFLICT"<<endl; else cout<<"NO CONFLICT"<<endl; for (int i = 0; i < 2000005; i++) { bs.reset(i); } } return 0; }
24.746667
174
0.320043
JazzikPeng
a1e20e895afafb332de7396bae57b9386878a71d
5,358
cpp
C++
SamplePhysics/RoughPlaneSolidBox/PhysicsModule.cpp
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
3
2021-08-02T04:03:03.000Z
2022-01-04T07:31:20.000Z
SamplePhysics/RoughPlaneSolidBox/PhysicsModule.cpp
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
null
null
null
SamplePhysics/RoughPlaneSolidBox/PhysicsModule.cpp
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
5
2019-10-13T02:44:19.000Z
2021-08-02T04:03:10.000Z
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Restricted Libraries source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4RestrictedLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #include "PhysicsModule.h" #include "Wm4Math.h" #include "Wm4OdeRungeKutta4.h" using namespace Wm4; //---------------------------------------------------------------------------- PhysicsModule::PhysicsModule () { Mu = 0.0; Gravity = 0.0; Angle = 0.0; SinAngle = 0.0; CosAngle = 0.0; XLocExt = 0.0; YLocExt = 0.0; ZLocExt = 0.0; m_dTime = 0.0; m_dDeltaTime = 0.0; memset(m_adState,0,6*sizeof(double)); memset(m_adAux,0,2*sizeof(double)); m_pkSolver = 0; } //---------------------------------------------------------------------------- PhysicsModule::~PhysicsModule () { WM4_DELETE m_pkSolver; } //---------------------------------------------------------------------------- void PhysicsModule::Initialize (double dTime, double dDeltaTime, double dX, double dW, double dTheta, double dXDot, double dWDot, double dThetaDot) { m_dTime = dTime; m_dDeltaTime = dDeltaTime; // state variables m_adState[0] = dX; m_adState[1] = dXDot; m_adState[2] = dW; m_adState[3] = dWDot; m_adState[4] = dTheta; m_adState[5] = dThetaDot; // auxiliary variables SinAngle = Mathd::Sin(Angle); CosAngle = Mathd::Cos(Angle); m_adAux[0] = Mu*Gravity; // c/m in the one-particle system example m_adAux[1] = Gravity*SinAngle; // RK4 differential equation solver. Since m_pkSolver is a base class // pointer, you can instead create a solver of whatever class you prefer. WM4_DELETE m_pkSolver; m_pkSolver = WM4_NEW OdeRungeKutta4d(4,m_dDeltaTime,OdeFunction,m_adAux); // set up for angular speed m_dTheta0 = dTheta; m_dThetaDer0 = dThetaDot; double dXX = XLocExt*XLocExt; double dXY = XLocExt*YLocExt; double dYY = YLocExt*YLocExt; double dTmp1 = dXX + dYY; double dTmp2 = Mathd::Sqrt(dTmp1); double dTmp3 = 4.0*dXY/3.0; double dTmp4 = 0.5*Mathd::Log((dTmp2+XLocExt)/(dTmp2-XLocExt)); double dTmp5 = 0.5*Mathd::Log((dTmp2+YLocExt)/(dTmp2-YLocExt)); double dNumer = dTmp3*dTmp2 + XLocExt*dXX*dTmp5 + YLocExt*dYY*dTmp4; double dDenom = dTmp3*dTmp1; double dCoeff = Mu*Gravity*dNumer/dDenom; double dAngSpeed = Mathd::FAbs(dThetaDot); if (dAngSpeed > Mathd::ZERO_TOLERANCE) { m_dAngVelCoeff = dCoeff/dAngSpeed; } else { m_dAngVelCoeff = 0.0; } } //---------------------------------------------------------------------------- void PhysicsModule::GetRectangle (double& rdX00, double& rdY00, double& rdX10, double& rdY10, double& rdX11, double& rdY11, double& rdX01, double& rdY01) const { // P = (x,y) + sx*XLocExt*(cos(A),sin(A)) + sy*YLocExt*(-sin(A),cos(A)) // where |sx| = 1 and |sy| = 1 (four choices on sign) double dCos = Mathd::Cos(m_adState[4]); double dSin = Mathd::Sin(m_adState[4]); // sx = -1, sy = -1 rdX00 = m_adState[0] - XLocExt*dCos + YLocExt*dSin; rdY00 = m_adState[2] - XLocExt*dSin - YLocExt*dCos; // sx = +1, sy = -1 rdX10 = m_adState[0] + XLocExt*dCos + YLocExt*dSin; rdY10 = m_adState[2] + XLocExt*dSin - YLocExt*dCos; // sx = +1, sy = +1 rdX11 = m_adState[0] + XLocExt*dCos - YLocExt*dSin; rdY11 = m_adState[2] + XLocExt*dSin + YLocExt*dCos; // sx = -1, sy = +1 rdX01 = m_adState[0] - XLocExt*dCos - YLocExt*dSin; rdY01 = m_adState[2] - XLocExt*dSin + YLocExt*dCos; } //---------------------------------------------------------------------------- void PhysicsModule::Update () { assert(m_pkSolver); if (!m_pkSolver) { return; } // take a single step in the ODE solver m_pkSolver->Update(m_dTime,m_adState,m_dTime,m_adState); // update for angular speed double dATmp = m_dAngVelCoeff*m_dTime; double dAngVelMult = 1.0 - dATmp; if (dAngVelMult > 0.0) { m_adState[5] = dAngVelMult*m_dThetaDer0; m_adState[4] = m_dTheta0 + m_dTime*(1.0-0.5*dATmp)*m_dThetaDer0; } else { m_adState[5] = 0.0; } } //---------------------------------------------------------------------------- void PhysicsModule::OdeFunction (double, const double* adState, void* pvData, double* adFValue) { double* adAux = (double*)pvData; double dVLen = Mathd::Sqrt(adState[1]*adState[1]+adState[3]*adState[3]); double dXDotFunction, dWDotFunction; if (dVLen > Mathd::ZERO_TOLERANCE) { double dTemp = -adAux[0]/dVLen; dXDotFunction = dTemp*adState[1]; dWDotFunction = dTemp*adState[3] - adAux[1]; } else { // velocity is effectively zero, so frictional force is zero dXDotFunction = 0.0; dWDotFunction = -adAux[1]; } // x function adFValue[0] = adState[1]; // dot(x) function adFValue[1] = dXDotFunction; // w function adFValue[2] = adState[3]; // dot(w) function adFValue[3] = dWDotFunction; } //----------------------------------------------------------------------------
30.271186
78
0.571669
wjezxujian
a1e305bcceccc83ccea3f39a11d878268ec6f531
10,848
cpp
C++
libs/system/src/CTimeLogger.cpp
skair39/mrpt
88238f8ac1abdcf15401e14dc3a9faa5c59ba559
[ "BSD-3-Clause" ]
2
2019-02-20T02:36:05.000Z
2019-02-20T02:46:51.000Z
libs/system/src/CTimeLogger.cpp
skair39/mrpt
88238f8ac1abdcf15401e14dc3a9faa5c59ba559
[ "BSD-3-Clause" ]
null
null
null
libs/system/src/CTimeLogger.cpp
skair39/mrpt
88238f8ac1abdcf15401e14dc3a9faa5c59ba559
[ "BSD-3-Clause" ]
null
null
null
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "system-precomp.h" // Precompiled headers #include <mrpt/system/CTimeLogger.h> #include <mrpt/system/string_utils.h> #include <mrpt/system/datetime.h> #include <mrpt/system/filesystem.h> #include <mrpt/core/bits_math.h> #include <iostream> #include <algorithm> #include <fstream> using namespace mrpt; using namespace mrpt::system; using namespace std; struct MyGlobalProfiler : public mrpt::system::CTimeLogger { MyGlobalProfiler() : mrpt::system::CTimeLogger("MRPT_global_profiler") {} ~MyGlobalProfiler() override { if (!m_data.empty()) { const std::string sFil("mrpt-global-profiler.csv"); this->saveToCSVFile(sFil); std::cout << "[MRPT global profiler] Write stats to: " << sFil << std::endl; } } MyGlobalProfiler(const MyGlobalProfiler&) = delete; MyGlobalProfiler(MyGlobalProfiler&&) = delete; MyGlobalProfiler& operator=(const MyGlobalProfiler&) = delete; MyGlobalProfiler& operator=(MyGlobalProfiler&&) = delete; }; static MyGlobalProfiler global_profiler; namespace mrpt::system { CTimeLogger& global_profiler_getref() noexcept { return global_profiler; } void global_profiler_enter(const char* func_name) noexcept { global_profiler.enter(func_name); } void global_profiler_leave(const char* func_name) noexcept { global_profiler.leave(func_name); } } // namespace mrpt::system CTimeLogger::CTimeLogger( bool enabled, const std::string& name, const bool keep_whole_history) : COutputLogger("CTimeLogger"), m_tictac(), m_enabled(enabled), m_name(name), m_keep_whole_history(keep_whole_history) { m_tictac.Tic(); } CTimeLogger::~CTimeLogger() { // Dump all stats: if (!m_data.empty()) // If logging is disabled, do nothing... dumpAllStats(); } void CTimeLogger::clear(bool deep_clear) { if (deep_clear) m_data.clear(); else { for (auto& e : m_data) e.second = TCallData(); } } std::string aux_format_string_multilines(const std::string& s, const size_t len) { std::string ret; for (size_t p = 0; p < s.size(); p += len) { ret += rightPad(s.substr(p), len, true); if (p + len < s.size()) ret += "\n"; } return ret; } void CTimeLogger::getStats(std::map<std::string, TCallStats>& out_stats) const { out_stats.clear(); for (const auto& e : m_data) { TCallStats& cs = out_stats[std::string(e.first)]; cs.min_t = e.second.min_t; cs.max_t = e.second.max_t; cs.total_t = e.second.mean_t; cs.mean_t = e.second.n_calls ? e.second.mean_t / e.second.n_calls : 0; cs.n_calls = e.second.n_calls; cs.last_t = e.second.last_t; } } std::string CTimeLogger::getStatsAsText(const size_t column_width) const { using std::string; using namespace std::string_literals; string stats_text; string name_tmp = m_name.size() != 0 ? " "s + m_name + ": "s : " "s; string mrpt_string = "MRPT CTimeLogger report "s; string top_header(name_tmp + mrpt_string); // append dashes to the header to reach column_width { const auto space_to_fill = top_header.size() < column_width ? (column_width - top_header.size()) / 2 : 2; std::string dashes_half(space_to_fill, '-'); top_header = dashes_half + top_header + dashes_half; if (dashes_half.size() % 2) { // what if column_width-top_header.size() is odd? top_header += '-'; } } std::string middle_header( " FUNCTION #CALLS MIN.T MEAN.T " "MAX.T TOTAL "); std::string bottom_header(column_width, '-'); stats_text += top_header + "\n"s; stats_text += middle_header + "\n"s; stats_text += bottom_header + "\n"s; // for all the timed sections: sort by inserting into a std::map using NameAndCallData = std::map<std::string_view, TCallData>; NameAndCallData stat_strs; for (const auto& i : m_data) stat_strs[i.first] = i.second; // format tree-like patterns like: // ---------- // foobar // foobar.a // foobar.b // ---------- // like: // ---------- // foobar // +-> a // +-> b // ---------- std::string last_parent; for (const auto& i : stat_strs) { string line = string(i.first); // make a copy const auto dot_pos = line.find("."); if (dot_pos == std::string::npos) { last_parent = line; } else { const auto parent_pos = line.find(last_parent); if (parent_pos != std::string::npos) { line = "+-> "s + line.substr(dot_pos); } } const string sMinT = unitsFormat(i.second.min_t, 1, false); const string sMaxT = unitsFormat(i.second.max_t, 1, false); const string sTotalT = unitsFormat(i.second.mean_t, 1, false); const string sMeanT = unitsFormat( i.second.n_calls ? i.second.mean_t / i.second.n_calls : 0, 1, false); stats_text += mrpt::format( "%s %7u %6s%c %6s%c %6s%c %6s%c\n", aux_format_string_multilines(line, 39).c_str(), static_cast<unsigned int>(i.second.n_calls), sMinT.c_str(), i.second.has_time_units ? 's' : ' ', sMeanT.c_str(), i.second.has_time_units ? 's' : ' ', sMaxT.c_str(), i.second.has_time_units ? 's' : ' ', sTotalT.c_str(), i.second.has_time_units ? 's' : ' '); } std::string footer(top_header); stats_text += footer + "\n"; return stats_text; } void CTimeLogger::saveToCSVFile(const std::string& csv_file) const { std::string s; s += "FUNCTION, #CALLS, LAST.T, MIN.T, MEAN.T, MAX.T, TOTAL.T [, " "WHOLE_HISTORY]\n"; for (const auto& i : m_data) { s += format( "\"%.*s\",%7u,%e,%e,%e,%e,%e", static_cast<int>(i.first.size()), i.first.data(), static_cast<unsigned int>(i.second.n_calls), i.second.last_t, i.second.min_t, i.second.n_calls ? i.second.mean_t / i.second.n_calls : 0, i.second.max_t, i.second.mean_t); if (i.second.whole_history) { const auto& wh = i.second.whole_history.value(); for (const double v : wh) { s += ", "; s += std::to_string(v); } } s += "\n"; } std::ofstream(csv_file) << s; } void CTimeLogger::saveToMFile(const std::string& file) const { using std::string; using namespace std::string_literals; string s; s += "function [s] = "s + mrpt::system::extractFileName(file) + "()\n" "s = struct();\n" "s.whole = struct();\n\n"s; std::string s_names = "s.names={"s; std::string s_counts = "s.count=["s; std::string s_mins = "s.min=["s; std::string s_maxs = "s.max=["s; std::string s_means = "s.mean=["s; for (const auto& i : m_data) { s_names += "'"s + i.first + "',"s; s_counts += std::to_string(i.second.n_calls) + ","s; s_mins += mrpt::format("%e,", i.second.min_t); s_maxs += mrpt::format("%e,", i.second.max_t); s_means += mrpt::format("%e,", i.second.mean_t); if (i.second.whole_history) { string clean_name = mrpt::system::fileNameStripInvalidChars(i.first); std::replace(clean_name.begin(), clean_name.end(), '.', '_'); std::replace(clean_name.begin(), clean_name.end(), '-', '_'); std::replace(clean_name.begin(), clean_name.end(), '+', '_'); std::replace(clean_name.begin(), clean_name.end(), '*', '_'); s += "s.whole."s + clean_name + "=["; const auto& wh = i.second.whole_history.value(); for (const double v : wh) s += mrpt::format("%e,", v); s += "];\n"; } } s_names += "};\n"s; s_counts += "];\n"s; s_mins += "];\n"s; s_maxs += "];\n"s; s_means += "];\n"s; s += s_names; s += s_counts; s += s_mins; s += s_maxs; s += s_means; s += "\n"s; std::ofstream(file) << s; } void CTimeLogger::dumpAllStats(const size_t column_width) const { MRPT_LOG_INFO_STREAM("dumpAllStats:\n" << getStatsAsText(column_width)); } void CTimeLogger::do_enter(const std::string_view& func_name) { TCallData& d = m_data[std::string(func_name)]; d.n_calls++; d.open_calls.push(0); // Dummy value, it'll be written below d.open_calls.top() = m_tictac.Tac(); // to avoid possible delays. } double CTimeLogger::do_leave(const std::string_view& func_name) { const double tim = m_tictac.Tac(); TCallData& d = m_data[std::string(func_name)]; if (!d.open_calls.empty()) { const double At = tim - d.open_calls.top(); d.open_calls.pop(); d.last_t = At; d.mean_t += At; if (d.n_calls == 1) { d.min_t = At; d.max_t = At; } else { mrpt::keep_min(d.min_t, At); mrpt::keep_max(d.max_t, At); } if (m_keep_whole_history) { // Init the first time: if (!d.whole_history) d.whole_history = decltype(d.whole_history)::value_type(); // Append to history: d.whole_history.value().push_back(At); } return At; } else return 0; // This shouldn't happen! } void CTimeLogger::registerUserMeasure( const std::string_view& event_name, const double value, const bool is_time) { if (!m_enabled) return; TCallData& d = m_data[std::string(event_name)]; d.has_time_units = is_time; d.last_t = value; d.mean_t += value; if (++d.n_calls == 1) { d.min_t = value; d.max_t = value; } else { mrpt::keep_min(d.min_t, value); mrpt::keep_max(d.max_t, value); } if (m_keep_whole_history) { // Init the first time: if (!d.whole_history) d.whole_history = decltype(d.whole_history)::value_type(); // Append to history: d.whole_history.value().push_back(value); } } CTimeLogger::TCallData::TCallData() = default; double CTimeLogger::getMeanTime(const std::string& name) const { TDataMap::const_iterator it = m_data.find(name); if (it == m_data.end()) return 0; else return it->second.n_calls ? it->second.mean_t / it->second.n_calls : 0; } double CTimeLogger::getLastTime(const std::string& name) const { TDataMap::const_iterator it = m_data.find(name); if (it == m_data.end()) return 0; else return it->second.last_t; } CTimeLoggerEntry::CTimeLoggerEntry( const CTimeLogger& logger, const std::string_view& section_name) : m_logger(const_cast<CTimeLogger&>(logger)), m_section_name(section_name) { m_entry = mrpt::Clock::now(); } CTimeLoggerEntry::~CTimeLoggerEntry() { const auto leave = mrpt::Clock::now(); const double dt = mrpt::system::timeDifference(m_entry, leave); m_logger.registerUserMeasure(m_section_name, dt, true); } CTimeLoggerSaveAtDtor::~CTimeLoggerSaveAtDtor() { using namespace std::string_literals; auto name = m_tm.getName() + ".m"s; name = fileNameStripInvalidChars(name); m_tm.logStr( LVL_INFO, "[CTimeLoggerSaveAtDtor] Saving stats to: `"s + name + "`"s); m_tm.saveToMFile(name); }
26.394161
80
0.637168
skair39
a1e3fa49c2eb328c10fc1fa12f945c8de4dbdf0c
192
hpp
C++
aluminium/hello.hpp
BaseOutside/Aluminium
0fe735b0acdf4f7494d23210be53e70eb427e6c1
[ "MIT" ]
1
2019-06-22T09:21:47.000Z
2019-06-22T09:21:47.000Z
aluminium/hello.hpp
BaseOutside/Aluminium
0fe735b0acdf4f7494d23210be53e70eb427e6c1
[ "MIT" ]
null
null
null
aluminium/hello.hpp
BaseOutside/Aluminium
0fe735b0acdf4f7494d23210be53e70eb427e6c1
[ "MIT" ]
null
null
null
#ifndef ALUMINIUM_HELLO #define ALUMINIUM_HELLO #include <iostream> namespace aluminium { void hello() { std::cout << "Hello World!!!" << std::endl; } } // namespace aluminium #endif
12.8
47
0.682292
BaseOutside
a1e8a97ef2fde29db8c0eb6d97ba0e98e4d91d9e
1,695
cpp
C++
src/sdk/thread/thread_local_storage.cpp
southbear-club/aru
24a3b28d9a168c28435e9cb5b5c10a2e404042a8
[ "MIT" ]
2
2021-10-21T12:25:23.000Z
2021-10-22T00:38:35.000Z
src/sdk/thread/thread_local_storage.cpp
southbear-club/aru
24a3b28d9a168c28435e9cb5b5c10a2e404042a8
[ "MIT" ]
null
null
null
src/sdk/thread/thread_local_storage.cpp
southbear-club/aru
24a3b28d9a168c28435e9cb5b5c10a2e404042a8
[ "MIT" ]
null
null
null
/** * Copyright © 2021 <wotsen>. * * 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 * * 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. * * @file thread_local_storage.cpp * @brief * @author wotsen (astralrovers@outlook.com) * @version 1.0.0 * @date 2021-04-05 * * @copyright MIT * */ #include "ars/sdk/thread/thread.hpp" #include "ars/sdk/thread/thread_local_storage.hpp" namespace ars { namespace sdk { ThreadLocalStorage ThreadLocalStorage::tls[ThreadLocalStorage::MAX_NUM]; const char* ThreadLocalStorage::threadName() { static char unnamed[32] = {0}; void* value = get(THREAD_NAME); if (value) { return (char*)value; } snprintf(unnamed, sizeof(unnamed)-1, "thread-%ld", (long)gettid()); return unnamed; } } // namespace sdk } // namespace ars
33.9
96
0.727434
southbear-club
a1e8b441b64fdb20f4eb7939ea3abf86db046306
987
cpp
C++
algorithms/binary-tree-level-order-traversal-ii.cpp
jlygit/leetcode-oj
66718f709b31ef0e7e091638d95418a5543019b4
[ "Apache-2.0" ]
1
2016-08-10T11:17:16.000Z
2016-08-10T11:17:16.000Z
algorithms/binary-tree-level-order-traversal-ii.cpp
jlygit/leetcode-oj
66718f709b31ef0e7e091638d95418a5543019b4
[ "Apache-2.0" ]
null
null
null
algorithms/binary-tree-level-order-traversal-ii.cpp
jlygit/leetcode-oj
66718f709b31ef0e7e091638d95418a5543019b4
[ "Apache-2.0" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> result; if(root==NULL) return result; queue<TreeNode*> Q; Q.push(root); // 第一层 int levelnums; // 当前层的节点个数 TreeNode* p; // 访问节点 while(!Q.empty()) { levelnums=Q.size(); // 当前层的节点个数 vector<int> v; while(levelnums--) { // 逐一访问并将左右子节点加入队列(下一层的节点) p=Q.front();Q.pop(); v.push_back(p->val); if(p->left) Q.push(p->left); if(p->right) Q.push(p->right); } result.push_back(v); // 当前层的节点值 } reverse(result.begin(),result.end()); return result; } };
29.909091
61
0.477204
jlygit
a1ea6b6b4d9dd8f97e2dd3ca0e90c044a6778f32
606
cpp
C++
tests/FileDescriptor_test.cpp
cppstack/unx
b05aa5354458b032073647e9b44fdd96b6884247
[ "MIT" ]
null
null
null
tests/FileDescriptor_test.cpp
cppstack/unx
b05aa5354458b032073647e9b44fdd96b6884247
[ "MIT" ]
null
null
null
tests/FileDescriptor_test.cpp
cppstack/unx
b05aa5354458b032073647e9b44fdd96b6884247
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <cst/unx/FileDescriptor.h> #include <cst/unx/os/unistd.h> #include <cst/unx/os/fcntl.h> namespace unx = cst::unx; TEST_CASE("FileDescriptor", "[FileDescriptor]") { const char* path = "tmp.txt"; int fd = -1; { unx::FileDescriptor fd1; unx::FileDescriptor fd2(unx::os::Open(path, O_RDWR|O_CREAT)); REQUIRE(fd2 != -1); fd1 = std::move(fd2); REQUIRE(fd2 == -1); fd = fd1; REQUIRE(::fcntl(fd, F_GETFD) != -1); } REQUIRE(::fcntl(fd, F_GETFD) == -1); ::unlink(path); }
19.548387
69
0.575908
cppstack
a1ed38fede52484e6355a42311d9ac9a4dac60c7
459
hxx
C++
src/mod/pub/lib/gfx-ext/gfx-trail.hxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
1
2017-12-26T14:29:37.000Z
2017-12-26T14:29:37.000Z
src/mod/pub/lib/gfx-ext/gfx-trail.hxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
src/mod/pub/lib/gfx-ext/gfx-trail.hxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
#pragma once #include "gfx-vxo.hxx" #include "gfx-surface.hxx" #include <deque> class gfx_trail : public gfx_vxo { public: gfx_trail(); virtual ~gfx_trail(); void add_position(glm::vec3 ipos); float get_line_thickness(); void set_line_thickness(float iline_thickness); int get_max_positions(); void set_max_positions(int imax_positions); private: int max_positions; float line_thickness; std::deque<glm::vec3> positions; };
18.36
50
0.723312
indigoabstract
a1ed5d409e83a33205dcfee65f5a4926f0789009
2,206
hpp
C++
include/rosbag2_converter_default_plugins/logging.hpp
klintan/rosbags2_nodejs_wrapper
65ebe15d242c06efb026c11f3ced35065f80e7d6
[ "MIT" ]
1
2018-04-12T08:06:00.000Z
2018-04-12T08:06:00.000Z
include/rosbag2_converter_default_plugins/logging.hpp
klintan/rosbags2_nodejs_wrapper
65ebe15d242c06efb026c11f3ced35065f80e7d6
[ "MIT" ]
1
2019-04-09T04:41:39.000Z
2019-04-09T04:41:39.000Z
include/rosbag2_converter_default_plugins/logging.hpp
klintan/rosbags2_nodejs_wrapper
65ebe15d242c06efb026c11f3ced35065f80e7d6
[ "MIT" ]
1
2019-01-02T18:57:04.000Z
2019-01-02T18:57:04.000Z
// Copyright 2018, Bosch Software Innovations GmbH. // // 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. #ifndef ROSBAG2_CONVERTER_DEFAULT_PLUGINS__LOGGING_HPP_ #define ROSBAG2_CONVERTER_DEFAULT_PLUGINS__LOGGING_HPP_ #include <sstream> #include <string> #include "rcutils/logging_macros.h" #define ROSBAG2_PACKAGE_NAME "rosbag2_converter_default_plugins" #define ROSBAG2_CONVERTER_DEFAULT_PLUGINS_LOG_INFO(...) \ RCUTILS_LOG_INFO_NAMED(ROSBAG2_PACKAGE_NAME, __VA_ARGS__) #define ROSBAG2_CONVERTER_DEFAULT_PLUGINS_LOG_INFO_STREAM(args) do { \ std::stringstream __ss; \ __ss << args; \ RCUTILS_LOG_INFO_NAMED(ROSBAG2_PACKAGE_NAME, __ss.str().c_str()); \ } while (0) #define ROSBAG2_CONVERTER_DEFAULT_PLUGINS_LOG_ERROR(...) \ RCUTILS_LOG_ERROR_NAMED(ROSBAG2_PACKAGE_NAME, __VA_ARGS__) #define ROSBAG2_CONVERTER_DEFAULT_PLUGINS_LOG_ERROR_STREAM(args) do { \ std::stringstream __ss; \ __ss << args; \ RCUTILS_LOG_ERROR_NAMED(ROSBAG2_PACKAGE_NAME, __ss.str().c_str()); \ } while (0) #define ROSBAG2_CONVERTER_DEFAULT_PLUGINS_LOG_WARN(...) \ RCUTILS_LOG_WARN_NAMED(ROSBAG2_PACKAGE_NAME, __VA_ARGS__) #define ROSBAG2_LOG_WARN_STREAM(args) do { \ std::stringstream __ss; \ __ss << args; \ RCUTILS_LOG_WARN_NAMED(ROSBAG2_PACKAGE_NAME, __ss.str().c_str()); \ } while (0) #define ROSBAG2_CONVERTER_DEFAULT_PLUGINS_LOG_DEBUG(...) \ RCUTILS_LOG_DEBUG_NAMED(ROSBAG2_PACKAGE_NAME, __VA_ARGS__) #define ROSBAG2_CONVERTER_DEFAULT_PLUGINS_LOG_DEBUG_STREAM(args) do { \ std::stringstream __ss; \ __ss << args; \ RCUTILS_LOG_DEBUG_NAMED(ROSBAG2_PACKAGE_NAME, __ss.str().c_str()); \ } while (0) #endif // ROSBAG2_CONVERTER_DEFAULT_PLUGINS__LOGGING_HPP_
35.580645
75
0.774252
klintan
a1f270985d5e62cc81223df8116d311463efcbc7
4,533
cpp
C++
newfs/main.cpp
DosDevs/zoom-zoom
c3c37c4b9b38ba81f55fcd79e6ff07fddbc3a5c5
[ "BSD-3-Clause" ]
null
null
null
newfs/main.cpp
DosDevs/zoom-zoom
c3c37c4b9b38ba81f55fcd79e6ff07fddbc3a5c5
[ "BSD-3-Clause" ]
null
null
null
newfs/main.cpp
DosDevs/zoom-zoom
c3c37c4b9b38ba81f55fcd79e6ff07fddbc3a5c5
[ "BSD-3-Clause" ]
null
null
null
#include <algorithm> #include <fstream> #include <iostream> #include <string> #include <vector> #include "Bpb.h" #include "Fat_12.h" #include "Octet.h" #include "Sector.h" #include "Storage_Device.h" using std::cout; using std::endl; using std::ifstream; using std::string; using std::vector; typedef char* PChar; // Preset sector counts. size_t const k_144_Floppy = 2880; #define SHOWB(b) cout << #b << ": " << ((b)? "true.": "false.") << endl; bool Seek( string const& File_Name, ifstream& Stream, size_t Offset, bool From_Start) { auto Reference = (From_Start? Stream.beg:Stream.end); if (!Stream.seekg(Offset, Reference)) { cout << "Cannot seek within file '" << File_Name << "'!" << endl; return false; } return true; } bool ReadFile(string const& File_Name, vector<uint8_t>& File_Contents) { ifstream Stream(File_Name); if (!Stream) { cout << "Cannot read file '" << File_Name << "'!" << endl; return false; } if (!Seek(File_Name, Stream, 0, false)) return false; size_t File_Size = Stream.tellg(); if (!Seek(File_Name, Stream, 0, true)) return false; File_Contents.resize(File_Size); return bool(Stream.read(PChar(&File_Contents[0]), File_Size)); } bool Write_File( NewFs::I_Storage_Device<uint8_t> const& Storage, string const& File_Name) { std::ofstream Stream(File_Name.c_str()); if (!Stream) { cout << "Cannot open file '" << File_Name << "' for writing!" << endl; return false; } for (int i = 0; i < Storage.Sector_Count(); ++i) { auto& Sector = Storage[i]; Stream.write(PChar(&Sector[0]), Sector.Octet_Count()); cout << "Writing sector " << i << ": " << Sector.Octet_Count() << " Bytes.\r"; if (!Stream) { cout << "\nCannot write to file '" << File_Name << "'!!" << endl; return false; } } cout << endl; return true; } NewFs::Bpb_Dos_3_2 Create_Bpb() { NewFs::Bpb_Dos_3_2 Bpb; // Bpb 2.0 Bpb.Bytes_Per_Sector = 512; Bpb.Sectors_Per_Cluster = 1; Bpb.Reserved_Sectors = 1; Bpb.Total_Fat_Count = 2; Bpb.Root_Directory_Entries = 224; Bpb.Total_Sector_Count = 2880; Bpb.Medium_Descriptor = 0xf0; Bpb.Sectors_Per_Fat = 9; // Bpb 3.0 Bpb.Sectors_Per_Track = 18; Bpb.Number_Of_Heads = 2; Bpb.Hidden_Sectors = 0; // Bpb 3.2 Bpb.Total_Sectors = 2880; return Bpb; } int main(int argc, char* argv[]) { if (argc < 3) { cout << "Usage: " << argv[0] << " <boot record image> <disk image> [file [...]]" << endl; return -1; } string const Disk_Image_File_Name = argv[1]; string const Boot_Record_Image_File_Name = argv[2]; vector<string> Files(argc - 3); std::copy(&argv[3], &argv[argc], &Files[0]); typedef NewFs::Sector<512, uint8_t> Sector_Type; cout << "Creating storage object." << endl; NewFs::Storage_Device<Sector_Type> Storage(512, k_144_Floppy); cout << "Reading boot record contents." << endl; vector<uint8_t> Boot_Record; if (!ReadFile(Boot_Record_Image_File_Name, Boot_Record)) { cout << "There was an error reading the boot record image." << endl; return -2; } cout << "Boot record is " << Boot_Record.size() << " bytes long." << endl; cout << "Creating File System." << std::endl; NewFs::Fat_12 Fat(Storage); Fat.Format(Create_Bpb()); Fat.Write_Boot_Record( &Boot_Record[0], &Boot_Record[Boot_Record.size()]); for(size_t i = 0; i < Files.size(); ++i) { cout << "Reading file " << Files[i]; vector<uint8_t> File_Contents; if (!ReadFile(Files[i], File_Contents)) { cout << "There was an error reading file '" << Files[i] << "'." << endl; return -2; } cout << "\rAdding file '" << Files[i] << "' which is " << File_Contents.size() << " bytes long." << endl; Fat.Write_File( Files[i], &File_Contents[0], &File_Contents[File_Contents.size()]); } cout << "Writing Image File." << std::endl; Write_File(Storage, Disk_Image_File_Name); return 0; }
22.112195
76
0.55107
DosDevs
a1f2fa397ab927be82d81d259097041ab0167d50
5,809
hpp
C++
fmo-cpp/include/fmo/processing.hpp
rozumden/fmo-android
40fed89df7f1ff5aa3718b9a35f361b399a0bca1
[ "MIT" ]
null
null
null
fmo-cpp/include/fmo/processing.hpp
rozumden/fmo-android
40fed89df7f1ff5aa3718b9a35f361b399a0bca1
[ "MIT" ]
null
null
null
fmo-cpp/include/fmo/processing.hpp
rozumden/fmo-android
40fed89df7f1ff5aa3718b9a35f361b399a0bca1
[ "MIT" ]
null
null
null
#ifndef FMO_PROCESSING_HPP #define FMO_PROCESSING_HPP #include <fmo/image.hpp> //#include <opencv2/core.hpp> #include <iostream> #include <fmo/algebra.hpp> namespace cv { template<typename _Tp> class Point_; template<typename _Tp, int cn> class Vec; template<typename _Tp> class Scalar_; typedef Point_<float> Point2f; typedef Vec<float, 2> Vec2f; typedef Vec<float, 4> Vec4f; typedef Scalar_<double> Scalar; } namespace fmo { /// Fitting curve struct SCurve { SCurve() {} virtual ~SCurve() {} public: double scale = 1; Vector2f shift{0,0}; float length = 0; Vector2f start{0,0}; Vector2f end{0,0}; Vector2f center{0,0}; virtual void draw(cv::Mat& cvVis, cv::Scalar &clr, float thickness = 1) const { }; virtual void drawSmooth(cv::Mat& cvVis, cv::Scalar &clr, float thickness = 1) const { }; virtual float maxDist(const std::vector<cv::Point2f>& pixels) const { return 0; }; virtual SCurve* clone() const { return new SCurve(*this); }; }; struct SLine : SCurve { SLine() {} Vector4f params{0,0,0,0}; Vector2f normal{0,0}; Vector2f perp{0,0}; Vector2f startSmooth{0,0}; Vector2f endSmooth{0,0}; public: virtual void draw(cv::Mat& cvVis, cv::Scalar &clr, float thickness) const override; virtual void drawSmooth(cv::Mat& cvVis, cv::Scalar &clr, float thickness) const override; virtual float maxDist(const std::vector<cv::Point2f>& pixels) const override; virtual SCurve* clone() const override { return new SLine(*this); } }; struct SCircle : SCurve { SCircle() { } float radius{0}; float x{0}; float y{0}; double startDegree{0}; double endDegree{360}; double startDegreeSmooth{0}; double endDegreeSmooth{180}; double size{0}; public: virtual void draw(cv::Mat& cvVis, cv::Scalar &clr, float thickness) const override; virtual void drawSmooth(cv::Mat& cvVis, cv::Scalar &clr, float thickness) const override; virtual float maxDist(const std::vector<cv::Point2f>& pixels) const override; virtual SCurve* clone() const override { return new SCircle(*this); } }; /// Saves an image to file. void save(const Mat& src, const std::string& filename); /// Copies image data. To accomodate the data from "src", resize() is called on "dst". void copy(const Mat& src, Mat& dst); /// Copies image data. To accomodate the data from "src", resize() is called on "dst". /// Regardless of the source format, the destination format is set to "format". Color /// conversions performed by this function are not guaranteed to make any sense. void copy(const Mat& src, Mat& dst, Format format); /// Converts the image "src" to a given color format and saves the result to "dst". One could /// pass the same object as both "src" and "dst", but doing so is ineffective, unless the /// conversion is YUV420SP to GRAY. Only some conversions are supported, namely: GRAY to BGR, /// BGR to GRAY, YUV420SP to BGR, YUV420SP to GRAY. void convert(const Mat& src, Mat& dst, Format format); /// Selects pixels that have a value less than the specified value; these are set to 0xFF while /// others are set to 0x00. Input image must be GRAY. void less_than(const Mat& src1, Mat& dst, uint8_t value); /// Selects pixels that have a value greater than the specified value; these are set to 0xFF /// while others are set to 0x00. Input image must be GRAY. void greater_than(const Mat& src1, Mat& dst, uint8_t value); void distance_transform(const Mat& src, Mat& dst); void local_maxima(const Mat& src, Mat& dst); void imfill(const Mat& src, Mat& dst); void imgrid(const std::vector<cv::Mat> &src, cv::Mat &dst, int grid_x, int grid_y); void imgridfull(const std::vector<cv::Mat> &src, cv::Mat &dst, int grid_x, int grid_y); void putcorner(const cv::Mat &src, cv::Mat &dst); /// Calculates the absolute difference between the two images. Input images must have the same /// format and size. void absdiff(const Mat& src1, const Mat& src2, Mat& dst); /// Resizes an image so that each dimension is divided by two. void subsample(const Mat& src, Mat& dst); /// Resizes an image exactly. void subsample_resize(const Mat& src, Mat& dst, float scale); /// Resizes an YUV image exactly. void subsample_resize_yuv(const Mat& src, Mat& dst, float scale); /// Calculates the per-pixel median of three images. void median3(const Image& src1, const Image& src2, const Image& src3, Image& dst); /// Calculates the per-pixel median of three images. void median5(const Image& src1, const Image& src2, const Image& src3, const Image& src4, const Image& src5, Image& dst); /// Flips an image in x axis. void flip(const Mat& src, Mat& dst); float fitline(const std::vector<cv::Point2f>& pixels, float fmoRadius, SLine &line); float fitcircle(const std::vector<cv::Point2f>& pixels, float fmoRadius, SCircle &circle); float fitcurve(const std::vector<cv::Point2f>& pixels, float fmoRadius, SCurve *&curve, SCircle &circle, SLine &line); float fitcurve(const std::vector<cv::Point2f>& pixels, float fmoRadius, SCurve *&curve, SCircle &circle, SLine &line, const cv::Vec2f &c1, const cv::Vec2f &c2); float fitcircle(const std::vector<cv::Point2f>& pixels, float fmoRadius, SCircle &circle, const cv::Vec2f &c1, const cv::Vec2f &c2); } #endif // FMO_PROCESSING_HPP
37
124
0.644173
rozumden
a1f45f33abbbd14759377981ebdaba3bf6e8e9fd
532
cpp
C++
src/mgos_arduino_newping.cpp
TridentTD/arduino-newping
67c93ee7432ef2cbba8c08bb2bf3a664000ee02f
[ "Apache-2.0" ]
null
null
null
src/mgos_arduino_newping.cpp
TridentTD/arduino-newping
67c93ee7432ef2cbba8c08bb2bf3a664000ee02f
[ "Apache-2.0" ]
null
null
null
src/mgos_arduino_newping.cpp
TridentTD/arduino-newping
67c93ee7432ef2cbba8c08bb2bf3a664000ee02f
[ "Apache-2.0" ]
null
null
null
#include <math.h> #include "mgos_arduino_newping.h" #define MGOS_NEWPING_RES_FAIL -12700 NewPing *mgos_newping_create(uint8_t trigger_pin, uint8_t echo_pin) { return new NewPing(trigger_pin, echo_pin); } void mgos_newping_close(NewPing *newping) { if (newping != nullptr) { delete newping; newping = nullptr; } } unsigned long mgos_newping_ping_cm(NewPing *newping) { if (newping == nullptr) return MGOS_NEWPING_RES_FAIL; float res = newping->ping_cm(); return isnan(res) ? MGOS_NEWPING_RES_FAIL : res; }
22.166667
69
0.740602
TridentTD
a1f4f723b4ddf6b4180a1d6af456d8aa069b8ae1
501
cpp
C++
src/pipeline/video/VideoSource.cpp
PlaymodesStudio/ofxPlaymodes2017
13ed5a77f75fa4c48f47d4e38ac10a5f085c7b31
[ "MIT" ]
null
null
null
src/pipeline/video/VideoSource.cpp
PlaymodesStudio/ofxPlaymodes2017
13ed5a77f75fa4c48f47d4e38ac10a5f085c7b31
[ "MIT" ]
1
2019-05-03T11:35:22.000Z
2019-05-03T23:22:58.000Z
src/pipeline/video/VideoSource.cpp
PlaymodesStudio/ofxPlaymodes2017
13ed5a77f75fa4c48f47d4e38ac10a5f085c7b31
[ "MIT" ]
null
null
null
/* * VideoSource.cpp * * Created on: 09-oct-2008 * Author: arturo castro */ #include "VideoSource.h" namespace ofxPm{ VideoSource::VideoSource() { //newFrameEvent.init("PlayModes.VideoSource.newFrameEvent"); width=-11; height=-11; } VideoSource::~VideoSource() { } void VideoSource::setWidth(int w) { width=w; } void VideoSource::setHeigth(int h) { height=h; } int VideoSource::getWidth() { return width; } int VideoSource::getHeight() { return height; } }
12.219512
61
0.654691
PlaymodesStudio
a1f52c1a85687881bb76c6348b5eaa6d7245e3a7
8,064
hpp
C++
s32v234_sdk/tools/emu/apu/src/apu_vbool.hpp
intesight/Panorama4AIWAYS
46e1988e54a5155be3b3b47c486b3f722be00b5c
[ "WTFPL" ]
null
null
null
s32v234_sdk/tools/emu/apu/src/apu_vbool.hpp
intesight/Panorama4AIWAYS
46e1988e54a5155be3b3b47c486b3f722be00b5c
[ "WTFPL" ]
null
null
null
s32v234_sdk/tools/emu/apu/src/apu_vbool.hpp
intesight/Panorama4AIWAYS
46e1988e54a5155be3b3b47c486b3f722be00b5c
[ "WTFPL" ]
2
2021-01-21T02:06:16.000Z
2021-01-28T10:47:37.000Z
/***************************************************************************** * * NXP Confidential Proprietary * * Copyright (c) 2013-2016 Freescale Semiconductor * Copyright 2017-2018 NXP * All Rights Reserved * ****************************************************************************** * * THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED 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 NXP OR ITS 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. * ****************************************************************************/ /** * \file APU_vbool.h * \brief APU vector boolean type * \author Igor Aleksandrowicz * \version * \date 26-August-2013 ****************************************************************************/ #ifndef APUVBOOL_HPP #define APUVBOOL_HPP #include "apu_config.hpp" #include "apu_cycles.hpp" #include <cassert> namespace APEX2 { /**************************************************************************** * globals ****************************************************************************/ //global vector condition state used for disabling CUs extern bool gEnabledCUs[VSIZE]; extern int _tileWidthInChunks; /**************************************************************************** * types ****************************************************************************/ typedef bool vbool_elem_T; class vbool { public: //vector boolean elements are public for easier interaction with the rest of the library and easier debugging //however this member does NOT exist in APU-C and shouldn't be used for the final code vbool_elem_T mElements[VSIZE]; vbool(); //broadcast vbool(const vbool_elem_T& arValue); vbool& operator=(const vbool& arRhs); //logical operations vbool operator== (const vbool& arOther) const; vbool operator!= (const vbool& arOther) const; vbool operator&& (const vbool& arOther) const; vbool operator|| (const vbool& arOther) const; vbool operator!() const; vbool operator~(); private: ///vector boolean move shifts and rotates declarations ///these functions don't modify *this vbool moveShiftLeft(const vbool& arFillVector) const; vbool moveShiftRight(const vbool& arFillVector) const; vbool moveRotateLeft(const vbool& arFillVector) const; vbool moveRotateRight(const vbool& arFillVector) const; ///vector boolean accumulation funtions declarations ///are all elements true / are any elements true? ///use caution when combining vall, vany with vif/velse, in this library they take only active CUs into account, in real ACF vany works like that but vall seems to be incorrect, vall seems to always returns false when some CUs are inactive vbool_elem_T all() const; vbool_elem_T any() const; //APU-C vector boolean move shifts and rotations operations are declared as friends /** vectorial move-shift-left *Move all values one CU to the left. Fill in the right-most CU with the right-most value in arVectorFill * *@parameter arVectorShift - Vector to be shifted *@parameter arVectorFill - Vector from which the right most value is filled */ friend vbool vmsl(const vbool& arVectorShift, const vbool& arVectorFill); /** vectorial move-shift-right *Move all values one CU to the right. Fill in the left-most CU with the left-most value in arVectorFill * *@parameter arVectorShift - Vector to be shifted *@parameter arVectorFill - Vector from which the left most value is filled */ friend vbool vmsr(const vbool& arVectorShift, const vbool& arVectorFill); /** vectorial move-rotate-left *Move all values one CU to the left. Fill in the right-most CU with the left-most value of the arVectorFill * *@parameter arVectorShift - Vector to be shifted *@parameter arVectorFill - Vector from which the left most value is filled */ friend vbool vmrl(const vbool& arVectorRotate, const vbool& arVectorFill); /** vectorial move-rotate-right *Move all values one CU to the right. Fill in the left-most CU with the right-most value in arVectorFill * *@parameter arVectorShift - Vector to be shifted *@parameter arVectorFill - Vector from which the right most value is filled */ friend vbool vmrr(const vbool& arVectorRotate, const vbool& arVectorFill); /** vectorial move-shift-left *Move all values one CU to the left. Fill in the right-most CU with the right-most value is set to zero * *@parameter arVectorShift - Vector to be shifted */ friend vbool vmsl(const vbool& arVectorShift); /** vectorial move-shift-right *Move all values one CU to the right. Fill in the left-most CU with the left-most value is filled with zero * *@parameter arVectorShift - Vector to be shifted */ friend vbool vmsr(const vbool& arVectorShift); /** vectorial move-rotate-left *Move all values one CU to the left. Fill in the right-most CU with the left-most value of the same vector * *@parameter arVectorShift - Vector to be shifted */ friend vbool vmrl(const vbool& arVectorRotate); /** vectorial move-rotate-right *Move all values one CU to the right. Fill in the left-most CU with the right-most value of the same vector * *@parameter arVectorShift - Vector to be shifted */ friend vbool vmrr(const vbool& arVectorRotate); /** *Depending on vc, select either values from va or vb * *@parameter va Source vector *@parameter vb Source Vector *@parameter vc boolean selection vector *@return if (vc ==true) va, else vb */ friend vbool vselect(const vbool& va, const vbool& vb, const vbool& vc); //APU-C vector boolean accumulation functions declared as friends /** *@return true, if all cu's contain a true value */ friend bool vall(const vbool& arCheck); /** *@return true, if at least one of the cu's contain a true value */ friend bool vany(const vbool& arCheck); }; /**************************************************************************** * non-member functions ****************************************************************************/ vbool vselect(const vbool& va, const vbool& vb, const vbool& vc); //APU-C operations declarations /** @return arVector[CU[aIndex]], i.e. the value of arVector in the aIndex-th CU */ vbool_elem_T vget(const vbool& arVector, int aIndex); /** Set at aIndex-th the arValue into arVector @param arVector - destination vector @param arValue - value to be set into destination @param aIndex - CU index where to set the value @return aVec[CU[aIndex]] = arValue; and aVec[all other CUs] = arVector[all other CUs] */ vbool vput(const vbool& arVector, const vbool_elem_T& arValue, int aIndex); vbool vmsl(const vbool& arVectorShift, const vbool& arVectorFill); vbool vmsr(const vbool& arVectorShift, const vbool& arVectorFill); vbool vmrl(const vbool& arVectorRotate, const vbool& arVectorFill); vbool vmrr(const vbool& arVectorRotate, const vbool& arVectorFill); vbool vmsl(const vbool& arVectorShift); vbool vmsr(const vbool& arVectorShift); vbool vmrl(const vbool& arVectorRotate); vbool vmrr(const vbool& arVectorRotate); bool vall(const vbool& arCheck); bool vany(const vbool& arCheck); //this vector boolean type std::string declaration is needed here //see apu_cycles.hpp template <> std::string GetVectorTypeString<vbool>(); } #endif /* APUVBOOL_HPP */
36.654545
242
0.653026
intesight
a1f7a022582f7262aaf30d8e38a14864692fa964
26,063
hpp
C++
include/UnityEngine/UI/MaskableGraphic.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/UnityEngine/UI/MaskableGraphic.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/UnityEngine/UI/MaskableGraphic.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.UI.Graphic #include "UnityEngine/UI/Graphic.hpp" // Including type: UnityEngine.UI.IMaterialModifier #include "UnityEngine/UI/IMaterialModifier.hpp" // Including type: UnityEngine.UI.IClippable #include "UnityEngine/UI/IClippable.hpp" // Including type: UnityEngine.UI.IMaskable #include "UnityEngine/UI/IMaskable.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::UI namespace UnityEngine::UI { // Forward declaring type: RectMask2D class RectMask2D; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Material class Material; // Forward declaring type: Rect struct Rect; // Forward declaring type: GameObject class GameObject; // Skipping declaration: Vector2 because it is already included! } // Completed forward declares // Type namespace: UnityEngine.UI namespace UnityEngine::UI { // Size: 0xC0 #pragma pack(push, 1) // Autogenerated type: UnityEngine.UI.MaskableGraphic // [TokenAttribute] Offset: FFFFFFFF class MaskableGraphic : public UnityEngine::UI::Graphic/*, public UnityEngine::UI::IMaterialModifier, public UnityEngine::UI::IClippable, public UnityEngine::UI::IMaskable*/ { public: // Nested type: UnityEngine::UI::MaskableGraphic::CullStateChangedEvent class CullStateChangedEvent; // protected System.Boolean m_ShouldRecalculateStencil // Size: 0x1 // Offset: 0x89 bool m_ShouldRecalculateStencil; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: m_ShouldRecalculateStencil and: m_MaskMaterial char __padding0[0x6] = {}; // protected UnityEngine.Material m_MaskMaterial // Size: 0x8 // Offset: 0x90 UnityEngine::Material* m_MaskMaterial; // Field size check static_assert(sizeof(UnityEngine::Material*) == 0x8); // private UnityEngine.UI.RectMask2D m_ParentMask // Size: 0x8 // Offset: 0x98 UnityEngine::UI::RectMask2D* m_ParentMask; // Field size check static_assert(sizeof(UnityEngine::UI::RectMask2D*) == 0x8); // private System.Boolean m_Maskable // Size: 0x1 // Offset: 0xA0 bool m_Maskable; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean m_IsMaskingGraphic // Size: 0x1 // Offset: 0xA1 bool m_IsMaskingGraphic; // Field size check static_assert(sizeof(bool) == 0x1); // [EditorBrowsableAttribute] Offset: 0xE6133C // [ObsoleteAttribute] Offset: 0xE6133C // protected System.Boolean m_IncludeForMasking // Size: 0x1 // Offset: 0xA2 bool m_IncludeForMasking; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: m_IncludeForMasking and: m_OnCullStateChanged char __padding5[0x5] = {}; // private UnityEngine.UI.MaskableGraphic/UnityEngine.UI.CullStateChangedEvent m_OnCullStateChanged // Size: 0x8 // Offset: 0xA8 UnityEngine::UI::MaskableGraphic::CullStateChangedEvent* m_OnCullStateChanged; // Field size check static_assert(sizeof(UnityEngine::UI::MaskableGraphic::CullStateChangedEvent*) == 0x8); // [EditorBrowsableAttribute] Offset: 0xE613A0 // [ObsoleteAttribute] Offset: 0xE613A0 // protected System.Boolean m_ShouldRecalculate // Size: 0x1 // Offset: 0xB0 bool m_ShouldRecalculate; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: m_ShouldRecalculate and: m_StencilValue char __padding7[0x3] = {}; // protected System.Int32 m_StencilValue // Size: 0x4 // Offset: 0xB4 int m_StencilValue; // Field size check static_assert(sizeof(int) == 0x4); // private readonly UnityEngine.Vector3[] m_Corners // Size: 0x8 // Offset: 0xB8 ::Array<UnityEngine::Vector3>* m_Corners; // Field size check static_assert(sizeof(::Array<UnityEngine::Vector3>*) == 0x8); // Creating value type constructor for type: MaskableGraphic MaskableGraphic(bool m_ShouldRecalculateStencil_ = {}, UnityEngine::Material* m_MaskMaterial_ = {}, UnityEngine::UI::RectMask2D* m_ParentMask_ = {}, bool m_Maskable_ = {}, bool m_IsMaskingGraphic_ = {}, bool m_IncludeForMasking_ = {}, UnityEngine::UI::MaskableGraphic::CullStateChangedEvent* m_OnCullStateChanged_ = {}, bool m_ShouldRecalculate_ = {}, int m_StencilValue_ = {}, ::Array<UnityEngine::Vector3>* m_Corners_ = {}) noexcept : m_ShouldRecalculateStencil{m_ShouldRecalculateStencil_}, m_MaskMaterial{m_MaskMaterial_}, m_ParentMask{m_ParentMask_}, m_Maskable{m_Maskable_}, m_IsMaskingGraphic{m_IsMaskingGraphic_}, m_IncludeForMasking{m_IncludeForMasking_}, m_OnCullStateChanged{m_OnCullStateChanged_}, m_ShouldRecalculate{m_ShouldRecalculate_}, m_StencilValue{m_StencilValue_}, m_Corners{m_Corners_} {} // Creating interface conversion operator: operator UnityEngine::UI::IMaterialModifier operator UnityEngine::UI::IMaterialModifier() noexcept { return *reinterpret_cast<UnityEngine::UI::IMaterialModifier*>(this); } // Creating interface conversion operator: operator UnityEngine::UI::IClippable operator UnityEngine::UI::IClippable() noexcept { return *reinterpret_cast<UnityEngine::UI::IClippable*>(this); } // Creating interface conversion operator: operator UnityEngine::UI::IMaskable operator UnityEngine::UI::IMaskable() noexcept { return *reinterpret_cast<UnityEngine::UI::IMaskable*>(this); } // Get instance field: protected System.Boolean m_ShouldRecalculateStencil bool _get_m_ShouldRecalculateStencil(); // Set instance field: protected System.Boolean m_ShouldRecalculateStencil void _set_m_ShouldRecalculateStencil(bool value); // Get instance field: protected UnityEngine.Material m_MaskMaterial UnityEngine::Material* _get_m_MaskMaterial(); // Set instance field: protected UnityEngine.Material m_MaskMaterial void _set_m_MaskMaterial(UnityEngine::Material* value); // Get instance field: private UnityEngine.UI.RectMask2D m_ParentMask UnityEngine::UI::RectMask2D* _get_m_ParentMask(); // Set instance field: private UnityEngine.UI.RectMask2D m_ParentMask void _set_m_ParentMask(UnityEngine::UI::RectMask2D* value); // Get instance field: private System.Boolean m_Maskable bool _get_m_Maskable(); // Set instance field: private System.Boolean m_Maskable void _set_m_Maskable(bool value); // Get instance field: private System.Boolean m_IsMaskingGraphic bool _get_m_IsMaskingGraphic(); // Set instance field: private System.Boolean m_IsMaskingGraphic void _set_m_IsMaskingGraphic(bool value); // Get instance field: protected System.Boolean m_IncludeForMasking bool _get_m_IncludeForMasking(); // Set instance field: protected System.Boolean m_IncludeForMasking void _set_m_IncludeForMasking(bool value); // Get instance field: private UnityEngine.UI.MaskableGraphic/UnityEngine.UI.CullStateChangedEvent m_OnCullStateChanged UnityEngine::UI::MaskableGraphic::CullStateChangedEvent* _get_m_OnCullStateChanged(); // Set instance field: private UnityEngine.UI.MaskableGraphic/UnityEngine.UI.CullStateChangedEvent m_OnCullStateChanged void _set_m_OnCullStateChanged(UnityEngine::UI::MaskableGraphic::CullStateChangedEvent* value); // Get instance field: protected System.Boolean m_ShouldRecalculate bool _get_m_ShouldRecalculate(); // Set instance field: protected System.Boolean m_ShouldRecalculate void _set_m_ShouldRecalculate(bool value); // Get instance field: protected System.Int32 m_StencilValue int _get_m_StencilValue(); // Set instance field: protected System.Int32 m_StencilValue void _set_m_StencilValue(int value); // Get instance field: private readonly UnityEngine.Vector3[] m_Corners ::Array<UnityEngine::Vector3>* _get_m_Corners(); // Set instance field: private readonly UnityEngine.Vector3[] m_Corners void _set_m_Corners(::Array<UnityEngine::Vector3>* value); // public UnityEngine.UI.MaskableGraphic/UnityEngine.UI.CullStateChangedEvent get_onCullStateChanged() // Offset: 0x1653F70 UnityEngine::UI::MaskableGraphic::CullStateChangedEvent* get_onCullStateChanged(); // public System.Void set_onCullStateChanged(UnityEngine.UI.MaskableGraphic/UnityEngine.UI.CullStateChangedEvent value) // Offset: 0x1653F78 void set_onCullStateChanged(UnityEngine::UI::MaskableGraphic::CullStateChangedEvent* value); // public System.Boolean get_maskable() // Offset: 0x1653F80 bool get_maskable(); // public System.Void set_maskable(System.Boolean value) // Offset: 0x1653F88 void set_maskable(bool value); // public System.Boolean get_isMaskingGraphic() // Offset: 0x1653FC0 bool get_isMaskingGraphic(); // public System.Void set_isMaskingGraphic(System.Boolean value) // Offset: 0x165290C void set_isMaskingGraphic(bool value); // private UnityEngine.Rect get_rootCanvasRect() // Offset: 0x1654140 UnityEngine::Rect get_rootCanvasRect(); // private UnityEngine.GameObject UnityEngine.UI.IClippable.get_gameObject() // Offset: 0x1654D9C UnityEngine::GameObject* UnityEngine_UI_IClippable_get_gameObject(); // public UnityEngine.Material GetModifiedMaterial(UnityEngine.Material baseMaterial) // Offset: 0x1653FC8 UnityEngine::Material* GetModifiedMaterial(UnityEngine::Material* baseMaterial); // public System.Void Cull(UnityEngine.Rect clipRect, System.Boolean validRect) // Offset: 0x16540E0 void Cull(UnityEngine::Rect clipRect, bool validRect); // private System.Void UpdateCull(System.Boolean cull) // Offset: 0x1654490 void UpdateCull(bool cull); // public System.Void SetClipRect(UnityEngine.Rect clipRect, System.Boolean validRect) // Offset: 0x1654574 void SetClipRect(UnityEngine::Rect clipRect, bool validRect); // public System.Void SetClipSoftness(UnityEngine.Vector2 clipSoftness) // Offset: 0x16545F0 void SetClipSoftness(UnityEngine::Vector2 clipSoftness); // public System.Void ParentMaskStateChanged() // Offset: 0x1654914 void ParentMaskStateChanged(); // private System.Void UpdateClipParent() // Offset: 0x165468C void UpdateClipParent(); // public System.Void RecalculateClipping() // Offset: 0x1654C08 void RecalculateClipping(); // public System.Void RecalculateMasking() // Offset: 0x1654C0C void RecalculateMasking(); // protected System.Void .ctor() // Offset: 0x1654C98 // Implemented from: UnityEngine.UI.Graphic // Base method: System.Void Graphic::.ctor() // Base method: System.Void UIBehaviour::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static MaskableGraphic* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::UI::MaskableGraphic::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<MaskableGraphic*, creationType>())); } // protected override System.Void OnEnable() // Offset: 0x165462C // Implemented from: UnityEngine.UI.Graphic // Base method: System.Void Graphic::OnEnable() void OnEnable(); // protected override System.Void OnDisable() // Offset: 0x16547F8 // Implemented from: UnityEngine.UI.Graphic // Base method: System.Void Graphic::OnDisable() void OnDisable(); // protected override System.Void OnTransformParentChanged() // Offset: 0x16548B4 // Implemented from: UnityEngine.UI.Graphic // Base method: System.Void Graphic::OnTransformParentChanged() void OnTransformParentChanged(); // protected override System.Void OnCanvasHierarchyChanged() // Offset: 0x1654918 // Implemented from: UnityEngine.UI.Graphic // Base method: System.Void Graphic::OnCanvasHierarchyChanged() void OnCanvasHierarchyChanged(); }; // UnityEngine.UI.MaskableGraphic #pragma pack(pop) static check_size<sizeof(MaskableGraphic), 184 + sizeof(::Array<UnityEngine::Vector3>*)> __UnityEngine_UI_MaskableGraphicSizeCheck; static_assert(sizeof(MaskableGraphic) == 0xC0); } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UI::MaskableGraphic*, "UnityEngine.UI", "MaskableGraphic"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::get_onCullStateChanged // Il2CppName: get_onCullStateChanged template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::UI::MaskableGraphic::CullStateChangedEvent* (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::get_onCullStateChanged)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "get_onCullStateChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::set_onCullStateChanged // Il2CppName: set_onCullStateChanged template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)(UnityEngine::UI::MaskableGraphic::CullStateChangedEvent*)>(&UnityEngine::UI::MaskableGraphic::set_onCullStateChanged)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "MaskableGraphic/CullStateChangedEvent")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "set_onCullStateChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::get_maskable // Il2CppName: get_maskable template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::get_maskable)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "get_maskable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::set_maskable // Il2CppName: set_maskable template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)(bool)>(&UnityEngine::UI::MaskableGraphic::set_maskable)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "set_maskable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::get_isMaskingGraphic // Il2CppName: get_isMaskingGraphic template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::get_isMaskingGraphic)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "get_isMaskingGraphic", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::set_isMaskingGraphic // Il2CppName: set_isMaskingGraphic template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)(bool)>(&UnityEngine::UI::MaskableGraphic::set_isMaskingGraphic)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "set_isMaskingGraphic", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::get_rootCanvasRect // Il2CppName: get_rootCanvasRect template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Rect (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::get_rootCanvasRect)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "get_rootCanvasRect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::UnityEngine_UI_IClippable_get_gameObject // Il2CppName: UnityEngine.UI.IClippable.get_gameObject template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::GameObject* (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::UnityEngine_UI_IClippable_get_gameObject)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "UnityEngine.UI.IClippable.get_gameObject", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::GetModifiedMaterial // Il2CppName: GetModifiedMaterial template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Material* (UnityEngine::UI::MaskableGraphic::*)(UnityEngine::Material*)>(&UnityEngine::UI::MaskableGraphic::GetModifiedMaterial)> { static const MethodInfo* get() { static auto* baseMaterial = &::il2cpp_utils::GetClassFromName("UnityEngine", "Material")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "GetModifiedMaterial", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{baseMaterial}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::Cull // Il2CppName: Cull template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)(UnityEngine::Rect, bool)>(&UnityEngine::UI::MaskableGraphic::Cull)> { static const MethodInfo* get() { static auto* clipRect = &::il2cpp_utils::GetClassFromName("UnityEngine", "Rect")->byval_arg; static auto* validRect = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "Cull", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{clipRect, validRect}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::UpdateCull // Il2CppName: UpdateCull template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)(bool)>(&UnityEngine::UI::MaskableGraphic::UpdateCull)> { static const MethodInfo* get() { static auto* cull = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "UpdateCull", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{cull}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::SetClipRect // Il2CppName: SetClipRect template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)(UnityEngine::Rect, bool)>(&UnityEngine::UI::MaskableGraphic::SetClipRect)> { static const MethodInfo* get() { static auto* clipRect = &::il2cpp_utils::GetClassFromName("UnityEngine", "Rect")->byval_arg; static auto* validRect = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "SetClipRect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{clipRect, validRect}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::SetClipSoftness // Il2CppName: SetClipSoftness template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)(UnityEngine::Vector2)>(&UnityEngine::UI::MaskableGraphic::SetClipSoftness)> { static const MethodInfo* get() { static auto* clipSoftness = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector2")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "SetClipSoftness", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{clipSoftness}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::ParentMaskStateChanged // Il2CppName: ParentMaskStateChanged template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::ParentMaskStateChanged)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "ParentMaskStateChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::UpdateClipParent // Il2CppName: UpdateClipParent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::UpdateClipParent)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "UpdateClipParent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::RecalculateClipping // Il2CppName: RecalculateClipping template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::RecalculateClipping)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "RecalculateClipping", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::RecalculateMasking // Il2CppName: RecalculateMasking template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::RecalculateMasking)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "RecalculateMasking", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::OnEnable // Il2CppName: OnEnable template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::OnEnable)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "OnEnable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::OnDisable // Il2CppName: OnDisable template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::OnDisable)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "OnDisable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::OnTransformParentChanged // Il2CppName: OnTransformParentChanged template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::OnTransformParentChanged)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "OnTransformParentChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::MaskableGraphic::OnCanvasHierarchyChanged // Il2CppName: OnCanvasHierarchyChanged template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::MaskableGraphic::*)()>(&UnityEngine::UI::MaskableGraphic::OnCanvasHierarchyChanged)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::MaskableGraphic*), "OnCanvasHierarchyChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
58.306488
815
0.739976
marksteward
a1fb7169cfad0587d3cdb2098c32b5d735366aa9
165
cpp
C++
HideousGameEngine/utests/Shaders/TextShaderTests.cpp
chunkyguy/hideous-engine
45a37a262897847613022e9c0d7a797b158a29f2
[ "MIT" ]
1
2019-09-13T18:18:07.000Z
2019-09-13T18:18:07.000Z
HideousGameEngine/utests/Shaders/TextShaderTests.cpp
chunkyguy/hideous-engine
45a37a262897847613022e9c0d7a797b158a29f2
[ "MIT" ]
null
null
null
HideousGameEngine/utests/Shaders/TextShaderTests.cpp
chunkyguy/hideous-engine
45a37a262897847613022e9c0d7a797b158a29f2
[ "MIT" ]
1
2019-11-21T06:32:56.000Z
2019-11-21T06:32:56.000Z
// // TextShader.cpp // HEAssets // // Created by Sid on 26/04/13. // Copyright (c) 2013 whackylabs. All rights reserved. // #include <he/Shaders/TextShader.h>
16.5
55
0.660606
chunkyguy
b80114e117e3e6b108f5913b94591af45be66534
1,472
cpp
C++
_src_/Core/Utls.cpp
daldegam/MuClientTools16
933d218501c188363096a8f9f73720c61b535d06
[ "MIT" ]
16
2021-07-15T04:00:38.000Z
2022-02-27T02:37:23.000Z
_src_/Core/Utls.cpp
daldegam/MuClientTools16
933d218501c188363096a8f9f73720c61b535d06
[ "MIT" ]
6
2021-08-05T05:01:35.000Z
2021-10-22T02:01:33.000Z
_src_/Core/Utls.cpp
daldegam/MuClientTools16
933d218501c188363096a8f9f73720c61b535d06
[ "MIT" ]
16
2021-07-18T02:40:12.000Z
2022-02-09T05:25:07.000Z
#include "Utls.h" //------------------------------------------------------------------------ //--Utls //------------------------------------------------------------------------ namespace Utls { void CreateParentDir(fs::path pPath) { //fs::path pParent = fs::_Parse_parent_path(pPath.wstring()); //fs::create_directories(pParent); fs::path pParent = fs::_Parse_parent_path(pPath.wstring()); if (!pParent.empty() && !fs::exists(pParent)) { Utls::CreateParentDir(pParent); fs::create_directory(pParent); } } fs::path RemoveSlashEnd(fs::path path) { if (path.empty()) return path; auto s = path.string(); auto c = s[s.length() - 1]; if (c == '/' || c == '\\') return s.substr(0, s.length() - 1); return path; } fs::path BackupPath(fs::path pFile) { fs::path pBak; if (fs::exists(pFile)) { int i = 0; std::wstring temp = pFile.wstring() + L"_bak_"; while (++i) { if (!fs::exists(temp + std::to_wstring(i))) { pBak = temp + std::to_wstring(i); break; } } try { fs::rename(pFile, pBak); } catch (std::exception ex) { PRINT_DEBUG(ex.what()); char msg[256]; printf(msg, "Use '%s' instead. \n", pBak); PRINT_DEBUG(msg); return pBak; } } return pFile; } void RemoveAllStringSpaces(std::string& s) { int count = 0; for (int i = 0; i < s.length(); i++) if (s[i] != ' ' && s[i] != '\t') s[count++] = s[i]; s.resize(count); } }
19.368421
74
0.5
daldegam
b803bc9be03161833dcab05a0ccceeb932e2854f
301
cpp
C++
1182.cpp
godmoonl/baekjoon
eb2193e5c914caebbbb6ac287ebca5865e7d04ca
[ "MIT" ]
1
2019-05-03T09:55:41.000Z
2019-05-03T09:55:41.000Z
1182.cpp
godmoonl/baekjoon
eb2193e5c914caebbbb6ac287ebca5865e7d04ca
[ "MIT" ]
null
null
null
1182.cpp
godmoonl/baekjoon
eb2193e5c914caebbbb6ac287ebca5865e7d04ca
[ "MIT" ]
null
null
null
#include <cstdio> int N, S, a[21]; int f(int n, int k,int c) { if (n == N && k == S && !c)return 1; if (n == N)return 0; return f(n+1, k + a[n],0)+f(n+1, k,c?1:0); } int main() { scanf("%d %d", &N, &S); for (int i = 0; i < N; i++) { scanf("%d", &a[i]); } printf("%d", f(0,0,1)); return 0; }
18.8125
43
0.448505
godmoonl
b809de1338b905e9616cf962db16422adbe81d09
2,668
cpp
C++
simulator/infra/config/config.cpp
gornik2000/mipt-mips
355e29434efcc32946634054c501cb26d61dd145
[ "MIT" ]
2
2020-09-22T13:44:39.000Z
2021-12-10T07:45:42.000Z
simulator/infra/config/config.cpp
cesarus777/mipt-mips
c940a7644c4ebb72ad2022d77afdbd4d1dcda0f6
[ "MIT" ]
null
null
null
simulator/infra/config/config.cpp
cesarus777/mipt-mips
c940a7644c4ebb72ad2022d77afdbd4d1dcda0f6
[ "MIT" ]
null
null
null
/* * config.cpp - implementation of Config class * Copyright 2017-2018 MIPT-MIPS */ #include "config.h" #include <popl.hpp> #include <sstream> namespace config { static AliasedSwitch help_option = { "h", "help", "print help"}; // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays, modernize-avoid-c-arrays, hicpp-avoid-c-arrays) void handleArgs( int argc, const char* const argv[], int start_index) try { BaseValue::options().parse( argc, argv, start_index); if ( help_option) throw HelpOption(); } catch ( const popl::invalid_option& e) { throw InvalidOption( e.what()); } std::string help() { return BaseValue::options().help(); } popl::OptionParser& BaseValue::options() { static popl::OptionParser instance( "Allowed options"); return instance; } template<typename T, Type type> static void add_option( popl::OptionParser* options, std::string_view alias, std::string_view name, std::string_view desc, const T& default_value, T* value) noexcept try { (void)default_value; if constexpr ( type == Type::SWITCH) // NOLINTNEXTLINE(bugprone-branch-clone) https://bugs.llvm.org/show_bug.cgi?id=44229 options->add<popl::Switch>( std::string( alias), std::string( name), std::string( desc), value); else if constexpr ( type == Type::OPTIONAL) options->add<popl::Value<T>>( std::string( alias), std::string( name), std::string( desc), default_value, value); else options->add<popl::Value<T>, popl::Attribute::required>( std::string( alias), std::string( name), std::string( desc), default_value, value); } catch ( const std::runtime_error& e) { std::cerr << "Bad option setup for '" << name << "' (" << e.what() << ")" << std::endl; std::terminate(); } catch ( ...) { std::cerr << "Bad option setup for '" << name << "' ( unknown exception )" << std::endl; std::terminate(); } template<typename T, Type type> BaseTValue<T, type>::BaseTValue( std::string_view alias, std::string_view name, std::string_view desc, const T& default_value) noexcept { // Workaround for Visual Studio bug // https://developercommunity.visualstudio.com/content/problem/846216/false-positive-c4297-for-constructor.html add_option<T, type>( &options(), alias, name, desc, default_value, &value); } template class BaseTValue<std::string, Type::OPTIONAL>; template class BaseTValue<std::string, Type::REQUIRED>; template class BaseTValue<uint32, Type::OPTIONAL>; template class BaseTValue<uint32, Type::REQUIRED>; template class BaseTValue<uint64, Type::OPTIONAL>; template class BaseTValue<uint64, Type::REQUIRED>; template class BaseTValue<bool, Type::SWITCH>; } // namespace config
35.105263
169
0.693778
gornik2000
b80ba1ca25904d2c946c36938190109ec2b69178
3,350
hpp
C++
include/System/Runtime/Remoting/Messaging/CallContext.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Runtime/Remoting/Messaging/CallContext.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Runtime/Remoting/Messaging/CallContext.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Runtime::Remoting::Messaging namespace System::Runtime::Remoting::Messaging { // Forward declaring type: LogicalCallContext class LogicalCallContext; } // Completed forward declares // Type namespace: System.Runtime.Remoting.Messaging namespace System::Runtime::Remoting::Messaging { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: System.Runtime.Remoting.Messaging.CallContext // [ComVisibleAttribute] Offset: D7E60C class CallContext : public ::Il2CppObject { public: // Creating value type constructor for type: CallContext CallContext() noexcept {} // static System.Object SetCurrentCallContext(System.Runtime.Remoting.Messaging.LogicalCallContext ctx) // Offset: 0x1A20520 static ::Il2CppObject* SetCurrentCallContext(System::Runtime::Remoting::Messaging::LogicalCallContext* ctx); // static System.Runtime.Remoting.Messaging.LogicalCallContext SetLogicalCallContext(System.Runtime.Remoting.Messaging.LogicalCallContext callCtx) // Offset: 0x1A20528 static System::Runtime::Remoting::Messaging::LogicalCallContext* SetLogicalCallContext(System::Runtime::Remoting::Messaging::LogicalCallContext* callCtx); // static public System.Object LogicalGetData(System.String name) // Offset: 0x1A20570 static ::Il2CppObject* LogicalGetData(::Il2CppString* name); // static private System.Object IllogicalGetData(System.String name) // Offset: 0x1A205D4 static ::Il2CppObject* IllogicalGetData(::Il2CppString* name); // static public System.Object GetData(System.String name) // Offset: 0x1A20638 static ::Il2CppObject* GetData(::Il2CppString* name); // static public System.Void SetData(System.String name, System.Object data) // Offset: 0x1A2066C static void SetData(::Il2CppString* name, ::Il2CppObject* data); // static public System.Void LogicalSetData(System.String name, System.Object data) // Offset: 0x1A20730 static void LogicalSetData(::Il2CppString* name, ::Il2CppObject* data); // private System.Void .ctor() // Offset: 0x1A20518 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static CallContext* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::Remoting::Messaging::CallContext::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<CallContext*, creationType>())); } }; // System.Runtime.Remoting.Messaging.CallContext #pragma pack(pop) } DEFINE_IL2CPP_ARG_TYPE(System::Runtime::Remoting::Messaging::CallContext*, "System.Runtime.Remoting.Messaging", "CallContext");
53.174603
159
0.725075
darknight1050
b80bb977eb7de00602a7f19dcb9534eba7c00b8f
702
cpp
C++
codes/Leetcode/leetcode061.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/Leetcode/leetcode061.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/Leetcode/leetcode061.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { ListNode* ans = new ListNode(0); ans->next = head; head = ans; int n = 0; ListNode* count = ans->next; while (count != NULL) { count = count->next; n++; } if (n == 0) return ans->next; else k %= n; ListNode* move = ans; while (k--) move = move->next; while (move->next != NULL) { head = head->next; move = move->next; } move->next = ans->next; ans->next = head->next; head->next = NULL; return ans->next; } };
20.647059
54
0.549858
JeraKrs
b80c061ecc8a591557d0bcb780dab4371df09641
1,719
cpp
C++
CPP/Linked List/detectCycleInList.cpp
deepakabari/MyCode
9c5f8b99f1bf04e58e233fedb9e517ae967e94cd
[ "MIT" ]
null
null
null
CPP/Linked List/detectCycleInList.cpp
deepakabari/MyCode
9c5f8b99f1bf04e58e233fedb9e517ae967e94cd
[ "MIT" ]
null
null
null
CPP/Linked List/detectCycleInList.cpp
deepakabari/MyCode
9c5f8b99f1bf04e58e233fedb9e517ae967e94cd
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; class node{ public: int val; node* next; node(int x){ val = x; next = NULL; } }; //function to insert node at end of the linked list void insertAtTail(node* &head, int x){ node* newNode = new node(x); if(head == NULL){ head = newNode; return; } node* temp = head; while(temp->next != NULL) temp=temp->next; temp->next = newNode; return; } void createCycle(node* &head, int pos){ node *temp = head; node *startNode; int count = 1; while (temp->next != NULL) { if (count == pos) { startNode = temp; } temp = temp->next; count++; } temp->next = startNode; } bool detectCycle(node* head){ if(head == NULL) return false; node* slow = head; node* fast = head; while(fast != NULL && fast->next != NULL){ fast = fast->next->next; slow = slow->next; if(slow == fast) return true; } return false; } //function to print linked list created void printList(node* head){ node* temp = head; while(temp != NULL){ cout << temp->val << "->"; temp = temp->next; } cout << "NULL" << endl; } int main(){ node* head = NULL; insertAtTail(head, 1); insertAtTail(head, 2); insertAtTail(head, 3); insertAtTail(head, 4); printList(head); createCycle(head, 2); printList(head); if(detectCycle(head) == true){ cout << "Cycle Detected" << endl; } else { cout << "Cylce Not Detected" << endl; } return 0; }
20.223529
52
0.503781
deepakabari
b80c38109b8a44fd36f58a22254daaf14e2f827d
1,785
cpp
C++
src/ProtoInput/ProtoInputHooks/FocusMessageLoop.cpp
Ilyaki/ProtoInput
dd29bf8d22349605d0e1950c1c5dc4893d72670e
[ "MIT" ]
16
2021-04-27T04:18:25.000Z
2022-02-27T21:13:57.000Z
src/ProtoInput/ProtoInputHooks/FocusMessageLoop.cpp
zZeck/ProtoInput
dd29bf8d22349605d0e1950c1c5dc4893d72670e
[ "MIT" ]
6
2021-06-22T16:55:37.000Z
2022-02-13T04:29:11.000Z
src/ProtoInput/ProtoInputHooks/FocusMessageLoop.cpp
zZeck/ProtoInput
dd29bf8d22349605d0e1950c1c5dc4893d72670e
[ "MIT" ]
4
2021-04-30T21:05:57.000Z
2022-02-07T06:12:00.000Z
#include "FocusMessageLoop.h" #include <cstdio> #include "HwndSelector.h" #include "GetKeyboardStateHook.h" namespace Proto { HANDLE FocusMessageLoop::loopThread = nullptr; bool FocusMessageLoop::running = false; int FocusMessageLoop::sleepMilliseconds = 5; FocusMessageLoop::ToSend FocusMessageLoop::messagesToSend{}; DWORD WINAPI LoopThread(LPVOID lpParameter) { printf("Starting focus message loop thread\n"); //TODO: need to close the thread handle when application closes //TODO: check how much cpu this uses AddThreadToACL(GetCurrentThreadId()); while(true) { const HWND hwnd = (HWND)HwndSelector::GetSelectedHwnd(); if (hwnd != nullptr) { if (FocusMessageLoop::messagesToSend.wm_activate) PostMessageW(hwnd, WM_ACTIVATE, WA_CLICKACTIVE, 0); if (FocusMessageLoop::messagesToSend.wm_activateapp) PostMessageW(hwnd, WM_ACTIVATEAPP, TRUE, 0); if (FocusMessageLoop::messagesToSend.wm_ncactivate) PostMessageW(hwnd, WM_NCACTIVATE, TRUE, 0); if (FocusMessageLoop::messagesToSend.wm_setfocus) PostMessageW(hwnd, WM_SETFOCUS, 0, 0); if (FocusMessageLoop::messagesToSend.wm_mouseactivate) PostMessageW(hwnd, WM_MOUSEACTIVATE, HwndSelector::GetSelectedHwnd(), 1); Sleep(FocusMessageLoop::sleepMilliseconds); } else { Sleep(100); } } return 0; } void FocusMessageLoop::SetupThread() { loopThread = CreateThread(nullptr, 0,(LPTHREAD_START_ROUTINE)LoopThread, GetModuleHandle(0), CREATE_SUSPENDED, 0); running = false; } void FocusMessageLoop::StartMessageLoop() { if (loopThread == nullptr) SetupThread(); ResumeThread(loopThread); running = true; } void FocusMessageLoop::PauseMessageLoop() { SuspendThread(loopThread); running = false; } void FocusMessageLoop::Cleanup() { CloseHandle(loopThread); } }
23.486842
131
0.755182
Ilyaki
b80dbc9bc65dc167dd1d7bd7ac5fe89bb87decc0
278
cpp
C++
Muriel/MuGameComponent.cpp
MurielSoftware/Muriel
169ab5a96e1cf70b47f7892906a3dca2d6481ae3
[ "Apache-2.0" ]
1
2017-03-01T12:15:27.000Z
2017-03-01T12:15:27.000Z
Muriel/MuGameComponent.cpp
MurielSoftware/Muriel
169ab5a96e1cf70b47f7892906a3dca2d6481ae3
[ "Apache-2.0" ]
1
2017-03-01T12:19:17.000Z
2017-03-01T12:19:52.000Z
Muriel/MuGameComponent.cpp
MurielSoftware/Muriel
169ab5a96e1cf70b47f7892906a3dca2d6481ae3
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "MuGameComponent.h" namespace Muriel { GameComponent::GameComponent(GameObject* owner, GameComponentType gameComponentType) { _owner = owner; _gameComponentType = gameComponentType; } GameComponent::~GameComponent() { } }
17.375
86
0.715827
MurielSoftware
b80e5ab40697ac702326ed923d2215168117d30d
301
cc
C++
PP0501A.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2021-02-01T11:21:56.000Z
2021-02-01T11:21:56.000Z
PP0501A.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
null
null
null
PP0501A.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2022-01-28T15:25:45.000Z
2022-01-28T15:25:45.000Z
// C++14 (gcc 8.3) #include <iostream> int GCD(int a, int b) { while (b != 0) { int temp{b}; b = a % b; a = temp; } return a; } int main() { int t; std::cin >> t; while (--t >= 0) { int a, b; std::cin >> a >> b; std::cout << GCD(a, b) << "\n"; } return 0; }
12.541667
35
0.415282
hkktr
b8118cdc334ea8f1bdbbfac518d8ff2948c1cf6f
4,064
hpp
C++
core/crypto/sr25519_types.hpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
core/crypto/sr25519_types.hpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
core/crypto/sr25519_types.hpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_CORE_CRYPTO_VRF_TYPES #define KAGOME_CORE_CRYPTO_VRF_TYPES extern "C" { #include <schnorrkel/schnorrkel.h> } #include <boost/multiprecision/cpp_int.hpp> #include <gsl/span> #include "common/blob.hpp" #include "common/mp_utils.hpp" namespace kagome::crypto { namespace constants::sr25519 { /** * Important constants to deal with sr25519 */ enum { KEYPAIR_SIZE = SR25519_KEYPAIR_SIZE, SECRET_SIZE = SR25519_SECRET_SIZE, PUBLIC_SIZE = SR25519_PUBLIC_SIZE, SIGNATURE_SIZE = SR25519_SIGNATURE_SIZE, SEED_SIZE = SR25519_SEED_SIZE }; namespace vrf { /** * Important constants to deal with vrf */ enum { PROOF_SIZE = SR25519_VRF_PROOF_SIZE, OUTPUT_SIZE = SR25519_VRF_OUTPUT_SIZE }; } // namespace vrf } // namespace constants::sr25519 using VRFPreOutput = std::array<uint8_t, constants::sr25519::vrf::OUTPUT_SIZE>; using VRFThreshold = boost::multiprecision::uint128_t; using VRFProof = std::array<uint8_t, constants::sr25519::vrf::PROOF_SIZE>; /** * Output of a verifiable random function. * Consists of pre-output, which is an internal representation of the * generated random value, and the proof to this value that servers as the * verification of its randomness. */ struct VRFOutput { // an internal representation of the generated random value VRFPreOutput output{}; // the proof to the output, serves as the verification of its randomness VRFProof proof{}; bool operator==(const VRFOutput &other) const; bool operator!=(const VRFOutput &other) const; }; /** * Output of a verifiable random function verification. */ struct VRFVerifyOutput { // indicates if the proof is valid bool is_valid; // indicates if the value is less than the provided threshold bool is_less; }; KAGOME_BLOB_STRICT_TYPEDEF(Sr25519SecretKey, constants::sr25519::SECRET_SIZE); KAGOME_BLOB_STRICT_TYPEDEF(Sr25519PublicKey, constants::sr25519::PUBLIC_SIZE); using Sr25519Seed = common::Blob<constants::sr25519::SEED_SIZE>; struct Sr25519Keypair { Sr25519SecretKey secret_key; Sr25519PublicKey public_key; Sr25519Keypair() = default; bool operator==(const Sr25519Keypair &other) const; bool operator!=(const Sr25519Keypair &other) const; }; KAGOME_BLOB_STRICT_TYPEDEF(Sr25519Signature, constants::sr25519::SIGNATURE_SIZE); /** * @brief outputs object of type VRFOutput to stream * @tparam Stream output stream type * @param s stream reference * @param v value to output * @return reference to stream */ template <class Stream, typename = std::enable_if_t<Stream::is_encoder_stream>> Stream &operator<<(Stream &s, const VRFOutput &o) { return s << o.output << o.proof; } /** * @brief decodes object of type VRFOutput from stream * @tparam Stream input stream type * @param s stream reference * @param v value to output * @return reference to stream */ template <class Stream, typename = std::enable_if_t<Stream::is_decoder_stream>> Stream &operator>>(Stream &s, VRFOutput &o) { return s >> o.output >> o.proof; } } // namespace kagome::crypto template <> struct std::hash<kagome::crypto::Sr25519SecretKey> { auto operator()(const kagome::crypto::Sr25519SecretKey &key) const { return boost::hash_range(key.cbegin(), key.cend()); // NOLINT } }; template <> struct std::hash<kagome::crypto::Sr25519PublicKey> { auto operator()(const kagome::crypto::Sr25519PublicKey &key) const { return boost::hash_range(key.cbegin(), key.cend()); // NOLINT } }; template <> struct std::hash<kagome::crypto::Sr25519Signature> { auto operator()(const kagome::crypto::Sr25519Signature &sig) const { return boost::hash_range(sig.cbegin(), sig.cend()); // NOLINT } }; #endif // KAGOME_CORE_CRYPTO_VRF_TYPES
28.619718
80
0.690207
igor-egorov
b812ae0e8b24d5eb11c8dbd65a9fc86065444c5a
16,102
cpp
C++
source/python/libpytimemory-profile.cpp
ocnkr/timemory
35c5e32b80db4ae30a10ae6f1ee08d24a2161b73
[ "MIT" ]
null
null
null
source/python/libpytimemory-profile.cpp
ocnkr/timemory
35c5e32b80db4ae30a10ae6f1ee08d24a2161b73
[ "MIT" ]
null
null
null
source/python/libpytimemory-profile.cpp
ocnkr/timemory
35c5e32b80db4ae30a10ae6f1ee08d24a2161b73
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2020, The Regents of the University of California, // through Lawrence Berkeley National Laboratory (subject to receipt of any // required approvals from the U.S. Dept. of Energy). 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. #if !defined(TIMEMORY_PYUNITS_SOURCE) # define TIMEMORY_PYUNITS_SOURCE #endif #include "libpytimemory-component-bundle.hpp" #include <cstdint> using namespace tim::component; //======================================================================================// // namespace pyprofile { // using profiler_t = tim::component_bundle<TIMEMORY_API, user_profiler_bundle>; using profiler_vec_t = std::vector<profiler_t>; using profiler_label_map_t = std::unordered_map<std::string, profiler_vec_t>; using profiler_index_map_t = std::unordered_map<uint32_t, profiler_label_map_t>; using strset_t = std::unordered_set<std::string>; // struct config { bool is_running = false; bool trace_c = true; bool include_internal = false; bool include_args = false; bool include_line = false; bool include_filename = true; bool full_filepath = false; int32_t max_stack_depth = std::numeric_limits<uint16_t>::max(); int32_t ignore_stack_depth = 0; int32_t base_stack_depth = -1; std::string base_module_path = ""; strset_t include_functions = {}; strset_t include_filenames = {}; tim::scope::config profiler_scope = tim::scope::get_default(); strset_t exclude_functions = { "FILE", "FUNC", "LINE", "get_fcode", "__exit__", "_handle_fromlist", "<module>", "_shutdown", "isclass", "isfunction", "basename", "_get_sep" }; strset_t exclude_filenames = { "__init__.py", "__main__.py", "functools.py", "<frozen importlib._bootstrap>", "_pylab_helpers.py", "threading.py", "encoder.py", "decoder.py" }; profiler_index_map_t records = {}; int32_t verbose = tim::settings::verbose() + ((tim::settings::debug()) ? 16 : 0); }; // inline config& get_config() { static auto* _instance = new config{}; static thread_local auto* _tl_instance = []() { static std::atomic<uint32_t> _count{ 0 }; auto _cnt = _count++; if(_cnt == 0) return _instance; auto* _tmp = new config{}; _tmp->is_running = _instance->is_running; _tmp->trace_c = _instance->trace_c; _tmp->include_internal = _instance->include_internal; _tmp->include_args = _instance->include_args; _tmp->include_line = _instance->include_line; _tmp->include_filename = _instance->include_filename; _tmp->full_filepath = _instance->full_filepath; _tmp->max_stack_depth = _instance->max_stack_depth; _tmp->base_module_path = _instance->base_module_path; _tmp->include_functions = _instance->include_functions; _tmp->include_filenames = _instance->include_filenames; _tmp->exclude_functions = _instance->exclude_functions; _tmp->exclude_filenames = _instance->exclude_filenames; _tmp->verbose = _instance->verbose; return _tmp; }(); return *_tl_instance; } // int32_t get_depth(PyFrameObject* frame) { return (frame->f_back) ? (get_depth(frame->f_back) + 1) : 0; } // void profiler_function(py::object pframe, const char* swhat, py::object arg) { if(!tim::settings::enabled()) return; if(user_profiler_bundle::bundle_size() == 0) { if(tim::settings::debug()) PRINT_HERE("%s", "Profiler bundle is empty"); return; } static thread_local auto& _config = get_config(); static auto _timemory_path = _config.base_module_path; auto* frame = reinterpret_cast<PyFrameObject*>(pframe.ptr()); int what = (strcmp(swhat, "call") == 0) ? PyTrace_CALL : (strcmp(swhat, "c_call") == 0) ? PyTrace_C_CALL : (strcmp(swhat, "return") == 0) ? PyTrace_RETURN : (strcmp(swhat, "c_return") == 0) ? PyTrace_C_RETURN : -1; // only support PyTrace_{CALL,C_CALL,RETURN,C_RETURN} if(what < 0) { if(tim::settings::debug()) PRINT_HERE("%s :: %s", "Ignoring what != {CALL,C_CALL,RETURN,C_RETURN}", swhat); return; } // if PyTrace_C_{CALL,RETURN} is not enabled if(!_config.trace_c && (what == PyTrace_C_CALL || what == PyTrace_C_RETURN)) { if(tim::settings::debug()) PRINT_HERE("%s :: %s", "Ignoring C call/return", swhat); return; } // get the depth of the frame auto _fdepth = get_depth(frame); if(_config.base_stack_depth < 0) _config.base_stack_depth = _fdepth; bool _iscall = (what == PyTrace_CALL || what == PyTrace_C_CALL); int32_t _sdepth = _fdepth - _config.base_stack_depth - 3; // if frame exceeds max stack-depth if(_iscall && _sdepth > _config.max_stack_depth) { if(tim::settings::debug()) PRINT_HERE("skipping %i > %i", (int) _sdepth, (int) _config.max_stack_depth); return; } // get the function name auto _get_funcname = [&]() -> std::string { return py::cast<std::string>(frame->f_code->co_name); }; // get the filename auto _get_filename = [&]() -> std::string { return py::cast<std::string>(frame->f_code->co_filename); }; // get the basename of the filename auto _get_basename = [&](const std::string& _fullpath) { if(_fullpath.find('/') != std::string::npos) return _fullpath.substr(_fullpath.find_last_of('/') + 1); return _fullpath; }; // get the arguments auto _get_args = [&]() { auto inspect = py::module::import("inspect"); return py::cast<std::string>( inspect.attr("formatargvalues")(*inspect.attr("getargvalues")(pframe))); }; // get the final label auto _get_label = [&](auto& _func, auto& _filename, auto& _fullpath) { // append the arguments if(_config.include_args) _func = TIMEMORY_JOIN("", _func, _get_args()); // append the filename if(_config.include_filename) { if(_config.full_filepath) _func = TIMEMORY_JOIN('/', _func, std::move(_fullpath)); else _func = TIMEMORY_JOIN('/', _func, std::move(_filename)); } // append the line number if(_config.include_line) _func = TIMEMORY_JOIN(':', _func, frame->f_lineno); return _func; }; auto& _only_funcs = _config.include_functions; auto& _skip_funcs = _config.exclude_functions; auto _func = _get_funcname(); if(!_only_funcs.empty() && _only_funcs.find(_func) == _only_funcs.end()) return; if(_skip_funcs.find(_func) != _skip_funcs.end()) { auto _manager = tim::manager::instance(); if(!_manager || _manager->is_finalized() || _func == "_shutdown") { auto sys = py::module::import("sys"); auto threading = py::module::import("threading"); sys.attr("setprofile")(py::none{}); threading.attr("setprofile")(py::none{}); } return; } auto& _only_files = _config.include_filenames; auto& _skip_files = _config.exclude_filenames; auto _full = _get_filename(); auto _file = _get_basename(_full); if(!_config.include_internal && strncmp(_full.c_str(), _timemory_path.c_str(), _timemory_path.length()) == 0) return; if(!_only_files.empty() && (_only_files.find(_file) == _only_files.end() && _only_files.find(_full) == _only_files.end())) { #if defined(DEBUG) if(tim::settings::debug()) { std::stringstream _opts; for(const auto& itr : _only_files) _opts << "| " << itr; PRINT_HERE("Skipping: [%s | %s | %s] due to [%s]", _func.c_str(), _file.c_str(), _full.c_str(), _opts.str().substr(2).c_str()); } #endif return; } if(_skip_files.find(_file) != _skip_files.end() || _skip_files.find(_full) != _skip_files.end()) return; DEBUG_PRINT_HERE("%8s | %s%s | %s | %s", swhat, _func.c_str(), _get_args().c_str(), _file.c_str(), _full.c_str()); auto _label = _get_label(_func, _file, _full); // start function auto _profiler_call = [&]() { auto& _entry = _config.records[_fdepth][_label]; _entry.emplace_back(profiler_t{ _label, _config.profiler_scope }); _entry.back().start(); }; // stop function auto _profiler_return = [&]() { auto fitr = _config.records.find(_fdepth); if(fitr == _config.records.end()) return; auto litr = fitr->second.find(_label); if(litr == fitr->second.end()) return; if(litr->second.empty()) return; litr->second.back().stop(); litr->second.pop_back(); }; // process what switch(what) { case PyTrace_CALL: case PyTrace_C_CALL: _profiler_call(); break; case PyTrace_RETURN: case PyTrace_C_RETURN: _profiler_return(); break; default: break; } // don't do anything with arg tim::consume_parameters(arg); } // py::module generate(py::module& _pymod) { py::module _prof = _pymod.def_submodule("profiler", "Profiling functions"); static auto _scope_set = [](bool _flat, bool _timeline) { get_config().profiler_scope = tim::scope::config{ _flat, _timeline }; }; pycomponent_bundle::generate<user_profiler_bundle>( _prof, "profiler_bundle", "User-bundle for Python profiling interface", _scope_set); auto _init = []() { try { auto _file = py::module::import("timemory").attr("__file__").cast<std::string>(); if(_file.find('/') != std::string::npos) _file = _file.substr(0, _file.find_last_of('/')); get_config().base_module_path = _file; } catch(py::cast_error& e) { std::cerr << "[profiler_init]> " << e.what() << std::endl; } if(get_config().is_running) return; get_config().records.clear(); get_config().base_stack_depth = -1; get_config().is_running = true; }; auto _fini = []() { if(!get_config().is_running) return; get_config().is_running = false; get_config().base_stack_depth = -1; get_config().records.clear(); }; _prof.def("profiler_function", &profiler_function, "Profiling function"); _prof.def("profiler_init", _init, "Initialize the profiler"); _prof.def("profiler_finalize", _fini, "Finalize the profiler"); py::class_<config> _pyconfig(_prof, "config", "Profiler configuration"); #define CONFIGURATION_PROPERTY(NAME, TYPE, DOC, ...) \ _pyconfig.def_property_static(NAME, [](py::object) { return __VA_ARGS__; }, \ [](py::object, TYPE val) { __VA_ARGS__ = val; }, DOC); CONFIGURATION_PROPERTY("_is_running", bool, "Profiler is currently running", get_config().is_running) CONFIGURATION_PROPERTY("trace_c", bool, "Enable tracing C functions", get_config().trace_c) CONFIGURATION_PROPERTY("include_internal", bool, "Include functions within timemory", get_config().include_internal) CONFIGURATION_PROPERTY("include_args", bool, "Encode the function arguments", get_config().include_args) CONFIGURATION_PROPERTY("include_line", bool, "Encode the function line number", get_config().include_line) CONFIGURATION_PROPERTY("include_filename", bool, "Encode the function filename (see also: full_filepath)", get_config().include_filename) CONFIGURATION_PROPERTY("full_filepath", bool, "Display the full filepath (instead of file basename)", get_config().full_filepath) CONFIGURATION_PROPERTY("max_stack_depth", int32_t, "Maximum stack depth to profile", get_config().max_stack_depth) CONFIGURATION_PROPERTY("verbosity", int32_t, "Verbosity of the logging", get_config().verbose) static auto _get_strset = [](const strset_t& _targ) { auto _out = py::list{}; for(auto itr : _targ) _out.append(itr); return _out; }; static auto _set_strset = [](py::list _inp, strset_t& _targ) { for(auto itr : _inp) _targ.insert(itr.cast<std::string>()); }; #define CONFIGURATION_PROPERTY_LAMBDA(NAME, DOC, GET, SET) \ _pyconfig.def_property_static(NAME, GET, SET, DOC); #define CONFIGURATION_STRSET(NAME, DOC, ...) \ { \ auto GET = [](py::object) { return _get_strset(__VA_ARGS__); }; \ auto SET = [](py::object, py::list val) { _set_strset(val, __VA_ARGS__); }; \ CONFIGURATION_PROPERTY_LAMBDA(NAME, DOC, GET, SET) \ } CONFIGURATION_STRSET("only_functions", "Function names to collect exclusively", get_config().include_functions) CONFIGURATION_STRSET("only_filenames", "File names to collect exclusively", get_config().include_filenames) CONFIGURATION_STRSET("skip_functions", "Function names to filter out of collection", get_config().exclude_functions) CONFIGURATION_STRSET("skip_filenames", "Filenames to filter out of collection", get_config().exclude_filenames) tim::operation::init<user_profiler_bundle>( tim::operation::mode_constant<tim::operation::init_mode::global>{}); return _prof; } } // namespace pyprofile // //======================================================================================//
39.273171
90
0.572972
ocnkr
b8130e30539af4f5a0fb4d36b613e3efdd28c662
2,536
cpp
C++
Box2D_Shapes/ModuleSceneIntro.cpp
rastabrandy02/Physics_2
bc4024409985d15ec6e1c5c00c78df062140fd6b
[ "MIT" ]
null
null
null
Box2D_Shapes/ModuleSceneIntro.cpp
rastabrandy02/Physics_2
bc4024409985d15ec6e1c5c00c78df062140fd6b
[ "MIT" ]
null
null
null
Box2D_Shapes/ModuleSceneIntro.cpp
rastabrandy02/Physics_2
bc4024409985d15ec6e1c5c00c78df062140fd6b
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "ModuleRender.h" #include "ModuleSceneIntro.h" #include "ModuleInput.h" #include "ModuleTextures.h" #include "ModulePhysics.h" ModuleSceneIntro::ModuleSceneIntro(Application* app, bool start_enabled) : Module(app, start_enabled) { circle = box = rick = NULL; } ModuleSceneIntro::~ModuleSceneIntro() {} // Load assets bool ModuleSceneIntro::Start() { LOG("Loading Intro assets"); bool ret = true; App->renderer->camera.x = App->renderer->camera.y = 0; circle = App->textures->Load("pinball/wheel.png"); box = App->textures->Load("pinball/crate.png"); rick = App->textures->Load("pinball/rick_head.png"); slime = App->textures->Load("pinball/slime_transparent.png"); return ret; } // Load assets bool ModuleSceneIntro::CleanUp() { LOG("Unloading Intro scene"); return true; } // Update: draw background update_status ModuleSceneIntro::Update() { // TODO 5: Move all creation of bodies on 1,2,3 key press here in the scene if (App->input->GetKey(SDL_SCANCODE_1) == KEY_DOWN) { circles.add(App->physics->CreateCircle(App->input->GetMouseX(), App->input->GetMouseY(), 25)); //if(circles->body->GetPosition().x > 5) App->physics->CreateChain(App->input->GetMouseX(), App->input->GetMouseY(), slime_transparent, 64, 4);; } if (App->input->GetKey(SDL_SCANCODE_2) == KEY_DOWN) { boxes.add(App->physics->CreateRectangle(App->input->GetMouseX(), App->input->GetMouseY(), 50, 25)); } if (App->input->GetKey(SDL_SCANCODE_3) == KEY_DOWN) { //BodyPointer* chains = App->physics->CreateChain(App->input->GetMouseX(), App->input->GetMouseY(), slime_transparent, 64, 4); slimes.add(App->physics->CreateChain(App->input->GetMouseX() - 500, App->input->GetMouseY() - 500, slimeArray, 64, 1)); } // TODO 7: Draw all the circles using "circle" texture p2List_item<PhysBody*>* c = slimes.getFirst(); while (c != NULL) { int x, y; c->data->GetPosition(x, y); App->renderer->Blit(slime, x, y, NULL, 1.0f, c->data->GetRotation()); c = c->next; } c = circles.getFirst(); while (c != NULL) { int x, y; c->data->GetPosition(x, y); x -= 25; y -= 25; //if (c->data->Contains(App->input->GetMouseX(), App->input->GetMouseY())) App->renderer->Blit(circle, x, y, NULL, 1.0f, c->data->GetRotation()); c = c->next; } c = boxes.getFirst(); while (c != NULL) { int x, y; c->data->GetPosition(x, y); App->renderer->Blit(box, x, y, NULL, 1.0f, c->data->GetRotation()); c = c->next; } return UPDATE_CONTINUE; }
25.36
146
0.662461
rastabrandy02
b8185a74a008a1eaafb6f7dae672a2801d02cb25
704
cpp
C++
S05/PointToMeAndYou.cpp
stevekeol/-Thinking-in-Cpp-PracticeCode
5b147e704015bbda364ab069f1de58dcef7ab14a
[ "MIT" ]
2
2017-06-20T12:16:30.000Z
2021-11-12T12:06:57.000Z
S05/PointToMeAndYou.cpp
stevekeol/-Thinking-in-Cpp-PracticeCode
5b147e704015bbda364ab069f1de58dcef7ab14a
[ "MIT" ]
null
null
null
S05/PointToMeAndYou.cpp
stevekeol/-Thinking-in-Cpp-PracticeCode
5b147e704015bbda364ab069f1de58dcef7ab14a
[ "MIT" ]
null
null
null
//: S05:PointToMeAndYou.cpp // From "Thinking in C++, 2nd Edition, Volume 1, Annotated Solutions Guide" // by Chuck Allison, (c) 2001 MindView, Inc. all rights reserved // Available at www.BruceEckel.com. #include <iostream> using namespace std; class You; // Forward declaration class Me { public: void ProcessYou(You* p) { cout << "Processing You at " << p << endl; } }; class You { public: void ProcessMe(Me* p) { cout << "Processing Me at " << p << endl; } }; int main() { Me me; You you; me.ProcessYou(&you); you.ProcessMe(&me); } /* Output: Processing You at 0065FDF4 Processing Me at 0065FDFC */ ///:~
19.027027
76
0.586648
stevekeol
b818f9ad3564f15010b76c28efad7831423b2a1e
1,694
cc
C++
src/BufferedInputStream.cc
RUNDSP/avro-nodejs
7136be348dbb6c57af27be387196254ca1711977
[ "Apache-2.0" ]
null
null
null
src/BufferedInputStream.cc
RUNDSP/avro-nodejs
7136be348dbb6c57af27be387196254ca1711977
[ "Apache-2.0" ]
null
null
null
src/BufferedInputStream.cc
RUNDSP/avro-nodejs
7136be348dbb6c57af27be387196254ca1711977
[ "Apache-2.0" ]
null
null
null
#include "BufferedInputStream.hh" namespace avronode { /** * Deconstructor for BufferedInputStream * destroy mutex and release the vector buffer */ BufferedInputStream::~BufferedInputStream(){ } /** * [BufferedInputStream::next description] * @param data [description] * @param len [description] * @return [description] */ bool BufferedInputStream::next(const uint8_t** data, size_t* len) { pthread_mutex_lock(&lock); if(data_.totalLength == 0){ pthread_cond_wait( &cond, &lock); if(!read_){ return false; } } *len = data_.readBlock(const_cast<uint8_t**>(data)); pthread_mutex_unlock(&lock); return true; } /** * */ long BufferedInputStream::size(){ return data_.totalLength; } /** * decrements the internal buffer index by len. * @param len [description] */ void BufferedInputStream::backup(size_t len) { cur_ -= len; } /** * [BufferedInputStream::append description] * @param in [description] * @param len [description] */ void BufferedInputStream::append(uint8_t* in , int len) { pthread_mutex_lock( &lock); data_.appendData(in, 0, len); pthread_cond_signal( &cond ); pthread_mutex_unlock( &lock); } void BufferedInputStream::close(){ pthread_mutex_lock( &lock); read_ = false; pthread_cond_signal( &cond ); pthread_mutex_unlock( &lock); } /** * skips len number of bytes in the internal buffer. * @param len [description] */ void BufferedInputStream::skip(size_t len) { printf("skip count\n"); } /** * returns the current number of bytes read off the internal buffer. * @return [description] */ size_t BufferedInputStream::byteCount() const { return cur_; } } // namespace avronode
19.471264
69
0.687721
RUNDSP
b8199a65347074f735e13a1f8de5d2380ed2aa8a
17,782
tpp
C++
src/hypro/util/matlab/reachability/@MHyProCondition/MCondition.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
22
2016-10-05T12:19:01.000Z
2022-01-23T09:14:41.000Z
src/hypro/util/matlab/reachability/@MHyProCondition/MCondition.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
23
2017-05-08T15:02:39.000Z
2021-11-03T16:43:39.000Z
src/hypro/util/matlab/reachability/@MHyProCondition/MCondition.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
12
2017-06-07T23:51:09.000Z
2022-01-04T13:06:21.000Z
#include "MCondition.h" void MCondition::new_empty( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - new_empty: Expecting an output!" ); plhs[0] = convertPtr2Mat<hypro::Condition<double>>( new hypro::Condition<double>() ); } void MCondition::new_mat_vec( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - new_mat_vec: Expecting an output!" ); if ( nrhs < 4 ) mexErrMsgTxt( "MCondition - new_mat_vec: One or more input arguments are missing!" ); if ( nrhs > 4 ) mexWarnMsgTxt( "MCondition - new_mat_vec: One or more input arguments were ignored!" ); const mwSize *mat_dims, *vec_dims; int mat_rows, mat_cols, vec_len; mat_dims = mxGetDimensions( prhs[2] ); vec_dims = mxGetDimensions( prhs[3] ); mat_rows = mat_dims[0]; mat_cols = mat_dims[1]; vec_len = vec_dims[0]; hypro::matrix_t<double> matrix = ObjectHandle::mMatrix2Hypro( prhs[2], mat_rows, mat_cols ); hypro::vector_t<double> vector = ObjectHandle::mVector2Hypro( prhs[3], vec_len ); plhs[0] = convertPtr2Mat<hypro::Condition<double>>( new hypro::Condition<double>( matrix, vector ) ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "new_mat_vec input:\n" ); // mexPrintf( "matrix:\n" ); // for ( int i = 0; i < matrix.rows(); i++ ) { // for ( int j = 0; j < matrix.cols(); j++ ) { // mexPrintf( " %f", matrix( i, j ) ); // } // mexPrintf( "\n" ); // } // mexPrintf( "vector:\n" ); // for ( int j = 0; j < vector.rows(); j++ ) { // mexPrintf( " %f", vector( j ) ); // } // mexPrintf( "\n" ); // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::new_constr_set( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - new_constr_set: Expecting an output!" ); if ( nrhs < 3 ) mexErrMsgTxt( "MCondition - new_constr_set: One or more input arguments are missing!" ); if ( nrhs > 3 ) mexWarnMsgTxt( "MCondition - new_constr_set: One or more input arguments were ignored!" ); const hypro::ConstraintSet<double>* constraint = convertMat2Ptr<hypro::ConstraintSet<double>>( prhs[2] ); // hypro::Condition<double>* cond = new hypro::Condition<double>(*constraint); mexErrMsgTxt( "Not implemented!" ); // plhs[0] = convertPtr2Mat<hypro::Condition<double>>(cond); } void MCondition::copy( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - copy: Expecting an output!" ); if ( nrhs < 3 ) mexErrMsgTxt( "MCondition - copy: One or more input arguments are missing!" ); if ( nrhs > 3 ) mexWarnMsgTxt( "MCondition - copy: One or more input arguments were ignored!" ); hypro::Condition<double>* origin = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); plhs[0] = convertPtr2Mat<hypro::Condition<double>>( new hypro::Condition<double>( *origin ) ); } void MCondition::delete_condition( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nrhs < 3 ) mexErrMsgTxt( "MCondition - delete_condition: Expecting an output." ); if ( nrhs > 3 ) mexWarnMsgTxt( "MCondition - delete_condition: One or more arguments were ignored." ); destroyObject<hypro::Condition<double>>( prhs[2] ); } void MCondition::size( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - size: Expecting an output!" ); if ( nrhs < 3 ) mexErrMsgTxt( "MCondition - size: One or more input arguments are missing!" ); if ( nrhs > 3 ) mexWarnMsgTxt( "MCondition - size: One or more input arguments were ignored!" ); hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); std::size_t s = cond->size(); plhs[0] = mxCreateDoubleScalar( s ); } void MCondition::isempty( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - isempty: Expecting an output." ); if ( nrhs < 3 ) mexErrMsgTxt( "MCondition - isempty: One or more arguments are missing." ); if ( nrhs > 3 ) mexErrMsgTxt( "MCondition - isempty: One or more arguments were ignored." ); hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); const bool ans = cond->empty(); plhs[0] = mxCreateLogicalScalar( ans ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "is_empty input:\n" ); // if ( ans ) { // mexPrintf( "empty\n" ); // } else { // mexPrintf( "not empty\n" ); // } // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::getMatrix( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - getMatrix: One output expected!" ); if ( nrhs < 3 ) mexErrMsgTxt( "MCondition - getMatrix: One or more arguments are missing!" ); if ( nrhs > 3 ) mexErrMsgTxt( "MCondition - getMatrix: One or more arguments were ignored!" ); hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); hypro::matrix_t<double> mat = cond->getMatrix(); plhs[0] = mxCreateDoubleMatrix( mat.rows(), mat.cols(), mxREAL ); ObjectHandle::convert2Matlab( mat, plhs[0], mat.rows(), mat.cols() ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "getMatrix output:\n" ); // mexPrintf( "matrix:\n" ); // for ( int i = 0; i < mat.rows(); i++ ) { // for ( int j = 0; j < mat.cols(); j++ ) { // mexPrintf( " %f", mat( i, j ) ); // } // mexPrintf( "\n" ); // } // mexPrintf( "\n" ); // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::getVector( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - getVector: One output expected!" ); if ( nrhs < 3 ) mexErrMsgTxt( "MCondition - getVector: One or more arguments are missing!" ); if ( nrhs > 3 ) mexErrMsgTxt( "MCondition - getVector: One or more arguments were ignored!" ); hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); hypro::vector_t<double> vec = cond->getVector(); plhs[0] = mxCreateDoubleMatrix( vec.rows(), 1, mxREAL ); ObjectHandle::convert2Matlab( vec, plhs[0], vec.rows(), 1 ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "vector output:\n" ); // mexPrintf( "vector:\n" ); // for ( int j = 0; j < vec.cols(); j++ ) { // mexPrintf( " %f", vec( j ) ); // } // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::isAxisAligned( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - isAxisAligned: Expecting an output." ); if ( nrhs < 3 ) mexErrMsgTxt( "MCondition - isAxisAligned: One or more arguments are missing." ); if ( nrhs > 3 ) mexErrMsgTxt( "MCondition - isAxisAligned: One or more arguments were ignored." ); hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); const bool ans = cond->isAxisAligned(); plhs[0] = mxCreateLogicalScalar( ans ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "isAxisAligned output:\n" ); // if ( ans ) { // mexPrintf( "aligned\n" ); // } else { // mexPrintf( "not aligned\n" ); // } // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::isAxisAligned_at( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - isAxisAligned_at: Expecting an output." ); if ( nrhs < 4 ) mexErrMsgTxt( "MCondition - isAxisAligned_at: One or more arguments are missing." ); if ( nrhs > 4 ) mexErrMsgTxt( "MCondition - isAxisAligned_at: One or more arguments were ignored." ); hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); std::size_t s = mxGetScalar( prhs[3] ); const bool ans = cond->isAxisAligned( s ); plhs[0] = mxCreateLogicalScalar( ans ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "isAxisAligned input:\n" ); // mexPrintf( "at: %d\n", (double)s ); // if ( ans ) { // mexPrintf( "aligned\n" ); // } else { // mexPrintf( "not aligned\n" ); // } // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::setMatrix( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nrhs < 4 ) mexErrMsgTxt( "MCondition - setMatrix: One or more arguments are missing!" ); if ( nrhs > 4 ) mexErrMsgTxt( "MCondition - setMatrix: One or more arguments were ignored!" ); const mwSize* dims; int rows, cols; dims = mxGetDimensions( prhs[3] ); rows = dims[0]; cols = dims[1]; hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); hypro::matrix_t<double> mat = ObjectHandle::mMatrix2Hypro( prhs[3], rows, cols ); cond->setMatrix( mat ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "setMatrix input:\n" ); // mexPrintf( "matrix:\n" ); // for ( int i = 0; i < mat.rows(); i++ ) { // for ( int j = 0; j < mat.cols(); j++ ) { // mexPrintf( " %f", mat( i, j ) ); // } // mexPrintf( "\n" ); // } // mexPrintf( "\n" ); // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::setVector( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nrhs < 5 ) mexErrMsgTxt( "MCondition - setVector: One or more arguments are missing!" ); if ( nrhs > 5 ) mexErrMsgTxt( "MCondition - setVector: One or more arguments were ignored!" ); const mwSize* dims; int len; dims = mxGetDimensions( prhs[3] ); len = dims[0]; hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); hypro::vector_t<double> vec = ObjectHandle::mVector2Hypro( prhs[3], len ); std::size_t s = (std::size_t)mxGetScalar( prhs[4] ); cond->setVector( vec, s ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "vector input:\n" ); // mexPrintf( "vector:\n" ); // for ( int j = 0; j < vec.cols(); j++ ) { // mexPrintf( " %f", vec( j ) ); // } // mexPrintf( "at: %d\n", (double)s ); // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::constraints( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - constraints: Expecting an output." ); if ( nrhs < 3 ) mexErrMsgTxt( "MCondition - constraints: One or more arguments are missing!" ); if ( nrhs > 3 ) mexErrMsgTxt( "MCondition - constraints: One or more arguments were ignored!" ); hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); std::vector<hypro::ConstraintSet<double>> constrs = cond->constraints(); mxArray* m_out_constrs; int len = constrs.size(); const mwSize dims[2] = {1, (mwSize)len}; plhs[0] = m_out_constrs = mxCreateCellArray( 2, dims ); objArray2Matlab( constrs, m_out_constrs, len ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "constraints output:\n" ); // for ( int i = 0; i < constrs.size(); i++ ) { // hypro::matrix_t<double> mat = constrs[i].matrix(); // mexPrintf( "matrix %d:\n", i ); // for ( int i = 0; i < mat.rows(); i++ ) { // for ( int j = 0; j < mat.cols(); j++ ) { // mexPrintf( " %f", mat( i, j ) ); // } // mexPrintf( "\n" ); // } // mexPrintf( "vector %d:\n", i ); // hypro::vector_t<double> vec = constrs[i].vector(); // for ( int j = 0; j < vec.cols(); j++ ) { // mexPrintf( " %f", vec( j ) ); // } // mexPrintf( "\n" ); // } // mexPrintf( "\n" ); // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::hash( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - hash: Expecting an output!" ); if ( nrhs < 3 ) mexErrMsgTxt( "MCondition - hash: One or more input arguments are missing!" ); if ( nrhs > 3 ) mexWarnMsgTxt( "MCondition - hash: One or more input arguments were ignored!" ); hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); std::size_t s = cond->hash(); plhs[0] = mxCreateDoubleScalar( s ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "hash output:\n" ); // mexPrintf( "hash: %d\n", (double)s ); // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::getDotRepresentation( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - getDotRepresentation: Expecting an output!" ); if ( nrhs < 4 ) mexErrMsgTxt( "MCondition - getDotRepresentation: One or more input arguments are missing!" ); if ( nrhs > 4 ) mexWarnMsgTxt( "MCondition - getDotRepresentation: One or more input arguments were ignored!" ); hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); std::vector<std::string> strs = ObjectHandle::mStringVector2Hypro( prhs[3] ); std::string ans = cond->getDotRepresentation( strs ); plhs[0] = mxCreateString( ans.c_str() ); } void MCondition::decompose( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { // TODO: } void MCondition::equals( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs < 1 ) mexErrMsgTxt( "MCondition - ==: Expecting an output!" ); if ( nrhs < 4 ) mexErrMsgTxt( "MCondition - ==: One or more arguments are missing!" ); hypro::Condition<double>* cond_1 = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); hypro::Condition<double>* cond_2 = convertMat2Ptr<hypro::Condition<double>>( prhs[3] ); mxLogical ans = false; if ( *cond_1 == *cond_2 ) { ans = true; } plhs[0] = mxCreateLogicalScalar( ans ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "equals input:\n" ); // if ( ans ) { // mexPrintf( "equal\n" ); // } else { // mexPrintf( "not equal\n" ); // } // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::unequals( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs < 1 ) mexErrMsgTxt( "MCondition - !=: Expecting an output!" ); if ( nrhs < 4 ) mexErrMsgTxt( "MCondition - !=: One or more arguments are missing!" ); hypro::Condition<double>* cond_1 = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); hypro::Condition<double>* cond_2 = convertMat2Ptr<hypro::Condition<double>>( prhs[3] ); mxLogical ans = false; if ( *cond_1 != *cond_2 ) { ans = true; } plhs[0] = mxCreateLogicalScalar( ans ); // //+++++++++++++TESTING++++++++++++++++++++ // mexPrintf( "unequals input:\n" ); // if ( ans ) { // mexPrintf( "unequal\n" ); // } else { // mexPrintf( "not unequal\n" ); // } // //+++++++++++++TESTING++++++++++++++++++++ } void MCondition::outstream( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nrhs < 3 ) mexErrMsgTxt( "MCondition - ostream: One or more input arguments are missing." ); if ( nrhs > 3 ) mexWarnMsgTxt( "MCondition - ostream: One or more input arguments were ignored." ); hypro::Condition<double>* cond = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); hypro::matrix_t<double> mat = cond->getMatrix(); hypro::vector_t<double> vec = cond->getVector(); int rows = mat.rows(); int cols = mat.cols(); int len = vec.size(); mexPrintf( "Matrix: [" ); for ( int i = 0; i < rows; i++ ) { for ( int j = 0; j < cols; j++ ) { mexPrintf( "%f ", mat( i, j ) ); } mexPrintf( "\n" ); } mexPrintf( "]\n" ); mexPrintf( "Vector: [" ); for ( int i = 0; i < len; i++ ) { mexPrintf( "%f ", vec( i ) ); } mexPrintf( "]\n\n" ); } void MCondition::combine( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { if ( nlhs != 1 ) mexErrMsgTxt( "MCondition - getDotRepresentation: Expecting an output!" ); if ( nrhs < 8 ) mexErrMsgTxt( "MCondition - getDotRepresentation: One or more input arguments are missing!" ); if ( nrhs > 8 ) mexWarnMsgTxt( "MCondition - getDotRepresentation: One or more input arguments were ignored!" ); hypro::Condition<double>* obj = convertMat2Ptr<hypro::Condition<double>>( prhs[2] ); hypro::Condition<double>* lhs = convertMat2Ptr<hypro::Condition<double>>( prhs[3] ); hypro::Condition<double>* rhs = convertMat2Ptr<hypro::Condition<double>>( prhs[4] ); std::vector<std::string> haVar = ObjectHandle::mStringVector2Hypro( prhs[5] ); std::vector<std::string> lhsVar = ObjectHandle::mStringVector2Hypro( prhs[6] ); std::vector<std::string> rhsVar = ObjectHandle::mStringVector2Hypro( prhs[7] ); } void MCondition::process( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) { int cmd = mxGetScalar( prhs[1] ); if ( cmd == 2 ) { new_empty( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 4 ) { new_constr_set( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 5 ) { new_mat_vec( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 3 ) { copy( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 1 ) { delete_condition( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 6 ) { size( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 7 ) { isempty( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 8 ) { getMatrix( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 9 ) { getVector( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 10 ) { isAxisAligned( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 11 ) { isAxisAligned_at( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 12 ) { setMatrix( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 13 ) { setVector( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 14 ) { constraints( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 15 ) { hash( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 16 ) { getDotRepresentation( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 17 ) { decompose( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 18 ) { equals( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 19 ) { unequals( nlhs, plhs, nrhs, prhs ); return; } if ( cmd == 20 ) { combine( nlhs, plhs, nrhs, prhs ); return; } mexErrMsgTxt( "MCondition - Command not recognized." ); }
37.834043
113
0.606119
hypro
b81e15d2222e9bb1a5f039038038f92543cd97b8
1,025
cpp
C++
QSynthesis/Frontend/Tabs/Tuning/Graphics/GraphicsLifters/GraphicsLifter_Assist.cpp
SineStriker/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
3
2021-12-08T05:30:52.000Z
2021-12-18T10:46:49.000Z
QSynthesis/Frontend/Tabs/Tuning/Graphics/GraphicsLifters/GraphicsLifter_Assist.cpp
QSynthesis/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
null
null
null
QSynthesis/Frontend/Tabs/Tuning/Graphics/GraphicsLifters/GraphicsLifter_Assist.cpp
QSynthesis/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
null
null
null
#include "../../Params/Areas/LiftersArea.h" #include "../../TuningGroup.h" #include "../GraphicsLifter.h" using namespace Qs::Panels; double GraphicsLifter::convertRatioToProp(Props prop, double ratio) { double result = 0; switch (prop) { case Intensity: result = ratio * 200; break; case Modulation: result = (ratio - 0.5) / 0.5 * 200; break; case Velocity: result = (ratio >= 0.5) ? ((ratio - 0.5) / 0.5 * 100 + 100) : (ratio / 0.5 * 200 - 100); break; default: break; } return result; } double GraphicsLifter::convertPropToRatio(Props prop, double props) { double result = 0; switch (prop) { case Intensity: result = props / 200; break; case Modulation: result = props / 200 * 0.5 + 0.5; break; case Velocity: result = (props >= 100) ? ((props - 100) / 100 * 0.5 + 0.5) : ((props + 100) / 200 * 0.5); break; default: break; } return result; }
24.404762
98
0.54439
SineStriker
b81facccf3b95fd9fb848c9837b321efec2d60a0
8,956
cpp
C++
src/fonted/fonted.cpp
Zax37/hge
2bacee126c08c4d12f0d9d3c58ac5c2033a6e6e2
[ "Zlib" ]
null
null
null
src/fonted/fonted.cpp
Zax37/hge
2bacee126c08c4d12f0d9d3c58ac5c2033a6e6e2
[ "Zlib" ]
null
null
null
src/fonted/fonted.cpp
Zax37/hge
2bacee126c08c4d12f0d9d3c58ac5c2033a6e6e2
[ "Zlib" ]
null
null
null
/* ** Haaf's Game Engine 1.8 ** Copyright (C) 2003, Relish Games ** hge.relishgames.com ** ** Bitmap Font Builder */ #include "fonted.h" #include <cstdio> #include "fontlist.h" #include "hgeguictrls.h" #include "hgeguirange.h" HGE* hge = nullptr; hgeFont* fnt; hgeGUI* gui; HTEXTURE tex_gui; HTEXTURE tex_font = 0; hgeSprite *spr_font = nullptr; hgeSprite *spr_black; hgeSprite *spr_left_pane1; hgeSprite *spr_left_pane2; hgeSprite* spr_cursor; CFontList* font_list = nullptr; FEditorState state; float psx = 484; float psy = 300; float fw2; float fh2; void init_editor(); void done_editor(); void create_gui(); HTEXTURE generate_font(); bool frame_func() { const auto dt = hge->Timer_GetDelta(); // Update fw2 = spr_font->GetWidth() / 2; fh2 = spr_font->GetHeight() / 2; hge->Input_GetMousePos(&state.mx_, &state.my_); if (hge->Input_GetKeyState(HGEK_LBUTTON)) { if (state.drag_) { psx = state.drag_old_x_ + (state.mx_ - state.drag_x_offset_); psy = state.drag_old_y_ + (state.my_ - state.drag_y_offset_); } } else { state.drag_ = false; } if (handle_keys(hge->Input_GetKey())) { return true; } return do_commands(gui->Update(dt)); } bool render_func() { int i; char szTemp[128]; // Render hge->Gfx_BeginScene(); hge->Gfx_Clear(0xFF404040); spr_black->SetTextureRect(0, 0, spr_font->GetWidth(), spr_font->GetHeight()); spr_black->Render(psx - fw2, psy - fh2); spr_font->Render(psx - fw2, psy - fh2); float u0, v0, u1, v1; if (state.b_box_) for (i = state.sr_.First; i <= state.sr_.Last; i++) { u0 = static_cast<float>(vChars[i].x) + psx - fw2; u1 = u0 + vChars[i].w; v0 = static_cast<float>(vChars[i].y) + psy - fh2; v1 = v0 + vChars[i].h; hge->Gfx_RenderLine(u0 + 0.5f, v0 + 0.5f, u1, v0 + 0.5f, 0xFF95883F); hge->Gfx_RenderLine(u1, v0 + 0.5f, u1, v1, 0xFF95883F); hge->Gfx_RenderLine(u1, v1, u0 + 0.5f, v1, 0xFF95883F); hge->Gfx_RenderLine(u0 + 0.5f, v1, u0 + 0.5f, v0 + 0.5f, 0xFF95883F); } sprintf(szTemp, "Texture size: %dx%d", static_cast<int>(spr_font->GetWidth()), static_cast<int>(spr_font->GetHeight())); fnt->SetColor(0xFF808080); fnt->Render(176, 580, HGETEXT_LEFT, szTemp); for (i = state.sr_.First; i <= state.sr_.Last; i++) { u0 = static_cast<float>(vChars[i].x) + psx - fw2; u1 = u0 + vChars[i].w; v0 = static_cast<float>(vChars[i].y) + psy - fh2; v1 = v0 + vChars[i].h; if (state.mx_ >= u0 && state.mx_ < u1 && state.my_ >= v0 && state.my_ < v1) { hge->Gfx_RenderLine(u0 + 0.5f, v0 + 0.5f, u1, v0 + 0.5f, 0xFFFF0000); hge->Gfx_RenderLine(u1, v0 + 0.5f, u1, v1, 0xFFFF0000); hge->Gfx_RenderLine(u1, v1, u0 + 0.5f, v1, 0xFFFF0000); hge->Gfx_RenderLine(u0 + 0.5f, v1, u0 + 0.5f, v0 + 0.5f, 0xFFFF0000); if (i >= 32 && i <= 126) sprintf(szTemp, "\"%c\" = x:%d y:%d w:%d h:%d a:%d c:%d", static_cast<char>(i), vChars[i].x, vChars[i].y, vChars[i].w, vChars[i].h, vChars[i].a, vChars[i].c); else sprintf(szTemp, "0x%02X = x:%d y:%d w:%d h:%d a:%d c:%d", i, vChars[i].x, vChars[i].y, vChars[i].w, vChars[i].h, vChars[i].a, vChars[i].c); fnt->Render(790, 580, HGETEXT_RIGHT, szTemp); } } spr_left_pane1->Render(0, 0); spr_left_pane2->Render(0, 512); gui->Render(); if (state.help_) { fnt->SetColor(0xFFFFFFFF); fnt->Render(189, 18, HGETEXT_LEFT, "Left mouse button - drag font texture\n" "Typefaces listbox - use Up/Down arrows, Mouse wheel\n" "Characters range - click and drag\n" "Esc - Exit\n\n" "A saved font includes two files: .FNT and .PNG\n" "You could apply any additional effects to the saved PNG in your graphics editor\n" "Edit FONTED.INI file to run in fullscreen"); } if (hge->Input_IsMouseOver()) { spr_cursor->Render(state.mx_, state.my_); } hge->Gfx_EndScene(); return false; } int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { hge = hgeCreate(HGE_VERSION); hge->System_SetState(HGE_INIFILE, "fonted.ini"); hge->System_SetState(HGE_LOGFILE, "fonted.log"); hge->System_SetState(HGE_FRAMEFUNC, frame_func); hge->System_SetState(HGE_RENDERFUNC, render_func); hge->System_SetState(HGE_TITLE, "HGE Bitmap Font Builder"); hge->System_SetState(HGE_SCREENWIDTH, 800); hge->System_SetState(HGE_SCREENHEIGHT, 600); hge->System_SetState(HGE_SCREENBPP, 32); hge->System_SetState(HGE_USESOUND, false); hge->System_SetState(HGE_WINDOWED, hge->Ini_GetInt("HGE", "FullScreen", 0) == 0); if (hge->System_Initiate()) { init_editor(); hge->System_Start(); done_editor(); } else { MessageBox(nullptr, hge->System_GetErrorMessage(), "Error", MB_OK | MB_ICONERROR | MB_TASKMODAL); } hge->System_Shutdown(); hge->Release(); return 0; } void init_editor() { hge->Resource_AttachPack("fonted.paq"); fnt = new hgeFont("font3.fnt"); state.help_ = false; state.b_box_ = false; state.drag_ = false; font_list = new CFontList(); font_list->BuildList(); state.font_family_ = font_list->GetFontByIdx(0); state.size_ = 20; state.pad_top_ = hge->Ini_GetInt("HGE", "PaddingTop", 0); state.pad_btm_ = hge->Ini_GetInt("HGE", "PaddingBottom", 0); state.pad_lft_ = hge->Ini_GetInt("HGE", "PaddingLeft", 0); state.pad_rgt_ = hge->Ini_GetInt("HGE", "PaddingRight", 0); state.bold_ = false; state.italic_ = false; state.antialias_ = true; state.sr_.First = 32; state.sr_.Last = 126; cmd_generate_font(); tex_gui = hge->Texture_Load("fgui.png"); spr_cursor = new hgeSprite(tex_gui, 487, 181, 19, 26); spr_black = new hgeSprite(0, 0, 0, 100, 100); spr_black->SetColor(0xFF000000); spr_left_pane1 = new hgeSprite(tex_gui, 0, 0, 168, 512); spr_left_pane2 = new hgeSprite(tex_gui, 336, 0, 168, 88); gui = new hgeGUI(); create_gui(); } void done_editor() { delete gui; delete spr_left_pane1; delete spr_left_pane2; delete spr_cursor; delete fnt; delete spr_font; delete spr_black; delete font_list; hge->Texture_Free(tex_font); hge->Texture_Free(tex_gui); hge->Resource_RemoveAllPacks(); } void create_gui() { gui->AddCtrl(new hgeGUIButton(CMD_SAVE, 9, 485, 47, 17, tex_gui, 336, 338)); gui->AddCtrl(new hgeGUIButton(CMD_EXIT, 111, 485, 47, 17, tex_gui, 336, 338)); hgeGUIButton* button = new hgeGUIButton(CMD_HELP, 60, 485, 47, 17, tex_gui, 336, 338); button->SetMode(true); gui->AddCtrl(button); button = new hgeGUIButton(CMD_BOLD, 9, 180, 8, 8, tex_gui, 368, 176); button->SetMode(true); button->SetState(state.bold_); gui->AddCtrl(button); button = new hgeGUIButton(CMD_ITALIC, 52, 180, 8, 8, tex_gui, 368, 176); button->SetMode(true); button->SetState(state.italic_); gui->AddCtrl(button); button = new hgeGUIButton(CMD_ANTIALIAS, 97, 180, 8, 8, tex_gui, 368, 176); button->SetMode(true); button->SetState(state.antialias_); gui->AddCtrl(button); button = new hgeGUIButton(CMD_BOUNDINGBOX, 9, 461, 8, 8, tex_gui, 368, 176); button->SetMode(true); button->SetState(state.b_box_); gui->AddCtrl(button); hgeGUIListbox* listbox = new hgeGUIListbox( CMD_FAMILYLIST, 10, 44, 139, 128, fnt, 0xFF7697A4, 0xFFBBCBD2, 0x40D4C25A); for (int i = 0; i < font_list->GetNumFonts(); i++) { listbox->AddItem(font_list->GetFontByIdx(i)); } gui->AddCtrl(listbox); hgeGUISlider* slider = new hgeGUISlider(CMD_FAMILYSLIDER, 152, 44, 6, 128, tex_gui, 417, 177, 6, 6, true); slider->SetMode(0, static_cast<float>(listbox->GetNumItems()) - listbox->GetNumRows(), HGESLIDER_BAR); slider->SetValue(0); gui->AddCtrl(slider); auto range = new hgeGUIRange(CMD_CHARRANGE, 14, 266, 144, 144, 16, 16, 0x4D99FCD2); range->SetRange(state.sr_.First, state.sr_.Last); gui->AddCtrl(range); slider = new hgeGUISlider(CMD_FONTSIZE, 10, 219, 148, 6, tex_gui, 417, 177, 6, 6, false); slider->SetMode(5, 80, HGESLIDER_BAR); slider->SetValue(static_cast<float>(state.size_)); gui->AddCtrl(slider); auto text = new hgeGUIText(CMD_TFONTSIZE, 116, 205, 28, 12, fnt); text->SetMode(HGETEXT_RIGHT); text->printf("%d", state.size_); gui->AddCtrl(text); }
30.256757
103
0.600603
Zax37
b82296653233f473b3b5d77c844dd2ecf9e5c80d
1,505
cpp
C++
src/basic_algorithm.cpp
mnikic777/myers-agrep
3db19846d2d582689629c9e96232332473ac823f
[ "MIT" ]
1
2021-03-04T01:05:13.000Z
2021-03-04T01:05:13.000Z
src/basic_algorithm.cpp
mnikic777/myers-agrep
3db19846d2d582689629c9e96232332473ac823f
[ "MIT" ]
1
2020-05-14T15:10:18.000Z
2020-05-14T15:57:02.000Z
src/basic_algorithm.cpp
mnikic777/myers-agrep
3db19846d2d582689629c9e96232332473ac823f
[ "MIT" ]
null
null
null
// // Created by Martin Gluhak. // /** * Basic version of Myers agrep which works when pattern length is <= size of machine word. */ #include <cstdio> #include <unistd.h> #include "basic_algorithm.hpp" #include "globals.hpp" using namespace std; uint64_t Peqb[SIGMA]; void basic_precompute(const char *pattern, int m) { uint64_t bitPos = 1; for (int i = 0; pattern[i] != '\0'; ++i) { Peqb[pattern[i]] |= bitPos; bitPos = bitPos << 1; } } int basic_search(int fd, int k, int m) { int score = m; uint64_t Mbit = ONE << (m - 1); uint64_t Pv = (uint64_t) -1; uint64_t Mv = 0; uint64_t Eq; uint64_t Xv, Xh; uint64_t Ph, Mh; ssize_t bytes_num; for (int buff = 0; (bytes_num = read(fd, buffer, MAX_BUF)) > 0; buff += bytes_num) { for (int i = 0; i < bytes_num; ++i) { Eq = Peqb[buffer[i]]; Xv = Eq | Mv; Xh = (((Eq & Pv) + Pv) ^ Pv) | Eq; Ph = Mv | (~(Xh | Pv)); Mh = Pv & Xh; if (Ph & Mbit) { score += 1; } if (Mh & Mbit) { score -= 1; } Ph <<= 1; Mh <<= 1; Pv = Mh | (~(Xv | Ph)); Mv = Ph & Xv; if (score <= k) { if (score < k) { k = score; matches.clear(); } matches.push_back(buff + i); } } } return k; }
21.5
91
0.437874
mnikic777
b826e3af5b0b19ba11e6a020226140a493788c8c
18,806
cpp
C++
Mythology_Parade_Engine/Core/FoWManager.cpp
BernatCasanas/Mythology-Parade
e80ed76f0a0b17b7d1890e95563f1b0098acbe84
[ "MIT" ]
null
null
null
Mythology_Parade_Engine/Core/FoWManager.cpp
BernatCasanas/Mythology-Parade
e80ed76f0a0b17b7d1890e95563f1b0098acbe84
[ "MIT" ]
null
null
null
Mythology_Parade_Engine/Core/FoWManager.cpp
BernatCasanas/Mythology-Parade
e80ed76f0a0b17b7d1890e95563f1b0098acbe84
[ "MIT" ]
null
null
null
#include "FoWManager.h" #include "j1App.h" #include "j1Textures.h" #include "j1Map.h" #include "j1Render.h" #include "j1Input.h" FoWManager::FoWManager() { height = 0; width = 0; } FoWManager::~FoWManager() { CleanUp(); } bool FoWManager::Awake(pugi::xml_node&) { bool ret = true; active = false; return ret; } bool FoWManager::Start() { bool ret = true; smoothFoWtexture = App->tex->Load("maps/fogTiles.png"); debugFoWtexture = App->tex->Load("maps/fogTilesDebug.png"); if (smoothFoWtexture == nullptr || debugFoWtexture == nullptr); ret = false; //---------Initialize the map being used to translate bits to texture ID---------// //Straight-forward cases bitToTextureTable.insert(std::pair<unsigned short, int>(fow_ALL, 0)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_NNN, 1)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_WWW, 2)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_EEE, 3)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_SSS, 4)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_CNW, 5)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_CSE, 6)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_CNE, 7)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_CSW, 8)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_JNE, 9)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_JSW, 10)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_JNW, 11)); bitToTextureTable.insert(std::pair<unsigned short, int>(fow_JSE, 12)); //more complicated cases (combinations) //diagonals bitToTextureTable.insert(std::pair<unsigned short, int>(20, 9)); bitToTextureTable.insert(std::pair<unsigned short, int>(80, 10)); bitToTextureTable.insert(std::pair<unsigned short, int>(17, 11)); bitToTextureTable.insert(std::pair<unsigned short, int>(272, 12)); bitToTextureTable.insert(std::pair<unsigned short, int>(273, 13)); bitToTextureTable.insert(std::pair<unsigned short, int>(84, 14)); //lines bitToTextureTable.insert(std::pair<unsigned short, int>(23, 1)); bitToTextureTable.insert(std::pair<unsigned short, int>(308, 3)); bitToTextureTable.insert(std::pair<unsigned short, int>(89, 2)); bitToTextureTable.insert(std::pair<unsigned short, int>(464, 4)); //joints bitToTextureTable.insert(std::pair<unsigned short, int>(6, 9)); bitToTextureTable.insert(std::pair<unsigned short, int>(36, 9)); bitToTextureTable.insert(std::pair<unsigned short, int>(72, 10)); bitToTextureTable.insert(std::pair<unsigned short, int>(192, 10)); bitToTextureTable.insert(std::pair<unsigned short, int>(3, 11)); bitToTextureTable.insert(std::pair<unsigned short, int>(9, 11)); bitToTextureTable.insert(std::pair<unsigned short, int>(384, 12)); bitToTextureTable.insert(std::pair<unsigned short, int>(288, 12)); //corners bitToTextureTable.insert(std::pair<unsigned short, int>(4, 9)); bitToTextureTable.insert(std::pair<unsigned short, int>(64, 10)); bitToTextureTable.insert(std::pair<unsigned short, int>(1, 11)); bitToTextureTable.insert(std::pair<unsigned short, int>(256, 12)); //------------------------end of map initialization------------------------// return ret; } bool FoWManager::PreUpdate() { bool ret = true; //deletes all the entities that request to do so //for (int i = 0; i < fowEntities.size(); i++) //{ // if (fowEntities[i]->deleteEntity) // { // delete fowEntities[i]; // fowEntities[i] = nullptr; // fowEntities.erase(fowEntities.begin() + i); // i--; // } //} //debug input handling //if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN) //{ // ResetFoWMap(); // MapNeedsUpdate(); //} if (App->scene->godMode && App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN) { debugMode = !debugMode; MapNeedsUpdate(); } return ret; } bool FoWManager::Update(float dt) { bool ret = true; //We update the fowMap only when its needed if (foWMapNeedsRefresh) { UpdateFoWMap(); foWMapNeedsRefresh = false; } return ret; } bool FoWManager::PostUpdate() { bool ret = true; DrawFoWMap(); return ret; } bool FoWManager::CleanUp() { bool ret = true; DeleteFoWMap(); int i = 0; //while (fowEntities.size() > 0) //{ // if (fowEntities[i] != nullptr) // { // delete fowEntities[i]; // fowEntities[i] = nullptr; // fowEntities.erase(fowEntities.begin() + i); // i--; // } // i++; //} //fowEntities.clear(); if (debugFoWtexture != nullptr) { App->tex->UnLoad(debugFoWtexture); debugFoWtexture = nullptr; } if (smoothFoWtexture != nullptr) { App->tex->UnLoad(smoothFoWtexture); smoothFoWtexture = nullptr; } return ret; } void FoWManager::ResetFoWMap() { if (fowMap != nullptr) { memset(fowMap, NULL, width * height); for (int i = 0; i < width * height; i++) { fowMap[i].tileShroudBits = fow_ALL; fowMap[i].tileFogBits = fow_ALL; } } } FoWDataStruct* FoWManager::GetFoWTileState(iPoint mapPos)const { FoWDataStruct* ret = nullptr; if (CheckFoWTileBoundaries(mapPos) && fowMap != nullptr) { ret = &fowMap[(mapPos.y * width) + mapPos.x]; } return ret; } bool FoWManager::CheckFoWTileBoundaries(iPoint mapPos)const { bool ret = false; if (mapPos.x >= 0 && mapPos.x < width && mapPos.y >= 0 && mapPos.y < height) ret = true; return ret; } void FoWManager::CreateFoWMap(uint w, uint h) { width = w; height = h; //TODO 1: Complete this function to create a FoWMap. EASY! //If a map has already been created you will need to delete it first, hint: there's a function for that :) //Note that the map will be a 1 dimensional array and you might need the 2 variables above to set it up. The map should be stored in the variable "fowMap" //Don't forget to reset it once is creeated, hint: there's another function for that :) DeleteFoWMap(); fowMap = new FoWDataStruct[width * height]; ResetFoWMap(); MapNeedsUpdate(); } void FoWManager::DeleteFoWMap() { if (fowMap != nullptr) { RELEASE_ARRAY(fowMap); fowMap = nullptr; } } void FoWManager::UpdateFoWMap() { if (fowMap != nullptr) { for (int i = 0; i < width * height; i++) { fowMap[i].tileFogBits = fow_ALL; } //for (int i = 0; i < fowEntities.size(); i++) //{ // fowEntities[i]->Update(); //} if (!debugMode) { //for (int i = 0; i < fowEntities.size(); i++) //{ // if (CheckTileVisibility(fowEntities[i]->GetPos())) // { // fowEntities[i]->isVisible = true; // } // else fowEntities[i]->isVisible = false; //} } else { //for (int i = 0; i < fowEntities.size(); i++) //{ // fowEntities[i]->isVisible = true; //} } } } void FoWManager::DrawFoWMap() { j1PerfTimer timer; double oldT = timer.ReadMs(); iPoint A = App->map->WorldToMap(-App->render->camera.x, -App->render->camera.y); iPoint B = App->map->WorldToMap(-App->render->camera.x + App->render->camera.w, -App->render->camera.y + App->render->camera.h); //Approach 2.0 for (int a = A.x + A.y - 2; a <= B.x + B.y - 5 /* or 2*/; a++) { for (int b = A.x - A.y - 2; b <= B.x - B.y + 2; b++) { if ((b & 1) != (a & 1)) continue; int x = (a + b) / 2; int y = (a - b) / 2; FoWDataStruct* tileInfo = GetFoWTileState({ x, y }); int fogId = -1; int shroudId = -1; if (tileInfo != nullptr) { //This if's make the code go 2 times slower if (bitToTextureTable.find(tileInfo->tileFogBits) != bitToTextureTable.end()) { fogId = bitToTextureTable[tileInfo->tileFogBits]; } if (bitToTextureTable.find(tileInfo->tileShroudBits) != bitToTextureTable.end()) { shroudId = bitToTextureTable[tileInfo->tileShroudBits]; } } iPoint worldDrawPos; App->map->MapToWorld(x, y, worldDrawPos.x, worldDrawPos.y); SDL_Texture* displayFogTexture = nullptr; if (debugMode) { displayFogTexture = debugFoWtexture; } else displayFogTexture = smoothFoWtexture; //draw fog if (fogId != -1) { SDL_SetTextureAlphaMod(displayFogTexture, 128);//set the alpha of the texture to half to reproduce fog SDL_Rect r = { fogId * 64,0,64,64 }; //this rect crops the desired fog Id texture from the fogTiles spritesheet App->render->Blit(displayFogTexture, worldDrawPos.x, worldDrawPos.y - 16, &r); //App->render->Blit(displayFogTexture, worldDrawPos.x, worldDrawPos.y - 15, {64, 60}, &r, 1.0f); } if (shroudId != -1) { SDL_SetTextureAlphaMod(displayFogTexture, 255);//set the alpha to white again SDL_Rect r = { shroudId * 64,0,64,64 }; //this rect crops the desired fog Id texture from the fogTiles spritesheet App->render->Blit(displayFogTexture, worldDrawPos.x, worldDrawPos.y - 16, &r); //App->render->Blit(displayFogTexture, worldDrawPos.x, worldDrawPos.y - 15, { 64, 60 }, &r, 1.0f); } } } //LOG("Time: %f", timer.ReadMs() - oldT); } //TODO 2: Complete this function: given a position and a flag, create a new entity and return a pointer to it (or nullptr if something has gone wrong) //Note that the FoWManager needs to know about the entity we are creating, try to find where the FoWManager module stores all the FoWEntities and add it there //FoWEntity* FoWManager::CreateFoWEntity(iPoint pos, bool providesVisibility) //{ // FoWEntity* entity = nullptr; // // entity = new FoWEntity(pos, providesVisibility); // // if (entity != nullptr) // { // fowEntities.push_back(entity); // } // // return entity; //} //TODO 5: Complete the following function: it shoud return the tile visibility (true if visible, otherwise false) //This function will be used to check if we need to draw a certain entity bool FoWManager::CheckTileVisibility(iPoint mapPos)const { bool ret = false; //First check if the entity is inside the map //& get the tile fog information,its state, to check if is visible. //Note that the function that you need does both things for you, it is recommended to check and understand what the needed function does FoWDataStruct* tileState = GetFoWTileState(mapPos); if (tileState != nullptr) { //Entity will only be visible in visible areas (no fog nor shroud) //Think about what happens with the smooth borders, are the considered visble or fogged? //Also, do you need to check both the fog and shroud states? if (tileState->tileFogBits != fow_ALL) ret = true; } return ret; } bool FoWManager::CheckTileVisibilityWithoutCountingShroud(iPoint mapPos)const { bool ret = false; //First check if the entity is inside the map //& get the tile fog information,its state, to check if is visible. //Note that the function that you need does both things for you, it is recommended to check and understand what the needed function does FoWDataStruct* tileState = GetFoWTileState(mapPos); if (tileState != nullptr) { //Entity will only be visible in visible areas (no fog nor shroud) //Think about what happens with the smooth borders, are the considered visble or fogged? //Also, do you need to check both the fog and shroud states? if (tileState->tileShroudBits != fow_ALL) ret = true; } return ret; } void FoWManager::MapNeedsUpdate() { if (foWMapNeedsRefresh == false) foWMapNeedsRefresh = true; } void FoWManager::GetTilesInsideRadius(int fowRadius, fPoint position, iPoint offSet, std::vector<iPoint>& ret)const { int length = (fowRadius * 2) + 1; //Adding + (collisionRect.w / 2) maybe bad, think about it iPoint startingPos = App->map->WorldToMap(static_cast<int>(position.x) + offSet.x, static_cast<int>(position.y) + offSet.y) - fowRadius; iPoint finishingPos = startingPos + length; //Creates a vector with all the tiles inside a bounding box delimited by the radius for (int i = startingPos.y; i < finishingPos.y; i++) { for (int j = startingPos.x; j < finishingPos.x; j++) { ret.push_back({ j,i }); } } } //TODO 3: Comprehend and complete this function: (this is the function that does the magic for us) void FoWManager::ApplyMaskToTiles(int fowRadius, std::vector<iPoint>& tilesAffected) { unsigned short* precMask = &GetMaskFromRadius(fowRadius)[0]; if (precMask != nullptr) { for (int i = 0; i < tilesAffected.size(); i++) { FoWDataStruct* tileValue = GetFoWTileState(tilesAffected[i]); if (tileValue != nullptr) { tileValue->tileShroudBits &= *precMask; tileValue->tileFogBits &= *precMask; } precMask++; } } } unsigned short* FoWManager::GetMaskFromRadius(int radius) { unsigned short* ret = nullptr; if (maskMap.count(radius) > 0) //if the key is found { ret = maskMap.at(radius).mask; } return ret; } void FoWManager::RequestMaskGeneration(int radius) { if (maskMap.count(radius) > 0) { maskMap.at(radius).numberOfUsers += 1; } else { MaskData data; data.numberOfUsers = 1; data.mask = GenerateCircleJoints(radius, GenerateCircleBorders(radius, GenerateCircle(radius))); maskMap.insert(std::pair<uint, MaskData>(radius, data)); //Fill Corners //Fill joints } } void FoWManager::RequestMaskDeletion(int radius) { if (radius > 0) { if (maskMap.count(radius) > 0) { if (maskMap.at(radius).numberOfUsers > 1) { maskMap.at(radius).numberOfUsers -= 1; } else { //delete mask RELEASE_ARRAY(maskMap.at(radius).mask); maskMap.at(radius).mask = nullptr; maskMap.erase(radius); } } } } unsigned short* FoWManager::GenerateCircle(int radius) { unsigned short* circle = nullptr; int diameter = (radius * 2) + 1; iPoint center = { radius,radius }; circle = new unsigned short[diameter * diameter]; for (int y = 0; y < diameter; y++) { for (int x = 0; x < diameter; x++) { if (InsideCircle(center, { x,y }, radius) == true) { circle[(y * diameter) + x] = fow_NON; } else { circle[(y * diameter) + x] = fow_ALL; } } } return circle; } unsigned short* FoWManager::GenerateCircleBorders(int radius, unsigned short* mask) { int diameter = (radius * 2) + 1; for (int y = 0; y < diameter; y++) { for (int x = 0; x < diameter; x++) { if (mask[(y * diameter) + x] == fow_NON) { //do tile check and change unsigned short aux = CheckCornersFromNeighbours({ x,y }, diameter, mask); switch (aux) { case fow_neighbour_W: mask[(y * diameter) + x] = fow_WWW; break; case fow_neighbour_E: mask[(y * diameter) + x] = fow_EEE; break; case fow_neighbour_N: mask[(y * diameter) + x] = fow_NNN; break; case fow_neighbour_S: mask[(y * diameter) + x] = fow_SSS; break; case fow_neighbour_CNE: mask[(y * diameter) + x] = fow_CNE; break; case fow_neighbour_CNW: mask[(y * diameter) + x] = fow_CNW; break; case fow_neighbour_CSE: mask[(y * diameter) + x] = fow_CSE; break; case fow_neighbour_CSW: mask[(y * diameter) + x] = fow_CSW; break; case fow_neighbour_HE: mask[(y * diameter) + x] = fow_ALL; mask[(y * diameter) + x + 1] = fow_WWW; break; case fow_neighbour_HW: mask[(y * diameter) + x] = fow_ALL; mask[(y * diameter) + x - 1] = fow_EEE; break; case fow_neighbour_HN: mask[(y * diameter) + x] = fow_ALL; mask[((y - 1) * diameter) + x] = fow_SSS; break; case fow_neighbour_HS: mask[(y * diameter) + x] = fow_ALL; mask[((y + 1) * diameter) + x + 1] = fow_NNN; break; } } } } return mask; } unsigned short* FoWManager::GenerateCircleJoints(int radius, unsigned short* mask) { int diameter = (radius * 2) + 1; for (int y = 0; y < diameter; y++) { for (int x = 0; x < diameter; x++) { if (mask[(y * diameter) + x] == fow_NON) { //do tile check and change unsigned short aux = CheckJointsFromNeighbours({ x,y }, diameter, mask); switch (aux) { case fow_neighbour_CNE: mask[(y * diameter) + x] = fow_JNE; break; case fow_neighbour_CNW: mask[(y * diameter) + x] = fow_JNW; break; case fow_neighbour_CSE: mask[(y * diameter) + x] = fow_JSE; break; case fow_neighbour_CSW: mask[(y * diameter) + x] = fow_JSW; break; } } } } return mask; } bool FoWManager::InsideCircle(iPoint center, iPoint tile, float radius) { float distance_squared = center.DistanceNoSqrt(tile); return distance_squared < (radius + 0.5f) * (radius + 0.5f); } unsigned short FoWManager::CheckCornersFromNeighbours(iPoint pos, int diameter, unsigned short* mask) { unsigned short ret = 0; //check West tile if (pos.x == 0) { ret += fow_neighbour_W; } else { if (mask[(pos.y * diameter) + pos.x - 1] == fow_ALL) { ret += fow_neighbour_W; } } //check East tile if (pos.x == diameter - 1) { ret += fow_neighbour_E; } else { if (mask[(pos.y * diameter) + pos.x + 1] == fow_ALL) { ret += fow_neighbour_E; } } //check North tile if (pos.y == 0) { ret += fow_neighbour_N; } else { if (mask[((pos.y - 1) * diameter) + pos.x] == fow_ALL) { ret += fow_neighbour_N; } } //check South tile if (pos.y == diameter - 1) { ret += fow_neighbour_S; } else { if (mask[((pos.y + 1) * diameter) + pos.x] == fow_ALL) { ret += fow_neighbour_S; } } return ret; } unsigned short FoWManager::CheckJointsFromNeighbours(iPoint pos, int diameter, unsigned short* mask) { unsigned short ret = 0; int leftTileId = (pos.y * diameter) + pos.x - 1; int rightTileId = (pos.y * diameter) + pos.x + 1; int upperTileId = ((pos.y - 1) * diameter) + pos.x; int bottomTileId = ((pos.y + 1) * diameter) + pos.x; if (mask[leftTileId] == fow_CNW || mask[leftTileId] == fow_CNE || mask[leftTileId] == fow_CSE || mask[leftTileId] == fow_CSW || mask[leftTileId] == fow_WWW || mask[leftTileId] == fow_SSS || mask[leftTileId] == fow_NNN || mask[leftTileId] == fow_EEE) { ret += fow_neighbour_W; } //check East tile if (mask[rightTileId] == fow_CNW || mask[rightTileId] == fow_CNE || mask[rightTileId] == fow_CSE || mask[rightTileId] == fow_CSW || mask[rightTileId] == fow_WWW || mask[rightTileId] == fow_SSS || mask[rightTileId] == fow_NNN || mask[rightTileId] == fow_EEE) { ret += fow_neighbour_E; } //check North tile if (mask[upperTileId] == fow_CNW || mask[upperTileId] == fow_CNE || mask[upperTileId] == fow_CSE || mask[upperTileId] == fow_CSW || mask[upperTileId] == fow_WWW || mask[upperTileId] == fow_SSS || mask[upperTileId] == fow_NNN || mask[upperTileId] == fow_EEE) { ret += fow_neighbour_N; } //check South tile if (mask[bottomTileId] == fow_CNW || mask[bottomTileId] == fow_CNE || mask[bottomTileId] == fow_CSE || mask[bottomTileId] == fow_CSW || mask[bottomTileId] == fow_WWW || mask[bottomTileId] == fow_SSS || mask[bottomTileId] == fow_NNN || mask[bottomTileId] == fow_EEE) { ret += fow_neighbour_S; } return ret; }
24.079385
158
0.656546
BernatCasanas
b8277a6cd9e39877bfd6aebad2f85c14e9c46d01
2,682
cpp
C++
AppleOpenSource/WebKit2-7609.3.5.1.3/WebProcess/WebCoreSupport/WebProgressTrackerClient.cpp
lzackx/Zone
bf8a3d2b965c383a691a6e7b61d23db15ce11dba
[ "MIT" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
AppleOpenSource/WebKit2-7609.3.5.1.3/WebProcess/WebCoreSupport/WebProgressTrackerClient.cpp
lzackx/Zone
bf8a3d2b965c383a691a6e7b61d23db15ce11dba
[ "MIT" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebKit/WebProcess/WebCoreSupport/WebProgressTrackerClient.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebProgressTrackerClient.h" #include "WebPage.h" #include "WebPageProxyMessages.h" #include <WebCore/Frame.h> #include <WebCore/Page.h> #include <WebCore/ProgressTracker.h> namespace WebKit { using namespace WebCore; WebProgressTrackerClient::WebProgressTrackerClient(WebPage& webPage) : m_webPage(webPage) { } void WebProgressTrackerClient::progressStarted(Frame& originatingProgressFrame) { if (!originatingProgressFrame.isMainFrame()) return; m_webPage.setMainFrameProgressCompleted(false); m_webPage.send(Messages::WebPageProxy::DidStartProgress()); } void WebProgressTrackerClient::progressEstimateChanged(Frame& originatingProgressFrame) { if (!originatingProgressFrame.isMainFrame()) return; double progress = m_webPage.corePage()->progress().estimatedProgress(); m_webPage.send(Messages::WebPageProxy::DidChangeProgress(progress)); } void WebProgressTrackerClient::progressFinished(Frame& originatingProgressFrame) { if (!originatingProgressFrame.isMainFrame()) return; m_webPage.setMainFrameProgressCompleted(true); // Notify the bundle client. m_webPage.injectedBundleLoaderClient().didFinishProgress(m_webPage); m_webPage.send(Messages::WebPageProxy::DidFinishProgress()); } } // namespace WebKit
35.76
87
0.766965
lzackx
b827b4d40f40857b98701b8334e3079249e82e8d
4,913
hpp
C++
src/user/userDefined_base.hpp
bartvbw/MILO
334e9bdec954b0cb82da0576b339729e3f39afd0
[ "BSD-2-Clause" ]
3
2018-10-23T21:04:15.000Z
2020-01-03T21:49:05.000Z
src/user/userDefined_base.hpp
bartvbw/MILO
334e9bdec954b0cb82da0576b339729e3f39afd0
[ "BSD-2-Clause" ]
1
2018-11-27T23:41:57.000Z
2018-11-27T23:41:57.000Z
src/user/userDefined_base.hpp
bartvbw/MILO
334e9bdec954b0cb82da0576b339729e3f39afd0
[ "BSD-2-Clause" ]
1
2018-11-13T15:53:47.000Z
2018-11-13T15:53:47.000Z
/*********************************************************************** Multiscale/Multiphysics Interfaces for Large-scale Optimization (MILO) Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this software.” Questions? Contact Tim Wildey (tmwilde@sandia.gov) and/or Bart van Bloemen Waanders (bartv@sandia.gov) ************************************************************************/ #ifndef USERDEFBASE_H #define USERDEFBASE_H #include "trilinos.hpp" #include "preferences.hpp" #include "workset.hpp" class UserDefinedBase { public: UserDefinedBase() {} ; ~UserDefinedBase() {}; UserDefinedBase(Teuchos::RCP<Teuchos::ParameterList> & settings) {} ; ////////////////////////////////////////////////////////////////////////////////////// // Update the values of the parameters ////////////////////////////////////////////////////////////////////////////////////// virtual Kokkos::View<AD*,AssemblyDevice> boundaryNeumannSource(const string & physics, const string & var, const Teuchos::RCP<workset> & wkset) { int numip = wkset->ip_side.dimension(1); Kokkos::View<AD*,AssemblyDevice> vals("neumann values",numip); //defaults to zeros // Specialize for physics, var and test return vals; } ////////////////////////////////////////////////////////////////////////////////////// // Update the values of the parameters ////////////////////////////////////////////////////////////////////////////////////// virtual Kokkos::View<AD*,AssemblyDevice> boundaryRobinSource(const string & physics, const string & var, const Teuchos::RCP<workset> & wkset) { int numip = wkset->ip_side.dimension(1); Kokkos::View<AD*,AssemblyDevice> vals("robin values",numip); //defaults to zeros // Specialize for physics, var and test return vals; } ////////////////////////////////////////////////////////////////////////////////////// // Update the values of the parameters ////////////////////////////////////////////////////////////////////////////////////// virtual Kokkos::View<AD*,AssemblyDevice> boundaryDirichletSource(const string & physics, const string & var, const Teuchos::RCP<workset> & wkset) { int numip = wkset->ip_side.dimension(1); Kokkos::View<AD*,AssemblyDevice> vals("dirichlet values",numip); //defaults to zeros // Specialize for physics, var and test return vals; } ////////////////////////////////////////////////////////////////////////////////////// // Update the values of the parameters ////////////////////////////////////////////////////////////////////////////////////// virtual Kokkos::View<AD*,AssemblyDevice> volumetricSource(const string & physics, const string & var, const Teuchos::RCP<workset> & wkset) { int numip = wkset->ip.dimension(1); Kokkos::View<AD*,AssemblyDevice> vals("source",numip); //defaults to zeros // Specialize for physics, var and test return vals; } ////////////////////////////////////////////////////////////////////////////////////// // Update the values of the parameters ////////////////////////////////////////////////////////////////////////////////////// virtual Kokkos::View<AD*,AssemblyDevice> coefficient(const string & name, const Teuchos::RCP<workset> & wkset) { int numip = wkset->ip.dimension(1); Kokkos::View<AD*,AssemblyDevice> vals("coefficient values",numip); //defaults to zeros // Specialize for physics, var and test return vals; } ////////////////////////////////////////////////////////////////////////////////////// // Update the values of the parameters ////////////////////////////////////////////////////////////////////////////////////// virtual void updateParameters(const vector<vector<AD> > & params, const vector<string> & paramnames) { } ////////////////////////////////////////////////////////////////////////////////////// // Update the values of the parameters ////////////////////////////////////////////////////////////////////////////////////// virtual vector<vector<double> > setInitialParams(const DRV & nodes, const vector<vector<int> > & indices) { vector<vector<double> > param_initial_vals; for (int n = 0; n < indices.size(); n++) { param_initial_vals.push_back(vector<double>(indices[n].size())); } return param_initial_vals; } protected: //////////////////////////// // vectors of parameters (vector<AD>) //////////////////////////// }; #endif
33.882759
141
0.454508
bartvbw
b8286a4d2e57bafec1ae0b846a7ac8905cdf7fca
7,306
cpp
C++
framework/tarscpp/util/src/tc_openssl.cpp
hfcrwx/Tars-v2.4.20
b0782b3fad556582470cddaa4416874126bd105c
[ "BSD-3-Clause" ]
null
null
null
framework/tarscpp/util/src/tc_openssl.cpp
hfcrwx/Tars-v2.4.20
b0782b3fad556582470cddaa4416874126bd105c
[ "BSD-3-Clause" ]
null
null
null
framework/tarscpp/util/src/tc_openssl.cpp
hfcrwx/Tars-v2.4.20
b0782b3fad556582470cddaa4416874126bd105c
[ "BSD-3-Clause" ]
null
null
null
/** * Tencent is pleased to support the open source community by making Tars * available. * * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the * License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ #if TARS_SSL #include <openssl/err.h> #include <openssl/ssl.h> #include "util/tc_openssl.h" namespace tars { bool TC_OpenSSL::_initialize = false; ////////////////////////////////////////////////////////////////////////////////////////// TC_OpenSSL::TC_OpenSSL(SSL* ssl) : _ssl(ssl), _bHandshaked(false), _isServer(false), _err(0), _plainBuf(NULL) {} TC_OpenSSL::~TC_OpenSSL() { release(); } void TC_OpenSSL::release() { if (_ssl) { SSL_free(_ssl); _ssl = NULL; } _bHandshaked = false; _err = 0; } void TC_OpenSSL::init(bool isServer) { _bHandshaked = false; _isServer = isServer; _err = 0; } std::string TC_OpenSSL::getErrMsg() const { std::shared_ptr<BIO> bio(BIO_new(BIO_s_mem()), BIO_free); ERR_print_errors(bio.get()); string buffer; buffer.resize(255); unsigned int startPos = 0; unsigned int bytesRead = 0; while (true) { int ret = BIO_read(bio.get(), &buffer[startPos], static_cast<int>(buffer.size() - startPos)); if (ret > 0) { bytesRead += ret; } if (bytesRead < buffer.size()) { break; } startPos = static_cast<unsigned int>(buffer.size()); buffer.resize(2 * buffer.size()); } buffer.resize(bytesRead); return buffer; } void TC_OpenSSL::setReadBufferSize(size_t size) { BIO_set_read_buffer_size(SSL_get_rbio(_ssl), size); } void TC_OpenSSL::setWriteBufferSize(size_t size) { BIO_set_write_buffer_size(SSL_get_rbio(_ssl), size); } bool TC_OpenSSL::isHandshaked() const { return _bHandshaked; } int TC_OpenSSL::doHandshake(TC_NetWorkBuffer& out, const void* data, size_t size) { assert(!_bHandshaked); assert(_ssl); if (data && size) { // 写入ssl内存缓冲区 BIO_write(SSL_get_rbio(_ssl), data, size); } ERR_clear_error(); int ret = _isServer ? SSL_accept(_ssl) : SSL_connect(_ssl); _err = 0; if (ret <= 0) { _err = SSL_get_error(_ssl, ret); if (_err != SSL_ERROR_WANT_READ) { return _err; } } if (ret == 1) { _bHandshaked = true; } getMemData(SSL_get_wbio(_ssl), out); return 0; } int TC_OpenSSL::write(const char* data, size_t size, TC_NetWorkBuffer& out) { if (!_bHandshaked) { //握手数据不用加密 out.addBuffer(data, size); return 0; } // 会话数据需加密 ERR_clear_error(); int ret = SSL_write(_ssl, data, size); if (ret <= 0) { _err = SSL_get_error(_ssl, ret); return _err; } _err = 0; getMemData(SSL_get_wbio(_ssl), out); return _err; } int TC_OpenSSL::read(const void* data, size_t size, TC_NetWorkBuffer& out) { bool usedData = false; if (!_bHandshaked) { usedData = true; _plainBuf.clearBuffers(); int ret = doHandshake(out, data, size); if (ret != 0) return ret; // if (_bHandshaked) ; // TODO onHandshake } // 不要用else,因为数据可能紧跟着最后的握手而来 if (_bHandshaked) { if (!usedData) { // 写入ssl内存缓冲区 BIO_write(SSL_get_rbio(_ssl), data, size); } _err = doSSLRead(_ssl, _plainBuf); if (_err != 0) { return SSL_ERROR_SSL; } } return 0; } void TC_OpenSSL::getMemData(BIO* bio, TC_NetWorkBuffer& buf) { while (true) { char data[8 * 1024]; int bytes = BIO_read(bio, data, sizeof(data)); if (bytes <= 0) return; buf.addBuffer(data, bytes); } } int TC_OpenSSL::doSSLRead(SSL* ssl, TC_NetWorkBuffer& out) { while (true) { char plainBuf[32 * 1024]; ERR_clear_error(); int bytes = SSL_read(ssl, plainBuf, sizeof plainBuf); if (bytes > 0) { out.addBuffer(plainBuf, bytes); } else { int err = SSL_get_error(ssl, bytes); // when peer issued renegotiation, here will demand us to send handshake // data. write to mem bio will always success, only need to check whether // has data to send. // assert (err != SSL_ERROR_WANT_WRITE); if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_ZERO_RETURN) { // printf("DoSSLRead err %d\n", err); return err; } break; } } return 0; } void TC_OpenSSL::initialize() { if (!_initialize) { _initialize = true; (void)SSL_library_init(); OpenSSL_add_all_algorithms(); ERR_load_ERR_strings(); SSL_load_error_strings(); } } shared_ptr<TC_OpenSSL::CTX> TC_OpenSSL::newCtx(const std::string& cafile, const std::string& certfile, const std::string& keyfile, bool verifyClient, const string& ciphers) { initialize(); SSL_CTX* ctx = SSL_CTX_new(SSLv23_method()); if (!ctx) return NULL; #define RETURN_IF_FAIL(call) \ if ((call) <= 0) { \ ERR_print_errors_fp(stderr); \ return NULL; \ } int mode = SSL_VERIFY_NONE; if (verifyClient) mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; if (!cafile.empty()) mode |= SSL_VERIFY_PEER; SSL_CTX_set_verify(ctx, mode, NULL); SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); SSL_CTX_clear_options(ctx, SSL_OP_LEGACY_SERVER_CONNECT); SSL_CTX_clear_options(ctx, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); RETURN_IF_FAIL(SSL_CTX_set_session_id_context(ctx, (const unsigned char*)ctx, sizeof ctx)); if (!cafile.empty()) RETURN_IF_FAIL(SSL_CTX_load_verify_locations(ctx, cafile.data(), NULL)); // 客户端可以不提供证书的 if (!certfile.empty()) RETURN_IF_FAIL( SSL_CTX_use_certificate_file(ctx, certfile.data(), SSL_FILETYPE_PEM)); if (!keyfile.empty()) { RETURN_IF_FAIL( SSL_CTX_use_PrivateKey_file(ctx, keyfile.data(), SSL_FILETYPE_PEM)); RETURN_IF_FAIL(SSL_CTX_check_private_key(ctx)); } if (!ciphers.empty()) { RETURN_IF_FAIL(SSL_CTX_set_cipher_list(ctx, ciphers.c_str())); } #undef RETURN_IF_FAIL return std::make_shared<TC_OpenSSL::CTX>(ctx); } shared_ptr<TC_OpenSSL> TC_OpenSSL::newSSL( const std::shared_ptr<TC_OpenSSL::CTX>& ctx) { initialize(); SSL* ssl = SSL_new(ctx->ctx); SSL_set_mode(ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); // allow retry // ssl-write with // different args SSL_set_bio(ssl, BIO_new(BIO_s_mem()), BIO_new(BIO_s_mem())); BIO_set_mem_eof_return(SSL_get_rbio(ssl), -1); BIO_set_mem_eof_return(SSL_get_wbio(ssl), -1); return std::make_shared<TC_OpenSSL>(ssl); } } // end namespace tars #endif
25.106529
90
0.623871
hfcrwx
b8298e5407f8347efe9e6ef690e958f60792671e
910
cpp
C++
code/graphs/kruskall.cpp
spaanse/TeamReferenceDocument
c78808c37de76a061645fac58c283e9537be6869
[ "MIT" ]
null
null
null
code/graphs/kruskall.cpp
spaanse/TeamReferenceDocument
c78808c37de76a061645fac58c283e9537be6869
[ "MIT" ]
5
2020-10-29T10:12:52.000Z
2020-10-29T21:03:00.000Z
code/graphs/kruskall.cpp
spaanse/TeamReferenceDocument
c78808c37de76a061645fac58c283e9537be6869
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <utility> #include <tuple> #include <algorithm> using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> ii; typedef vector<ii> vii; typedef int64_t ll; struct uf { vi p; uf(int n) : p(n,-1) {} int find(int n){ return p[n]<0 ? n : p[n] = find(p[n]);} int size(int n) {return -p[find(n)];} bool same(int x, int y) { return find(x)==find(y);} void join(int x, int y) { x = find(x); y = find(y); if (x == y) return; if (p[x] > p[y]) swap(x,y); p[x] += p[y]; p[y] = x; } }; //69H // Include Union Find struct edge{int c,f,t; bool operator<(edge &o){return c<o.c;}}; typedef vector<edge> ve; ve kruskall(int n, ve edges){ sort(edges.begin(),edges.end()); uf ts(n); ve mst; mst.reserve(n); for(edge e:edges)if(!ts.same(e.f,e.t)){ mst.push_back(e); ts.join(e.f,e.t);} return mst;} int main() { return 0; }
21.666667
41
0.606593
spaanse
b82b6ae4c3af75aa2f63051a78b4608d85cc2bf6
178
cc
C++
trial_targets/pic_on_pic.cc
adambreland/cpp-simple_bazel_cpp_toolchain
9530aad19a03b3ede56d51f6700b726249d51fe9
[ "MIT" ]
2
2021-08-29T00:21:49.000Z
2022-01-27T07:36:04.000Z
trial_targets/pic_on_pic.cc
adambreland/cpp-simple_bazel_cpp_toolchain
9530aad19a03b3ede56d51f6700b726249d51fe9
[ "MIT" ]
null
null
null
trial_targets/pic_on_pic.cc
adambreland/cpp-simple_bazel_cpp_toolchain
9530aad19a03b3ede56d51f6700b726249d51fe9
[ "MIT" ]
null
null
null
#include "pic_on_pic.h" #include <string> #include "pic1.h" std::string pic_on_pic_func() { std::string result {"pic_on_"}; result.append(pic1_func()); return result; }
13.692308
33
0.685393
adambreland
b82baa424c6e0b566e442ec826eea35ca3daa92c
302
cpp
C++
Ch7/7-2/Ch7-2.5.cpp
TaejuKwon/Cpp_practice
54e57cc2d4e610414c3a110663b6c0b477c2855c
[ "MIT" ]
null
null
null
Ch7/7-2/Ch7-2.5.cpp
TaejuKwon/Cpp_practice
54e57cc2d4e610414c3a110663b6c0b477c2855c
[ "MIT" ]
null
null
null
Ch7/7-2/Ch7-2.5.cpp
TaejuKwon/Cpp_practice
54e57cc2d4e610414c3a110663b6c0b477c2855c
[ "MIT" ]
null
null
null
// 파일 쓰기 #include <fstream> #include <iostream> #include <string> int main() { // 파일 쓰기 준비 // std::ofstream out("test.txt"); std::ofstream out("test.txt", std::ios::app); std::string s; if (out.is_open()) { // out << "이걸 쓰자~"; out << "덧붙이기"; } return 0; }
16.777778
49
0.506623
TaejuKwon
b82ec6978705463775a978d33ecabde068205625
6,769
hpp
C++
src/hlxproxyd/ObjectControllerBasis.hpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
1
2021-05-21T21:10:09.000Z
2021-05-21T21:10:09.000Z
src/hlxproxyd/ObjectControllerBasis.hpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
12
2021-06-12T16:42:30.000Z
2022-02-01T18:44:42.000Z
src/hlxproxyd/ObjectControllerBasis.hpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Grant Erickson * 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. * */ /** * @file * This file defines a base object for.... * */ #ifndef OPENHLXPROXYOBJECTCONTROLLERBASIS_HPP #define OPENHLXPROXYOBJECTCONTROLLERBASIS_HPP #include <OpenHLX/Client/CommandManager.hpp> #include <OpenHLX/Common/Errors.hpp> #include <OpenHLX/Common/Timeout.hpp> #include <OpenHLX/Server/CommandManager.hpp> namespace HLX { namespace Proxy { /** * @brief * A base object for.... * * @ingroup proxy * */ class ObjectControllerBasis { public: virtual ~ObjectControllerBasis(void); // Intializer(s) virtual Common::Status Init(Client::CommandManager &aClientCommandManager, Server::CommandManager &aServerCommandManager, const Common::Timeout &aTimeout); // Configuration Management Methods virtual Common::Status QueryCurrentConfiguration(Server::ConnectionBasis &aConnection, Common::ConnectionBuffer::MutableCountedPointer &aBuffer); // Command Proxying Common::Status ProxyMutationCommand(Server::ConnectionBasis &aClientConnection, const uint8_t *aRequestBuffer, const size_t &aRequestSize, const Common::RegularExpression::Matches &aMatches, const Client::Command::ResponseBasis &aExpectedResponse, Client::CommandManager::OnCommandCompleteFunc aOnCommandCompleteHandler, Client::CommandManager::OnCommandErrorFunc aOnCommandErrorHandler, void *aClientContext); Common::Status ProxyObservationCommand(Server::ConnectionBasis &aClientConnection, const uint8_t *aRequestBuffer, const size_t &aRequestSize, const Common::RegularExpression::Matches &aMatches, const Client::Command::ResponseBasis &aExpectedResponse, Client::CommandManager::OnCommandCompleteFunc aOnCommandCompleteHandler, Client::CommandManager::OnCommandErrorFunc aOnCommandErrorHandler, Server::CommandManager::OnRequestReceivedFunc aOnRequestReceivedHandler, void *aClientContext, void *aServerContext); // Notification Proxying Common::Status ProxyNotification(const uint8_t *aNotificationBuffer, const size_t &aNotificationSize, const Common::RegularExpression::Matches &aNotificationMatches, Client::CommandManager::OnNotificationReceivedFunc aOnNotificationReceivedHandler, void *aClientContext); protected: ObjectControllerBasis(void); private: // Command Proxy Handlers void ProxyErrorHandler(Client::Command::ExchangeBasis::MutableCountedPointer &aClientExchange, const Common::Error &aClientError, Server::ConnectionBasis &aClientConnection, Client::CommandManager::OnCommandErrorFunc aOnCommandErrorHandler, void * aContext); void ProxyObservationCompleteHandler(Client::Command::ExchangeBasis::MutableCountedPointer &aClientExchange, const Common::RegularExpression::Matches &aClientMatches, Server::ConnectionBasis &aClientConnection, const uint8_t *aRequestBuffer, const size_t &aRequestSize, const Common::RegularExpression::Matches &aServerMatches, Client::CommandManager::OnCommandCompleteFunc aOnCommandCompleteHandler, Server::CommandManager::OnRequestReceivedFunc aOnRequestReceivedHandler, void * aClientContext, void * aServerContext); void ProxyMutationCompleteHandler(Client::Command::ExchangeBasis::MutableCountedPointer &aClientExchange, const Common::RegularExpression::Matches &aClientMatches, Server::ConnectionBasis &aClientConnection, const uint8_t *aRequestBuffer, const size_t &aRequestSize, const Common::RegularExpression::Matches &aServerMatches, Client::CommandManager::OnCommandCompleteFunc aOnCommandCompleteHandler, void * aContext); public: // Command Proxy Handler Trampolines static void ProxyErrorHandler(Client::Command::ExchangeBasis::MutableCountedPointer &aClientExchange, const Common::Error &aClientError, void *aContext); static void ProxyObservationCompleteHandler(Client::Command::ExchangeBasis::MutableCountedPointer &aClientExchange, const Common::RegularExpression::Matches &aClientMatches, void *aContext); static void ProxyMutationCompleteHandler(Client::Command::ExchangeBasis::MutableCountedPointer &aExchange, const Common::RegularExpression::Matches &aClientMatches, void *aContext); private: Client::CommandManager * mClientCommandManager; Server::CommandManager * mServerCommandManager; Common::Timeout mTimeout; }; }; // namespace Proxy }; // namespace HLX #endif // OPENHLXPROXYOBJECTCONTROLLERBASIS_HPP
47.335664
159
0.583395
gerickson
b8331ac426cb96618f3f47f712cf6cae90e908f8
2,388
cpp
C++
src/mainwindow.cpp
bornjre/qtaria
1d44162cc728788c7b231279bce2bf381aade417
[ "MIT" ]
null
null
null
src/mainwindow.cpp
bornjre/qtaria
1d44162cc728788c7b231279bce2bf381aade417
[ "MIT" ]
null
null
null
src/mainwindow.cpp
bornjre/qtaria
1d44162cc728788c7b231279bce2bf381aade417
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); myDownloader = new qtwebhandler(); myDownloader->moveToThread(&worker); worker.start(); //connects connect(myDownloader,&DownloaderInterface::signal_update_item_stats,this,&MainWindow::slot_update_item_stats); // connect(myDownloader,&DownloaderInterface::signal_update_global_stats,this,&MainWindow::slot_update_item_stats); connect(myDownloader,&DownloaderInterface::signal_download_added,this,&MainWindow::slot_download_added); connect(myDownloader,&DownloaderInterface::signal_error_occured,this,&MainWindow::slot_error_occured); connect(myDownloader,&DownloaderInterface::signal_paused,this,&MainWindow::slot_paused); connect(myDownloader,&DownloaderInterface::signal_resumed,this,&MainWindow::slot_resumed); connect(myDownloader,&DownloaderInterface::signal_deleted,this,&MainWindow::slot_deleted); connect(myDownloader,&DownloaderInterface::signal_downloadfinished,this,&MainWindow::slot_downloadfinished); ui->verticalLayout_4->addWidget(&qw); } MainWindow::~MainWindow() { delete ui; } /*since addnewdialog (dialog to input new url) cannot call downloadmanager so it * passes new url and stuff to mainwindow and it passes into downloadmanager*/ void MainWindow::emitAddNewDownload(QString url,QString location) { // http://speed.hetzner.de/100MB.bin // QString url = " http://ipv4.download.thinkbroadband.com/5MB.zip "; myDownloader->addNewDownload(url, new_ui_element()->id); } listwidget * MainWindow::new_ui_element() { auto lw = new listwidget(&qw); map_of_widgets.insert(lw->id, lw); return lw; } void MainWindow::delete_ui_element(qint32 id) { } void MainWindow::on_actionAddNew_triggered() { newDialog = new addNewDialog(this); newDialog->show(); } void MainWindow::slot_update_item_stats( qint32 id, QString progress) { } void MainWindow::slot_update_global_stats(QString progress) { } void MainWindow::slot_download_added(qint32 id) { } void MainWindow::slot_paused(qint32 id) { } void MainWindow::slot_error_occured(qint32 id) { } void MainWindow::slot_resumed(qint32 id) { } void MainWindow::slot_deleted(qint32 id) { } void MainWindow::slot_downloadfinished(qint32 id) { }
25.404255
118
0.757538
bornjre
b835e48d560b38f6e0672ffe56d151c74f9c569b
6,615
cpp
C++
libs/spirit/test/x3/char1.cpp
btzy/boost-1.72.0-mirror
defad0f34b0abc884032b57dd4eb93f18f679bf1
[ "BSL-1.0" ]
1
2020-03-01T03:04:05.000Z
2020-03-01T03:04:05.000Z
libs/spirit/test/x3/char1.cpp
btzy/boost-1.72.0-mirror
defad0f34b0abc884032b57dd4eb93f18f679bf1
[ "BSL-1.0" ]
null
null
null
libs/spirit/test/x3/char1.cpp
btzy/boost-1.72.0-mirror
defad0f34b0abc884032b57dd4eb93f18f679bf1
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2001-2015 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser Copyright (c) 2019 Christian Mazakas 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) =============================================================================*/ #define BOOST_SPIRIT_X3_UNICODE #include <boost/detail/lightweight_test.hpp> #include <boost/spirit/home/x3.hpp> #include <boost/utility/string_view.hpp> #include <iostream> #include <vector> #include <algorithm> #include "test.hpp" int main() { using spirit_test::test; { using namespace boost::spirit::x3::ascii; BOOST_TEST(test("x", 'x')); BOOST_TEST(test(L"x", L'x')); BOOST_TEST(!test("y", 'x')); BOOST_TEST(!test(L"y", L'x')); BOOST_TEST(test("x", char_)); BOOST_TEST(test("x", char_('x'))); BOOST_TEST(!test("x", char_('y'))); BOOST_TEST(test("x", char_('a', 'z'))); BOOST_TEST(!test("x", char_('0', '9'))); BOOST_TEST(test("0", char_('0', '9'))); BOOST_TEST(test("9", char_('0', '9'))); BOOST_TEST(!test("0", ~char_('0', '9'))); BOOST_TEST(!test("9", ~char_('0', '9'))); BOOST_TEST(!test("x", ~char_)); BOOST_TEST(!test("x", ~char_('x'))); BOOST_TEST(test(" ", ~char_('x'))); BOOST_TEST(test("X", ~char_('x'))); BOOST_TEST(!test("x", ~char_('b', 'y'))); BOOST_TEST(test("a", ~char_('b', 'y'))); BOOST_TEST(test("z", ~char_('b', 'y'))); BOOST_TEST(test("x", ~~char_)); BOOST_TEST(test("x", ~~char_('x'))); BOOST_TEST(!test(" ", ~~char_('x'))); BOOST_TEST(!test("X", ~~char_('x'))); BOOST_TEST(test("x", ~~char_('b', 'y'))); BOOST_TEST(!test("a", ~~char_('b', 'y'))); BOOST_TEST(!test("z", ~~char_('b', 'y'))); } { using namespace boost::spirit::x3::ascii; BOOST_TEST(test(" x", 'x', space)); BOOST_TEST(test(L" x", L'x', space)); BOOST_TEST(test(" x", char_, space)); BOOST_TEST(test(" x", char_('x'), space)); BOOST_TEST(!test(" x", char_('y'), space)); BOOST_TEST(test(" x", char_('a', 'z'), space)); BOOST_TEST(!test(" x", char_('0', '9'), space)); } { using namespace boost::spirit::x3::standard_wide; BOOST_TEST(test(L"x", char_)); BOOST_TEST(test(L"x", char_(L'x'))); BOOST_TEST(!test(L"x", char_(L'y'))); BOOST_TEST(test(L"x", char_(L'a', L'z'))); BOOST_TEST(!test(L"x", char_(L'0', L'9'))); BOOST_TEST(!test(L"x", ~char_)); BOOST_TEST(!test(L"x", ~char_(L'x'))); BOOST_TEST(test(L" ", ~char_(L'x'))); BOOST_TEST(test(L"X", ~char_(L'x'))); BOOST_TEST(!test(L"x", ~char_(L'b', L'y'))); BOOST_TEST(test(L"a", ~char_(L'b', L'y'))); BOOST_TEST(test(L"z", ~char_(L'b', L'y'))); BOOST_TEST(test(L"x", ~~char_)); BOOST_TEST(test(L"x", ~~char_(L'x'))); BOOST_TEST(!test(L" ", ~~char_(L'x'))); BOOST_TEST(!test(L"X", ~~char_(L'x'))); BOOST_TEST(test(L"x", ~~char_(L'b', L'y'))); BOOST_TEST(!test(L"a", ~~char_(L'b', L'y'))); BOOST_TEST(!test(L"z", ~~char_(L'b', L'y'))); } // unicode (normal ASCII) { using namespace boost::spirit::x3::unicode; BOOST_TEST(test(U"abcd", +char_(U"abcd"))); BOOST_TEST(!test(U"abcd", +char_(U"qwer"))); auto const sub_delims = char_(U"!$&'()*+,;="); auto const delims = std::vector<boost::u32string_view>{U"!", U"$", U"&", U"'", U"(", U")", U"*", U"+", U",", U";", U"="}; auto const matched_all_sub_delims = std::all_of(delims.begin(), delims.end(), [&](auto const delim) -> bool { return test(delim, sub_delims); }); BOOST_TEST(matched_all_sub_delims); } // unicode (escaped Unicode char literals) { using namespace boost::spirit::x3::unicode; auto const chars = char_(U"\u0024\u00a2\u0939\u20ac\U00010348"); auto const test_strings = std::vector<boost::u32string_view>{U"\u0024", U"\u00a2", U"\u0939", U"\u20ac", U"\U00010348"}; auto const bad_test_strings = std::vector<boost::u32string_view>{U"a", U"B", U"c", U"\u0409"}; auto const all_matched = std::all_of(test_strings.begin(), test_strings.end(), [&](auto const test_str) -> bool { return test(test_str, chars); }); auto const none_matched = std::all_of(bad_test_strings.begin(), bad_test_strings.end(), [&](auto const bad_test_str) -> bool { return !test(bad_test_str, chars); }); BOOST_TEST(all_matched); BOOST_TEST(none_matched); } { // single char strings! namespace ascii = boost::spirit::x3::ascii; namespace wide = boost::spirit::x3::standard_wide; BOOST_TEST(test("x", "x")); BOOST_TEST(test(L"x", L"x")); BOOST_TEST(test("x", ascii::char_("x"))); BOOST_TEST(test(L"x", wide::char_(L"x"))); BOOST_TEST(test("x", ascii::char_("a", "z"))); BOOST_TEST(test(L"x", wide::char_(L"a", L"z"))); } { // chsets namespace ascii = boost::spirit::x3::ascii; namespace wide = boost::spirit::x3::standard_wide; BOOST_TEST(test("x", ascii::char_("a-z"))); BOOST_TEST(!test("1", ascii::char_("a-z"))); BOOST_TEST(test("1", ascii::char_("a-z0-9"))); BOOST_TEST(test("x", wide::char_(L"a-z"))); BOOST_TEST(!test("1", wide::char_(L"a-z"))); BOOST_TEST(test("1", wide::char_(L"a-z0-9"))); std::string set = "a-z0-9"; BOOST_TEST(test("x", ascii::char_(set))); #ifdef SPIRIT_NO_COMPILE_CHECK test("", ascii::char_(L"a-z0-9")); #endif } { namespace ascii = boost::spirit::x3::ascii; char const* input = "\x80"; // ascii > 7 bits (this should fail, not assert!) BOOST_TEST(!test(input, ascii::char_)); BOOST_TEST(!test(input, ascii::char_('a'))); BOOST_TEST(!test(input, ascii::alnum)); BOOST_TEST(!test(input, ascii::char_("a-z"))); BOOST_TEST(!test(input, ascii::char_('0', '9'))); } return boost::report_errors(); }
33.241206
112
0.511867
btzy
b83b935f88dc8e388a70bf56c27b1856f83ddaa3
20,464
cpp
C++
OpenSim/Common/XMLDocument.cpp
justicelee/opensim-core
80ce7795b861a0d797bdac9202f71a2556d89969
[ "Apache-2.0" ]
2
2017-06-14T15:38:45.000Z
2019-01-25T05:40:09.000Z
OpenSim/Common/XMLDocument.cpp
justicelee/opensim-core
80ce7795b861a0d797bdac9202f71a2556d89969
[ "Apache-2.0" ]
null
null
null
OpenSim/Common/XMLDocument.cpp
justicelee/opensim-core
80ce7795b861a0d797bdac9202f71a2556d89969
[ "Apache-2.0" ]
1
2020-11-11T14:33:06.000Z
2020-11-11T14:33:06.000Z
/* -------------------------------------------------------------------------- * * OpenSim: XMLDocument.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Frank C. Anderson * * * * 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. * * -------------------------------------------------------------------------- */ /* Note: This code was originally developed by Realistic Dynamics Inc. * Author: Frank C. Anderson */ //----------------------------------------------------------------------------- // INCLUDES //----------------------------------------------------------------------------- #include "XMLDocument.h" #include "Object.h" using namespace OpenSim; using namespace std; //----------------------------------------------------------------------------- // CONSTANTS //----------------------------------------------------------------------------- // This list of version numbers is not complete // 20301 for separation of RRATool, CMCTool // 20302 for Muscle's pennation_angle -> pennation_angle_at_optimal // 20303 // 30000 for OpenSim 3.0 release // 30500 for OpenSim 4.0 development and Connectors // 30501 for changing serialization of Marker // 30502 for changing serialization of Geometry // 30503 for changing serialization of Ground // 30505 for changing serialization of Joint to create offset frames // 30506 for testing 30505 conversion code // 30507 for changing serialization of Coordinates owned by Joint // 30508 for moving Connector's connectee_name to enclosing Component. // 30509 for replacing 'isDisabled' with: 'appliesForce', 'isEnforced' and // 'enabled', for Force, Constraint and Controller, respectively // 30510 for renaming Connector to Socket. // 30511 for replacing Probe::isDisabled with Probe::enabled. // 30512 for removing Model::FrameSet and moving frames to components list // 30513 for removing internal (silent) clamping of Muscle controls (excitations) // 30514 for removing "reverse" property from Joint // 30515 for WrapObject color, display_preference, VisibleObject -> Appearance // 30516 for GeometryPath default_color -> Appearance const int XMLDocument::LatestVersion = 30516; //============================================================================= // DESTRUCTOR AND CONSTRUCTOR(S) //============================================================================= //----------------------------------------------------------------------------- // DESTRUCTOR //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Handle delete of an XMLDocument object. */ XMLDocument::~XMLDocument() { for(int i = 0; i < _defaultObjects.size(); i++) { delete _defaultObjects.get(i); } _defaultObjects.setSize(0); } //----------------------------------------------------------------------------- // CONSTRUCTOR(S) //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Construct a XMLDocument object with a locally generated DOMDocument. * This constructor is used when an XML document is going to be generated * locally in memory without reference to an XML file. The initial * DOMDocument is empty. */ XMLDocument::XMLDocument() { setRootTag("OpenSimDocument"); stringstream latestVersionString; latestVersionString << LatestVersion; _documentVersion = LatestVersion; getRootElement().setAttributeValue("Version", latestVersionString.str()); } //_____________________________________________________________________________ /** * Construct an XMLDocument object from an XML document. * A parser is created for the purpose of reading in the XML file. * * @param aFileName File name of the XML document. */ XMLDocument::XMLDocument(const string &aFileName) : SimTK::Xml::Document(aFileName) { _fileName = aFileName; // Update document version based on parsing updateDocumentVersion(); } //_____________________________________________________________________________ /** * Construct a copy of an XMLDocument object. The document an all its nodes * are copied; however, the parser associated with the copied document, if * any, is not copied. */ XMLDocument::XMLDocument(const XMLDocument &aDocument): SimTK::Xml::Document(aDocument) { _documentVersion = aDocument.getDocumentVersion(); _fileName = aDocument.getFileName(); } //============================================================================= // CONSTRUCTION //============================================================================= //_____________________________________________________________________________ //============================================================================= // SET AND GET //============================================================================= //----------------------------------------------------------------------------- // DOCUMENT //----------------------------------------------------------------------------- void XMLDocument:: setFileName(const string &aFileName) { _fileName = aFileName; } const string &XMLDocument:: getFileName() const { return _fileName; } //============================================================================= // IO //============================================================================= //----------------------------------------------------------------------------- // PRINT //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Print the XML document to file. * * @param aFileName File name of the document to which to print */ bool XMLDocument:: print(const string &aFileName) { // Standard Out if(aFileName.empty()) { cout << *this; cout << flush; // File } else { setIndentString("\t"); writeToFile(aFileName); } return true; } //_____________________________________________________________________________ //----------------------------------------------------------------------------- // FORMATTER //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // STREAM OUTPUT //----------------------------------------------------------------------------- //_____________________________________________________________________________ //-------------------------------------------------------------------------- // VERSIONING /BACKWARD COMPATIBILITY SUPPORT //-------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Convert passed in version number to a string * The string is usually more compact e.g. 010100 -> 1_1 (rather than 11 which would confuse 110000 with 010100) */ void XMLDocument:: getVersionAsString(const int aVersion, std::string& aString) { char pad[3]; int ver = aVersion; aString = ""; int div = 10000; for(int i=0; i<3; i++) { int digits = ver / div; sprintf(pad, "%02d",digits); ver -= div*(ver / div); div /=100; aString += string(pad); if (ver ==0) break; aString +=(i<2?"_":""); } } //_____________________________________________________________________________ /** * Update member variable _documentVersion based on parsing * Key assumption is that parsing has finished but no Object parsing is done yet */ void XMLDocument:: updateDocumentVersion() { // Check root node if it's OpenSimDocument std::string rootTag = getRootTag(); if (rootTag == "OpenSimDocument"){ _documentVersion = getRootElement().getRequiredAttributeValueAs<int>("Version"); } else { _documentVersion = 10500; // Old version pre 1.6 } // Validate >= 10500 and < latest as sanity check assert(_documentVersion >= 10500 && _documentVersion <= LatestVersion); } //_____________________________________________________________________________ /** * getRootDataElement returns a pointer to the real root node that contains objects * works as a wrapper to get around the new root node <OpenSimDocument introduced in 1.6 */ SimTK::Xml::Element XMLDocument:: getRootDataElement() { // Check root node if it's OpenSimDocument std::string rootTag = getRootTag(); if (rootTag == "OpenSimDocument"){ _documentVersion = getRootElement().getRequiredAttributeValueAs<int>("Version"); return (*getRootElement().element_begin()); } else { _documentVersion = 10500; // Old version pre 1.6 return getRootElement(); } } /** */ void XMLDocument::addDefaultObject(OpenSim::Object *aDefaultObject) { _defaultObjects.append(aDefaultObject); } void XMLDocument::writeDefaultObjects(SimTK::Xml::Element& elmt) { if (_defaultObjects.getSize()==0) return; // Make node for "defaults" SimTK::Xml::Element defaultsElement("defaults"); elmt.insertNodeAfter(elmt.node_end(), defaultsElement); for(int i=0; i < _defaultObjects.getSize(); i++){ _defaultObjects.get(i)->updateXMLNode(defaultsElement); } } void XMLDocument::copyDefaultObjects(const XMLDocument &aDocument){ _defaultObjects.setSize(0); for (int i=0; i< aDocument._defaultObjects.getSize(); i++) _defaultObjects.append(aDocument._defaultObjects.get(i)->clone()); } /*static*/ void XMLDocument::renameChildNode(SimTK::Xml::Element& aNode, std::string oldElementName, std::string newElementName) { SimTK::Xml::element_iterator elmtIter(aNode.element_begin(oldElementName)); if (elmtIter!=aNode.element_end()){ elmtIter->setElementTag(newElementName); } } bool XMLDocument::isEqualTo(XMLDocument& aOtherDocument, double toleranceForDoubles, bool compareDefaults, bool compareVersionNumbers) { bool equal = true; if (compareVersionNumbers) equal = (_documentVersion == aOtherDocument._documentVersion); if (!equal) return false; // Get Roots SimTK::Xml::Element root1= getRootElement(); SimTK::Xml::Element root2= aOtherDocument.getRootElement(); //if (!equal) return false; // Cycle through children and compare. Order is assumed to be the same for now SimTK::Array_<SimTK::Xml::Element> elts1 = root1.getAllElements(); SimTK::Array_<SimTK::Xml::Element> elts2 = root2.getAllElements(); if (elts1.size() != elts2.size()){ cout << "Different number of children at Top level" << endl; equal = false; } if (!equal) return false; // Recursively compare Elements SimTK::String s1,s2; for(unsigned it = 0; it < elts1.size(); it++){ elts1[it].writeToString(s1); elts2[it].writeToString(s2); if (elts1[it].getElementTag()==elts2[it].getElementTag() && elts1[it].getElementTag()=="defaults" && !compareDefaults) continue; equal = isElementEqual(elts1[it], elts2[it], toleranceForDoubles); if (!equal){ cout << elts1[it].getElementTag() << " is different" << endl; return false; } } return true; } bool XMLDocument::isElementEqual(SimTK::Xml::Element& elt1, SimTK::Xml::Element& elt2, double toleranceForDoubles) { SimTK::String s1,s2; elt1.writeToString(s1); elt2.writeToString(s2); SimTK::Xml::attribute_iterator att1 = elt1.attribute_begin(); SimTK::Xml::attribute_iterator att2 = elt2.attribute_begin(); // Handle different # attributes if ( (att1 == elt1.attribute_end() && att2 != elt2.attribute_end()) || (att1 != elt1.attribute_end() && att2 == elt2.attribute_end()) ){ cout << "Number of attributes is different, element " << elt1.getElementTag() << endl; return false; } bool equal =true; // Same size attributes including none for(att1 = elt1.attribute_begin(); att1 != elt1.attribute_end() && equal; att1++, att2++){ equal = (att1->getName() == att2->getName()); equal = equal && (att1->getValue() == att2->getValue()); if (!equal) { cout << "Attribute " << att1->getName() << " is different " << att1->getValue() << "vs." << att2->getValue() << endl; } } if (!equal) return false; // Attributes match now children SimTK::Array_<SimTK::Xml::Element> elts1 = elt1.getAllElements(); SimTK::Array_<SimTK::Xml::Element> elts2 = elt2.getAllElements(); if (elts1.size() != elts2.size()){ cout << "Different number of children for Element " << elt1.getElementTag() << endl; equal = false; } if (!equal) return false; // Recursively compare Elements unless Value Elements in that case do direct compare for(unsigned it = 0; it < elts1.size() && equal; it++){ SimTK::String elt1Tag = elts1[it].getElementTag(); cout << "Compare " << elt1Tag << endl; SimTK::Xml::element_iterator elt2_iter = elt2.element_begin(elt1Tag); if (elt2_iter==elt2.element_end()){ cout << "Element " << elt1Tag << " was not found in reference document" << endl; equal = false; break; } bool value1 = elts1[it].isValueElement(); bool value2 = elt2_iter->isValueElement(); equal = (value1 == value2); if (!equal){ cout << elts1[it].getElementTag() << " is different. One is Value Element the other isn't" << endl; return false; } if (value1){ // We should check if this's a double or array of doubles in that case we can getValueAs<double> try { SimTK::Array_<double> v1, v2; elts1[it].getValueAs(v1); elt2_iter->getValueAs(v2); for(unsigned ix=0; ix<v1.size() && equal; ix++) equal = (std::fabs(v1[ix]-v2[ix]) < toleranceForDoubles); } catch(...){ equal = (elts1[it].getValue() == elt2_iter->getValue()); } } else // recur equal = isElementEqual(elts1[it], elts2[it], toleranceForDoubles); if (!equal){ cout << elts1[it].getElementTag() << " is different" << endl; SimTK::String pad; elts1[it].writeToString(pad); cout << pad << endl; cout << "------------------- vs. ------" << endl; elts2[it].writeToString(pad); cout << pad << endl; return equal; } } return equal; } /* * Helper function to add connector to the xmlElement passed in */ void XMLDocument::addConnector(SimTK::Xml::Element& element, const std::string& connectorTag, const std::string& connectorName, const std::string& connectorValue) { SimTK::Xml::element_iterator connectors_node = element.element_begin("connectors"); //SimTK::String debug; //Only used for debugging if (connectors_node == element.element_end()){ SimTK::Xml::Element connectorsElement("connectors"); element.insertNodeBefore(element.element_begin(), connectorsElement); connectors_node = element.element_begin("connectors"); } // Here we're guaranteed connectors node exists, add individual connector SimTK::Xml::Element newConnectorElement(connectorTag); newConnectorElement.setAttributeValue("name", connectorName); //newConnectorElement.writeToString(debug); SimTK::Xml::Element connecteeElement("connectee_name"); connecteeElement.insertNodeAfter(connecteeElement.element_end(), SimTK::Xml::Text(connectorValue)); // Insert text under newConnectorElement newConnectorElement.insertNodeAfter(newConnectorElement.element_end(), connecteeElement); connectors_node->insertNodeAfter(connectors_node->element_end(), newConnectorElement); //connectors_node->writeToString(debug); } void XMLDocument::updateConnectors30508(SimTK::Xml::Element& componentElt) { using ElementItr = SimTK::Xml::element_iterator; ElementItr connectors_node = componentElt.element_begin("connectors"); // See if there's a <connectors> element. if (connectors_node == componentElt.element_end()) return; for (ElementItr connectorElt = connectors_node->element_begin(); connectorElt != componentElt.element_end(); ++connectorElt) { // Grab name of Connector. const auto& connectorName = connectorElt->getRequiredAttributeValue("name"); // Grab value of connectee_name property. ElementItr connecteeNameElt = connectorElt->element_begin("connectee_name"); SimTK::String connecteeName; connecteeNameElt->getValueAs<std::string>(connecteeName); // Create new element for this connector's connectee name. SimTK::Xml::Element newConnecteeNameElt( "connector_" + connectorName + "_connectee_name"); newConnecteeNameElt.setValue(connecteeName); componentElt.insertNodeAfter(connectors_node, newConnecteeNameElt); } // No longer want the old syntax for connectors. componentElt.eraseNode(connectors_node); } void XMLDocument::addPhysicalOffsetFrame(SimTK::Xml::Element& element, const std::string& frameName, const std::string& parentFrameName, const SimTK::Vec3& location, const SimTK::Vec3& orientation) { SimTK::Xml::element_iterator frames_node = element.element_begin("frames"); //SimTK::String debug; //Only used for debugging if (frames_node == element.element_end()) { SimTK::Xml::Element framesElement("frames"); element.insertNodeBefore(element.element_begin(), framesElement); frames_node = element.element_begin("frames"); } // Here we're guaranteed frames node exists, add individual frame SimTK::Xml::Element newFrameElement("PhysicalOffsetFrame"); newFrameElement.setAttributeValue("name", frameName); //newFrameElement.writeToString(debug); XMLDocument::addConnector(newFrameElement, "Connector_PhysicalFrame_", "parent", parentFrameName); std::ostringstream transValue; transValue << location[0] << " " << location[1] << " " << location[2]; SimTK::Xml::Element translationElement("translation", transValue.str()); newFrameElement.insertNodeAfter(newFrameElement.element_end(), translationElement); std::ostringstream orientValue; orientValue << orientation[0] << " " << orientation[1] << " " << orientation[2]; SimTK::Xml::Element orientationElement("orientation", orientValue.str()); newFrameElement.insertNodeAfter(newFrameElement.element_end(), orientationElement); frames_node->insertNodeAfter(frames_node->element_end(), newFrameElement); //frames_node->writeToString(debug); }
40.522772
135
0.59182
justicelee
cdc8dca92c96e5f84331ea61679cd84157be770e
2,469
cc
C++
elements/ip/decipttl.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
32
2017-11-02T12:33:21.000Z
2022-02-07T22:25:58.000Z
elements/ip/decipttl.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
2
2019-02-18T08:47:16.000Z
2019-05-24T14:41:23.000Z
elements/ip/decipttl.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
10
2018-06-13T11:54:53.000Z
2020-09-08T06:52:43.000Z
/* * decipttl.{cc,hh} -- element decrements IP packet's time-to-live * Eddie Kohler, Robert Morris * * Copyright (c) 1999-2000 Massachusetts Institute of Technology * Copyright (c) 2008 Meraki, Inc. * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include "decipttl.hh" #include <click/glue.hh> #include <click/args.hh> #include <clicknet/ip.h> CLICK_DECLS DecIPTTL::DecIPTTL() : _active(true), _multicast(true) { _drops = 0; } DecIPTTL::~DecIPTTL() { } int DecIPTTL::configure(Vector<String> &conf, ErrorHandler *errh) { return Args(conf, this, errh) .read("ACTIVE", _active) .read("MULTICAST", _multicast).complete(); } Packet * DecIPTTL::simple_action(Packet *p) { assert(p->has_network_header()); if (!_active) return p; const click_ip *ip_in = p->ip_header(); if (!_multicast && IPAddress(ip_in->ip_dst).is_multicast()) return p; if (ip_in->ip_ttl <= 1) { ++_drops; checked_output_push(1, p); return 0; } else { WritablePacket *q = p->uniqueify(); if (!q) return 0; click_ip *ip = q->ip_header(); --ip->ip_ttl; // 19.Aug.1999 - incrementally update IP checksum as suggested by SOSP // reviewers, according to RFC1141, as updated by RFC1624. // new_sum = ~(~old_sum + ~old_halfword + new_halfword) // = ~(~old_sum + ~old_halfword + (old_halfword - 0x0100)) // = ~(~old_sum + ~old_halfword + old_halfword + ~0x0100) // = ~(~old_sum + ~0 + ~0x0100) // = ~(~old_sum + 0xFEFF) unsigned long sum = (~ntohs(ip->ip_sum) & 0xFFFF) + 0xFEFF; ip->ip_sum = ~htons(sum + (sum >> 16)); return q; } } void DecIPTTL::add_handlers() { add_data_handlers("drops", Handler::OP_READ, &_drops); add_data_handlers("active", Handler::OP_READ | Handler::OP_WRITE | Handler::CHECKBOX, &_active); } CLICK_ENDDECLS EXPORT_ELEMENT(DecIPTTL) ELEMENT_MT_SAFE(DecIPTTL)
27.741573
100
0.685703
MacWR
cdcbaf5a86c5688a2356d50ac878ec758c019d13
1,112
hpp
C++
include/tdc/util/concepts.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
1
2021-05-06T13:39:22.000Z
2021-05-06T13:39:22.000Z
include/tdc/util/concepts.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
1
2020-03-07T08:05:20.000Z
2020-03-07T08:05:20.000Z
include/tdc/util/concepts.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
2
2020-05-27T07:54:43.000Z
2021-11-18T13:29:14.000Z
#pragma once #include <concepts> #include <cstddef> #include <type_traits> #include <utility> namespace tdc { template<typename T> concept Arithmetic = std::is_arithmetic<T>::value; template<typename T> concept IndexAccess = requires(T a) { { a[std::declval<size_t>()] }; }; template<typename T> concept SizedIndexAccess = IndexAccess<T> && requires(T a) { { a.size() } -> std::unsigned_integral; }; template<typename T, typename V> concept IndexAccessTo = requires(T a) { { a[std::declval<size_t>()] } -> std::convertible_to<V>; }; template<typename T, typename V> concept SizedIndexAccessTo = IndexAccessTo<T, V> && requires(T a) { { a.size() } -> std::unsigned_integral; }; template<typename T, typename V> concept VectorCompilant = SizedIndexAccess<T> && std::semiregular<T> && std::copy_constructible<T> && std::move_constructible<T> && std::constructible_from<T, size_t> && requires(T a, V&& v) { { a.emplace_back(v) }; } && requires(T a, const V& v) { { a.push_back(v) }; }; } // namespace tdc
21.384615
60
0.627698
herlez
cdd05a6c3f7648a747d4e8459c4adffaebb29eee
5,390
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcWindowPanelOperationEnum.cpp
vjeranc/ifcplusplus
215859fb84d5be484d454c2767571dd168612329
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcWindowPanelOperationEnum.cpp
vjeranc/ifcplusplus
215859fb84d5be484d454c2767571dd168612329
[ "MIT" ]
1
2019-03-06T08:59:24.000Z
2019-03-06T08:59:24.000Z
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcWindowPanelOperationEnum.cpp
Imerso3D/ifcplusplus
84d1a5f58db232e07f4f3d233a9efb035f3babd2
[ "MIT" ]
1
2021-04-26T14:56:09.000Z
2021-04-26T14:56:09.000Z
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include <map> #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/IFC4/include/IfcWindowPanelOperationEnum.h" // TYPE IfcWindowPanelOperationEnum = ENUMERATION OF (SIDEHUNGRIGHTHAND ,SIDEHUNGLEFTHAND ,TILTANDTURNRIGHTHAND ,TILTANDTURNLEFTHAND ,TOPHUNG ,BOTTOMHUNG ,PIVOTHORIZONTAL ,PIVOTVERTICAL ,SLIDINGHORIZONTAL ,SLIDINGVERTICAL ,REMOVABLECASEMENT ,FIXEDCASEMENT ,OTHEROPERATION ,NOTDEFINED); shared_ptr<BuildingObject> IfcWindowPanelOperationEnum::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcWindowPanelOperationEnum> copy_self( new IfcWindowPanelOperationEnum() ); copy_self->m_enum = m_enum; return copy_self; } void IfcWindowPanelOperationEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const { if( is_select_type ) { stream << "IFCWINDOWPANELOPERATIONENUM("; } switch( m_enum ) { case ENUM_SIDEHUNGRIGHTHAND: stream << ".SIDEHUNGRIGHTHAND."; break; case ENUM_SIDEHUNGLEFTHAND: stream << ".SIDEHUNGLEFTHAND."; break; case ENUM_TILTANDTURNRIGHTHAND: stream << ".TILTANDTURNRIGHTHAND."; break; case ENUM_TILTANDTURNLEFTHAND: stream << ".TILTANDTURNLEFTHAND."; break; case ENUM_TOPHUNG: stream << ".TOPHUNG."; break; case ENUM_BOTTOMHUNG: stream << ".BOTTOMHUNG."; break; case ENUM_PIVOTHORIZONTAL: stream << ".PIVOTHORIZONTAL."; break; case ENUM_PIVOTVERTICAL: stream << ".PIVOTVERTICAL."; break; case ENUM_SLIDINGHORIZONTAL: stream << ".SLIDINGHORIZONTAL."; break; case ENUM_SLIDINGVERTICAL: stream << ".SLIDINGVERTICAL."; break; case ENUM_REMOVABLECASEMENT: stream << ".REMOVABLECASEMENT."; break; case ENUM_FIXEDCASEMENT: stream << ".FIXEDCASEMENT."; break; case ENUM_OTHEROPERATION: stream << ".OTHEROPERATION."; break; case ENUM_NOTDEFINED: stream << ".NOTDEFINED."; break; } if( is_select_type ) { stream << ")"; } } const std::wstring IfcWindowPanelOperationEnum::toString() const { switch( m_enum ) { case ENUM_SIDEHUNGRIGHTHAND: return L"SIDEHUNGRIGHTHAND"; case ENUM_SIDEHUNGLEFTHAND: return L"SIDEHUNGLEFTHAND"; case ENUM_TILTANDTURNRIGHTHAND: return L"TILTANDTURNRIGHTHAND"; case ENUM_TILTANDTURNLEFTHAND: return L"TILTANDTURNLEFTHAND"; case ENUM_TOPHUNG: return L"TOPHUNG"; case ENUM_BOTTOMHUNG: return L"BOTTOMHUNG"; case ENUM_PIVOTHORIZONTAL: return L"PIVOTHORIZONTAL"; case ENUM_PIVOTVERTICAL: return L"PIVOTVERTICAL"; case ENUM_SLIDINGHORIZONTAL: return L"SLIDINGHORIZONTAL"; case ENUM_SLIDINGVERTICAL: return L"SLIDINGVERTICAL"; case ENUM_REMOVABLECASEMENT: return L"REMOVABLECASEMENT"; case ENUM_FIXEDCASEMENT: return L"FIXEDCASEMENT"; case ENUM_OTHEROPERATION: return L"OTHEROPERATION"; case ENUM_NOTDEFINED: return L"NOTDEFINED"; } return L""; } shared_ptr<IfcWindowPanelOperationEnum> IfcWindowPanelOperationEnum::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map ) { if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcWindowPanelOperationEnum>(); } if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcWindowPanelOperationEnum>(); } shared_ptr<IfcWindowPanelOperationEnum> type_object( new IfcWindowPanelOperationEnum() ); if( boost::iequals( arg, L".SIDEHUNGRIGHTHAND." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_SIDEHUNGRIGHTHAND; } else if( boost::iequals( arg, L".SIDEHUNGLEFTHAND." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_SIDEHUNGLEFTHAND; } else if( boost::iequals( arg, L".TILTANDTURNRIGHTHAND." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_TILTANDTURNRIGHTHAND; } else if( boost::iequals( arg, L".TILTANDTURNLEFTHAND." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_TILTANDTURNLEFTHAND; } else if( boost::iequals( arg, L".TOPHUNG." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_TOPHUNG; } else if( boost::iequals( arg, L".BOTTOMHUNG." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_BOTTOMHUNG; } else if( boost::iequals( arg, L".PIVOTHORIZONTAL." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_PIVOTHORIZONTAL; } else if( boost::iequals( arg, L".PIVOTVERTICAL." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_PIVOTVERTICAL; } else if( boost::iequals( arg, L".SLIDINGHORIZONTAL." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_SLIDINGHORIZONTAL; } else if( boost::iequals( arg, L".SLIDINGVERTICAL." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_SLIDINGVERTICAL; } else if( boost::iequals( arg, L".REMOVABLECASEMENT." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_REMOVABLECASEMENT; } else if( boost::iequals( arg, L".FIXEDCASEMENT." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_FIXEDCASEMENT; } else if( boost::iequals( arg, L".OTHEROPERATION." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_OTHEROPERATION; } else if( boost::iequals( arg, L".NOTDEFINED." ) ) { type_object->m_enum = IfcWindowPanelOperationEnum::ENUM_NOTDEFINED; } return type_object; }
43.12
286
0.746011
vjeranc
cdd2ed9747197e5c655b1bb06fd56386a1f61019
5,619
cpp
C++
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-opsworks/source/model/ElasticLoadBalancer.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
2
2019-02-08T21:29:57.000Z
2021-07-27T06:59:19.000Z
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-opsworks/source/model/ElasticLoadBalancer.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-opsworks/source/model/ElasticLoadBalancer.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/opsworks/model/ElasticLoadBalancer.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace OpsWorks { namespace Model { ElasticLoadBalancer::ElasticLoadBalancer() : m_elasticLoadBalancerNameHasBeenSet(false), m_regionHasBeenSet(false), m_dnsNameHasBeenSet(false), m_stackIdHasBeenSet(false), m_layerIdHasBeenSet(false), m_vpcIdHasBeenSet(false), m_availabilityZonesHasBeenSet(false), m_subnetIdsHasBeenSet(false), m_ec2InstanceIdsHasBeenSet(false) { } ElasticLoadBalancer::ElasticLoadBalancer(const JsonValue& jsonValue) : m_elasticLoadBalancerNameHasBeenSet(false), m_regionHasBeenSet(false), m_dnsNameHasBeenSet(false), m_stackIdHasBeenSet(false), m_layerIdHasBeenSet(false), m_vpcIdHasBeenSet(false), m_availabilityZonesHasBeenSet(false), m_subnetIdsHasBeenSet(false), m_ec2InstanceIdsHasBeenSet(false) { *this = jsonValue; } ElasticLoadBalancer& ElasticLoadBalancer::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("ElasticLoadBalancerName")) { m_elasticLoadBalancerName = jsonValue.GetString("ElasticLoadBalancerName"); m_elasticLoadBalancerNameHasBeenSet = true; } if(jsonValue.ValueExists("Region")) { m_region = jsonValue.GetString("Region"); m_regionHasBeenSet = true; } if(jsonValue.ValueExists("DnsName")) { m_dnsName = jsonValue.GetString("DnsName"); m_dnsNameHasBeenSet = true; } if(jsonValue.ValueExists("StackId")) { m_stackId = jsonValue.GetString("StackId"); m_stackIdHasBeenSet = true; } if(jsonValue.ValueExists("LayerId")) { m_layerId = jsonValue.GetString("LayerId"); m_layerIdHasBeenSet = true; } if(jsonValue.ValueExists("VpcId")) { m_vpcId = jsonValue.GetString("VpcId"); m_vpcIdHasBeenSet = true; } if(jsonValue.ValueExists("AvailabilityZones")) { Array<JsonValue> availabilityZonesJsonList = jsonValue.GetArray("AvailabilityZones"); for(unsigned availabilityZonesIndex = 0; availabilityZonesIndex < availabilityZonesJsonList.GetLength(); ++availabilityZonesIndex) { m_availabilityZones.push_back(availabilityZonesJsonList[availabilityZonesIndex].AsString()); } m_availabilityZonesHasBeenSet = true; } if(jsonValue.ValueExists("SubnetIds")) { Array<JsonValue> subnetIdsJsonList = jsonValue.GetArray("SubnetIds"); for(unsigned subnetIdsIndex = 0; subnetIdsIndex < subnetIdsJsonList.GetLength(); ++subnetIdsIndex) { m_subnetIds.push_back(subnetIdsJsonList[subnetIdsIndex].AsString()); } m_subnetIdsHasBeenSet = true; } if(jsonValue.ValueExists("Ec2InstanceIds")) { Array<JsonValue> ec2InstanceIdsJsonList = jsonValue.GetArray("Ec2InstanceIds"); for(unsigned ec2InstanceIdsIndex = 0; ec2InstanceIdsIndex < ec2InstanceIdsJsonList.GetLength(); ++ec2InstanceIdsIndex) { m_ec2InstanceIds.push_back(ec2InstanceIdsJsonList[ec2InstanceIdsIndex].AsString()); } m_ec2InstanceIdsHasBeenSet = true; } return *this; } JsonValue ElasticLoadBalancer::Jsonize() const { JsonValue payload; if(m_elasticLoadBalancerNameHasBeenSet) { payload.WithString("ElasticLoadBalancerName", m_elasticLoadBalancerName); } if(m_regionHasBeenSet) { payload.WithString("Region", m_region); } if(m_dnsNameHasBeenSet) { payload.WithString("DnsName", m_dnsName); } if(m_stackIdHasBeenSet) { payload.WithString("StackId", m_stackId); } if(m_layerIdHasBeenSet) { payload.WithString("LayerId", m_layerId); } if(m_vpcIdHasBeenSet) { payload.WithString("VpcId", m_vpcId); } if(m_availabilityZonesHasBeenSet) { Array<JsonValue> availabilityZonesJsonList(m_availabilityZones.size()); for(unsigned availabilityZonesIndex = 0; availabilityZonesIndex < availabilityZonesJsonList.GetLength(); ++availabilityZonesIndex) { availabilityZonesJsonList[availabilityZonesIndex].AsString(m_availabilityZones[availabilityZonesIndex]); } payload.WithArray("AvailabilityZones", std::move(availabilityZonesJsonList)); } if(m_subnetIdsHasBeenSet) { Array<JsonValue> subnetIdsJsonList(m_subnetIds.size()); for(unsigned subnetIdsIndex = 0; subnetIdsIndex < subnetIdsJsonList.GetLength(); ++subnetIdsIndex) { subnetIdsJsonList[subnetIdsIndex].AsString(m_subnetIds[subnetIdsIndex]); } payload.WithArray("SubnetIds", std::move(subnetIdsJsonList)); } if(m_ec2InstanceIdsHasBeenSet) { Array<JsonValue> ec2InstanceIdsJsonList(m_ec2InstanceIds.size()); for(unsigned ec2InstanceIdsIndex = 0; ec2InstanceIdsIndex < ec2InstanceIdsJsonList.GetLength(); ++ec2InstanceIdsIndex) { ec2InstanceIdsJsonList[ec2InstanceIdsIndex].AsString(m_ec2InstanceIds[ec2InstanceIdsIndex]); } payload.WithArray("Ec2InstanceIds", std::move(ec2InstanceIdsJsonList)); } return payload; } } // namespace Model } // namespace OpsWorks } // namespace Aws
26.504717
134
0.747286
prateek-s
cddb8468720f583991230254e1f74bc09805831f
8,993
cpp
C++
src/engine/graphics/I3dMixer.cpp
gregtour/tedge-cpp
45f47ec7017d2124463430f1e584d9fb0dc8bdd8
[ "Apache-2.0" ]
1
2016-10-31T15:02:32.000Z
2016-10-31T15:02:32.000Z
src/engine/graphics/I3dMixer.cpp
gregtour/tedge-cpp
45f47ec7017d2124463430f1e584d9fb0dc8bdd8
[ "Apache-2.0" ]
null
null
null
src/engine/graphics/I3dMixer.cpp
gregtour/tedge-cpp
45f47ec7017d2124463430f1e584d9fb0dc8bdd8
[ "Apache-2.0" ]
1
2021-02-22T22:03:49.000Z
2021-02-22T22:03:49.000Z
/*---------------------------------------------------------------------------- I3D MIXER.CPP Copyright (c) 2011 eV Interactive, LLC contact: Matthew Harmon Matt@MatthewHarmon.com */ #include "SysLib.h" // Matt's operating system library #include "I3dMixer.h" #include "I3dAnim.h" #include "I3dModel.h" #include "I3dInstance.h" /*---------------------------------------------------------------------------- FRAME TO MAT4 Copied from QuatToMat4 Convert a quaternion to the corresponding (row major) 4X4 matrix. NOTE: s= 2.0 / ||q|| but since ||q|| = 1, then s = 2.0 */ MATRIX4* FrameToMat4( I3DBONEFRAME* f, MATRIX4* m) { QUAT* q = &f->rot; VECTOR3* p = &f->pos; VECTOR3* s = &f->scl; float x2; float y2; float z2; float wx2; float wy2; float wz2; float xx2; float xy2; float xz2; float yy2; float yz2; float zz2; // Precalcs to avoid duplication x2 = q->x * 2.0f; y2 = q->y * 2.0f; z2 = q->z * 2.0f; wx2 = q->w * x2; wy2 = q->w * y2; wz2 = q->w * z2; xx2 = q->x * x2; xy2 = q->x * y2; xz2 = q->x * z2; yy2 = q->y * y2; yz2 = q->y * z2; zz2 = q->z * z2; // Set the matrix m->e[0][0] = (1.0f - (yy2 + zz2)) * s->x; m->e[1][0] = (xy2 + wz2) * s->x; m->e[2][0] = (xz2 - wy2) * s->x; m->e[3][0] = p->x; m->e[0][1] = (xy2 - wz2) * s->y; m->e[1][1] = (1.0f - (xx2 + zz2)) * s->y; m->e[2][1] = (yz2 + wx2) * s->y; m->e[3][1] = p->y; m->e[0][2] = (xz2 + wy2) * s->z; m->e[1][2] = (yz2 - wx2) * s->z; m->e[2][2] = (1.0f - (xx2 + yy2)) * s->z; m->e[3][2] = p->z; m->e[0][3] = 0.0f; m->e[1][3] = 0.0f; m->e[2][3] = 0.0f; m->e[3][3] = 1.0f; return(m); } /*---------------------------------------------------------------------------- */ I3DMIXER::I3DMIXER( I3DMODEL* model, I3DINSTANCE* instance) { mModel = model; mInstance = instance; Stop(); } /*struct ANIMTRACK { I3DANIM* mAnim; I3D_PLAY_MODE mPlayMode; float mTime; int mFrame; float mFadeIn; float mFadeOut; float mTimeScale; };*/ /*---------------------------------------------------------------------------- */ int I3DMIXER::Play( I3DANIM* anim, I3D_PLAY_MODE mode, float weight, float fadeIn, float fadeOut, float seek) { int i; for (i=0; i<MAX_TRACKS; i++) { if (mAnimations[i].mAnim == NULL) { mAnimations[i].mAnim = anim; mAnimations[i].mWeight = weight; mAnimations[i].mFrame = 0; mAnimations[i].mPlayMode = mode; mAnimations[i].mTime = seek; mAnimations[i].mFadeIn = fadeIn; mAnimations[i].mFadeOut = fadeOut; mAnimations[i].mTimeScale = 1.0f; break; } } SlAssertEx(i < MAX_TRACKS, "Not enough animation playback tracks."); if (i == MAX_TRACKS) { return(SL_FAIL); } return(SL_SUCCESS); } /*---------------------------------------------------------------------------- */ void I3DMIXER::Clear( I3DANIM* anim) { int i; for (i=0; i<MAX_TRACKS; i++) { if (mAnimations[i].mAnim == anim) mAnimations[i].mAnim = NULL; } } /*---------------------------------------------------------------------------- */ void I3DMIXER::Stop() { int i; for (i=0; i<MAX_TRACKS; i++) { mAnimations[i].mAnim = NULL; } } /*---------------------------------------------------------------------------- */ void I3DMIXER::Update( float dt) { float animationWeight; MATRIX4* matrices; float* weights; int i; dt *= 10.0f; // process animation tracks matrices = mInstance->GetMatrixBuffer(); weights = mInstance->GetEmptyWeightBuffer(); // process all playing animations for (i=0; i<MAX_TRACKS; i++) { if (mAnimations[i].mAnim) { I3DANIM* anim = mAnimations[i].mAnim; SlAssert(anim); // advance animation mAnimations[i].mTime += mAnimations[i].mTimeScale * dt; if (mAnimations[i].mTime > anim->mAnimDuration) { if (mAnimations[i].mPlayMode == I3D_LOOP) { mAnimations[i].mTime -= anim->mAnimDuration; mAnimations[i].mFrame = 0; } else { mAnimations[i].mAnim = NULL; continue; } } // calculate weighting if (mAnimations[i].mTime < mAnimations[i].mFadeIn) animationWeight = mAnimations[i].mTime/mAnimations[i].mFadeIn; else if (mAnimations[i].mTime > mAnimations[i].mAnim->mAnimDuration - mAnimations[i].mFadeOut) animationWeight = (mAnimations[i].mAnim->mAnimDuration - mAnimations[i].mTime) / mAnimations[i].mFadeOut; else animationWeight = 1.0f; animationWeight *= mAnimations[i].mWeight; // find animation frames while (mAnimations[i].mFrame < anim->mNumFrames - 1) { if (mAnimations[i].mTime < anim->mKeyTimes[mAnimations[i].mFrame + 1]) break; mAnimations[i].mFrame++; } int nextFrame = (mAnimations[i].mFrame + 1) % anim->mNumFrames; float alpha = anim->GetBlendFactor(mAnimations[i].mFrame, nextFrame, mAnimations[i].mTime); I3DBONEFRAME blended; MATRIX4 local; // process all animated joints for (int j = 0; j < anim->mNumAnimBones; j++) { // blend each joint in the animation between the two frames I3DBONEFRAME* last = anim->GetBoneFrame(j, mAnimations[i].mFrame); I3DBONEFRAME* next = anim->GetBoneFrame(j, nextFrame); blended.pos = last->pos + (next->pos - last->pos) * alpha; QuatSlerp(&last->rot, &next->rot, alpha, &blended.rot); blended.scl = last->scl + (next->scl - last->scl) * alpha; // create a local transform matrix FrameToMat4(&blended, &local); // linearly blend with other animations int* indices = mModel->RetargetAnimation(mAnimations[i].mAnim); int index = indices[j]; // be sure the mapping is in bounds if (index >= 0 && index < mModel->mSkeleton->GetNumBones()) { float total = weights[index] + animationWeight; float beta = animationWeight / total; Mat4Lerp(&local, &matrices[index], beta, &matrices[index]); weights[index] = total; } } } } // create world transforms I3DBONE* parent = mModel->GetRootBone(); TransformRecursive(parent, matrices, weights, NULL); } /*---------------------------------------------------------------------------- */ void I3DMIXER::TransformRecursive( I3DBONE* bone, MATRIX4* matrices, float* weights, MATRIX4* globalTransform) { MATRIX4 temp; int boneId = mModel->GetBoneId(bone); //SlMemCpy(&temp, &matrices[boneId], sizeof(MATRIX4)); Mat4Copy(&temp, &matrices[boneId]); if (globalTransform) { Mat4Mul( &matrices[boneId],globalTransform, &temp); if (weights[boneId] > 0.1f) { Mat4Mul(&bone->mOffsetMat, &temp, &matrices[boneId]); } else { matrices[boneId] = temp; } } globalTransform = &temp;//&matrices[boneId]; bone = bone->mFirstChild; while (bone) { TransformRecursive(bone, matrices, weights, globalTransform); bone = bone->mNextSibling; } }
27.842105
122
0.421439
gregtour
cddc7d8d364725a991801cf57090ec813ce53841
1,528
cpp
C++
src/source/shader/ShadowMapProjectionTextureShader.cpp
Gregjksmith/Global-Illumination
c8a2c98f3f9b810df18c49956e723a2df9b27a40
[ "MIT" ]
null
null
null
src/source/shader/ShadowMapProjectionTextureShader.cpp
Gregjksmith/Global-Illumination
c8a2c98f3f9b810df18c49956e723a2df9b27a40
[ "MIT" ]
null
null
null
src/source/shader/ShadowMapProjectionTextureShader.cpp
Gregjksmith/Global-Illumination
c8a2c98f3f9b810df18c49956e723a2df9b27a40
[ "MIT" ]
null
null
null
#include "shader/ShadowMapProjectionTextureShader.h" ShadowMapProjectionTextureShader::ShadowMapProjectionTextureShader() { shaderType = SHADER_TYPE_SHADOW_MAP_PROJECTION_TEXTURE; addMain(SHADER_SOURCE_SHADOW_MAP_PROJECTION_TEXTURE_VERT, __shaderLinesVert); include(SHADER_MATERIAL_UTILS, __shaderLinesVert); include(SHADER_MATRIX_UTILS, __shaderLinesVert); include(SHADER_BRDF_UTILS, __shaderLinesVert); include(SHADER_ENVIRONMENT_MAP_UTILS, __shaderLinesVert); addMain(SHADER_SOURCE_SHADOW_MAP_PROJECTION_TEXTURE_GEOM, __shaderLinesGeom); include(SHADER_MATRIX_UTILS, __shaderLinesGeom); addMain(SHADER_SOURCE_SHADOW_MAP_PROJECTION_TEXTURE_FRAG, __shaderLinesFrag); include(SHADER_MATRIX_UTILS, __shaderLinesFrag); include(SHADER_GEOMETRY_UTILS, __shaderLinesFrag); include(SHADER_MATERIAL_UTILS, __shaderLinesFrag); include(SHADER_SHADOW_MAP_UTILS, __shaderLinesFrag); include(SHADER_LIGHT_UTILS, __shaderLinesFrag); include(SHADER_RANDOM_UTILS, __shaderLinesFrag); include(SHADER_BRDF_UTILS, __shaderLinesFrag); constructShader(); GLchar** attributes = new GLchar*[8]; attributes[0] = "position"; attributes[1] = "color"; attributes[2] = "normal"; attributes[3] = "materialIndex"; attributes[4] = "textureCoord"; attributes[5] = "basisX"; attributes[6] = "basisZ"; attributes[7] = "vertIndex"; addAttributes(attributes, 8); linkProgram(); setPrimitiveType(GL_TRIANGLES); } ShadowMapProjectionTextureShader::~ShadowMapProjectionTextureShader() { }
35.534884
79
0.803665
Gregjksmith
cde28c2219a8c4e42942ba829b2b2daed3897b37
18,531
cpp
C++
sketchbook/libraries/MRduinoWireless/mrduino.cpp
technoman72/BlocklyArduino_electrified
b91c1d37313ba5f5d0065e8cb264e7d7b45eb2e9
[ "MIT" ]
null
null
null
sketchbook/libraries/MRduinoWireless/mrduino.cpp
technoman72/BlocklyArduino_electrified
b91c1d37313ba5f5d0065e8cb264e7d7b45eb2e9
[ "MIT" ]
null
null
null
sketchbook/libraries/MRduinoWireless/mrduino.cpp
technoman72/BlocklyArduino_electrified
b91c1d37313ba5f5d0065e8cb264e7d7b45eb2e9
[ "MIT" ]
null
null
null
/** ****************************************************************************** * @file mrduino.cpp * @author Mace Robotics * @version 0.21 * @date 08/06/2017 * @brief lib for MRduino robot an MRduino Wireless * *******************************************************************************/ #include <Arduino.h> #include <math.h> #include <assert.h> #include "mrduino.h" static void forwardControl(int speed, int distance); static void backControl(int speed, int distance); static void turnRightControl(int speed, int angle); static void turnLeftControl(int speed, int angle); static boolean state_control = false; void initRobot() { Serial.begin(115200); controlDisable(); delay(0.5); } /********************************************************** * @brief led * @param None * @retval None **********************************************************/ void led(int led, int state) { String commande; commande = "#LED," + String(led) + "," + String(state) + "!"; Serial.println(commande); } /********************************************************** * @brief ledToggle * @param None * @retval None **********************************************************/ void ledToggle(int led) { String commande; commande = "#LEDT," + String(led) + "!"; Serial.println(commande); } /********************************************************** * @brief firmwareVersion * @param None * @retval None **********************************************************/ float firmwareVersion() { String commande; commande = "#FV!"; Serial.println(commande); return(readFloatData()); } /********************************************************** * @brief battery * @param None * @retval None **********************************************************/ float battery() { String commande; commande = "#BAT!"; Serial.println(commande); return(readFloatData()); } /********************************************************** * @brief battery * @param None * @retval None **********************************************************/ float temperature() { String commande; commande = "#TE!"; Serial.println(commande); return(readFloatData()); } /********************************************************** * @brief readSwitch * @param None * @retval None **********************************************************/ int readSwitch() { String commande; commande = "#SW!"; Serial.println(commande); return(readData()); } /********************************************************** * @brief irReceiver * @param None * @retval None **********************************************************/ int irReceiver() { String commande; commande = "#RC5!"; Serial.println(commande); return(readData()); } /********************************************************** * @brief motorRight * @param speed ( 0 to 100 ) * @retval None **********************************************************/ void motorRight(int speed, int direction) { String commande; commande = "#MOTR," + String(direction) + "," + String(speed) + "!"; Serial.println(commande); } /********************************************************** * @brief motorRight * @param speed ( 0 to 100 ) * @retval None **********************************************************/ void motorLeft(int speed, int direction) { String commande; commande = "#MOTL," + String(direction) + "," + String(speed) + "!"; Serial.println(commande); } /********************************************************** * @brief forward * @param speed ( 0 to 100 ) * @retval None **********************************************************/ void forward(int speed) { String commande; commande = "#MF," + String(speed) + "!"; Serial.println(commande); //forwardControl(speed, 9999); } /********************************************************** * @brief forwardC (forward with control) * @param speed ( 0 to 100 ) * @retval None **********************************************************/ void forwardC(int speed, int distance) { String commande; int state = 0; commande = "#MFC," + String(distance) + "," + String(speed) + "!"; Serial.println(commande); while(state != 3) { Serial.println("#TGS,1!"); Serial.println(state); state = readData(); } } /********************************************************** * @brief forward_mm (forward with control) * @param speed ( 0 to 100 ), distance millimeter * @retval None **********************************************************/ void forward_mm(int speed, int distance) { forwardC(speed, distance*4); } /********************************************************** * @brief back_mm (forward with control) * @param speed ( 0 to 100 ), distance millimeter * @retval None **********************************************************/ void back_mm(int speed, int distance) { backC(speed, distance*4); } /********************************************************** * @brief backC (back with control) * @param speed ( 0 to 100 ) * @retval None **********************************************************/ void backC(int speed, int distance) { String commande; int state = 0; commande = "#MBC," + String(distance) + "," + String(speed) + "!"; Serial.println(commande); while(state != 3) { Serial.println("#TGS,1!"); Serial.println(state); state = readData(); } } /********************************************************** * @brief back * @param speed ( 0 to 100 ) * @retval None **********************************************************/ void back(int speed) { String commande; commande = "#MB," + String(speed) + "!"; Serial.println(commande); //backControl(speed, 9999); } /********************************************************** * @brief turnLeft * @param speed ( 0 to 100 ) * @retval None **********************************************************/ void turnLeft(int speed) { String commande; commande = "#TL," + String(speed) + "!"; Serial.println(commande); } /********************************************************** * @brief turnLeftC * @param speed ( 0 to 100 ) * @retval None **********************************************************/ void turnLeftC(int speed, int distance) { String commande; int state = 0; commande = "#TLC," + String(distance) + "," + String(speed) + "!"; Serial.println(commande); while(state != 3) { Serial.println("#TGS,2!"); Serial.println(state); state = readData(); } } /********************************************************** * @brief turnRight_degree * @param speed ( 0 to 100 ), angle (0 to 360) * @retval None **********************************************************/ void turnRight_degree(int speed, unsigned int angle) { float angle_degree = 0; int angle_turn; if((angle >= 0)&&(angle <= 360)) { angle_degree = (float)(angle*546.0); angle_degree = (float)(angle_degree/90.0); angle_turn = (int)(angle_degree); turnRightC(speed, angle_turn); } else { // error angle value } } /********************************************************** * @brief turnLeft_degree * @param speed ( 0 to 100 ), angle (0 to 360) * @retval None **********************************************************/ void turnLeft_degree(int speed, unsigned int angle) { float angle_degree = 0; int angle_turn; if((angle >= 0)&&(angle <= 360)) { angle_degree = (float)(angle*546.0); angle_degree = (float)(angle_degree/90.0); angle_turn = (int)(angle_degree); turnLeftC(speed, angle_turn); } else { // error angle value } } /********************************************************** * @brief turnRight * @param speed ( 0 to 100 ) * @retval None **********************************************************/ void turnRight(int speed) { String commande; commande = "#TR," + String(speed) + "!"; Serial.println(commande); //turnRightControl(speed,99999); } /********************************************************** * @brief turnRightC * @param speed ( 0 to 100 ) * @retval None **********************************************************/ void turnRightC(int speed, int distance) { String commande; int state = 0; commande = "#TRC," + String(distance) + "," + String(speed) + "!"; Serial.println(commande); while(state != 3) { Serial.println("#TGS,2!"); Serial.println(state); state = readData(); } } /********************************************************** * @brief proxSensor * @param speed ( 0 to 100 ) * @retval None **********************************************************/ int proxSensor(int number) { String commande; int data; commande = "#PROX," + String(number) + "!"; Serial.println(commande); data = readData(); return data; } /********************************************************** * @brief ambiantLight * @param * @retval None **********************************************************/ int ambiantLight(int number) { String commande; int data; commande = "#AL," + String(number) + "!"; Serial.println(commande); data = readData(); return data; } /********************************************************** * @brief groundSensor * @param * @retval None **********************************************************/ int groundSensor(int number) { String commande; int data; commande = "#GR," + String(number) + "!"; Serial.println(commande); data = readData(); return data; } /********************************************************** * @brief controlEnable * @param * @retval None **********************************************************/ void controlEnable() { if(state_control == false) { Serial.println("#CRE!"); state_control = true; } else { // error } } /********************************************************** * @brief controlDisable * @param * @retval None **********************************************************/ void controlDisable() { Serial.println("#CRD!"); state_control = false; } /********************************************************** * @brief stop * @param * @retval None **********************************************************/ void stop() { //Serial.println("#STP!"); if(state_control == true) { controlDisable(); } Serial.println("#STP!"); } /********************************************************** * @brief read encoder left * @param * @retval None **********************************************************/ int encoderLeft() { String commande; int data; commande = "#EDL!"; Serial.println(commande); data = readData(); return data; } /********************************************************** * @brief read encoder right * @param * @retval None **********************************************************/ int encoderRight() { String commande; int data; commande = "#EDR!"; Serial.println(commande); data = readData(); return data; } /********************************************************** * @brief acceleroX * @param None * @retval None **********************************************************/ float acceleroX() { String commande; commande = "#ACCX!"; Serial.println(commande); return(readFloatData()); } /********************************************************** * @brief acceleroY * @param None * @retval None **********************************************************/ float acceleroY() { String commande; commande = "#ACCY!"; Serial.println(commande); return(readFloatData()); } /********************************************************** * @brief acceleroZ * @param None * @retval None **********************************************************/ float acceleroZ() { String commande; commande = "#ACCZ!"; Serial.println(commande); return(readFloatData()); } /********************************************************** * @brief acceleroZ * @param None * @retval None **********************************************************/ void speakerEnable() { String commande; commande = "#SPE!"; Serial.println(commande); } /********************************************************** * @brief readData * @param * @retval None **********************************************************/ int readData() { char c=0; String readString; while (c != '\n') { if (Serial.available() >0) { c = Serial.read(); //gets one byte from serial buffer if ( c != '$') readString += c; //makes the string readString } } return readString.toInt(); } /********************************************************** * @brief readFloatData * @param * @retval None **********************************************************/ float readFloatData() { char c=0; String readString; while (c != '\n') { if (Serial.available() >0) { c = Serial.read(); //gets one byte from serial buffer if ( c != '$') readString += c; //makes the string readString } } return readString.toFloat(); } /********************************************************** * @brief forwardControl * @param speed ( 0 to 100 ) * @retval None **********************************************************/ static void forwardControl(int speed, int distance) { String commande; controlEnable(); if(state_control == true) { commande = "#MFC," + String(distance) + "," + String(speed) + "!"; Serial.println(commande); } } /********************************************************** * @brief backControl * @param speed ( 0 to 100 ) * @retval None **********************************************************/ static void backControl(int speed, int distance) { String commande; controlEnable(); if(state_control == true) { commande = "#MBC," + String(distance) + "," + String(speed) + "!"; Serial.println(commande); } } /********************************************************** * @brief turnRightControl * @param * @retval None **********************************************************/ static void turnRightControl(int speed, int angle) { String commande; controlEnable(); if(state_control == true) { commande = "#TRC," + String(angle) + "," + String(speed) + "!"; Serial.println(commande); } } /********************************************************** * @brief turnRightControl * @param * @retval None **********************************************************/ static void turnLeftControl(int speed, int angle) { String commande; controlEnable(); if(state_control == true) { commande = "#TLC," + String(angle) + "," + String(speed) + "!"; Serial.println(commande); } } /********************************************************** * @brief turn_degree * 90° * | * @param 180°<--- ----> 0° (0 to 360°) * @retval None **********************************************************/ void turn_degree(int speed, unsigned int angle) { float angle_Robot; float angle_Consigne; // read actual robot position angle_Robot = robotPositionOrientation(); // conversion en degree angle_Robot = (angle_Robot*180.0)/(3.14); angle_Consigne = angle - angle_Robot; if(angle >= angle_Robot) { turnLeft_degree(10,abs(angle_Consigne)); } else { turnRight_degree(10,abs(angle_Consigne)); } } /********************************************************** * @brief robotPositionX * @param * @retval None **********************************************************/ float robotPositionX() { String commande; commande = "#POX!"; Serial.println(commande); return(readFloatData()); } /********************************************************** * @brief robotPositionY * @param None * @retval None **********************************************************/ float robotPositionY() { String commande; commande = "#POY!"; Serial.println(commande); return(-readFloatData()); } /********************************************************** * @brief robotPositionOrientation * @param None * @retval None **********************************************************/ float robotPositionOrientation() { String commande; commande = "#POO!"; Serial.println(commande); return(readFloatData()); } /********************************************************** * @brief robotGo * @param coordonner X and coordonner Y * @retval None **********************************************************/ void robotGo(int speed, int coord_X, int coord_Y) { int distance; float temp; float angle, angle_Robot; float coord_X_Robot, coord_Y_Robot; float coord_X_Goal, coord_Y_Goal; controlEnable(); // read actual robot position coord_X_Robot = robotPositionX(); coord_Y_Robot = robotPositionY(); // read actual robot position angle_Robot = robotPositionOrientation(); // conversion en degree angle_Robot = (angle_Robot*180.0)/(3.14); // calcul goal coordonner coord_X_Goal = (float)(coord_X - coord_X_Robot); coord_Y_Goal = (float)(coord_Y - coord_Y_Robot); if(coord_Y_Goal > 0) { distance = sqrt(coord_X_Goal*coord_X_Goal + coord_Y_Goal*coord_Y_Goal); temp = (float)((float)coord_X_Goal/(float)distance); if(temp > 1.0) { temp = 1.0; } if(temp < -1.0) { temp = -1.0; } angle = acos(temp); } else { if(coord_X_Goal > 0) { distance = sqrt(coord_X_Goal*coord_X_Goal + coord_Y_Goal*coord_Y_Goal); temp = (float)((float)coord_Y_Goal/(float)distance); if(temp > 1.0) { temp = 1.0; } if(temp < -1.0) { temp = -1.0; } angle = asin(temp); } else { distance = sqrt(coord_X_Goal*coord_X_Goal + coord_Y_Goal*coord_Y_Goal); temp = (float)((float)coord_X_Goal/(float)distance); if(temp > 1.0) { temp = 1.0; } if(temp < -1.0) { temp = -1.0; } temp = asin(temp); angle = -(1.5707 - temp); } } // conversion en degree angle = (angle*180.0)/(3.14); if(angle < 0) { angle = angle + 360; } turn_degree(speed,angle); forwardC(speed, distance); controlDisable(); } // end file
20.098698
81
0.430954
technoman72
cde5352e2c988c741768b2a96ff4e99b38c49290
5,026
c++
C++
lib/toolkit/src/window.c++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
lib/toolkit/src/window.c++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
lib/toolkit/src/window.c++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
#include "window.h++" using namespace Scr; using namespace Scr::Tk; Window::Window(Uint _height, Uint _width, const DisplayStyle & _style)throw() :Widget(_height, _width, _style) { activeWidget = elements.end(); } Screen& Window::GetScreen()throw(ParentNotDefined) { return GetParent().GetScreen(); } Uint Window::GetAbsoluteColumn()throw(ParentNotDefined) { return GetParent().GetAbsoluteColumn() + position.col; } Uint Window::GetAbsoluteRow()throw(ParentNotDefined) { return GetParent().GetAbsoluteRow() + position.row; } void Window::SetStylesheet(Stylesheet* _styleSheet)throw() { Widget::SetStylesheet(_styleSheet); for(WidgetList::iterator i=elements.begin(); i!=elements.end();++i) (*i)->SetStylesheet(_styleSheet); } void Window::AddWidget(Widget& widget) throw(ParentAlreadySet, WidgetAlreadyAdded) { if(elements[&widget] != elements.end()) THROW(WidgetAlreadyAdded); widget.SetParent(*this); if(styleSheet) widget.SetStylesheet(styleSheet); elements.push_back(&widget); // each widget must recv. OnStart. activeWidget is set after // OnStart, so when it is set, certainly Window::OnStart() was // already called! if(activeWidget != elements.end()) widget.OnStart(); } void Window::DelWidget(Widget& widget) throw(WidgetNotPresent) { if (&widget==*activeWidget) PassFocusRequest(TabFocus); if(elements[&widget] == elements.end()) THROW(WidgetNotPresent); elements.remove(&widget); widget.ReParent(NULL); } RootWindow& Window::GetRootWindow()throw(ParentNotDefined) { return GetParent().GetRootWindow(); } void Window::RedrawRequest(Widget& widget)throw() { if(IsHidden()) return; if (parentWindow != this) // this is not a root win { GetParent().RedrawRequest(*this); } else { Screen & screen=GetScreen();// main screen WidgetList::iterator i; for (i=elements[&widget]; i!=elements.end ();++i) { if((*i)->IsHidden ()) continue; // working subscreen Screen * ss; try { ss = screen.CreateSubScreen ((*i)->GetRow (), (*i)->GetCol (), (*i)->GetHeight (), (*i)->GetWidth ()); } catch (Scr::Screen::SubscreenOutOfRange) { continue; } (*i)->OnRedraw (*ss); delete ss; } screen.Refresh(); } } void Window::RedrawRequest()throw() { if (! elements.empty()) RedrawRequest(**(elements.begin())); } void Window::PassFocusRequest(FocusPolicy focustype)throw() { if (!elements.empty()) { if(activeWidget != elements.end()) { (*activeWidget)->OnUnFocus(focustype); } ++activeWidget; if (activeWidget == elements.end()) { if(focustype == TabFocus) { parentWindow->PassFocusRequest(focustype); return; } activeWidget = elements.end(); return; } if((*activeWidget)->IsHidden ()) PassFocusRequest(focustype); else (*activeWidget)->OnFocus(focustype); } } void Window::SetActiveWidget(Widget &w) throw(WidgetNotPresent) { if(activeWidget != elements.end()) { if (&w==*activeWidget) return; (*activeWidget)->OnUnFocus(AllFocus); } activeWidget = elements[&w]; if(activeWidget == elements.end()) THROW(WidgetNotPresent); (*activeWidget)->OnFocus(AllFocus); } Widget& Window::GetActiveWidget()const throw(WidgetNotPresent) { if(activeWidget == elements.end()) THROW(WidgetNotPresent); return **activeWidget; } void Window::OnFocus(FocusPolicy focustype)throw() { if (elements.empty()) return; if(activeWidget == elements.end()) { activeWidget = elements.begin(); if(activeWidget != elements.end()) { (*activeWidget)->OnFocus(focustype); } else { parentWindow->PassFocusRequest(focustype); } } else { (*activeWidget)->OnFocus(focustype); } } void Window::OnUnFocus(FocusPolicy focustype)throw() { if(activeWidget != elements.end()) { (*activeWidget)->OnUnFocus(focustype); } } void Window::OnStart()throw() { WidgetList::iterator i; for (i=elements.begin(); i!=elements.end();++i) { (*i)->OnStart(); } activeWidget=elements.begin(); } void Window::OnResize()throw() { for(WidgetList::iterator i=elements.begin(); i!=elements.end();++i) (*i)->OnResize(); } void Window::OnRedraw(Screen& screen)throw() { screen << GetStyle() << Control::Clear; WidgetList::iterator i; for (i=elements.begin(); i!=elements.end();++i) { if((*i)->IsHidden()) continue; if ( (*i)->GetCol()+(*i)->GetWidth()>GetWidth()) continue; if ( (*i)->GetRow()+(*i)->GetHeight()>GetHeight()) continue; Screen * ss; try { ss = screen.CreateSubScreen((*i)->GetRow(), (*i)->GetCol(), (*i)->GetHeight(), (*i)->GetWidth()); } catch (Scr::Screen::SubscreenOutOfRange) { continue; } (*i)->OnRedraw(*ss); delete ss; } } void Window::OnKeyDown(Key key)throw() { if (activeWidget!=elements.end()) { (*activeWidget) ->OnKeyDown(key);//pass to activeWidget element; } } void Window::SetSize(const Size& _size)throw() { if(!parentWindow) return; Widget::SetSize(_size); }
20.598361
71
0.656188
maciek-27
cde617490869999f37f7cf53a124b02323ef6260
7,905
hpp
C++
src/Frontends/FrontendShmemIPC.hpp
VANDAL/Sigil2
67e0762201d79575a25bdfe59eab257d206cff39
[ "BSD-3-Clause" ]
null
null
null
src/Frontends/FrontendShmemIPC.hpp
VANDAL/Sigil2
67e0762201d79575a25bdfe59eab257d206cff39
[ "BSD-3-Clause" ]
3
2016-10-17T21:17:10.000Z
2017-02-23T18:14:52.000Z
src/Frontends/FrontendShmemIPC.hpp
mdlui/Sigil2
67e0762201d79575a25bdfe59eab257d206cff39
[ "BSD-3-Clause" ]
null
null
null
#ifndef SIGIL2_FRONTEND_SHMEM_IPC_H #define SIGIL2_FRONTEND_SHMEM_IPC_H #include "Core/SigiLog.hpp" #include "Core/Frontends.hpp" #include "CommonShmemIPC.h" #include "Common.hpp" #include <thread> #include <fcntl.h> #include <sys/mman.h> /** * Sigil2 receives events from external tools via an array of * shared memory buffers. The external tools fill the buffers as a * forked process. See CommonShmemIPC.h for details of these buffers. * * There should exist at least 2 buffers, so the external tool can fill a buffer * while Sigil2 reads from the other buffer. * The optimal amount of buffering done depends on the system resources * and the variation in the event processing backend. * * Named pipes are used for syncing buffering between Sigil2 and the external * tool. This allows each process to block when they cannot proceed, * as in the case of no empty buffers to write to (external tool) * or no full buffers to read from (Sigil2 backend). * Otherwise each process would require less efficient synchronization methods * such as spinning. * * XXX The term 'full' buffer is for historical reasons. A buffer does not * necessarily have to be full when used by Sigil2. There should be metadata * available to let Sigil2 know how many valid events are in the buffer. */ using SigiLog::warn; using SigiLog::fatal; namespace Cleanup { auto setCleanupDir(std::string dir) -> void; }; //end namespace Cleanup template <typename SharedData> class ShmemFrontend : public FrontendIface { const std::string ipcDir; const std::string emptyFifoName; const std::string fullFifoName; const std::string shmemName; int emptyfd; int fullfd; FILE *shmemfp; SharedData *shmem; /* IPC configuration */ CircularQueue<int, SIGIL2_IPC_BUFFERS> q; Sem filled{0}, emptied{SIGIL2_IPC_BUFFERS}; int lastBufferIdx; /* Keep track of which buffers are in use/ready */ std::thread eventLoop; /* Asynchronously manage external events */ public: ShmemFrontend(const std::string &ipcDir) : ipcDir (ipcDir) , emptyFifoName(ipcDir + "/" + SIGIL2_IPC_EMPTYFIFO_BASENAME + "-" + std::to_string(uid)) , fullFifoName (ipcDir + "/" + SIGIL2_IPC_FULLFIFO_BASENAME + "-" + std::to_string(uid)) , shmemName (ipcDir + "/" + SIGIL2_IPC_SHMEM_BASENAME + "-" + std::to_string(uid)) { initShMem(); emptyfd = createAndOpenNewFifo(emptyFifoName.c_str(), O_WRONLY); fullfd = createAndOpenNewFifo(fullFifoName.c_str(), O_RDONLY); /* asynchronously manage communications with the external tool */ eventLoop = std::thread{&ShmemFrontend::receiveEventsLoop, this}; FrontendIface::nameBase = [&]{ assert(lastBufferIdx < decltype(lastBufferIdx){SIGIL2_IPC_BUFFERS}); return shmem->nameBuffers[lastBufferIdx].names; }; } ~ShmemFrontend() override { /* All communication with the external tool * should be completed by destruction */ eventLoop.join(); disconnect(); } virtual auto acquireBuffer() -> EventBufferPtr override final { filled.P(); lastBufferIdx = q.dequeue(); /* can be negative to signal the end of the event stream */ assert(lastBufferIdx < decltype(lastBufferIdx){SIGIL2_IPC_BUFFERS}); if (lastBufferIdx < 0) return nullptr; else return EventBufferPtr(&(shmem->eventBuffers[lastBufferIdx])); } virtual auto releaseBuffer(EventBufferPtr eventBuffer) -> void override final { eventBuffer.release(); emptied.V(); /* Tell Valgrind that the buffer is empty again */ assert(lastBufferIdx < decltype(lastBufferIdx){SIGIL2_IPC_BUFFERS} && lastBufferIdx >= 0); writeEmptyFifo(lastBufferIdx); } private: auto initShMem() -> void { /* Initialize IPC between Sigil2 and the external tool */ shmemfp = fopen(shmemName.c_str(), "wb+"); if (shmemfp == nullptr) fatal(std::string("sigil2 shared memory file open failed -- ") + strerror(errno)); /* XXX From write(2) man pages: * * On Linux, write() (and similar system calls) will transfer at most * 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes * actually transferred. (This is true on both 32-bit and 64-bit * systems.) * * fwrite doesn't have this limitation */ auto init = std::make_unique<SharedData>(); int count = fwrite(init.get(), sizeof(SharedData), 1, shmemfp); if (count != 1) { fclose(shmemfp); fatal(std::string("sigil2 shared memory file write failed -- ") + strerror(errno)); } shmem = reinterpret_cast<SharedData *> (mmap(nullptr, sizeof(SharedData), PROT_READ | PROT_WRITE, MAP_SHARED, fileno(shmemfp), 0)); if (shmem == MAP_FAILED) { fclose(shmemfp); fatal(std::string("sigil2 mmap shared memory failed -- ") + strerror(errno)); } } auto createAndOpenNewFifo(const char *path, int flags) const -> int { if (mkfifo(path, 0600) < 0) { if (errno == EEXIST) { if (remove(path) != 0) fatal(std::string("sigil2 could not delete old fifos -- ") + strerror(errno)); if (mkfifo(path, 0600) < 0) fatal(std::string("sigil2 failed to create fifos -- ") + strerror(errno)); } else fatal(std::string("sigil2 failed to create fifos -- ") + strerror(errno)); } int fd = open(path, flags); if (fd < 0) fatal(std::string("sigil2 failed to open fifo: ") + path + " -- " + strerror(errno)); return fd; } auto disconnect() -> void { munmap(shmem, sizeof(SharedData)); fclose(shmemfp); close(emptyfd); close(fullfd); } auto readFullFifo() -> int { /* Reads from 'full' fifo and returns the data. * This is an index to the buffer array in the shared memory. * It implicitly informs Sigil2 that buffer[idx] has * been filled with events and can be consumed by * the Sigil2 backend. */ int full_data; int res = read(fullfd, &full_data, sizeof(full_data)); if (res == 0) fatal("Unexpected end of fifo"); else if (res < 0) fatal(std::string("could not read from full-fifo -- ") + strerror(errno)); return full_data; } auto writeEmptyFifo(unsigned idx) -> void { /* The 'idx' sent informs the external tool that buffer[idx] * has been consumed by the Sigil2 backend, * and that the external tool can now fill it with events again. */ int res = write(emptyfd, &idx, sizeof(idx)); if (res < 0) fatal(std::string("could not send empty buffer status -- ") + strerror(errno)); } auto receiveEventsLoop() -> void { /* main event loop for managing the event buffers */ bool finished = false; while (finished == false) { /* external tool sends event buffer metadata */ unsigned fromTool = readFullFifo(); emptied.P(); if (fromTool == SIGIL2_IPC_FINISHED) { finished = true; } else { assert(fromTool < decltype(fromTool){SIGIL2_IPC_BUFFERS} && fromTool >= 0); q.enqueue(fromTool); filled.V(); } } /* Signal the end of the event stream */ q.enqueue(-1); filled.V(); } }; #endif
32.530864
107
0.603416
VANDAL
cde8ff172043d03a9b7c2943efde0a0353f2f62b
12,761
cpp
C++
3rdParty/Aria/src/ArPTZConnector.cpp
bellonemauro/myARIAtestApp
8223b5833ccf37cf9f503337858a46544d36a19c
[ "Linux-OpenIB" ]
null
null
null
3rdParty/Aria/src/ArPTZConnector.cpp
bellonemauro/myARIAtestApp
8223b5833ccf37cf9f503337858a46544d36a19c
[ "Linux-OpenIB" ]
null
null
null
3rdParty/Aria/src/ArPTZConnector.cpp
bellonemauro/myARIAtestApp
8223b5833ccf37cf9f503337858a46544d36a19c
[ "Linux-OpenIB" ]
null
null
null
/* Adept MobileRobots Robotics Interface for Applications (ARIA) Copyright (C) 2004-2005 ActivMedia Robotics LLC Copyright (C) 2006-2010 MobileRobots Inc. Copyright (C) 2011-2015 Adept Technology, Inc. Copyright (C) 2016 Omron Adept Technologies, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at robots@mobilerobots.com or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960 */ #include <string> #include <vector> #include <sstream> #include "ArExport.h" #include "ariaUtil.h" #include "ariaInternal.h" #include "ArLog.h" #include "ArFunctor.h" #include "ArPTZ.h" #include "ArPTZConnector.h" #include "ArConfig.h" #include "ArRobot.h" #include "ArRobotParams.h" std::map<std::string, ArPTZConnector::PTZCreateFunc*> ArPTZConnector::ourPTZCreateFuncs; AREXPORT ArPTZConnector::ArPTZConnector(ArArgumentParser* argParser, ArRobot *robot) : myArgParser(argParser), myRobot(robot), myParseArgsCallback(this, &ArPTZConnector::parseArgs), myLogOptionsCallback(this, &ArPTZConnector::logOptions) //myPopulateRobotParamsCB(this, &ArPTZConnector::populateRobotParams) { myParseArgsCallback.setName("ArPTZConnector parse args callback"); myLogOptionsCallback.setName("ArPTZConnector log options callback"); Aria::addParseArgsCB(&myParseArgsCallback); Aria::addLogOptionsCB(&myLogOptionsCallback); //ArRobotParams::addPopulateParamsCB(&myPopulateRobotParamsCB); } AREXPORT ArPTZConnector::~ArPTZConnector() { ///@todo not in Aria but should be: Aria::remParseArgsCB(&myParseArgsCallback); ///@todo not in Aria but should be: Aria::remLogOptionsCB(&myLogOptionsCallback); ///@todo delete objects from myConnectedPTZs ///@todo depopulate parameter slots from any ArRobotParams object that called our populate callback. // ArRobotParams::remPopulateParamsCB(&myPopulateRobotParamsCB); } AREXPORT bool ArPTZConnector::connect() { // Copy ArRobot's default parameters: myParams.resize(Aria::getMaxNumPTZs()); if(myRobot) { if(myRobot->getRobotParams()) myParams = myRobot->getRobotParams()->getPTZParams(); else ArLog::log(ArLog::Normal, "ArPTZConnector: Warning: no robot parameters, cannot set defaults for the robot type or loaded from parameter file. (To do so, connect to robot before connecting to PTZs.)"); } else { ArLog::log(ArLog::Normal, "ArPTZConnector: Warning: cannot use defaults for specific robot type or get configuration from robot parameter file, no robot connection."); } // "arguments" are from program command line. "parameters"/"params" are from // robot parameter file(s) or ARIA's internal defaults (ArRobotTypes.cpp) myConnectedPTZs.reserve(myParams.size()); // index in myConnectedPTZs corresponds to index from parameters and command line options, but the ArPTZ* may be NULL if not connected. size_t i = 0; size_t picount = 0; //assert(myArguments.size() >= myParams.size()); for(std::vector<ArPTZParams>::iterator pi = myParams.begin(); pi != myParams.end(); ++pi, ++i, ++picount) { //printf("]] myArguments.size is %d, i is %d\n", myArguments.size(), i); if(i < myArguments.size()) { // printf("]] merging myArguments[%d] into myParams[%d]\n", i, picount); pi->merge(myArguments[i]); } if(pi->type == "" || pi->type == "none" || pi->connect == false) // this ptz # was not specified in any parameters, or it was but with false connect flag { //puts("null type or \"none\" type or false connect flag, not creating or connecting."); //printf("connectflag=%d\n", pi->connect); //myConnectedPTZs.push_back(NULL); continue; } ArLog::log(ArLog::Normal, "ArPTZConnector: Connecting to PTZ #%d (type %s)...", i+1, pi->type.c_str()); if(ourPTZCreateFuncs.find(pi->type) == ourPTZCreateFuncs.end()) { ArLog::log(ArLog::Terse, "ArPTZConnector: Error: unrecognized PTZ type \"%s\" for PTZ #%d", pi->type.c_str(), i+1); //myConnectedPTZs.push_back(NULL); return false; } PTZCreateFunc *func = ourPTZCreateFuncs[pi->type]; ArPTZ *ptz = func->invokeR(i, *pi, myArgParser, myRobot); if(!ptz) { ArLog::log(ArLog::Terse, "ArPTZConnector: Error connecting to PTZ #%d (type %s).", i+1, pi->type.c_str()); ArLog::log(ArLog::Normal, "ArPTZConnector: Try specifying -ptzType (and -ptzSerialPort, -ptzRobotAuxSerialPort or -ptzAddress) program arguments, or set type and connection options in your robot's parameter file. Run with -help for all connection program options."); //myConnectedPTZs.push_back(NULL); return false; } if(pi->serialPort != "" && pi->serialPort != "none") { // memory leak? who is responsible for destroying serial connection, do we // need to store it and destroy it in our destructor or a disconnectAll // function? std::string logname = pi->type; logname += " "; logname += i; logname += " control serial connection on "; logname += pi->serialPort; ArDeviceConnection *serCon = ArDeviceConnectionCreatorHelper::createSerialConnection(pi->serialPort.c_str(), NULL, logname.c_str()); ptz->setDeviceConnection(serCon); } else if(pi->robotAuxPort != -1) { ptz->setAuxPort(pi->robotAuxPort); } ptz->setInverted(pi->inverted); if(ptz->init()) ArLog::log(ArLog::Verbose, "ArPTZConnector: Sucessfully initialized %s PTZ #%d ", ptz->getTypeName(), i+1); else ArLog::log(ArLog::Normal, "ArPTZConnector: Warning: Error initializing PTZ #%d (%s)", i+1, ptz->getTypeName()); // Resize ConnectedPTZs vector so that we can place this framegrabber at its correct index, even if any previous // PTZs were not stored because of errors creating them or they are not present in parameters or program options. // Any new elements created here are set to NULL. myConnectedPTZs.resize(i+1, NULL); // Add this PTZ to the connected list at its proper index (matching its index in parameters or program options) myConnectedPTZs[i] = ptz; } return true; } bool ArPTZConnector::parseArgs() { if(!myArgParser) return false; return parseArgs(myArgParser); } bool ArPTZConnector::parseArgs(ArArgumentParser *parser) { // Store command-line arguments in myArguments. They will be merged into // parameters in connect(). // puts("]]] ArPTZConnector::parseArgs"); if(!parser) return false; // -1 is a special case, checks for arguments implied for first PTZ, e.g. // -ptzType is the same as -ptz1Type. // Then proceeds normally with 0 for the first ptz (-ptz1...). for(int i = -1; i < (int)getMaxNumPTZs(); ++i) { //printf("parse args for %d\n", i); if(!parseArgsFor(parser, i)) return false; } return true; } bool ArPTZConnector::parseArgsFor(ArArgumentParser *parser, int which) { ArPTZParams newargs; const char *type = NULL; const char *serialPort = NULL; int auxPort = -1; const char *address = NULL; int tcpPort = -1; bool inverted = false; std::stringstream prefixconcat; prefixconcat << "-ptz"; // If which is -1 then we check for just -ptz... with no number, but it is // same as first ptz ("-ptz1...") if(which >= 0) prefixconcat << which+1; if(which < 0) which = 0; std::string prefix = prefixconcat.str(); //printf("checking for arguments for PTZ #%lu with prefix %s (e.g. %s)\n", which, prefix.c_str(), (prefix+"Type").c_str()); if(parser->checkParameterArgumentString( (prefix+"Type").c_str(), &type) && type != NULL) { if(ourPTZCreateFuncs.find(type) == ourPTZCreateFuncs.end()) { ArLog::log(ArLog::Terse, "ArPTZConnector: Error parsing arguments: unrecognized PTZ type \"%s\" given with %sType.", type, prefix.c_str()); return false; } newargs.type = type; newargs.connect = true; newargs.connectSet = true; //printf("found command line argument %sType. set type to %s and set connect and connectSet to true for ptz %d.\n", prefix.c_str(), type, which); } size_t nConOpt = 0; if(parser->checkParameterArgumentString( (prefix+"SerialPort").c_str(), &serialPort) && serialPort != NULL) { ++nConOpt; newargs.serialPort = serialPort; //printf("got serial port %s\n", serialPort); } if(parser->checkParameterArgumentInteger( (prefix+"RobotAuxSerialPort").c_str(), &auxPort) && auxPort != -1) { ++nConOpt; newargs.robotAuxPort = auxPort; //printf("got aux port %d\n", auxPort); } if(parser->checkParameterArgumentString( (prefix+"Address").c_str(), &address) && address != NULL) { ++nConOpt; newargs.address = address; //printf("got address %s\n", address); } // only one of serial port, aux port or address can be given if(nConOpt > 1) { ArLog::log(ArLog::Terse, "ArPTZConnector: Error: Only one of %sSerialPort, %sRobotAuxSerialPort or %sAddress may be given to select connection.", prefix.c_str(), prefix.c_str(), prefix.c_str() ); return false; } if(parser->checkParameterArgumentInteger( (prefix+"TCPPort").c_str(), &tcpPort) && tcpPort != -1) { newargs.tcpPort = tcpPort; newargs.tcpPortSet = true; //printf("got tcp port %d\n", tcpPort); } bool wasSet = false; if(parser->checkArgument((prefix+"Inverted").c_str())) { newargs.inverted = true; newargs.invertedSet = true; //printf("got inverted %d\n", inverted); } if(parser->checkParameterArgumentBool( (prefix+"Inverted").c_str(), &inverted, &wasSet) && wasSet) { newargs.inverted = inverted; newargs.invertedSet = true; //printf("got inverted %d\n", inverted); } if((size_t)which >= myArguments.size()) { // try not to assume we will be called with regular increasing which parameters, // (though we probably will be) so resize and set rather than use push_back: //printf("setting new, resized myArguments[%d] to these new params.\n", which); myArguments.resize(which+1); } // merge these rather than replacing them -- don't replace items in existing // myArguments[which] if not set in newargs. //myArguments[which] = newargs; myArguments[which].merge(newargs); return true; } AREXPORT void ArPTZConnector::logOptions() const { ArLog::log(ArLog::Terse, "Common PTU and Camera PTZ options:\n"); ArLog::log(ArLog::Terse, "\t-ptzType <type>\tSelect PTZ/PTU type. Required. Available types are:"); for(std::map<std::string, PTZCreateFunc*>::const_iterator i = ourPTZCreateFuncs.begin(); i != ourPTZCreateFuncs.end(); ++i) { ArLog::log(ArLog::Terse, "\t\t%s", (*i).first.c_str()); } ArLog::log(ArLog::Terse, "\t\tnone"); ArLog::log(ArLog::Terse, "\t-ptzInverted <true|false>\tIf true, reverse tilt and pan axes for cameras mounted upside down."); ArLog::log(ArLog::Terse, "\nOnly one of the following sets of connection parameters may be given:"); ArLog::log(ArLog::Terse, "\nFor computer serial port connections:"); ArLog::log(ArLog::Terse, "\t-ptzSerialPort <port>\tSerial port name."); ArLog::log(ArLog::Terse, "\nFor Pioneer robot auxilliary serial port connections:"); ArLog::log(ArLog::Terse, "\t-ptzRobotAuxSerialPort <1|2|3>\tUse specified Pioneer robot auxilliary serial port."); ArLog::log(ArLog::Terse, "\nFor network connections:"); ArLog::log(ArLog::Terse, "\t-ptzAddress <address>\tNetwork address or hostname for network connection."); ArLog::log(ArLog::Terse, "\t-ptzTcpPort <port>\tTCP port number for network connections."); ArLog::log(ArLog::Terse, "\nParameters for multiple cameras/units may be given like: -ptz1Type, -ptz2Type, -ptz3Type, etc."); ArLog::log(ArLog::Terse, "Some PTZ/PTU types may accept additional type-specific options. Refer to option documentation text specific to those types."); } AREXPORT void ArPTZConnector::registerPTZType(const std::string& typeName, ArPTZConnector::PTZCreateFunc* func) { ourPTZCreateFuncs[typeName] = func; }
38.905488
272
0.692579
bellonemauro
cdefa2cef984b38c33810cdfa503ed7fb34d8849
457
cpp
C++
ABC_202_B.cpp
kamlesh012/AtCoder-Editorials
d54e20da49317298096810a5a045253a810621a2
[ "Unlicense" ]
null
null
null
ABC_202_B.cpp
kamlesh012/AtCoder-Editorials
d54e20da49317298096810a5a045253a810621a2
[ "Unlicense" ]
null
null
null
ABC_202_B.cpp
kamlesh012/AtCoder-Editorials
d54e20da49317298096810a5a045253a810621a2
[ "Unlicense" ]
null
null
null
//Piece of Cake #include <bits/stdc++.h> #define int long long #define mod 1000000007 #define rep(i,n,s) for(int i=0;i<n;i+=s) using namespace std; void solve() { string str; cin >> str; int n = str.length(); reverse(str.begin(), str.end()); rep(i, str.length(), 1) { if (str[i] == '6')str[i] = '9'; else if (str[i] == '9')str[i] = '6'; } cout << str << endl; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); }
16.925926
40
0.588621
kamlesh012
cdf245727f5093f09ec724f997e90ce38d22cb56
16,566
cpp
C++
Testing/lsqLeastSquare3DTest.cpp
carlosparaciari/LeastSquarePackage
811d48dd7e8ecd8972da44ea6c7210a3e5a1f343
[ "BSD-3-Clause" ]
null
null
null
Testing/lsqLeastSquare3DTest.cpp
carlosparaciari/LeastSquarePackage
811d48dd7e8ecd8972da44ea6c7210a3e5a1f343
[ "BSD-3-Clause" ]
null
null
null
Testing/lsqLeastSquare3DTest.cpp
carlosparaciari/LeastSquarePackage
811d48dd7e8ecd8972da44ea6c7210a3e5a1f343
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================= LeastSquaresPackage: A software package for estimating the rotation and translation of rigid bodies. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include "catch.hpp" #include "lsqCatchMain.h" #include "lsqLeastSquare3D.h" #include "lsqComputeRotation.h" #include <Eigen/Dense> #include <iostream> TEST_CASE( "Throw exception when we pop an element from empty array", "[add_remove_points]" ) { lsq::LeastSquare3D add_example; Eigen::Vector3d point_3D; SECTION( "Pop an element from the first vector" ) { REQUIRE_THROWS( point_3D = add_example.pop_point_first_vector() ); } SECTION( "Pop an element from the second vector" ) { REQUIRE_THROWS( point_3D = add_example.pop_point_second_vector() ); } } TEST_CASE( "Add 3D point to first and second set", "[add_remove_points]" ) { lsq::LeastSquare3D add_example; Eigen::Vector3d point_3D_in = {1,2,3}; Eigen::Vector3d point_3D_out; SECTION( "Add point to first vector and pop it out" ) { add_example.add_point_first_vector(point_3D_in); point_3D_out = add_example.pop_point_first_vector(); REQUIRE( point_3D_out == point_3D_in ); } SECTION( "Add point to second vector and pop it out" ) { add_example.add_point_second_vector(point_3D_in); point_3D_out = add_example.pop_point_second_vector(); REQUIRE( point_3D_out == point_3D_in ); } SECTION( "Check if the two vectors have same size when they are empty" ) { REQUIRE( add_example.same_number_of_points() == true ); } SECTION( "Check if the two vectors have same size when it is true" ) { add_example.add_point_first_vector(point_3D_in); add_example.add_point_second_vector(point_3D_in); REQUIRE( add_example.same_number_of_points() == true ); } SECTION( "Check if the two vectors have same size when it is false" ) { add_example.add_point_first_vector(point_3D_in); add_example.add_point_second_vector(point_3D_in); add_example.add_point_second_vector(point_3D_in); REQUIRE( add_example.same_number_of_points() == false ); } } TEST_CASE( "Compute centroid for the sets of points and update the set", "[centroids]" ) { lsq::LeastSquare3D centroid_example; Eigen::Vector3d point_3D_in; point_3D_in = {1.,0.,0.}; centroid_example.add_point_first_vector(point_3D_in); point_3D_in = {0.,1.,0.}; centroid_example.add_point_first_vector(point_3D_in); point_3D_in = {0.,0.,1.}; centroid_example.add_point_first_vector(point_3D_in); Eigen::Vector3d expected_centroid = {0.,0.,0.}; Eigen::Vector3d obtained_centroid; SECTION( "Get first centroid without having computed it" ) { obtained_centroid = centroid_example.get_centroid_first_vector(); REQUIRE( expected_centroid == obtained_centroid ); } SECTION( "Get second centroid without having computed it" ) { obtained_centroid = centroid_example.get_centroid_second_vector(); REQUIRE( expected_centroid == obtained_centroid ); } expected_centroid = {1./3., 1./3., 1./3.}; SECTION( "Compute first centroid and check it" ) { centroid_example.centroid_first_vector(); obtained_centroid = centroid_example.get_centroid_first_vector(); REQUIRE( expected_centroid == obtained_centroid ); } SECTION( "Compute again the first centroid and check that it does not change" ) { centroid_example.centroid_first_vector(); obtained_centroid = centroid_example.get_centroid_first_vector(); REQUIRE( expected_centroid == obtained_centroid ); } SECTION( "Compute second centroid and get an error (the second vector is empty)" ) { REQUIRE_THROWS( centroid_example.centroid_second_vector() ); } Eigen::Vector3d expected_point; Eigen::Vector3d obtained_point; std::vector<Eigen::Vector3d> expected_updated_first_vector; expected_updated_first_vector.push_back( Eigen::Vector3d( {0.-1./3., 0.-1./3., 1.-1./3.} ) ); expected_updated_first_vector.push_back( Eigen::Vector3d( {0.-1./3., 1.-1./3., 0.-1./3.} ) ); expected_updated_first_vector.push_back( Eigen::Vector3d( {1.-1./3., 0.-1./3., 0.-1./3.} ) ); SECTION( "Update the first set of points around the centroid" ) { centroid_example.centroid_first_vector(); centroid_example.update_first_points_around_centroid(); for(int i = 0 ; i < 3 ; ++i) { obtained_point = centroid_example.pop_point_first_vector(); expected_point = expected_updated_first_vector[i]; REQUIRE( expected_point == obtained_point ); } } SECTION( "Updating the second set of points around the centroid gives an error since it is empty" ) { REQUIRE_THROWS( centroid_example.update_second_points_around_centroid() ); } } TEST_CASE( "Compute the H matrix for the problem", "[H_matrix]" ) { lsq::LeastSquare3D H_matrix_example; Eigen::Vector3d point_one; Eigen::Vector3d point_two; Eigen::Matrix3d obtained_matrix; Eigen::Matrix3d expected_matrix = Eigen::Matrix3d::Zero(3, 3); SECTION( "Return the H matrix without compute it." ) { obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "No element in both sets of points." ) { REQUIRE_THROWS( H_matrix_example.compute_H_matrix() ); } SECTION( "No element in first sets of points." ) { point_two = {1.,0.,0.}; H_matrix_example.add_point_second_vector(point_two); REQUIRE_THROWS( H_matrix_example.compute_H_matrix() ); } SECTION( "No element in second sets of points." ) { point_one = {1.,0.,0.}; H_matrix_example.add_point_first_vector(point_one); REQUIRE_THROWS( H_matrix_example.compute_H_matrix() ); } SECTION( "One element in each set of points: xx case" ) { point_one = {1.,0.,0.}; point_two = {1.,0.,0.}; expected_matrix(0,0) = 1; H_matrix_example.add_point_first_vector(point_one); H_matrix_example.add_point_second_vector(point_two); H_matrix_example.compute_H_matrix(); obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "One element in each set of points: xy case" ) { point_one = {1.,0.,0.}; point_two = {0.,1.,0.}; expected_matrix(0,1) = 1; H_matrix_example.add_point_first_vector(point_one); H_matrix_example.add_point_second_vector(point_two); H_matrix_example.compute_H_matrix(); obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "One element in each set of points: xz case" ) { point_one = {1.,0.,0.}; point_two = {0.,0.,1.}; expected_matrix(0,2) = 1; H_matrix_example.add_point_first_vector(point_one); H_matrix_example.add_point_second_vector(point_two); H_matrix_example.compute_H_matrix(); obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "One element in each set of points: yx case" ) { point_one = {0.,1.,0.}; point_two = {1.,0.,0.}; expected_matrix(1,0) = 1; H_matrix_example.add_point_first_vector(point_one); H_matrix_example.add_point_second_vector(point_two); H_matrix_example.compute_H_matrix(); obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "One element in each set of points: yy case" ) { point_one = {0.,1.,0.}; point_two = {0.,1.,0.}; expected_matrix(1,1) = 1; H_matrix_example.add_point_first_vector(point_one); H_matrix_example.add_point_second_vector(point_two); H_matrix_example.compute_H_matrix(); obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "One element in each set of points: yz case" ) { point_one = {0.,1.,0.}; point_two = {0.,0.,1.}; expected_matrix(1,2) = 1; H_matrix_example.add_point_first_vector(point_one); H_matrix_example.add_point_second_vector(point_two); H_matrix_example.compute_H_matrix(); obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "One element in each set of points: zx case" ) { point_one = {0.,0.,1.}; point_two = {1.,0.,0.}; expected_matrix(2,0) = 1; H_matrix_example.add_point_first_vector(point_one); H_matrix_example.add_point_second_vector(point_two); H_matrix_example.compute_H_matrix(); obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "One element in each set of points: zy case" ) { point_one = {0.,0.,1.}; point_two = {0.,1.,0.}; expected_matrix(2,1) = 1; H_matrix_example.add_point_first_vector(point_one); H_matrix_example.add_point_second_vector(point_two); H_matrix_example.compute_H_matrix(); obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "One element in each set of points: zz case" ) { point_one = {0.,0.,1.}; point_two = {0.,0.,1.}; expected_matrix(2,2) = 1; H_matrix_example.add_point_first_vector(point_one); H_matrix_example.add_point_second_vector(point_two); H_matrix_example.compute_H_matrix(); obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "Two element in first set, one in the second." ) { point_one = {1.,0.,0.}; H_matrix_example.add_point_first_vector(point_one); point_two = {1.,0.,0.}; H_matrix_example.add_point_second_vector(point_two); point_one = {0.,1.,0.}; H_matrix_example.add_point_first_vector(point_one); expected_matrix(0,0) = 1; H_matrix_example.compute_H_matrix(); obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "Two element in first set, two in the second." ) { point_one = {1.,0.,0.}; H_matrix_example.add_point_first_vector(point_one); point_two = {1.,0.,0.}; H_matrix_example.add_point_second_vector(point_two); expected_matrix(0,0) = 1; point_one = {0.,1.,0.}; H_matrix_example.add_point_first_vector(point_one); point_two = {0.,0.,1.}; H_matrix_example.add_point_second_vector(point_two); expected_matrix(1,2) = 1; H_matrix_example.compute_H_matrix(); obtained_matrix = H_matrix_example.get_H_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } } TEST_CASE( "Set the algorithm we use for computing the rotation", "[set_strategy]" ) { lsq::LeastSquare3D strategy_example; std::unique_ptr<lsq::ComputeRotation> algorithm( new lsq::SVDMethod() ); SECTION( "Check that the pointer algorithm is not empty." ) { if( !algorithm ) { REQUIRE(false); } REQUIRE(true); } SECTION( "Check that the pointer to the selected algorithm in the class is empty." ) { if( strategy_example.is_rotation_strategy() ) { REQUIRE(false); } REQUIRE(true); } strategy_example.set_rotation_strategy( std::move(algorithm) ); SECTION( "Check that the pointer algorithm is empty." ) { if( algorithm ) { REQUIRE(false); } REQUIRE(true); } SECTION( "Check that the pointer to the selected algorithm in the class is not empty." ) { if( !strategy_example.is_rotation_strategy() ) { REQUIRE(false); } REQUIRE(true); } } TEST_CASE( "Compute the rotation matrix for the problem", "[R_matrix]" ) { lsq::LeastSquare3D rotation_example; Eigen::Matrix3d obtained_matrix; Eigen::Matrix3d expected_matrix = Eigen::Matrix3d::Zero(3, 3); SECTION( "Return the rotation without computing it." ) { obtained_matrix = rotation_example.get_rotation_matrix(); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "Compute the rotation with the SVDMethod, without first computing H." ) { std::unique_ptr<lsq::ComputeRotation> algorithm( new lsq::SVDMethod() ); rotation_example.set_rotation_strategy( std::move(algorithm) ); rotation_example.compute_rotation_matrix(); obtained_matrix = rotation_example.get_rotation_matrix(); expected_matrix = Eigen::Matrix3d::Identity(3, 3); REQUIRE( expected_matrix == obtained_matrix ); } SECTION( "Compute the rotation with the QuaternionMethod, without first computing H." ) { std::unique_ptr<lsq::ComputeRotation> newalgorithm( new lsq::QuaternionMethod() ); rotation_example.set_rotation_strategy( std::move(newalgorithm) ); rotation_example.compute_rotation_matrix(); obtained_matrix = rotation_example.get_rotation_matrix(); expected_matrix = Eigen::Matrix3d::Identity(3, 3); REQUIRE( expected_matrix == obtained_matrix ); } Eigen::Vector3d point_3D; point_3D = {1.,0.,0.}; rotation_example.add_point_first_vector(point_3D); point_3D = {0.,1.,0.}; rotation_example.add_point_first_vector(point_3D); point_3D = {0.,0.,1.}; rotation_example.add_point_first_vector(point_3D); point_3D = {1.,0.,0.}; rotation_example.add_point_second_vector(point_3D); point_3D = {0.,0.,-1.}; rotation_example.add_point_second_vector(point_3D); point_3D = {0.,1.,0.}; rotation_example.add_point_second_vector(point_3D); SECTION( "Properly compute the rotation with the SVDMethod." ) { std::unique_ptr<lsq::ComputeRotation> algorithm( new lsq::SVDMethod() ); rotation_example.set_rotation_strategy( std::move(algorithm) ); rotation_example.centroid_first_vector(); rotation_example.update_first_points_around_centroid(); rotation_example.centroid_second_vector(); rotation_example.update_second_points_around_centroid(); rotation_example.compute_H_matrix(); rotation_example.compute_rotation_matrix(); obtained_matrix = rotation_example.get_rotation_matrix(); expected_matrix(0,0) = 1.; expected_matrix(2,1) = -1.; expected_matrix(1,2) = 1.; REQUIRE( obtained_matrix.isApprox(expected_matrix,1.e-10) ); } SECTION( "Properly compute the rotation with the QuaternionMethod." ) { std::unique_ptr<lsq::ComputeRotation> newalgorithm( new lsq::QuaternionMethod() ); rotation_example.set_rotation_strategy( std::move(newalgorithm) ); rotation_example.add_point_second_vector(point_3D); rotation_example.centroid_first_vector(); rotation_example.update_first_points_around_centroid(); rotation_example.centroid_second_vector(); rotation_example.update_second_points_around_centroid(); rotation_example.compute_H_matrix(); rotation_example.compute_rotation_matrix(); obtained_matrix = rotation_example.get_rotation_matrix(); expected_matrix(0,0) = 1.; expected_matrix(2,1) = -1.; expected_matrix(1,2) = 1.; REQUIRE( obtained_matrix.isApprox(expected_matrix,1.e-10) ); } } TEST_CASE( "Compute the translation vector for the problem", "[translation_vector]" ) { lsq::LeastSquare3D translation_example; Eigen::Vector3d point_one; Eigen::Vector3d point_two; Eigen::Vector3d obtained_vector; Eigen::Vector3d expected_vector = Eigen::Vector3d::Zero(3); SECTION( "Return the translation without computing it." ) { obtained_vector = translation_example.get_translation_vector(); REQUIRE( expected_vector == obtained_vector ); } SECTION( "Compute the translation vector without computing centroids and rotation." ) { translation_example.compute_translation_vector(); obtained_vector = translation_example.get_translation_vector(); REQUIRE( expected_vector == obtained_vector ); } SECTION( "Compute the translation vector while computing the centroids (no rotation though)." ) { point_one = {1.,0.,0.}; translation_example.add_point_first_vector(point_one); translation_example.centroid_first_vector(); /* This first centroid should be useless since rotation is zero matrix. */ point_two = {0.,1.,0.}; translation_example.add_point_second_vector(point_two); translation_example.centroid_second_vector(); translation_example.compute_translation_vector(); obtained_vector = translation_example.get_translation_vector(); expected_vector = {0.,1.,0.}; REQUIRE( expected_vector == obtained_vector ); } }
33.399194
124
0.714415
carlosparaciari
cdf8919d846c0fb7c12c8ac13438c3aa758097fd
20,355
cpp
C++
Src/VC/bcgcbpro/BCGPAppointmentStorage.cpp
iclosure/smartsoft
62eaed49efd8306642b928ef4f2d96e36aca6527
[ "MIT" ]
null
null
null
Src/VC/bcgcbpro/BCGPAppointmentStorage.cpp
iclosure/smartsoft
62eaed49efd8306642b928ef4f2d96e36aca6527
[ "MIT" ]
null
null
null
Src/VC/bcgcbpro/BCGPAppointmentStorage.cpp
iclosure/smartsoft
62eaed49efd8306642b928ef4f2d96e36aca6527
[ "MIT" ]
1
2020-05-11T05:36:49.000Z
2020-05-11T05:36:49.000Z
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of BCGControlBar Library Professional Edition // Copyright (C) 1998-2012 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // // BCGPAppointmentStorage.cpp : implementation file // #include "stdafx.h" #include "BCGPAppointmentStorage.h" #ifndef BCGP_EXCLUDE_PLANNER #include "BCGPPlannerManagerCtrl.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CBCGPAppointmentBaseStorage IMPLEMENT_DYNAMIC(CBCGPAppointmentBaseStorage, CObject) ///////////////////////////////////////////////////////////////////////////// // CBCGPAppointmentBaseResourceInfo IMPLEMENT_DYNAMIC(CBCGPAppointmentBaseResourceInfo, CObject) ///////////////////////////////////////////////////////////////////////////// // CBCGPAppointmentBaseMultiStorage IMPLEMENT_DYNAMIC(CBCGPAppointmentBaseMultiStorage, CBCGPAppointmentBaseStorage) ///////////////////////////////////////////////////////////////////////////// // CBCGPAppointmentStorage IMPLEMENT_DYNCREATE(CBCGPAppointmentStorage, CBCGPAppointmentBaseStorage) CBCGPAppointmentStorage::CBCGPAppointmentStorage () : m_bAutoDelete (TRUE) , m_dwRecurrenceLastID (0) { } CBCGPAppointmentStorage::~CBCGPAppointmentStorage () { RemoveAll (); } BOOL CBCGPAppointmentStorage::Add (CBCGPAppointment* pApp) { ASSERT_VALID (pApp); if (pApp == NULL) { return FALSE; } if (pApp->IsRecurrence ()) { if (AddRecurrence (pApp)) { return TRUE; } } COleDateTime dtS (pApp->GetStart ()); COleDateTime dtF (pApp->GetFinish ()); int nYear = dtS.GetYear (); int nDay = dtS.GetDayOfYear (); XDayCollection* yearVal = NULL; m_Collection.Lookup (nYear, yearVal); if (yearVal == NULL) { yearVal = new XDayCollection; m_Collection.SetAt (nYear, yearVal); } XBCGPAppointmentList* dayVal = NULL; yearVal->Lookup (nDay, dayVal); if (dayVal == NULL) { dayVal = new XBCGPAppointmentList; yearVal->SetAt (nDay, dayVal); } BOOL bAdd = FALSE; POSITION pos = dayVal->GetTailPosition (); while (pos != NULL) { POSITION posPrev = pos; CBCGPAppointment* pAppPrev = dayVal->GetPrev (pos); COleDateTime dtPrevS (pAppPrev->GetStart ()); COleDateTime dtPrevF (pAppPrev->GetFinish ()); if (dtS.GetHour () == dtPrevS.GetHour () && dtS.GetMinute () == dtPrevS.GetMinute () && dtF.GetHour () == dtPrevF.GetHour () && dtF.GetMinute () == dtPrevF.GetMinute ()) { dayVal->InsertAfter (posPrev, pApp); bAdd = TRUE; break; } } if (!bAdd) { pos = dayVal->GetHeadPosition (); while (pos != NULL) { POSITION posPrev = pos; CBCGPAppointment* pAppNext = dayVal->GetNext (pos); COleDateTime dtNextS (pAppNext->GetStart ()); if (dtS.GetHour () < dtNextS.GetHour () || (dtS.GetHour () == dtNextS.GetHour () && dtS.GetMinute () < dtNextS.GetMinute ()) ) { dayVal->InsertBefore (posPrev, pApp); bAdd = TRUE; break; } } } if (!bAdd) { dayVal->AddTail (pApp); } if (!CBCGPPlannerView::IsOneDay (pApp->GetStart (), pApp->GetFinish ())) { m_CollectionMulti.Add (pApp); SortAppointments (m_CollectionMulti, (int) m_CollectionMulti.GetSize ()); } return TRUE; } BOOL CBCGPAppointmentStorage::Update (CBCGPAppointment* pApp, const COleDateTime& dtOld, BOOL bForceAdd/* = FALSE*/) { ASSERT_VALID (pApp); if (pApp == NULL) { return FALSE; } if (pApp->IsRecurrence ()) { if (UpdateRecurrence (pApp, dtOld)) { return TRUE; } } BOOL bDelete = IsAutoDelete (); SetAutoDelete (FALSE); COleDateTime dtS (pApp->GetStart ()); COleDateTime dtF (pApp->GetFinish ()); if (dtOld != COleDateTime ()) { pApp->SetInterval (dtOld, dtOld); } BOOL bFound = Remove (pApp); if (!bForceAdd && !bFound) { SetAutoDelete (bDelete); return FALSE; } pApp->SetInterval (dtS, dtF); Add (pApp); SetAutoDelete (bDelete); return TRUE; } BOOL CBCGPAppointmentStorage::Remove (CBCGPAppointment* pApp) { ASSERT_VALID (pApp); if (pApp == NULL) { return FALSE; } if (pApp->IsRecurrence ()) { if (RemoveRecurrence (pApp)) { return TRUE; } } COleDateTime dt (pApp->GetStart ()); int nYear = dt.GetYear (); int nDay = dt.GetDayOfYear (); XDayCollection* yearVal = NULL; m_Collection.Lookup (nYear, yearVal); if (yearVal == NULL) { return FALSE; } XBCGPAppointmentList* dayVal = NULL; yearVal->Lookup (nDay, dayVal); if (dayVal == NULL) { return FALSE; } POSITION pos = dayVal->Find (pApp); if (pos == NULL) { return FALSE; } dayVal->RemoveAt (pos); if (dayVal->GetCount () == 0) { delete dayVal; yearVal->RemoveKey (nDay); } if (yearVal->GetCount () == 0) { delete yearVal; m_Collection.RemoveKey (nYear); } for (int i = 0; i < m_CollectionMulti.GetSize (); i++) { if (m_CollectionMulti [i] == pApp) { m_CollectionMulti.RemoveAt (i); break; } } if (IsAutoDelete ()) { delete pApp; } return TRUE; } BOOL CBCGPAppointmentStorage::RemoveAllRecurrence () { POSITION pos = m_Recurrences.GetStartPosition (); while (pos != NULL) { DWORD nID = 0; CBCGPAppointment* pRecurrence = NULL; m_Recurrences.GetNextAssoc (pos, nID, pRecurrence); ASSERT_VALID (pRecurrence); if (pRecurrence != NULL) { if (IsAutoDelete ()) { delete pRecurrence; } } } m_Recurrences.RemoveAll (); return TRUE; } BOOL CBCGPAppointmentStorage::RemoveAll () { RemoveAllRecurrence (); POSITION yearPos = m_Collection.GetStartPosition (); int yearKey = 0; XDayCollection* yearVal = NULL; while (yearPos != NULL) { m_Collection.GetNextAssoc (yearPos, yearKey, yearVal); if (yearVal != NULL) { POSITION dayPos = yearVal->GetStartPosition (); int dayKey = 0; XBCGPAppointmentList* dayVal = NULL; while (dayPos != NULL) { yearVal->GetNextAssoc (dayPos, dayKey, dayVal); if (dayVal != NULL) { if (IsAutoDelete ()) { POSITION pos = dayVal->GetHeadPosition (); while (pos != NULL) { CBCGPAppointment* pApp = dayVal->GetNext (pos); if (pApp != NULL) { delete pApp; } } } dayVal->RemoveAll (); delete dayVal; } } yearVal->RemoveAll (); delete yearVal; } } m_Collection.RemoveAll (); m_CollectionMulti.RemoveAll (); return TRUE; } void CBCGPAppointmentStorage::Query (XBCGPAppointmentArray& ar, const COleDateTime& date1, const COleDateTime& date2) { ar.RemoveAll (); { POSITION pos = m_Recurrences.GetStartPosition (); while (pos != NULL) { DWORD nID = 0; CBCGPAppointment* pRecurrence = NULL; m_Recurrences.GetNextAssoc (pos, nID, pRecurrence); ASSERT_VALID (pRecurrence); if (pRecurrence != NULL) { XBCGPAppointmentArray arRec; pRecurrence->GetRecurrence ()->Query (arRec, date1, date2); ar.Append (arRec); } } } int nCount = (int)(date2 - date1).GetTotalDays () + 1; COleDateTime dt (date1); COleDateTimeSpan span (1, 0, 0, 0); int i = 0; for (i = 0; i < nCount; i++) { int nYear = dt.GetYear (); int nDay = dt.GetDayOfYear (); XDayCollection* yearVal = NULL; m_Collection.Lookup (nYear, yearVal); if (yearVal != NULL) { XBCGPAppointmentList* dayVal = NULL; yearVal->Lookup (nDay, dayVal); if (dayVal != NULL) { POSITION pos = dayVal->GetHeadPosition (); while (pos != NULL) { CBCGPAppointment* pApp = dayVal->GetNext (pos); if (pApp != NULL) { ar.Add (pApp); } } } } dt += span; } for (i = 0; i < m_CollectionMulti.GetSize (); i++) { CBCGPAppointment* pApp = m_CollectionMulti [i]; if (pApp->GetStart () < date1) { if ((date1 <= pApp->GetFinish () && pApp->GetFinish () <= date2) || date2 < pApp->GetFinish ()) { if (pApp->GetFinish () != COleDateTime (date1.GetYear (), date1.GetMonth (), date1.GetDay (), 0, 0, 0) || pApp->IsAllDay ()) { ar.Add (pApp); } } } else { break; } } if (ar.GetSize () > 0) { SortAppointments (ar, (int) ar.GetSize ()); } } void CBCGPAppointmentStorage::QueryAll (XBCGPAppointmentArray& ar) { for (POSITION posYear = m_Collection.GetStartPosition (); posYear != NULL;) { int nYear = -1; XDayCollection* yearVal = NULL; m_Collection.GetNextAssoc (posYear, nYear, yearVal); if (yearVal != NULL) { for (POSITION posDay = yearVal->GetStartPosition (); posDay != NULL;) { int nDay = -1; XBCGPAppointmentList* dayVal = NULL; yearVal->GetNextAssoc (posDay, nDay, dayVal); if (dayVal != NULL) { for (POSITION pos = dayVal->GetHeadPosition (); pos != NULL;) { CBCGPAppointment* pApp = dayVal->GetNext (pos); if (pApp != NULL) { ASSERT_VALID (pApp); ar.Add (pApp); } } } } } } for (POSITION pos = m_Recurrences.GetStartPosition (); pos != NULL;) { DWORD key = 0; CBCGPAppointment* pApp = NULL; m_Recurrences.GetNextAssoc (pos, key, pApp); if (pApp != NULL) { ASSERT_VALID (pApp); ar.Add (pApp); } } } BOOL CBCGPAppointmentStorage::IsEmpty () const { return m_Collection.IsEmpty (); } CBCGPAppointment* CBCGPAppointmentStorage::GetRecurrence (DWORD ID) const { CBCGPAppointment* pRecurrence = NULL; if (m_Recurrences.Lookup (ID, pRecurrence)) { return pRecurrence; } return NULL; } BOOL CBCGPAppointmentStorage::AddRecurrence (CBCGPAppointment* pApp) { ASSERT_VALID (pApp); ASSERT (pApp->IsRecurrence ()); if (pApp->IsRecurrenceClone ()) { CBCGPAppointment* pRecurrence = GetRecurrence (pApp->GetRecurrenceID ()); if (pRecurrence != NULL) { CBCGPAppointmentPropertyList props; pApp->GetProperties (props); pRecurrence->GetRecurrence ()-> DoException (pApp->GetRecurrenceDate (), props, FALSE); delete pApp; return TRUE; } } else { DWORD ID = pApp->GetRecurrenceID (); if (ID == 0) { m_dwRecurrenceLastID++; pApp->SetRecurrenceID (m_dwRecurrenceLastID); } else { if (m_dwRecurrenceLastID < ID) { m_dwRecurrenceLastID = ID; } } m_Recurrences[m_dwRecurrenceLastID] = pApp; return TRUE; } return FALSE; } BOOL CBCGPAppointmentStorage::RemoveRecurrence (CBCGPAppointment* pApp) { ASSERT_VALID (pApp); ASSERT (pApp->IsRecurrence ()); DWORD ID = pApp->GetRecurrenceID (); CBCGPAppointment* pRecurrence = GetRecurrence (ID); if (pApp->IsRecurrenceClone ()) { if (pRecurrence != NULL) { CBCGPAppointmentPropertyList props; pApp->GetProperties (props); pRecurrence->GetRecurrence ()-> DoException (pApp->GetRecurrenceDate (), props, TRUE); } delete pApp; } else { if (pRecurrence != NULL) { if (IsAutoDelete ()) { delete pRecurrence; } m_Recurrences.RemoveKey (ID); } } return TRUE; } BOOL CBCGPAppointmentStorage::UpdateRecurrence (CBCGPAppointment* pApp, const COleDateTime& /*dtOld*/) { ASSERT_VALID (pApp); ASSERT (pApp->IsRecurrence ()); if (pApp->IsRecurrenceClone ()) { CBCGPAppointment* pRecurrence = GetRecurrence (pApp->GetRecurrenceID ()); ASSERT_VALID (pRecurrence); CBCGPAppointmentPropertyList props; pApp->GetProperties (props); pRecurrence->GetRecurrence ()-> DoException (pApp->GetRecurrenceDate (), props, FALSE); //delete pApp; } return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CBCGPAppointmentMultiStorage IMPLEMENT_DYNCREATE(CBCGPAppointmentMultiStorage, CBCGPAppointmentBaseMultiStorage) CBCGPAppointmentMultiStorage::CBCGPAppointmentMultiStorage () : m_CurrentResourceID (e_UnknownResourceID) { } CBCGPAppointmentMultiStorage::~CBCGPAppointmentMultiStorage () { POSITION pos = m_ResourceCollection.GetStartPosition (); UINT nResourceID = 0; XResource* pResource = NULL; while (pos != NULL) { m_ResourceCollection.GetNextAssoc (pos, nResourceID, pResource); if (pResource != NULL) { delete pResource; pResource = NULL; } } } BOOL CBCGPAppointmentMultiStorage::AddStorage (UINT nResourceID, CBCGPAppointmentBaseStorage* pStorage, CBCGPAppointmentBaseResourceInfo* pInfo/* = NULL*/, BOOL bAutoDelete /*= TRUE*/) { if (nResourceID == e_UnknownResourceID) { ASSERT (FALSE); return FALSE; } ASSERT_VALID (pStorage); if (pStorage == NULL) { return FALSE; } XResource* pResource = LookupResource (nResourceID); if (pResource != NULL) { ASSERT (FALSE); return FALSE; } pResource = new XResource (pStorage, pInfo, bAutoDelete); if (m_ResourceCollection.IsEmpty ()) { m_CurrentResourceID = nResourceID; } m_ResourceCollection[nResourceID] = pResource; return TRUE; } BOOL CBCGPAppointmentMultiStorage::RemoveStorage (UINT nResourceID) { XResource* pResource = LookupResource (nResourceID); if (pResource == NULL) { ASSERT (FALSE); return FALSE; } if (m_ResourceCollection.RemoveKey (nResourceID)) { delete pResource; if (m_CurrentResourceID == nResourceID) { m_CurrentResourceID = e_UnknownResourceID; } return TRUE; } return FALSE; } CBCGPAppointmentBaseStorage* CBCGPAppointmentMultiStorage::GetStorage (UINT nResourceID) const { XResource* pResource = LookupResource (nResourceID); if (pResource == NULL) { ASSERT (FALSE); return NULL; } return pResource->m_pStorage; } int CBCGPAppointmentMultiStorage::GetCount () const { return (int) m_ResourceCollection.GetCount (); } const int c_MAXSTACK = 2048; const int c_HT_PREC = 4; inline int CompareResourceID (UINT nResource1, UINT nResource2) { if (nResource1 < nResource2) { return -1; } else if (nResource2 < nResource1) { return 1; } return 0; } void SortResourceIDs (CBCGPAppointmentMultiStorage::XResourceIDArray& a, int size) { int i, j; int lb, ub; int lbstack[c_MAXSTACK], ubstack[c_MAXSTACK]; int stackpos = 1; int ppos; UINT pivot = 0; lbstack[1] = 0; ubstack[1] = size-1; do { lb = lbstack[stackpos]; ub = ubstack[stackpos]; stackpos--; do { ppos = (lb + ub) >> 1; i = lb; j = ub; pivot = a[ppos]; do { while (CompareResourceID (a[i], pivot) == -1) i++; while (CompareResourceID (pivot, a[j]) == -1) j--; if (i <= j) { if (i < j) { UINT temp = a[i]; a[i] = a[j]; a[j] = temp; } i++; j--; } } while (i <= j); if (i < ppos) { if (i < ub) { stackpos++; lbstack[ stackpos ] = i; ubstack[ stackpos ] = ub; } ub = j; } else { if (j > lb) { stackpos++; lbstack[ stackpos ] = lb; ubstack[ stackpos ] = j; } lb = i; } } while (lb < ub); } while ( stackpos != 0 ); } void CBCGPAppointmentMultiStorage::GetResourceIDs (XResourceIDArray& ar) const { ar.RemoveAll (); POSITION pos = m_ResourceCollection.GetStartPosition (); UINT nResourceID = 0; XResource* pResource = NULL; while (pos != NULL) { m_ResourceCollection.GetNextAssoc (pos, nResourceID, pResource); ar.Add (nResourceID); } SortResourceIDs (ar, (int) ar.GetSize ()); } const CBCGPAppointmentBaseResourceInfo* CBCGPAppointmentMultiStorage::GetResourceInfo (UINT nResourceID) const { XResource* pResource = LookupResource (nResourceID); if (pResource == NULL) { ASSERT (FALSE); return NULL; } return pResource->m_pResourceInfo; } CBCGPAppointmentMultiStorage::XResource* CBCGPAppointmentMultiStorage::LookupResource (UINT nResourceID) const { XResource* pResource = NULL; m_ResourceCollection.Lookup (nResourceID, pResource); return pResource; } BOOL CBCGPAppointmentMultiStorage::SetCurrentResourceID (UINT nResourceID) { if (nResourceID != e_UnknownResourceID) { if (LookupResource (nResourceID) == NULL) { return FALSE; } } m_CurrentResourceID = nResourceID; return TRUE; } UINT CBCGPAppointmentMultiStorage::GetCurrentResourceID () const { return m_CurrentResourceID; } BOOL CBCGPAppointmentMultiStorage::Add (CBCGPAppointment* pApp) { ASSERT_VALID (pApp); if (pApp == NULL) { return FALSE; } UINT nResourceID = GetCurrentResourceID (); if (pApp->GetResourceID () != e_UnknownResourceID) { nResourceID = pApp->GetResourceID (); } CBCGPAppointmentBaseStorage* pStorage = GetStorage (nResourceID); if (pStorage == NULL) { return FALSE; } pApp->SetResourceID (nResourceID); return pStorage->Add (pApp); } BOOL CBCGPAppointmentMultiStorage::Update (CBCGPAppointment* pApp, const COleDateTime& dtOld, BOOL bForceAdd/* = FALSE*/) { ASSERT_VALID (pApp); if (pApp == NULL) { return FALSE; } UINT nResourceID = GetCurrentResourceID (); if (pApp->GetResourceID () != e_UnknownResourceID) { nResourceID = pApp->GetResourceID (); } CBCGPAppointmentBaseStorage* pStorage = GetStorage (nResourceID); if (pStorage == NULL) { return FALSE; } return pStorage->Update (pApp, dtOld, bForceAdd); } BOOL CBCGPAppointmentMultiStorage::Remove (CBCGPAppointment* pApp) { ASSERT_VALID (pApp); if (pApp == NULL) { return FALSE; } UINT nResourceID = GetCurrentResourceID (); if (pApp->GetResourceID () != e_UnknownResourceID) { nResourceID = pApp->GetResourceID (); } CBCGPAppointmentBaseStorage* pStorage = GetStorage (nResourceID); if (pStorage == NULL) { return FALSE; } return pStorage->Remove (pApp); } BOOL CBCGPAppointmentMultiStorage::RemoveAll () { UINT nResourceID = GetCurrentResourceID (); if (nResourceID != e_UnknownResourceID) { CBCGPAppointmentBaseStorage* pStorage = GetStorage (nResourceID); if (pStorage != NULL) { return pStorage->RemoveAll (); } return FALSE; } POSITION pos = m_ResourceCollection.GetStartPosition (); XResource* pResource = NULL; while (pos != NULL) { m_ResourceCollection.GetNextAssoc (pos, nResourceID, pResource); if (pResource != NULL && pResource->m_pStorage != NULL) { pResource->m_pStorage->RemoveAll (); } } return TRUE; } void CBCGPAppointmentMultiStorage::Query (XBCGPAppointmentArray& ar, const COleDateTime& date1, const COleDateTime& date2) { UINT nResourceID = GetCurrentResourceID (); if (nResourceID != e_UnknownResourceID) { CBCGPAppointmentBaseStorage* pStorage = GetStorage (nResourceID); if (pStorage != NULL) { pStorage->Query (ar, date1, date2); } } else { POSITION pos = m_ResourceCollection.GetStartPosition (); XResource* pResource = NULL; XBCGPAppointmentArray arTmp; while (pos != NULL) { m_ResourceCollection.GetNextAssoc (pos, nResourceID, pResource); if (pResource != NULL && pResource->m_pStorage != NULL) { arTmp.RemoveAll (); pResource->m_pStorage->Query (arTmp, date1, date2); ar.Append (arTmp); } } } } void CBCGPAppointmentMultiStorage::QueryAll (XBCGPAppointmentArray& ar) { UINT nResourceID = GetCurrentResourceID (); if (nResourceID != e_UnknownResourceID) { CBCGPAppointmentBaseStorage* pStorage = GetStorage (nResourceID); if (pStorage != NULL) { pStorage->QueryAll (ar); } } else { POSITION pos = m_ResourceCollection.GetStartPosition (); XResource* pResource = NULL; XBCGPAppointmentArray arTmp; while (pos != NULL) { m_ResourceCollection.GetNextAssoc (pos, nResourceID, pResource); if (pResource != NULL && pResource->m_pStorage != NULL) { arTmp.RemoveAll (); pResource->m_pStorage->QueryAll (arTmp); ar.Append (arTmp); } } } } BOOL CBCGPAppointmentMultiStorage::IsEmpty () const { UINT nResourceID = GetCurrentResourceID (); if (nResourceID != e_UnknownResourceID) { CBCGPAppointmentBaseStorage* pStorage = GetStorage (nResourceID); if (pStorage != NULL) { return pStorage->IsEmpty (); } return FALSE; } return m_ResourceCollection.IsEmpty (); } CBCGPAppointment* CBCGPAppointmentMultiStorage::GetRecurrence (DWORD ID) const { CBCGPAppointmentBaseStorage* pStorage = GetStorage (GetCurrentResourceID ()); if (pStorage == NULL) { return NULL; } return pStorage->GetRecurrence (ID); } #endif // BCGP_EXCLUDE_PLANNER
18.725851
122
0.650602
iclosure
a804ab0673092803b356c45d570da26c82f749d2
4,061
cpp
C++
src/main.cpp
MoochMcGee/IBM5150
6fd6d7dc24764881274c13a8a97739c314a9e9d0
[ "WTFPL" ]
5
2015-05-05T10:42:21.000Z
2019-07-21T06:40:20.000Z
src/main.cpp
MoochMcGee/IBM5150
6fd6d7dc24764881274c13a8a97739c314a9e9d0
[ "WTFPL" ]
null
null
null
src/main.cpp
MoochMcGee/IBM5150
6fd6d7dc24764881274c13a8a97739c314a9e9d0
[ "WTFPL" ]
null
null
null
#include <cstdio> #include <vector> #include <string> #include <functional> #include <chrono> #include <thread> #include "interface.h" #include "misc.h" enum { update_frame = 1, update_scanline = 2, update_pixel = 4, update_clock = 8 }; #include "cpu.h" #include "mda.h" #include "cga.h" #include "savestate.h" int main(int ac, char** av) { if(ac < 2) { printf("Usage:\n\tibm5150 configfile\n"); return 1; } PIC::pic[0].init1 = false; PIC::pic[0].init2 = false; PIC::pic[0].enabled = false; DMA_XT::chan[0].access_flip_flop = false; CPU::cr0 = 0; char* isa1 = new char[10]; char* biosrom = new char[256]; char* mdarom = new char[256]; FILE* config = fopen(av[1],"r"); fscanf(config,"isa1=%s\n",isa1); fscanf(config,"biosrom=%s\n",biosrom); fscanf(config,"mdarom=%s\n",mdarom); fclose(config); FILE* bios = fopen(biosrom,"rb"); fseek(bios,0,SEEK_END); long size = ftell(bios); fseek(bios,0,SEEK_SET); fread(RAM::RAM + (0x100000 - size),1,size,bios); FILE* mda = fopen(mdarom,"rb"); fread(MDA::ROM,1,0x2000,mda); fseek(mda,0,SEEK_SET); fread(CGA::ROM,1,0x2000,mda); fclose(mda); fclose(bios); std::string isa1slot = isa1; delete[] isa1; INTERFACE::init(); if(isa1slot == "mda") { IO_XT::handlers.push_back(MDA::mdacrtc); INTERFACE::window_caption("IBM5150: CPU: 8086 SYSTEM: IBM PC 5150 ISA1: MDA"); } if(isa1slot == "cga") { IO_XT::handlers.push_back(CGA::cgacrtc); INTERFACE::window_caption("IBM5150: CPU: 8086 SYSTEM: IBM PC 5150 ISA1: CGA"); } IO_XT::handlers.push_back(DMA_XT::handler); IO_XT::handlers.push_back(DMA_XT::handler2); IO_XT::handlers.push_back(PPI::handler); IO_XT::handlers.push_back(PIT::pit); IO_XT::handlers.push_back(PIC::pic1); IO_XT::handlers.push_back(FDC::handler); bool quit = false; int i = 0; FILE* fp = fopen("save/mem.dump","rb"); if(fp != NULL) { fread(RAM::RAM,0x100000,1,fp); fclose(fp); } fp = fopen("save/reg.dump","rb"); if(fp != NULL) { fread(&CPU::ax,2,1,fp); fread(&CPU::bx,2,1,fp); fread(&CPU::cx,2,1,fp); fread(&CPU::dx,2,1,fp); fread(&CPU::si,2,1,fp); fread(&CPU::di,2,1,fp); fread(&CPU::sp,2,1,fp); fread(&CPU::bp,2,1,fp); fread(&CPU::ip,2,1,fp); fread(&CPU::cs,2,1,fp); fread(&CPU::ds,2,1,fp); fread(&CPU::es,2,1,fp); fread(&CPU::ss,2,1,fp); fread(&CPU::flags,2,1,fp); fclose(fp); } fp = fopen("save/mda.dump","rb"); if(fp != NULL) { fread(&MDA::hdisp,1,1,fp); fread(&MDA::vdisp,1,1,fp); fread(&MDA::maxscan,1,1,fp); fread(&MDA::dispmode,1,1,fp); fclose(fp); } fp = fopen("save/cga.dump","rb"); if(fp != NULL) { fread(&CGA::hdisp,1,1,fp); fread(&CGA::vdisp,1,1,fp); fread(&CGA::maxscan,1,1,fp); fread(&CGA::dispmode,1,1,fp); fclose(fp); } fp = fopen("save/pic.dump","rb"); if(fp != NULL) { fread(&PIC::pic[0].intrmask,1,1,fp); fread(&PIC::pic[0].offset,1,1,fp); fread(&PIC::pic[0].enabled,sizeof(bool),1,fp); fclose(fp); } bool debugsaved = false; std::thread pitthread([]() { PIT::tick(); std::this_thread::sleep_for(std::chrono::microseconds(1)); }); while(INTERFACE::quitflag == false) { if(i==100) { i = 0; if(isa1slot == "mda") MDA::tick_frame(); if(isa1slot == "cga") CGA::tick_frame(); INTERFACE::update_screen(); } //TODO: remove SDL_* prefix INTERFACE::handle_events(); CPU::tick(); if(CPU::hint == true) CPU::hint = false; i++; } pitthread.join(); INTERFACE::quit(); return 0; }
22.943503
87
0.526964
MoochMcGee
a808fe6ab437440bf0e851370987b10c6b0bc364
1,374
cpp
C++
11_CPP/06_CPP06/ex02/B.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
11_CPP/06_CPP06/ex02/B.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
11_CPP/06_CPP06/ex02/B.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* B.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tderwedu <tderwedu@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/21 11:13:12 by tderwedu #+# #+# */ /* Updated: 2021/10/21 11:17:08 by tderwedu ### ########.fr */ /* */ /* ************************************************************************** */ #include "B.hpp" /* ======================= CONSTRUCTORS / DESTRUCTORS ======================= */ B::B(void) : Base() {} B::B(B const& src) { *this = src; } B::~B() {} /* ============================ MEMBER FUNCTIONS ============================ */ /* =========================== OPERBTOR OVERLOBDS =========================== */ B& B::operator=(B const& rhs) { (void)rhs; return (*this); } /* =============================== EXCEPTIONS =============================== */
36.157895
80
0.173945
tderwedu
a80a1eb4d141371e4e17f28fc630b4523476ac99
1,863
cpp
C++
avc_navigation/src/pid_controller.cpp
masebet/avc_2019
3c2dbf344842d9ceb627d377f9d8100e258d01bd
[ "MIT" ]
null
null
null
avc_navigation/src/pid_controller.cpp
masebet/avc_2019
3c2dbf344842d9ceb627d377f9d8100e258d01bd
[ "MIT" ]
null
null
null
avc_navigation/src/pid_controller.cpp
masebet/avc_2019
3c2dbf344842d9ceb627d377f9d8100e258d01bd
[ "MIT" ]
1
2018-11-30T17:40:30.000Z
2018-11-30T17:40:30.000Z
//include header #include <pid_controller.hpp> //default constructor PIDController::PIDController(double kp, double ki, double kd, double min, double max, double dt) { //set class variable values to passed values this->_kp = kp; this->_ki = ki; this->_kd = kd; this->_min_output = min; this->_max_output = max; this->_dt = dt; //initialize other variables this->_integral_value = 0; this->_previous_error = 0; //set initial set point to 0 this->_set_point = 0; } //default destructor PIDController::~PIDController() {} //set functions //set class set_point value void PIDController::setSetPoint(double set_point) { this->_set_point = set_point; } //other functions //calculate output based on input with predefined set point double PIDController::calculate(double input) { //initialize output value double output = 0; //calculate current error double error = input - this->_set_point; //add proportional term to output output += this->_kp * error; //update integral value and add integral term to output this->_integral_value += error * this->_dt; output += this->_ki * this->_integral_value; //add derivative term to output output += this->_kd * ((error - this->_previous_error) / this->_dt); //verify output is within specified range if (output > this->_max_output) output = this->_max_output; else if (output < this->_min_output) output = this->_min_output; //set previous error value to current error this->_previous_error = error; //return calculated output value return output; } //calculate output based on input and new set point double PIDController::calculate(double set_point, double input) { //set set_point to passed value this->setSetPoint(set_point); //call calculate function with passed input and return result return this->calculate(input); }
22.178571
96
0.716049
masebet
a80b8ae1c7e9766ff4327bd5202c4b5cac5f11c9
1,095
cpp
C++
chap14/Page585_multiple_conversion.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
50
2016-01-08T14:28:53.000Z
2022-01-21T12:55:00.000Z
chap14/Page585_multiple_conversion.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
2
2017-06-05T16:45:20.000Z
2021-04-17T13:39:24.000Z
chap14/Page585_multiple_conversion.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
18
2016-08-17T15:23:51.000Z
2022-03-26T18:08:43.000Z
// Warning: this is for verification. It cannot compile. struct A { A(int = 0); // usually a bad idea to have two A(double); //conversions from arithmetic types operator int() const; // usually a bad idea to have two operator double() const; // conversions to arithmetic types // other members }; int main() { // ambiguity #1 void f2(long double); A a; f2(a); // error ambiguous: f(A::operator int()) // or: f(A::operator double()) // ambiguity #2 long lg = 0; A a2(lg); // error ambiguous: A::A(int) or A::A(double) // #3 // promoting short to int is better than converting short to double short s = 42; A a3(s); // use A::A(int) return 0; } void f2(long double) {} // Note: #1 is ambiguous because conversion from int to long double and double // from long double has the same rank(there's no "float promotion"); // #2 is ambiguous because conversion from long to int and double to int has the // same rank(shrink from long to int is arithmetic conversion rather than // integral promotion).
35.322581
80
0.635616
sjbarigye
a80c5631b5ab783f4fb20d0e47dcd4d2d0a46c8d
713
cpp
C++
LongestCommonPrefix/LongestCommonPrefix.cpp
yergen/leetcode
7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab
[ "MIT" ]
null
null
null
LongestCommonPrefix/LongestCommonPrefix.cpp
yergen/leetcode
7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab
[ "MIT" ]
null
null
null
LongestCommonPrefix/LongestCommonPrefix.cpp
yergen/leetcode
7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include<vector> #include<algorithm> using namespace::std; class Solution { public: string longestCommonPrefix(vector<string>& strs) { int n = strs.size(); if (n == 0) return ""; int minString = int(strs[0].size()); for (int i = 1; i < n; i++) minString = min(int(strs[i].size()), minString); string prefix = ""; int j; for (int i = 0; i < minString; i++) { for (j = 1; j < n; j++) { if (strs[j][i] != strs[0][i]) break; } if (j == n) prefix += strs[0][i]; else return prefix; } return prefix; } }; int main() { vector<string> str = {""}; Solution sol; cout << sol.longestCommonPrefix(str) << endl; return 0; }
17.390244
51
0.565217
yergen