hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
6c782b8510844bec43bfbdbef92f39910506f105
858
cpp
C++
src/HostViewBHO/Factory.cpp
inria-muse/hostview-win
db890b83956081d98e64005873eb2e7e4c6891e6
[ "MIT" ]
1
2018-07-22T16:39:08.000Z
2018-07-22T16:39:08.000Z
src/HostViewBHO/Factory.cpp
inria-muse/hostview-win
db890b83956081d98e64005873eb2e7e4c6891e6
[ "MIT" ]
null
null
null
src/HostViewBHO/Factory.cpp
inria-muse/hostview-win
db890b83956081d98e64005873eb2e7e4c6891e6
[ "MIT" ]
1
2021-03-08T06:59:28.000Z
2021-03-08T06:59:28.000Z
#include "common.h" #include "Factory.h" #include "Plugin.h" const IID CFactory::SupportedIIDs[] = {IID_IUnknown, IID_IClassFactory}; CFactory::CFactory() : CUnknown<IClassFactory>(SupportedIIDs, 2) { } CFactory::~CFactory() { } STDMETHODIMP CFactory::CreateInstance(IUnknown *pUnkOuter, REFIID riid, void **ppvObject) { if(pUnkOuter != NULL) { return CLASS_E_NOAGGREGATION; } if(IsBadWritePtr(ppvObject, sizeof(void*))) { return E_POINTER; } (*ppvObject) = NULL; CBHOPlugin* pObject = new CBHOPlugin(); if(pObject == NULL) { return E_OUTOFMEMORY; } HRESULT hr = pObject->QueryInterface(riid, ppvObject); if(FAILED(hr)) { delete pObject; } return hr; } STDMETHODIMP CFactory::LockServer(BOOL fLock) { if(fLock) { InterlockedIncrement(&nDllRefCount); } else { InterlockedDecrement(&nDllRefCount); } return S_OK; }
15.321429
89
0.706294
inria-muse
6c78d1de7d65ea97d301f5e18a99150380fe92d1
5,624
cpp
C++
cmdriver/src/CmXmlStringTokenizer.cpp
kit-transue/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
2
2015-11-24T03:31:12.000Z
2015-11-24T16:01:57.000Z
cmdriver/src/CmXmlStringTokenizer.cpp
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
null
null
null
cmdriver/src/CmXmlStringTokenizer.cpp
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
1
2019-05-19T02:26:08.000Z
2019-05-19T02:26:08.000Z
/************************************************************************* * Copyright (c) 2015, Synopsys, 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ #include <stdlib.h> #include <string.h> #include "CmXmlStringTokenizer.h" const int CmXmlStringTokenizer::ONE_SIDE_TOKEN = 0; const int CmXmlStringTokenizer::BOTH_SIDES_TOKEN = 1; CmXmlStringTokenizer::CmXmlStringTokenizer(const char *str, const char *delim, int mode) { this->str = strdup(str); this->delim = strdup(delim); this->mode = mode; this->curPtr = this->str; } //constructor CmXmlStringTokenizer::~CmXmlStringTokenizer() { free(this->str); free(this->delim); } //destructor char* CmXmlStringTokenizer::nextToken(int *begNdx) { char *token = NULL; if(this->mode == CmXmlStringTokenizer::ONE_SIDE_TOKEN) { token = nextToken1(); } else if(this->mode == CmXmlStringTokenizer::BOTH_SIDES_TOKEN) { token = nextToken2(); } // Calculate index of the beginning of the token if(begNdx != NULL) { *begNdx = (token != NULL) ? (int)(token - this->str) : -1; } return token; } //nextToken int CmXmlStringTokenizer::howManyTokensLeft() { int amount = 0; if(this->mode == CmXmlStringTokenizer::ONE_SIDE_TOKEN) { amount = howManyTokensLeft1(); } else if(this->mode == CmXmlStringTokenizer::BOTH_SIDES_TOKEN) { amount = howManyTokensLeft2(); } return amount; } //howManyTokensLeft char* CmXmlStringTokenizer::nextToken1() { // Check arguments if(this->curPtr == NULL || this->delim == NULL) { return NULL; } // Token starts from current position char *token = this->curPtr; // Find first occurence of one of the delimeters this->curPtr = strpbrk(this->curPtr, this->delim); // If found -> place '\0' instead of delimeter and // go to the beginning of the next token. if(this->curPtr != NULL) { this->curPtr[0] = 0; this->curPtr++; } // Return pointer to the beginning of the current token return token; } //nextToken1 char* CmXmlStringTokenizer::nextToken2() { // Check arguments if(this->curPtr == NULL || this->delim == NULL) { return NULL; } // Try to find the beginning of the next token char *token = strpbrk(this->curPtr, this->delim); // There are no more tokens if(token == NULL) { this->curPtr = NULL; return NULL; } // This character is used as boundary for this token char bound = token[0]; token++; // This is expected to be a right boundary of this token char *endPtr = strchr(token, bound); if(endPtr == NULL) { this->curPtr = NULL; return NULL; } // Move further behind the current token endPtr[0] = 0; this->curPtr = endPtr + 1; return token; } //nextToken2 int CmXmlStringTokenizer::howManyTokensLeft1() { // Check arguments if(this->curPtr == NULL || this->delim == NULL) { return 0; } // Number of tokens equals to number of delimeters plus 1 int amount = 0; for(char *ptr = this->curPtr; ptr != NULL; ptr = strpbrk(ptr + 1, this->delim)) { amount++; } return amount; } //howManyTokensLeft1 int CmXmlStringTokenizer::howManyTokensLeft2() { // Check arguments if(this->curPtr == NULL || this->delim == NULL) { return 0; } // Number of tokens equals number of pair of delimiters int amount = 0; for(char *ptr = this->curPtr; ptr != NULL; ptr = strpbrk(ptr, this->delim)) { char bound = *ptr++; char *endPtr = strchr(ptr, bound); if(endPtr == NULL) { break; } else { amount++; ptr = endPtr + 1; } } return amount; } //howManyTokensLeft2 // END OF FILE
28.548223
90
0.585526
kit-transue
6c7e3a240169920f0aa7c99a2331f254a65f01bc
421
cpp
C++
src/Y/Y403.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
src/Y/Y403.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
src/Y/Y403.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
#include<iostream> #include<algorithm> using namespace std; double arr[101]; int main(){ double a,ave=0; cin>>a; for(int i=0;i<a-1;i++) cin>>arr[i]; int tmp=a-1; sort(arr,arr+tmp); for(int i=a-2;i>0;i--) ave+=arr[i]; ave/=a-2; if(ave>=50) cout<<"0"<<endl; else{ ave-=arr[1]/(a-2); for(int i=0;i<=100;i++){ if(ave+i/(a-2)>=50){ cout<<i<<endl; return 0; } }cout<<"FAIL"<<endl; return 0; } }
16.84
36
0.553444
wlhcode
6c7ead9f8211077b6a7af65c1e3b7750297ba267
318
cpp
C++
Solutions-to-Books/C++Primer/Chapter03/3.02.cpp
Horizon-Blue/playground
4bd42bfcec60b8e89e127f4784c99f6ba669d359
[ "MIT" ]
2
2016-08-31T19:13:24.000Z
2017-02-18T18:48:31.000Z
Solutions-to-Books/C++Primer/Chapter03/3.02.cpp
Horizon-Blue/playground
4bd42bfcec60b8e89e127f4784c99f6ba669d359
[ "MIT" ]
1
2018-12-10T16:32:26.000Z
2018-12-27T19:50:48.000Z
Solutions-to-Books/C++Primer/Chapter03/3.02.cpp
Horizon-Blue/playground
4bd42bfcec60b8e89e127f4784c99f6ba669d359
[ "MIT" ]
null
null
null
/* Exercise 3.2: Write a program to read the standard input * a line at a time. Modify your program to read a word at * a time */ // Xiaoyan Wang 10/26/2015 #include <iostream> #include <string> using namespace std; int main() { string line; while (getline(cin, line)) cout << line << endl; return 0; }
18.705882
59
0.663522
Horizon-Blue
6c8ce34734194fcd195d7131f5bf7e060a2a4107
947
cpp
C++
apps/2d/euler/test_exact1/AfterQinit.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
apps/2d/euler/test_exact1/AfterQinit.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
apps/2d/euler/test_exact1/AfterQinit.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
/* #include <iostream> #include <iomanip> #include "dogdefs.h" #include "IniParams.h" */ #include "DogSolverCart2.h" #include <string.h> // For strcpy and strcat (some compilers don't need this) #include "IniParams.h" // Function that is called after initial condition void AfterQinit(DogSolverCart2& solver) { // DogStateCart2& state = solver.fetch_state(); // dTensorBC4& aux = state.fetch_aux(); // dTensorBC4& q = state.fetch_q(); // const int mx = q.getsize(1); // const int my = q.getsize(2); // const int meqn = q.getsize(3); // const int kmax = q.getsize(4); // const int mbc = q.getmbc(); // const int maux = aux.getsize(3); // const int space_order = global_ini_params.get_space_order(); // Output parameters to file in outputdir char eulerhelp[200]; strcpy( eulerhelp, solver.get_outputdir() ); strcat( eulerhelp, "/eulerhelp.dat"); eulerParams.write_eulerhelp( eulerhelp ); }
27.852941
86
0.669483
dcseal
6c8dbddac1c11a71d1f0bf12b64a9e7b95a05d59
691
hpp
C++
Public/Ava/Private/Platform/Arch.hpp
vasama/Ava
c1e6fb87a493dc46ce870220c632069f00875d2c
[ "MIT" ]
null
null
null
Public/Ava/Private/Platform/Arch.hpp
vasama/Ava
c1e6fb87a493dc46ce870220c632069f00875d2c
[ "MIT" ]
null
null
null
Public/Ava/Private/Platform/Arch.hpp
vasama/Ava
c1e6fb87a493dc46ce870220c632069f00875d2c
[ "MIT" ]
null
null
null
#pragma once #if defined(Ava_X86) \ || defined(__i386__) \ || defined(__i486__) \ || defined(__i586__) \ || defined(__i686__) \ || defined(_M_IX86) # ifndef Ava_X86 # define Ava_X86 1 # endif # define Ava_32 1 # define Ava_ARCH x86 #elif defined(Ava_X64) \ || defined(__x86_64) \ || defined(__x86_64__) \ || defined(__amd64) \ || defined(__amd64__) \ || defined(_M_X64) # ifndef Ava_X64 # define Ava_X64 1 # endif # define Ava_64 1 # define Ava_ARCH x64 #else # error Unsupported architecture #endif #ifndef Ava_32 # define Ava_32 0 #endif #ifndef Ava_64 # define Ava_64 0 #endif #ifndef Ava_X86 # define Ava_X86 0 #endif #ifndef Ava_X64 # define Ava_X64 0 #endif
15.704545
32
0.691751
vasama
6c8e13b5d49c84522cb7a74452c7f089529ce49c
841
cpp
C++
OJ/LeetCode/leetcode/problems/offer39.cpp
ONGOING-Z/DataStructure
9099393d1c7dfabc3e2939586ea6d1d254631eb2
[ "MIT" ]
null
null
null
OJ/LeetCode/leetcode/problems/offer39.cpp
ONGOING-Z/DataStructure
9099393d1c7dfabc3e2939586ea6d1d254631eb2
[ "MIT" ]
2
2021-10-31T10:05:45.000Z
2022-02-12T15:17:53.000Z
OJ/LeetCode/leetcode/offer39.cpp
ONGOING-Z/Learn-Algorithm-and-DataStructure
3a512bd83cc6ed5035ac4550da2f511298b947c0
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <cstdio> #include <vector> #include <algorithm> using namespace std; /* Offer */ /* Type: */ /* 题目信息 */ /* *剑指 Offer 39. 数组中出现次数超过一半的数字 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。   你可以假设数组是非空的,并且给定的数组总是存在多数元素。   示例 1: 输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 输出: 2   限制: 1 <= 数组长度 <= 50000 */ /* my solution */ // solution-1, 44ms, defeat 75.70% // 使用map找每个数字的频次,然后再遍历,找到频次符号条件的数字返回。 // O(n) class Solution { public: int majorityElement(vector<int>& nums) { map<int, int> mp; for (int num : nums) mp[num]++; for (auto e : mp) { if (e.second > nums.size() / 2) return e.first; } return -1; } }; /* better solution */ // solution-x, ms, defeat % /* 一些总结 */ // 1. 题意: // // 需要注意的点: // 1. // 2. // 3.
13.786885
44
0.530321
ONGOING-Z
6c915f68204c33100c70f4ef5405fb1b844abbf3
1,205
cpp
C++
src/engine/test/maptest.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/engine/test/maptest.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/engine/test/maptest.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <gen/floodfill.hpp> using namespace eXl; TEST(DunAtk, FloodFillTest) { AABB2Di box(Vector2i::ZERO, Vector2i::ONE * 8); { Vector<char> testVec = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, -1, 0, 0, -1, -1, 0, 0, 0, -1, -1, 0, 0, -1, -1, -1, 0, -1, -1, -1, 0, -1, 0, 0, 0, -1, -1, -1, 0, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; Vector<uint32_t> out_comps; uint32_t numComps = FloodFill::ExtractComponents(testVec, box, out_comps); ASSERT_EQ(numComps, 2); Vector<AABB2DPolygoni> polys; FloodFill::MakePolygons(testVec, box, [](char iVal) { return iVal == 0; }, polys); ASSERT_EQ(polys.size(), 2); } Vector<bool> testVec = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, }; Vector<AABB2DPolygoni> polys; FloodFill::MakePolygons(testVec, box, FloodFill::ValidOperator<bool>(), polys); ASSERT_EQ(polys.size(), 2); }
23.627451
86
0.483817
eXl-Nic
6c95b467682542463fdbce08ee620d070e45c08d
6,096
cc
C++
RecoLocalCalo/HGCalRecAlgos/src/ClusterTools.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
RecoLocalCalo/HGCalRecAlgos/src/ClusterTools.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
RecoLocalCalo/HGCalRecAlgos/src/ClusterTools.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "RecoLocalCalo/HGCalRecAlgos/interface/ClusterTools.h" #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/ForwardDetId/interface/ForwardSubdetector.h" #include "DataFormats/HcalDetId/interface/HcalSubdetector.h" #include "Geometry/HGCalGeometry/interface/HGCalGeometry.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "DataFormats/Common/interface/Handle.h" #include "vdt/vdtMath.h" #include <iostream> using namespace hgcal; ClusterTools::ClusterTools() {} ClusterTools::ClusterTools(const edm::ParameterSet& conf, edm::ConsumesCollector& sumes) : eetok(sumes.consumes<HGCRecHitCollection>(conf.getParameter<edm::InputTag>("HGCEEInput"))), fhtok(sumes.consumes<HGCRecHitCollection>(conf.getParameter<edm::InputTag>("HGCFHInput"))), bhtok(sumes.consumes<HGCRecHitCollection>(conf.getParameter<edm::InputTag>("HGCBHInput"))), caloGeometryToken_{sumes.esConsumes()} {} void ClusterTools::getEvent(const edm::Event& ev) { eerh_ = &ev.get(eetok); fhrh_ = &ev.get(fhtok); bhrh_ = &ev.get(bhtok); } void ClusterTools::getEventSetup(const edm::EventSetup& es) { rhtools_.setGeometry(es.getData(caloGeometryToken_)); } float ClusterTools::getClusterHadronFraction(const reco::CaloCluster& clus) const { float energy = 0.f, energyHad = 0.f; const auto& hits = clus.hitsAndFractions(); for (const auto& hit : hits) { const auto& id = hit.first; const float fraction = hit.second; if (id.det() == DetId::HGCalEE) { energy += eerh_->find(id)->energy() * fraction; } else if (id.det() == DetId::HGCalHSi) { const float temp = fhrh_->find(id)->energy(); energy += temp * fraction; energyHad += temp * fraction; } else if (id.det() == DetId::HGCalHSc) { const float temp = bhrh_->find(id)->energy(); energy += temp * fraction; energyHad += temp * fraction; } else if (id.det() == DetId::Forward) { switch (id.subdetId()) { case HGCEE: energy += eerh_->find(id)->energy() * fraction; break; case HGCHEF: { const float temp = fhrh_->find(id)->energy(); energy += temp * fraction; energyHad += temp * fraction; } break; default: throw cms::Exception("HGCalClusterTools") << " Cluster contains hits that are not from HGCal! " << std::endl; } } else if (id.det() == DetId::Hcal && id.subdetId() == HcalEndcap) { const float temp = bhrh_->find(id)->energy(); energy += temp * fraction; energyHad += temp * fraction; } else { throw cms::Exception("HGCalClusterTools") << " Cluster contains hits that are not from HGCal! " << std::endl; } } float fraction = -1.f; if (energy > 0.f) { fraction = energyHad / energy; } return fraction; } math::XYZPoint ClusterTools::getMultiClusterPosition(const reco::HGCalMultiCluster& clu) const { if (clu.clusters().empty()) return math::XYZPoint(); double acc_x = 0.0; double acc_y = 0.0; double acc_z = 0.0; double totweight = 0.; double mcenergy = getMultiClusterEnergy(clu); for (const auto& ptr : clu.clusters()) { if (mcenergy != 0) { if (ptr->energy() < .01 * mcenergy) continue; //cutoff < 1% layer contribution } const double weight = ptr->energy(); // weigth each corrdinate only by the total energy of the layer cluster acc_x += ptr->x() * weight; acc_y += ptr->y() * weight; acc_z += ptr->z() * weight; totweight += weight; } if (totweight != 0) { acc_x /= totweight; acc_y /= totweight; acc_z /= totweight; } // return x/y/z in absolute coordinates return math::XYZPoint(acc_x, acc_y, acc_z); } int ClusterTools::getLayer(const DetId detid) const { return rhtools_.getLayerWithOffset(detid); } double ClusterTools::getMultiClusterEnergy(const reco::HGCalMultiCluster& clu) const { double acc = 0.0; for (const auto& ptr : clu.clusters()) { acc += ptr->energy(); } return acc; } bool ClusterTools::getWidths(const reco::CaloCluster& clus, double& sigmaetaeta, double& sigmaphiphi, double& sigmaetaetal, double& sigmaphiphil) const { if (getLayer(clus.hitsAndFractions()[0].first) > (int)rhtools_.lastLayerEE()) return false; const math::XYZPoint& position(clus.position()); unsigned nhit = clus.hitsAndFractions().size(); sigmaetaeta = 0.; sigmaphiphi = 0.; sigmaetaetal = 0.; sigmaphiphil = 0.; double sumw = 0.; double sumlogw = 0.; for (unsigned int ih = 0; ih < nhit; ++ih) { const DetId& id = (clus.hitsAndFractions())[ih].first; if ((clus.hitsAndFractions())[ih].second == 0.) continue; if ((id.det() == DetId::HGCalEE) || (id.det() == DetId::Forward && id.subdetId() == HGCEE)) { const HGCRecHit* theHit = &(*eerh_->find(id)); GlobalPoint cellPos = rhtools_.getPosition(id); double weight = theHit->energy(); // take w0=2 To be optimized double logweight = 0; if (clus.energy() != 0) { logweight = std::max(0., 2 + log(theHit->energy() / clus.energy())); } double deltaetaeta2 = (cellPos.eta() - position.eta()) * (cellPos.eta() - position.eta()); double deltaphiphi2 = (cellPos.phi() - position.phi()) * (cellPos.phi() - position.phi()); sigmaetaeta += deltaetaeta2 * weight; sigmaphiphi += deltaphiphi2 * weight; sigmaetaetal += deltaetaeta2 * logweight; sigmaphiphil += deltaphiphi2 * logweight; sumw += weight; sumlogw += logweight; } } if (sumw <= 0.) return false; sigmaetaeta /= sumw; sigmaetaeta = std::sqrt(sigmaetaeta); sigmaphiphi /= sumw; sigmaphiphi = std::sqrt(sigmaphiphi); if (sumlogw != 0) { sigmaetaetal /= sumlogw; sigmaetaetal = std::sqrt(sigmaetaetal); sigmaphiphil /= sumlogw; sigmaphiphil = std::sqrt(sigmaphiphil); } return true; }
34.055866
119
0.636975
ckamtsikis
6c966b5fa941144b13f247c752bb089933b97764
18,592
cpp
C++
src/gpu/vk/GrVkGpuCommandBuffer.cpp
juanpca12/Google-Skia
42e6798696ac3a93a2b7ba7a9d6a84b77eba0116
[ "Apache-2.0" ]
null
null
null
src/gpu/vk/GrVkGpuCommandBuffer.cpp
juanpca12/Google-Skia
42e6798696ac3a93a2b7ba7a9d6a84b77eba0116
[ "Apache-2.0" ]
null
null
null
src/gpu/vk/GrVkGpuCommandBuffer.cpp
juanpca12/Google-Skia
42e6798696ac3a93a2b7ba7a9d6a84b77eba0116
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrVkGpuCommandBuffer.h" #include "GrMesh.h" #include "GrPipeline.h" #include "GrRenderTargetPriv.h" #include "GrTextureAccess.h" #include "GrTexturePriv.h" #include "GrVkCommandBuffer.h" #include "GrVkGpu.h" #include "GrVkPipeline.h" #include "GrVkRenderPass.h" #include "GrVkRenderTarget.h" #include "GrVkResourceProvider.h" #include "GrVkTexture.h" void get_vk_load_store_ops(const GrGpuCommandBuffer::LoadAndStoreInfo& info, VkAttachmentLoadOp* loadOp, VkAttachmentStoreOp* storeOp) { switch (info.fLoadOp) { case GrGpuCommandBuffer::LoadOp::kLoad: *loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; break; case GrGpuCommandBuffer::LoadOp::kClear: *loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; break; case GrGpuCommandBuffer::LoadOp::kDiscard: *loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; break; default: SK_ABORT("Invalid LoadOp"); *loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; } switch (info.fStoreOp) { case GrGpuCommandBuffer::StoreOp::kStore: *storeOp = VK_ATTACHMENT_STORE_OP_STORE; break; case GrGpuCommandBuffer::StoreOp::kDiscard: *storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; break; default: SK_ABORT("Invalid StoreOp"); *storeOp = VK_ATTACHMENT_STORE_OP_STORE; } } GrVkGpuCommandBuffer::GrVkGpuCommandBuffer(GrVkGpu* gpu, GrVkRenderTarget* target, const LoadAndStoreInfo& colorInfo, const LoadAndStoreInfo& stencilInfo) : fGpu(gpu) , fRenderTarget(target) , fIsEmpty(true) { VkAttachmentLoadOp vkLoadOp; VkAttachmentStoreOp vkStoreOp; get_vk_load_store_ops(colorInfo, &vkLoadOp, &vkStoreOp); GrVkRenderPass::LoadStoreOps vkColorOps(vkLoadOp, vkStoreOp); get_vk_load_store_ops(stencilInfo, &vkLoadOp, &vkStoreOp); GrVkRenderPass::LoadStoreOps vkStencilOps(vkLoadOp, vkStoreOp); GrVkRenderPass::LoadStoreOps vkResolveOps(VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_STORE_OP_STORE); const GrVkResourceProvider::CompatibleRPHandle& rpHandle = target->compatibleRenderPassHandle(); if (rpHandle.isValid()) { fRenderPass = fGpu->resourceProvider().findRenderPass(rpHandle, vkColorOps, vkResolveOps, vkStencilOps); } else { fRenderPass = fGpu->resourceProvider().findRenderPass(*target, vkColorOps, vkResolveOps, vkStencilOps); } GrColorToRGBAFloat(colorInfo.fClearColor, fColorClearValue.color.float32); fCommandBuffer = GrVkSecondaryCommandBuffer::Create(gpu, gpu->cmdPool(), fRenderPass); fCommandBuffer->begin(gpu, target->framebuffer()); } GrVkGpuCommandBuffer::~GrVkGpuCommandBuffer() { fCommandBuffer->unref(fGpu); fRenderPass->unref(fGpu); } GrGpu* GrVkGpuCommandBuffer::gpu() { return fGpu; } void GrVkGpuCommandBuffer::end() { fCommandBuffer->end(fGpu); } void GrVkGpuCommandBuffer::onSubmit(const SkIRect& bounds) { // Change layout of our render target so it can be used as the color attachment fRenderTarget->setImageLayout(fGpu, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, false); // If we are using a stencil attachment we also need to update its layout if (GrStencilAttachment* stencil = fRenderTarget->renderTargetPriv().getStencilAttachment()) { GrVkStencilAttachment* vkStencil = (GrVkStencilAttachment*)stencil; vkStencil->setImageLayout(fGpu, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, false); } if (GrVkImage* msaaImage = fRenderTarget->msaaImage()) { msaaImage->setImageLayout(fGpu, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, false); } for (int i = 0; i < fSampledImages.count(); ++i) { fSampledImages[i]->setImageLayout(fGpu, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, false); } fGpu->submitSecondaryCommandBuffer(fCommandBuffer, fRenderPass, &fColorClearValue, fRenderTarget, bounds); } void GrVkGpuCommandBuffer::discard(GrRenderTarget* target) { if (fIsEmpty) { // We will change the render pass to do a clear load instead GrVkRenderPass::LoadStoreOps vkColorOps(VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_STORE); GrVkRenderPass::LoadStoreOps vkStencilOps(VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_STORE); GrVkRenderPass::LoadStoreOps vkResolveOps(VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_STORE); const GrVkRenderPass* oldRP = fRenderPass; GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(target); const GrVkResourceProvider::CompatibleRPHandle& rpHandle = vkRT->compatibleRenderPassHandle(); if (rpHandle.isValid()) { fRenderPass = fGpu->resourceProvider().findRenderPass(rpHandle, vkColorOps, vkResolveOps, vkStencilOps); } else { fRenderPass = fGpu->resourceProvider().findRenderPass(*vkRT, vkColorOps, vkResolveOps, vkStencilOps); } SkASSERT(fRenderPass->isCompatible(*oldRP)); oldRP->unref(fGpu); } } void GrVkGpuCommandBuffer::onClearStencilClip(GrRenderTarget* target, const SkIRect& rect, bool insideClip) { SkASSERT(target); GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(target); GrStencilAttachment* sb = target->renderTargetPriv().getStencilAttachment(); // this should only be called internally when we know we have a // stencil buffer. SkASSERT(sb); int stencilBitCount = sb->bits(); // The contract with the callers does not guarantee that we preserve all bits in the stencil // during this clear. Thus we will clear the entire stencil to the desired value. VkClearDepthStencilValue vkStencilColor; memset(&vkStencilColor, 0, sizeof(VkClearDepthStencilValue)); if (insideClip) { vkStencilColor.stencil = (1 << (stencilBitCount - 1)); } else { vkStencilColor.stencil = 0; } VkClearRect clearRect; // Flip rect if necessary SkIRect vkRect = rect; if (kBottomLeft_GrSurfaceOrigin == vkRT->origin()) { vkRect.fTop = vkRT->height() - rect.fBottom; vkRect.fBottom = vkRT->height() - rect.fTop; } clearRect.rect.offset = { vkRect.fLeft, vkRect.fTop }; clearRect.rect.extent = { (uint32_t)vkRect.width(), (uint32_t)vkRect.height() }; clearRect.baseArrayLayer = 0; clearRect.layerCount = 1; uint32_t stencilIndex; SkAssertResult(fRenderPass->stencilAttachmentIndex(&stencilIndex)); VkClearAttachment attachment; attachment.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT; attachment.colorAttachment = 0; // this value shouldn't matter attachment.clearValue.depthStencil = vkStencilColor; fCommandBuffer->clearAttachments(fGpu, 1, &attachment, 1, &clearRect); fIsEmpty = false; } void GrVkGpuCommandBuffer::onClear(GrRenderTarget* target, const SkIRect& rect, GrColor color) { // parent class should never let us get here with no RT SkASSERT(target); VkClearColorValue vkColor; GrColorToRGBAFloat(color, vkColor.float32); GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(target); if (fIsEmpty && rect.width() == target->width() && rect.height() == target->height()) { // We will change the render pass to do a clear load instead GrVkRenderPass::LoadStoreOps vkColorOps(VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE); GrVkRenderPass::LoadStoreOps vkStencilOps(VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_STORE_OP_STORE); GrVkRenderPass::LoadStoreOps vkResolveOps(VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_STORE_OP_STORE); const GrVkRenderPass* oldRP = fRenderPass; const GrVkResourceProvider::CompatibleRPHandle& rpHandle = vkRT->compatibleRenderPassHandle(); if (rpHandle.isValid()) { fRenderPass = fGpu->resourceProvider().findRenderPass(rpHandle, vkColorOps, vkResolveOps, vkStencilOps); } else { fRenderPass = fGpu->resourceProvider().findRenderPass(*vkRT, vkColorOps, vkResolveOps, vkStencilOps); } SkASSERT(fRenderPass->isCompatible(*oldRP)); oldRP->unref(fGpu); GrColorToRGBAFloat(color, fColorClearValue.color.float32); return; } // We always do a sub rect clear with clearAttachments since we are inside a render pass VkClearRect clearRect; // Flip rect if necessary SkIRect vkRect = rect; if (kBottomLeft_GrSurfaceOrigin == vkRT->origin()) { vkRect.fTop = vkRT->height() - rect.fBottom; vkRect.fBottom = vkRT->height() - rect.fTop; } clearRect.rect.offset = { vkRect.fLeft, vkRect.fTop }; clearRect.rect.extent = { (uint32_t)vkRect.width(), (uint32_t)vkRect.height() }; clearRect.baseArrayLayer = 0; clearRect.layerCount = 1; uint32_t colorIndex; SkAssertResult(fRenderPass->colorAttachmentIndex(&colorIndex)); VkClearAttachment attachment; attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; attachment.colorAttachment = colorIndex; attachment.clearValue.color = vkColor; fCommandBuffer->clearAttachments(fGpu, 1, &attachment, 1, &clearRect); fIsEmpty = false; return; } //////////////////////////////////////////////////////////////////////////////// void GrVkGpuCommandBuffer::bindGeometry(const GrPrimitiveProcessor& primProc, const GrNonInstancedMesh& mesh) { // There is no need to put any memory barriers to make sure host writes have finished here. // When a command buffer is submitted to a queue, there is an implicit memory barrier that // occurs for all host writes. Additionally, BufferMemoryBarriers are not allowed inside of // an active RenderPass. GrVkVertexBuffer* vbuf; vbuf = (GrVkVertexBuffer*)mesh.vertexBuffer(); SkASSERT(vbuf); SkASSERT(!vbuf->isMapped()); fCommandBuffer->bindVertexBuffer(fGpu, vbuf); if (mesh.isIndexed()) { GrVkIndexBuffer* ibuf = (GrVkIndexBuffer*)mesh.indexBuffer(); SkASSERT(ibuf); SkASSERT(!ibuf->isMapped()); fCommandBuffer->bindIndexBuffer(fGpu, ibuf); } } sk_sp<GrVkPipelineState> GrVkGpuCommandBuffer::prepareDrawState( const GrPipeline& pipeline, const GrPrimitiveProcessor& primProc, GrPrimitiveType primitiveType, const GrVkRenderPass& renderPass) { sk_sp<GrVkPipelineState> pipelineState = fGpu->resourceProvider().findOrCreateCompatiblePipelineState(pipeline, primProc, primitiveType, renderPass); if (!pipelineState) { return pipelineState; } pipelineState->setData(fGpu, primProc, pipeline); pipelineState->bind(fGpu, fCommandBuffer); GrVkPipeline::SetDynamicState(fGpu, fCommandBuffer, pipeline); return pipelineState; } static void append_sampled_images(const GrProcessor& processor, const GrVkGpu* gpu, SkTArray<GrVkImage*>* sampledImages) { if (int numTextures = processor.numTextures()) { GrVkImage** images = sampledImages->push_back_n(numTextures); int i = 0; do { const GrTextureAccess& texAccess = processor.textureAccess(i); GrVkTexture* vkTexture = static_cast<GrVkTexture*>(processor.texture(i)); SkASSERT(vkTexture); const GrTextureParams& params = texAccess.getParams(); // Check if we need to regenerate any mip maps if (GrTextureParams::kMipMap_FilterMode == params.filterMode()) { if (vkTexture->texturePriv().mipMapsAreDirty()) { gpu->generateMipmap(vkTexture); vkTexture->texturePriv().dirtyMipMaps(false); } } images[i] = vkTexture; } while (++i < numTextures); } } void GrVkGpuCommandBuffer::onDraw(const GrPipeline& pipeline, const GrPrimitiveProcessor& primProc, const GrMesh* meshes, int meshCount) { if (!meshCount) { return; } GrRenderTarget* rt = pipeline.getRenderTarget(); GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(rt); const GrVkRenderPass* renderPass = vkRT->simpleRenderPass(); SkASSERT(renderPass); GrPrimitiveType primitiveType = meshes[0].primitiveType(); sk_sp<GrVkPipelineState> pipelineState = this->prepareDrawState(pipeline, primProc, primitiveType, *renderPass); if (!pipelineState) { return; } append_sampled_images(primProc, fGpu, &fSampledImages); for (int i = 0; i < pipeline.numFragmentProcessors(); ++i) { append_sampled_images(pipeline.getFragmentProcessor(i), fGpu, &fSampledImages); } append_sampled_images(pipeline.getXferProcessor(), fGpu, &fSampledImages); for (int i = 0; i < meshCount; ++i) { const GrMesh& mesh = meshes[i]; GrMesh::Iterator iter; const GrNonInstancedMesh* nonIdxMesh = iter.init(mesh); do { if (nonIdxMesh->primitiveType() != primitiveType) { // Technically we don't have to call this here (since there is a safety check in // pipelineState:setData but this will allow for quicker freeing of resources if the // pipelineState sits in a cache for a while. pipelineState->freeTempResources(fGpu); SkDEBUGCODE(pipelineState = nullptr); primitiveType = nonIdxMesh->primitiveType(); pipelineState = this->prepareDrawState(pipeline, primProc, primitiveType, *renderPass); if (!pipelineState) { return; } } SkASSERT(pipelineState); this->bindGeometry(primProc, *nonIdxMesh); if (nonIdxMesh->isIndexed()) { fCommandBuffer->drawIndexed(fGpu, nonIdxMesh->indexCount(), 1, nonIdxMesh->startIndex(), nonIdxMesh->startVertex(), 0); } else { fCommandBuffer->draw(fGpu, nonIdxMesh->vertexCount(), 1, nonIdxMesh->startVertex(), 0); } fIsEmpty = false; fGpu->stats()->incNumDraws(); } while ((nonIdxMesh = iter.next())); } // Technically we don't have to call this here (since there is a safety check in // pipelineState:setData but this will allow for quicker freeing of resources if the // pipelineState sits in a cache for a while. pipelineState->freeTempResources(fGpu); }
42.447489
100
0.554862
juanpca12
6c972bda8864d4c341abda36d045af3774fc6f79
3,151
cpp
C++
main.cpp
fogwizard/fillsize
54928fbd50989beb92676e4d6703b3b18ab93eed
[ "Apache-2.0" ]
null
null
null
main.cpp
fogwizard/fillsize
54928fbd50989beb92676e4d6703b3b18ab93eed
[ "Apache-2.0" ]
null
null
null
main.cpp
fogwizard/fillsize
54928fbd50989beb92676e4d6703b3b18ab93eed
[ "Apache-2.0" ]
null
null
null
#include <unistd.h> #include <string.h> #include "iostream" #include "stdio.h" #include "stdint.h" #include "fillsize.h" #include "mergebin.h" #include "alignbin.h" #include "ddbin.h" using namespace std; int usage(void) { cout << "Usage: fillsize <filename> [address]" << endl; return 0; } int usage_merge(void) { cout << "Usage: fillsize -merge <loader> <offset> <app>" << endl; return 0; } int usage_align(void) { cout << "Usage: fillsize -align <inFile> <alignValue>" << endl; return 0; } int usage_dd(void) { cout << "Usage: fillsize -dd <inFile> <outFile> [skip] [out_length]" << endl; return 0; } int main(int argc, const char *argv[]) { if((argc >= 2) && (0 == strcmp("-merge", argv[1]))) { cout << "merge function active" << endl; mergeBin *mf = NULL; if(argc != 5) { return usage_merge(); } /* check input file */ if (-1 == access(argv[2], 0)) { cout << "file:" << argv[2] << " not exist" << endl; return usage_merge(); } if (-1 == access(argv[4], 0)) { cout << "file:" << argv[4] << " not exist" << endl; return usage_merge(); } mf = new mergeBin(argv[2], argv[3], argv[4]); mf->fill_loader(); mf->fill_app(); mf->fill_magic(); cout << "merge function end..." << endl; return 0; } /* align tool */ if((argc >= 2) && (0 == strcmp("-align", argv[1]))) { if((argc != 4) &&(argc != 5)) { return usage_align(); } /* check input file */ if (-1 == access(argv[2], 0)) { cout << "file:" << argv[2] << " not exist" << endl; return usage_align(); } alignBin *ab; if(4 == argc) { ab = new alignBin(argv[2], argv[3]); } else { ab = new alignBin(argv[2], argv[3], argv[4]); } ab->do_align(); return 0; } /* dd tool */ if((argc >= 2) && (0 == strcmp("-dd", argv[1]))) { if((4 != argc) && (5 != argc) &&(6 != argc)) { return usage_dd(); } /* check input file */ if (-1 == access(argv[2], 0)) { cout << "file:" << argv[2] << " not exist" << endl; return usage_dd(); } ddBin *dd; switch(argc) { case 4: dd = new ddBin(argv[2], argv[3]); break; case 5: dd = new ddBin(argv[2], argv[3], argv[4]); break; case 6: dd = new ddBin(argv[2], argv[3], argv[4], argv[5]); break; } dd->dd(); return 0; } /* check argc */ if((2 != argc) && (3 != argc)) { return usage(); } /* check input file */ if (-1 == access(argv[1], 0)) { cout << "file:" << argv[1] << " not exist" << endl; return 0; } fillVal * pf = NULL; if(argc == 3) { pf = new fillVal(argv[1], argv[2]); } else { pf = new fillVal(argv[1]); } pf->fill_size(); pf->fill_version(); return 0; }
23.514925
81
0.449064
fogwizard
6c97f885ad15183170d14e65e2a69c1f73357736
3,632
cpp
C++
src/kgw.cpp
Warants/whosa
ff46f1e5158c29601f8a83f9de77be1eca95f9f2
[ "MIT" ]
13
2017-09-17T16:54:25.000Z
2021-03-19T11:58:16.000Z
src/kgw.cpp
Warants/whosa
ff46f1e5158c29601f8a83f9de77be1eca95f9f2
[ "MIT" ]
7
2015-01-20T07:44:53.000Z
2021-11-26T18:58:38.000Z
src/kgw.cpp
Warants/whosa
ff46f1e5158c29601f8a83f9de77be1eca95f9f2
[ "MIT" ]
2
2018-01-02T16:49:00.000Z
2018-05-17T10:58:28.000Z
// Copyright (c) 2015-2015 The e-Gulden developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <math.h> #include "chain.h" #include "chainparams.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" unsigned int KimotoGravityWell(const CBlockIndex* pindexLast, uint64_t TargetBlockSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax, const Consensus::Params& params) { const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; uint64_t PastBlocksMass = 0; int64_t PastRateActualSeconds = 0; int64_t PastRateTargetSeconds = 0; double PastRateAdjustmentRatio = double(1); arith_uint256 PastDifficultyAverage, PastDifficultyAveragePrev; double EventHorizonDeviation, EventHorizonDeviationFast, EventHorizonDeviationSlow; if(BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t) BlockLastSolved->nHeight < PastBlocksMin) return UintToArith256(params.powLimit).GetCompact(); for(unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if(PastBlocksMax > 0 && i > PastBlocksMax) break; PastBlocksMass++; PastDifficultyAverage.SetCompact(BlockReading->nBits); if(i > 1) { if(PastDifficultyAverage >= PastDifficultyAveragePrev) { PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; } else { PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) / i); } } PastDifficultyAveragePrev = PastDifficultyAverage; PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime(); PastRateTargetSeconds = TargetBlockSpacingSeconds * PastBlocksMass; PastRateActualSeconds = (PastRateActualSeconds < 0) ? 0 : PastRateActualSeconds; PastRateAdjustmentRatio = (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) ? double(PastRateTargetSeconds) / double(PastRateActualSeconds) : double(1); EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass) / double(144)), -1.228)); EventHorizonDeviationFast = EventHorizonDeviation; EventHorizonDeviationSlow = 1 / EventHorizonDeviation; if((PastBlocksMass >= PastBlocksMin && (PastRateAdjustmentRatio <= EventHorizonDeviationSlow || PastRateAdjustmentRatio >= EventHorizonDeviationFast)) || (BlockReading->pprev == NULL)) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } arith_uint256 bnNew(PastDifficultyAverage); if(PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { bnNew *= PastRateActualSeconds; bnNew /= PastRateTargetSeconds; } const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); if(bnNew > bnPowLimit) { bnNew = bnPowLimit; } // Debug /* LogPrintf("Difficulty Retarget - Kimoto Gravity Well [Block: %d]\n", pindexLast->nHeight); LogPrintf("PastRateAdjustmentRatio = %g\n", PastRateAdjustmentRatio); LogPrintf("Before: %08x %s\n", pindexLast->nBits, uint256().SetCompact(pindexLast->nBits).ToString().c_str()); LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str()); */ return bnNew.GetCompact(); }
39.912088
178
0.683645
Warants
6c9c7eeaeeae6c6002e13a0d123fb399a645e383
414
hpp
C++
addons/handhelds/rf7800/CfgVehicles.hpp
MrDj200/task-force-arma-3-radio
21bb54d5d0e0b31b0522dc67e6923edb9ad85247
[ "RSA-MD" ]
300
2015-01-14T11:19:48.000Z
2022-01-18T19:46:55.000Z
addons/handhelds/rf7800/CfgVehicles.hpp
MrDj200/task-force-arma-3-radio
21bb54d5d0e0b31b0522dc67e6923edb9ad85247
[ "RSA-MD" ]
742
2015-01-07T05:25:39.000Z
2022-03-15T17:06:34.000Z
addons/handhelds/rf7800/CfgVehicles.hpp
MrDj200/task-force-arma-3-radio
21bb54d5d0e0b31b0522dc67e6923edb9ad85247
[ "RSA-MD" ]
280
2015-01-01T08:58:00.000Z
2022-03-23T12:37:38.000Z
class Item_TFAR_rf7800str: Item_Base_F { scope = PUBLIC; scopeCurator = PUBLIC; displayName = "RF-7800S-TR"; author = "Nkey"; vehicleClass = "Items"; class TransportItems { MACRO_ADDITEM(TFAR_rf7800str,1); }; #include "\z\tfar\addons\static_radios\edenAttributes.hpp" }; HIDDEN_CLASS(Item_tf_rf7800str : Item_TFAR_rf7800str); //#Deprecated dummy class for backwards compat
31.846154
101
0.705314
MrDj200
6c9c9307cbb8f2accc00f4d6c2b95e578f656b53
499
cpp
C++
acmicpc/2216.cpp
juseongkr/BOJ
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
7
2020-02-03T10:00:19.000Z
2021-11-16T11:03:57.000Z
acmicpc/2216.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2021-01-03T06:58:24.000Z
2021-01-03T06:58:24.000Z
acmicpc/2216.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2020-01-22T14:34:03.000Z
2020-01-22T14:34:03.000Z
#include <iostream> using namespace std; #define MAX 3001 int dp[MAX][MAX]; int main() { string s, r; int a, b, c; cin >> a >> b >> c >> s >> r; for (int i=1; i<MAX; ++i) dp[i][0] = dp[0][i] = i*b; for (int i=1; i<=s.length(); ++i) { for (int j=1; j<=r.length(); ++j) { if (s[i-1] == r[j-1]) dp[i][j] = dp[i-1][j-1] + a; else dp[i][j] = max(dp[i-1][j-1] + max(b * 2, c), max(dp[i][j-1], dp[i-1][j]) + b); } } cout << dp[s.length()][r.length()] << '\n'; return 0; }
17.206897
82
0.452906
juseongkr
6c9e0c8de1a52f1b2c3ede08a3d2cecc3760e90f
2,052
hpp
C++
include/example.hpp
m1nuz/modern-cpp-opengl-examples
6e79d772b12201f5be791d5c00622b0e4ccfe2ea
[ "MIT" ]
null
null
null
include/example.hpp
m1nuz/modern-cpp-opengl-examples
6e79d772b12201f5be791d5c00622b0e4ccfe2ea
[ "MIT" ]
null
null
null
include/example.hpp
m1nuz/modern-cpp-opengl-examples
6e79d772b12201f5be791d5c00622b0e4ccfe2ea
[ "MIT" ]
null
null
null
#pragma once #include <application.hpp> #include <graphics.hpp> struct RunExampleAppInfo { std::string_view title; std::function<void( )> on_init = []( ) {}; std::function<void( )> on_update = []( ) {}; std::function<void( int, int )> on_present; std::function<void( )> on_cleanup = []( ) {}; }; class ExampleApp { public: ExampleApp( ) = default; ExampleApp( const ExampleApp& ) = delete; auto operator=( const ExampleApp& ) -> ExampleApp& = delete; auto run( const RunExampleAppInfo& info ) -> int { return _run( info.title, info.on_init, info.on_update, info.on_present, info.on_cleanup ); } private: template <typename OnInit, typename OnUpdate, typename OnPresent, typename OnCleanup> auto _run( std::string_view title, OnInit on_init, OnUpdate on_update, OnPresent on_present, OnCleanup on_cleanup ) -> int { using namespace std::literals; glfwSetErrorCallback( []( int error, const char* description ) { journal::error( _tag, "Error {} {}", error, description ); } ); if ( !glfwInit( ) ) return EXIT_FAILURE; atexit( glfwTerminate ); auto window = application::create_window( { .width = 1440, .height = 1080, .title = title } ); if ( !window ) { journal::error( _tag, "Couldn't create window" ); return EXIT_FAILURE; } graphics::default_framebuffer.width = window->width; graphics::default_framebuffer.height = window->height; on_init( ); _mainloop.run( std::chrono::milliseconds { 16ms }, on_update, [&]( ) { if ( application::is_window_closed( *window ) ) { _mainloop.stop( ); } on_present( window->width, window->height ); application::process_window( *window ); } ); on_cleanup( ); return EXIT_SUCCESS; } static constexpr std::string_view _tag = "Example"; application::Window _window; application::Mainloop _mainloop; };
31.090909
119
0.60575
m1nuz
6ca08faebb0efa76551de501597b813846bbab56
10,679
cpp
C++
3rdparty/openmm/serialization/src/TabulatedFunctionProxies.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
5
2020-07-31T17:33:03.000Z
2022-01-01T19:24:37.000Z
3rdparty/openmm/serialization/src/TabulatedFunctionProxies.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
11
2020-06-16T05:05:42.000Z
2022-03-30T09:59:14.000Z
3rdparty/openmm/serialization/src/TabulatedFunctionProxies.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
9
2020-01-24T12:02:37.000Z
2020-10-16T06:23:56.000Z
/* -------------------------------------------------------------------------- * * OpenMM * * -------------------------------------------------------------------------- * * This is part of the OpenMM molecular simulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2014 Stanford University and the Authors. * * Authors: Peter Eastman * * Contributors: * * * * 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, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * * USE OR OTHER DEALINGS IN THE SOFTWARE. * * -------------------------------------------------------------------------- */ #include "openmm/serialization/TabulatedFunctionProxies.h" #include "openmm/serialization/SerializationNode.h" #include "openmm/TabulatedFunction.h" #include <sstream> using namespace OpenMM; using namespace std; Continuous1DFunctionProxy::Continuous1DFunctionProxy() : SerializationProxy("Continuous1DFunction") { } void Continuous1DFunctionProxy::serialize(const void* object, SerializationNode& node) const { node.setIntProperty("version", 1); const Continuous1DFunction& function = *reinterpret_cast<const Continuous1DFunction*>(object); double min, max; vector<double> values; function.getFunctionParameters(values, min, max); node.setDoubleProperty("min", min); node.setDoubleProperty("max", max); SerializationNode& valuesNode = node.createChildNode("Values"); for (auto v : values) valuesNode.createChildNode("Value").setDoubleProperty("v", v); } void* Continuous1DFunctionProxy::deserialize(const SerializationNode& node) const { if (node.getIntProperty("version") != 1) throw OpenMMException("Unsupported version number"); const SerializationNode& valuesNode = node.getChildNode("Values"); vector<double> values; for (auto& child : valuesNode.getChildren()) values.push_back(child.getDoubleProperty("v")); return new Continuous1DFunction(values, node.getDoubleProperty("min"), node.getDoubleProperty("max")); } Continuous2DFunctionProxy::Continuous2DFunctionProxy() : SerializationProxy("Continuous2DFunction") { } void Continuous2DFunctionProxy::serialize(const void* object, SerializationNode& node) const { node.setIntProperty("version", 1); const Continuous2DFunction& function = *reinterpret_cast<const Continuous2DFunction*>(object); int xsize, ysize; double xmin, xmax, ymin, ymax; vector<double> values; function.getFunctionParameters(xsize, ysize, values, xmin, xmax, ymin, ymax); node.setDoubleProperty("xsize", xsize); node.setDoubleProperty("ysize", ysize); node.setDoubleProperty("xmin", xmin); node.setDoubleProperty("xmax", xmax); node.setDoubleProperty("ymin", ymin); node.setDoubleProperty("ymax", ymax); SerializationNode& valuesNode = node.createChildNode("Values"); for (auto v : values) valuesNode.createChildNode("Value").setDoubleProperty("v", v); } void* Continuous2DFunctionProxy::deserialize(const SerializationNode& node) const { if (node.getIntProperty("version") != 1) throw OpenMMException("Unsupported version number"); const SerializationNode& valuesNode = node.getChildNode("Values"); vector<double> values; for (auto& child : valuesNode.getChildren()) values.push_back(child.getDoubleProperty("v")); return new Continuous2DFunction(node.getIntProperty("xsize"), node.getIntProperty("ysize"), values, node.getDoubleProperty("xmin"), node.getDoubleProperty("xmax"), node.getDoubleProperty("ymin"), node.getDoubleProperty("ymax")); } Continuous3DFunctionProxy::Continuous3DFunctionProxy() : SerializationProxy("Continuous3DFunction") { } void Continuous3DFunctionProxy::serialize(const void* object, SerializationNode& node) const { node.setIntProperty("version", 1); const Continuous3DFunction& function = *reinterpret_cast<const Continuous3DFunction*>(object); int xsize, ysize, zsize; double xmin, xmax, ymin, ymax, zmin, zmax; vector<double> values; function.getFunctionParameters(xsize, ysize, zsize, values, xmin, xmax, ymin, ymax, zmin, zmax); node.setDoubleProperty("xsize", xsize); node.setDoubleProperty("ysize", ysize); node.setDoubleProperty("zsize", zsize); node.setDoubleProperty("xmin", xmin); node.setDoubleProperty("xmax", xmax); node.setDoubleProperty("ymin", ymin); node.setDoubleProperty("ymax", ymax); node.setDoubleProperty("zmin", zmin); node.setDoubleProperty("zmax", zmax); SerializationNode& valuesNode = node.createChildNode("Values"); for (auto v : values) valuesNode.createChildNode("Value").setDoubleProperty("v", v); } void* Continuous3DFunctionProxy::deserialize(const SerializationNode& node) const { if (node.getIntProperty("version") != 1) throw OpenMMException("Unsupported version number"); const SerializationNode& valuesNode = node.getChildNode("Values"); vector<double> values; for (auto& child : valuesNode.getChildren()) values.push_back(child.getDoubleProperty("v")); return new Continuous3DFunction(node.getIntProperty("xsize"), node.getIntProperty("ysize"), node.getIntProperty("zsize"), values, node.getDoubleProperty("xmin"), node.getDoubleProperty("xmax"), node.getDoubleProperty("ymin"), node.getDoubleProperty("ymax"), node.getDoubleProperty("zmin"), node.getDoubleProperty("zmax")); } Discrete1DFunctionProxy::Discrete1DFunctionProxy() : SerializationProxy("Discrete1DFunction") { } void Discrete1DFunctionProxy::serialize(const void* object, SerializationNode& node) const { node.setIntProperty("version", 1); const Discrete1DFunction& function = *reinterpret_cast<const Discrete1DFunction*>(object); vector<double> values; function.getFunctionParameters(values); SerializationNode& valuesNode = node.createChildNode("Values"); for (auto v : values) valuesNode.createChildNode("Value").setDoubleProperty("v", v); } void* Discrete1DFunctionProxy::deserialize(const SerializationNode& node) const { if (node.getIntProperty("version") != 1) throw OpenMMException("Unsupported version number"); const SerializationNode& valuesNode = node.getChildNode("Values"); vector<double> values; for (auto& child : valuesNode.getChildren()) values.push_back(child.getDoubleProperty("v")); return new Discrete1DFunction(values); } Discrete2DFunctionProxy::Discrete2DFunctionProxy() : SerializationProxy("Discrete2DFunction") { } void Discrete2DFunctionProxy::serialize(const void* object, SerializationNode& node) const { node.setIntProperty("version", 1); const Discrete2DFunction& function = *reinterpret_cast<const Discrete2DFunction*>(object); int xsize, ysize; vector<double> values; function.getFunctionParameters(xsize, ysize, values); node.setDoubleProperty("xsize", xsize); node.setDoubleProperty("ysize", ysize); SerializationNode& valuesNode = node.createChildNode("Values"); for (auto v : values) valuesNode.createChildNode("Value").setDoubleProperty("v", v); } void* Discrete2DFunctionProxy::deserialize(const SerializationNode& node) const { if (node.getIntProperty("version") != 1) throw OpenMMException("Unsupported version number"); const SerializationNode& valuesNode = node.getChildNode("Values"); vector<double> values; for (auto& child : valuesNode.getChildren()) values.push_back(child.getDoubleProperty("v")); return new Discrete2DFunction(node.getIntProperty("xsize"), node.getIntProperty("ysize"), values); } Discrete3DFunctionProxy::Discrete3DFunctionProxy() : SerializationProxy("Discrete3DFunction") { } void Discrete3DFunctionProxy::serialize(const void* object, SerializationNode& node) const { node.setIntProperty("version", 1); const Discrete3DFunction& function = *reinterpret_cast<const Discrete3DFunction*>(object); int xsize, ysize, zsize; vector<double> values; function.getFunctionParameters(xsize, ysize, zsize, values); node.setDoubleProperty("xsize", xsize); node.setDoubleProperty("ysize", ysize); node.setDoubleProperty("zsize", zsize); SerializationNode& valuesNode = node.createChildNode("Values"); for (auto v : values) valuesNode.createChildNode("Value").setDoubleProperty("v", v); } void* Discrete3DFunctionProxy::deserialize(const SerializationNode& node) const { if (node.getIntProperty("version") != 1) throw OpenMMException("Unsupported version number"); const SerializationNode& valuesNode = node.getChildNode("Values"); vector<double> values; for (auto& child : valuesNode.getChildren()) values.push_back(child.getDoubleProperty("v")); return new Discrete3DFunction(node.getIntProperty("xsize"), node.getIntProperty("ysize"), node.getIntProperty("zsize"), values); }
51.095694
140
0.679183
merkys
6cab74507e15993510bc4f9bf6f18d5cd7894d44
1,227
cpp
C++
spicetrade/playaction.cpp
mvaganov/spicetrade
123b009365deb5b8dcdfc4a2f2dd7b28fa2f024e
[ "Unlicense" ]
null
null
null
spicetrade/playaction.cpp
mvaganov/spicetrade
123b009365deb5b8dcdfc4a2f2dd7b28fa2f024e
[ "Unlicense" ]
null
null
null
spicetrade/playaction.cpp
mvaganov/spicetrade
123b009365deb5b8dcdfc4a2f2dd7b28fa2f024e
[ "Unlicense" ]
null
null
null
#include "playaction.h" #include "game.h" #include "playerstate.h" void PlayAction::PrintAction (Game& g, const PlayAction* a, int bg) { int ofcolor = CLI::getFcolor (), obcolor = CLI::getBcolor (); CLI::setColor (CLI::COLOR::LIGHT_GRAY, bg); const int width = 5; std::string str = a?a->input:""; int leadSpace = width - str.length (); for (int i = 0; i < leadSpace; ++i) { CLI::putchar (' '); } for (int i = 0; i < str.length (); ++i) { CLI::setColor (g.ColorOfRes (str[i]), bg); CLI::putchar (str[i]); } CLI::setColor (CLI::COLOR::LIGHT_GRAY, bg); CLI::putchar (':'); str = a?a->output:""; leadSpace = width - str.length (); for (int i = 0; i < str.length (); ++i) { CLI::setColor (g.ColorOfRes (str[i]), bg); CLI::putchar (str[i]); } CLI::setColor (CLI::COLOR::LIGHT_GRAY, bg); for (int i = 0; i < leadSpace; ++i) { CLI::putchar (' '); } CLI::setColor (ofcolor, obcolor); } void PlayAction::DoIt(Game& g, Player& p, const PlayAction* a) { Player::SubtractResources (g, a->input, p.inventory); Player::AddResources (g, p.upgradeChoices, a->output, p.inventory, p.hand, p.played); p.hand.RemoveAt (p.currentRow); if (a->output == "cards") { p.hand.Add (a); } else { p.played.Add (a); } }
30.675
86
0.613692
mvaganov
6cab7fa05d581a570217933c054ae37ae60cda3c
2,236
cpp
C++
ege/ege3d/tests/Primitives.cpp
sppmacd/ege
a82ff6fccc8ac1bce5a50ed5a8f101b63f58b020
[ "MIT" ]
1
2020-12-30T17:21:11.000Z
2020-12-30T17:21:11.000Z
ege/ege3d/tests/Primitives.cpp
sppmacd/ege
a82ff6fccc8ac1bce5a50ed5a8f101b63f58b020
[ "MIT" ]
20
2020-09-02T08:37:13.000Z
2021-09-02T06:47:08.000Z
ege/ege3d/tests/Primitives.cpp
sppmacd/ege
a82ff6fccc8ac1bce5a50ed5a8f101b63f58b020
[ "MIT" ]
null
null
null
#include "ege3d/window/GLError.h" #include <ege3d/window/RenderingState.h> #include <ege3d/window/SystemEvent.h> #include <ege3d/window/Renderable.h> #include <ege3d/window/Renderer.h> #include <ege/debug/Logger.h> #include <GL/gl.h> class MyRenderable : public EGE3d::Renderable { public: virtual void render(EGE3d::RenderingState const& state) override { EGE3d::Renderer renderer(state); renderer.renderRectangle({10, 10, 20, 20}, EGE::Colors::red); renderer.renderCircle({45, 20}, 10, EGE::Colors::red); renderer.renderCircle({70, 20}, 10, EGE::Colors::red, 5); renderer.renderTexturedRectangle({90, 10, 16, 16}, texture, {0, 0, 32, 32}); renderer.renderTexturedRectangle({120, 10, 32, 32}, texture, {0, 0, 32, 32}); } virtual void updateGeometry() override { image = makeUnique<EGE::ColorRGBA[]>(32*32); for(unsigned x = 0; x < 32; x++) { for(unsigned y = 0; y < 32; y++) { image[y * 32 + x] = (x+y) % 2 == 0 ? EGE::Colors::green : EGE::Colors::red; } } texture = EGE3d::Texture::createFromColorArray({32, 32}, image.get()); } private: EGE3d::Texture texture; // TODO: Add some EGE3d::Image wrapper for this!! EGE::UniquePtr<EGE::ColorRGBA[]> image; }; int main() { EGE3d::Window window; window.create(500, 500, "EGE3d Test", EGE3d::WindowSettings()); glClearColor(0.0, 0.1, 0.0, 0.0); MyRenderable renderable; while(window.isOpen()) { while(true) { auto event = window.nextEvent(false); if(!event.hasValue()) break; if(event.value().getEventType() == EGE3d::SystemEventType::EClose) { window.close(); break; } } // Clear the window // TODO: Maybe this should also go to states? glClear(GL_COLOR_BUFFER_BIT); // Ortho test. EGE3d::RenderingState state(window); state.applyClip({500, 500}); // No clip renderable.fullRender(state); // Flush the back buffer window.display(); } window.close(); return 0; }
27.604938
91
0.568426
sppmacd
6cac158add29e0233fccedc7182d74b1daa8631f
696
cpp
C++
src/acpi/apic/apic.cpp
AlexandreArduino/mykernel
488a947c87457b11471a06f3fd0544d6145806d7
[ "BSD-3-Clause" ]
9
2022-01-30T12:54:58.000Z
2022-01-30T16:51:45.000Z
src/acpi/apic/apic.cpp
AlexandreArduino/mykernel
488a947c87457b11471a06f3fd0544d6145806d7
[ "BSD-3-Clause" ]
null
null
null
src/acpi/apic/apic.cpp
AlexandreArduino/mykernel
488a947c87457b11471a06f3fd0544d6145806d7
[ "BSD-3-Clause" ]
null
null
null
#include "apic.h" APIC apic; void APIC::init(uint64_t *apic_address) { if(apic_address == NULL) Exceptions::panic("No APIC table found!"); else this->apic = (struct MADTDescriptor*)apic_address; log.log("APIC::init", "MADT table located at 0x"); log.logln(String((uint64_t)this->apic, HEXADECIMAL)); // this->mask_all_interrupts(); log.log("APIC::init", "Local APIC address : 0x"); log.logln(String((uint64_t)this->apic->lapic_address, HEXADECIMAL)); } void APIC::mask_all_interrupts(){ log.logln("APIC::mask_all_interrupts", "Masking all PIC Interrupts..."); asm ("cli"); outb(PIC1_DATA, 0b11111111); outb(PIC2_DATA, 0b11111111); asm ("sti"); }
31.636364
76
0.672414
AlexandreArduino
6cadf170e2336281579a3af94cc8bfd4947efb1f
2,380
hpp
C++
modules/core/base/include/nt2/predicates/functions/arecatcompatible.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/base/include/nt2/predicates/functions/arecatcompatible.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/base/include/nt2/predicates/functions/arecatcompatible.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2014 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2012 - 2014 MetaScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_PREDICATES_FUNCTIONS_ARECATCOMPATIBLE_HPP_INCLUDED #define NT2_PREDICATES_FUNCTIONS_ARECATCOMPATIBLE_HPP_INCLUDED #include <nt2/include/functor.hpp> namespace nt2 { namespace tag { /*! @brief Tag for arecatcompatible functor **/ struct arecatcompatible_ : ext::abstract_<arecatcompatible_> { typedef ext::abstract_<arecatcompatible_> parent; template<class... Args> static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args) BOOST_AUTO_DECLTYPE_BODY( dispatching_arecatcompatible_( ext::adl_helper(), static_cast<Args&&>(args)... ) ) }; } namespace ext { template<class Site, class... Ts> BOOST_FORCEINLINE generic_dispatcher<tag::arecatcompatible_, Site> dispatching_arecatcompatible_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...) { return generic_dispatcher<tag::arecatcompatible_, Site>(); } template<class... Args> struct impl_arecatcompatible_; } /*! @brief Check for concatenation compatibility For two given expressions and a given dimension, arecatcompatible verifies that the concatenation of both table along the chosen dimension is valid. @param a0 First expression to concatenate @param a1 Second expression to concatenate @param dim Dimension along which the concatenation is tested @return a boolean value that evaluates to true if @c a0 and @c a1 can be concatenated along thier @c dim dimension. **/ template< class A0, class A1,class D> BOOST_FORCEINLINE typename meta::call<tag::arecatcompatible_(A0 const&, A1 const&, D const&)>::type arecatcompatible(A0 const& a0, A1 const& a1, D const& dim) { return typename make_functor<tag::arecatcompatible_,A0>::type()(a0,a1,dim); } } #endif
37.1875
191
0.657563
psiha
6cb6ea097e8db7ecef00a4aa0fe85d64aeb3890c
2,569
cpp
C++
qfontdialog_c.cpp
mariuszmaximus/qt5pas-aarch64-linux-gnu
c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b
[ "Apache-2.0" ]
null
null
null
qfontdialog_c.cpp
mariuszmaximus/qt5pas-aarch64-linux-gnu
c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b
[ "Apache-2.0" ]
null
null
null
qfontdialog_c.cpp
mariuszmaximus/qt5pas-aarch64-linux-gnu
c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b
[ "Apache-2.0" ]
null
null
null
//****************************************************************************** // Copyright (c) 2005-2013 by Jan Van hijfte // // See the included file COPYING.TXT for details about the copyright. // // 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. //****************************************************************************** #include "qfontdialog_c.h" QFontDialogH QFontDialog_Create(QWidgetH parent) { return (QFontDialogH) new QFontDialog((QWidget*)parent); } void QFontDialog_Destroy(QFontDialogH handle) { delete (QFontDialog *)handle; } QFontDialogH QFontDialog_Create2(const QFontH initial, QWidgetH parent) { return (QFontDialogH) new QFontDialog(*(const QFont*)initial, (QWidget*)parent); } void QFontDialog_setCurrentFont(QFontDialogH handle, const QFontH font) { ((QFontDialog *)handle)->setCurrentFont(*(const QFont*)font); } void QFontDialog_currentFont(QFontDialogH handle, QFontH retval) { *(QFont *)retval = ((QFontDialog *)handle)->currentFont(); } void QFontDialog_selectedFont(QFontDialogH handle, QFontH retval) { *(QFont *)retval = ((QFontDialog *)handle)->selectedFont(); } void QFontDialog_setOption(QFontDialogH handle, QFontDialog::FontDialogOption option, bool on) { ((QFontDialog *)handle)->setOption(option, on); } bool QFontDialog_testOption(QFontDialogH handle, QFontDialog::FontDialogOption option) { return (bool) ((QFontDialog *)handle)->testOption(option); } void QFontDialog_setOptions(QFontDialogH handle, unsigned int options) { ((QFontDialog *)handle)->setOptions((QFontDialog::FontDialogOptions)options); } unsigned int QFontDialog_options(QFontDialogH handle) { return (unsigned int) ((QFontDialog *)handle)->options(); } void QFontDialog_open(QFontDialogH handle, QObjectH receiver, const char* member) { ((QFontDialog *)handle)->open((QObject*)receiver, member); } void QFontDialog_setVisible(QFontDialogH handle, bool visible) { ((QFontDialog *)handle)->setVisible(visible); } void QFontDialog_getFont(QFontH retval, bool* ok, QWidgetH parent) { *(QFont *)retval = QFontDialog::getFont(ok, (QWidget*)parent); } void QFontDialog_getFont2(QFontH retval, bool* ok, const QFontH initial, QWidgetH parent, PWideString title, unsigned int options) { QString t_title; copyPWideStringToQString(title, t_title); *(QFont *)retval = QFontDialog::getFont(ok, *(const QFont*)initial, (QWidget*)parent, t_title, (QFontDialog::FontDialogOptions)options); }
29.872093
137
0.718178
mariuszmaximus
6cb73fda4716b5a9fa5f0a3c719dce99a1759de1
21,058
cpp
C++
apiwznm/PnlWznmNavJob.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
3
2020-09-20T16:24:48.000Z
2021-12-01T19:44:51.000Z
apiwznm/PnlWznmNavJob.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
apiwznm/PnlWznmNavJob.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
/** * \file PnlWznmNavJob.cpp * API code for job PnlWznmNavJob (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 5 Dec 2020 */ // IP header --- ABOVE #include "PnlWznmNavJob.h" using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class PnlWznmNavJob::VecVDo ******************************************************************************/ uint PnlWznmNavJob::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butjobviewclick") return BUTJOBVIEWCLICK; if (s == "butjobnewcrdclick") return BUTJOBNEWCRDCLICK; if (s == "butsgeviewclick") return BUTSGEVIEWCLICK; if (s == "butsgenewcrdclick") return BUTSGENEWCRDCLICK; if (s == "butmtdviewclick") return BUTMTDVIEWCLICK; if (s == "butmtdnewcrdclick") return BUTMTDNEWCRDCLICK; if (s == "butblkviewclick") return BUTBLKVIEWCLICK; if (s == "butblknewcrdclick") return BUTBLKNEWCRDCLICK; if (s == "butcalviewclick") return BUTCALVIEWCLICK; if (s == "butcalnewcrdclick") return BUTCALNEWCRDCLICK; return(0); }; string PnlWznmNavJob::VecVDo::getSref( const uint ix ) { if (ix == BUTJOBVIEWCLICK) return("ButJobViewClick"); if (ix == BUTJOBNEWCRDCLICK) return("ButJobNewcrdClick"); if (ix == BUTSGEVIEWCLICK) return("ButSgeViewClick"); if (ix == BUTSGENEWCRDCLICK) return("ButSgeNewcrdClick"); if (ix == BUTMTDVIEWCLICK) return("ButMtdViewClick"); if (ix == BUTMTDNEWCRDCLICK) return("ButMtdNewcrdClick"); if (ix == BUTBLKVIEWCLICK) return("ButBlkViewClick"); if (ix == BUTBLKNEWCRDCLICK) return("ButBlkNewcrdClick"); if (ix == BUTCALVIEWCLICK) return("ButCalViewClick"); if (ix == BUTCALNEWCRDCLICK) return("ButCalNewcrdClick"); return(""); }; /****************************************************************************** class PnlWznmNavJob::ContIac ******************************************************************************/ PnlWznmNavJob::ContIac::ContIac( const uint numFLstJob , const uint numFLstSge , const uint numFLstMtd , const uint numFLstBlk , const uint numFLstCal ) : Block() { this->numFLstJob = numFLstJob; this->numFLstSge = numFLstSge; this->numFLstMtd = numFLstMtd; this->numFLstBlk = numFLstBlk; this->numFLstCal = numFLstCal; mask = {NUMFLSTJOB, NUMFLSTSGE, NUMFLSTMTD, NUMFLSTBLK, NUMFLSTCAL}; }; bool PnlWznmNavJob::ContIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacWznmNavJob"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemIacWznmNavJob"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstJob", numFLstJob)) add(NUMFLSTJOB); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstSge", numFLstSge)) add(NUMFLSTSGE); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstMtd", numFLstMtd)) add(NUMFLSTMTD); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstBlk", numFLstBlk)) add(NUMFLSTBLK); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstCal", numFLstCal)) add(NUMFLSTCAL); }; return basefound; }; void PnlWznmNavJob::ContIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContIacWznmNavJob"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemIacWznmNavJob"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "numFLstJob", numFLstJob); writeUintAttr(wr, itemtag, "sref", "numFLstSge", numFLstSge); writeUintAttr(wr, itemtag, "sref", "numFLstMtd", numFLstMtd); writeUintAttr(wr, itemtag, "sref", "numFLstBlk", numFLstBlk); writeUintAttr(wr, itemtag, "sref", "numFLstCal", numFLstCal); xmlTextWriterEndElement(wr); }; set<uint> PnlWznmNavJob::ContIac::comm( const ContIac* comp ) { set<uint> items; if (numFLstJob == comp->numFLstJob) insert(items, NUMFLSTJOB); if (numFLstSge == comp->numFLstSge) insert(items, NUMFLSTSGE); if (numFLstMtd == comp->numFLstMtd) insert(items, NUMFLSTMTD); if (numFLstBlk == comp->numFLstBlk) insert(items, NUMFLSTBLK); if (numFLstCal == comp->numFLstCal) insert(items, NUMFLSTCAL); return(items); }; set<uint> PnlWznmNavJob::ContIac::diff( const ContIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {NUMFLSTJOB, NUMFLSTSGE, NUMFLSTMTD, NUMFLSTBLK, NUMFLSTCAL}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmNavJob::StatApp ******************************************************************************/ PnlWznmNavJob::StatApp::StatApp( const uint ixWznmVExpstate , const bool LstJobAlt , const bool LstSgeAlt , const bool LstMtdAlt , const bool LstBlkAlt , const bool LstCalAlt , const uint LstJobNumFirstdisp , const uint LstSgeNumFirstdisp , const uint LstMtdNumFirstdisp , const uint LstBlkNumFirstdisp , const uint LstCalNumFirstdisp ) : Block() { this->ixWznmVExpstate = ixWznmVExpstate; this->LstJobAlt = LstJobAlt; this->LstSgeAlt = LstSgeAlt; this->LstMtdAlt = LstMtdAlt; this->LstBlkAlt = LstBlkAlt; this->LstCalAlt = LstCalAlt; this->LstJobNumFirstdisp = LstJobNumFirstdisp; this->LstSgeNumFirstdisp = LstSgeNumFirstdisp; this->LstMtdNumFirstdisp = LstMtdNumFirstdisp; this->LstBlkNumFirstdisp = LstBlkNumFirstdisp; this->LstCalNumFirstdisp = LstCalNumFirstdisp; mask = {IXWZNMVEXPSTATE, LSTJOBALT, LSTSGEALT, LSTMTDALT, LSTBLKALT, LSTCALALT, LSTJOBNUMFIRSTDISP, LSTSGENUMFIRSTDISP, LSTMTDNUMFIRSTDISP, LSTBLKNUMFIRSTDISP, LSTCALNUMFIRSTDISP}; }; bool PnlWznmNavJob::StatApp::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string srefIxWznmVExpstate; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppWznmNavJob"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemAppWznmNavJob"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "srefIxWznmVExpstate", srefIxWznmVExpstate)) { ixWznmVExpstate = VecWznmVExpstate::getIx(srefIxWznmVExpstate); add(IXWZNMVEXPSTATE); }; if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstJobAlt", LstJobAlt)) add(LSTJOBALT); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstSgeAlt", LstSgeAlt)) add(LSTSGEALT); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstMtdAlt", LstMtdAlt)) add(LSTMTDALT); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstBlkAlt", LstBlkAlt)) add(LSTBLKALT); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstCalAlt", LstCalAlt)) add(LSTCALALT); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstJobNumFirstdisp", LstJobNumFirstdisp)) add(LSTJOBNUMFIRSTDISP); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstSgeNumFirstdisp", LstSgeNumFirstdisp)) add(LSTSGENUMFIRSTDISP); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstMtdNumFirstdisp", LstMtdNumFirstdisp)) add(LSTMTDNUMFIRSTDISP); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstBlkNumFirstdisp", LstBlkNumFirstdisp)) add(LSTBLKNUMFIRSTDISP); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstCalNumFirstdisp", LstCalNumFirstdisp)) add(LSTCALNUMFIRSTDISP); }; return basefound; }; set<uint> PnlWznmNavJob::StatApp::comm( const StatApp* comp ) { set<uint> items; if (ixWznmVExpstate == comp->ixWznmVExpstate) insert(items, IXWZNMVEXPSTATE); if (LstJobAlt == comp->LstJobAlt) insert(items, LSTJOBALT); if (LstSgeAlt == comp->LstSgeAlt) insert(items, LSTSGEALT); if (LstMtdAlt == comp->LstMtdAlt) insert(items, LSTMTDALT); if (LstBlkAlt == comp->LstBlkAlt) insert(items, LSTBLKALT); if (LstCalAlt == comp->LstCalAlt) insert(items, LSTCALALT); if (LstJobNumFirstdisp == comp->LstJobNumFirstdisp) insert(items, LSTJOBNUMFIRSTDISP); if (LstSgeNumFirstdisp == comp->LstSgeNumFirstdisp) insert(items, LSTSGENUMFIRSTDISP); if (LstMtdNumFirstdisp == comp->LstMtdNumFirstdisp) insert(items, LSTMTDNUMFIRSTDISP); if (LstBlkNumFirstdisp == comp->LstBlkNumFirstdisp) insert(items, LSTBLKNUMFIRSTDISP); if (LstCalNumFirstdisp == comp->LstCalNumFirstdisp) insert(items, LSTCALNUMFIRSTDISP); return(items); }; set<uint> PnlWznmNavJob::StatApp::diff( const StatApp* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {IXWZNMVEXPSTATE, LSTJOBALT, LSTSGEALT, LSTMTDALT, LSTBLKALT, LSTCALALT, LSTJOBNUMFIRSTDISP, LSTSGENUMFIRSTDISP, LSTMTDNUMFIRSTDISP, LSTBLKNUMFIRSTDISP, LSTCALNUMFIRSTDISP}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmNavJob::StatShr ******************************************************************************/ PnlWznmNavJob::StatShr::StatShr( const bool LstJobAvail , const bool ButJobViewActive , const bool ButJobNewcrdActive , const bool LstSgeAvail , const bool ButSgeViewActive , const bool ButSgeNewcrdActive , const bool LstMtdAvail , const bool ButMtdViewActive , const bool ButMtdNewcrdActive , const bool LstBlkAvail , const bool ButBlkViewActive , const bool ButBlkNewcrdActive , const bool LstCalAvail , const bool ButCalViewActive , const bool ButCalNewcrdActive ) : Block() { this->LstJobAvail = LstJobAvail; this->ButJobViewActive = ButJobViewActive; this->ButJobNewcrdActive = ButJobNewcrdActive; this->LstSgeAvail = LstSgeAvail; this->ButSgeViewActive = ButSgeViewActive; this->ButSgeNewcrdActive = ButSgeNewcrdActive; this->LstMtdAvail = LstMtdAvail; this->ButMtdViewActive = ButMtdViewActive; this->ButMtdNewcrdActive = ButMtdNewcrdActive; this->LstBlkAvail = LstBlkAvail; this->ButBlkViewActive = ButBlkViewActive; this->ButBlkNewcrdActive = ButBlkNewcrdActive; this->LstCalAvail = LstCalAvail; this->ButCalViewActive = ButCalViewActive; this->ButCalNewcrdActive = ButCalNewcrdActive; mask = {LSTJOBAVAIL, BUTJOBVIEWACTIVE, BUTJOBNEWCRDACTIVE, LSTSGEAVAIL, BUTSGEVIEWACTIVE, BUTSGENEWCRDACTIVE, LSTMTDAVAIL, BUTMTDVIEWACTIVE, BUTMTDNEWCRDACTIVE, LSTBLKAVAIL, BUTBLKVIEWACTIVE, BUTBLKNEWCRDACTIVE, LSTCALAVAIL, BUTCALVIEWACTIVE, BUTCALNEWCRDACTIVE}; }; bool PnlWznmNavJob::StatShr::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrWznmNavJob"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemShrWznmNavJob"; if (basefound) { if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstJobAvail", LstJobAvail)) add(LSTJOBAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButJobViewActive", ButJobViewActive)) add(BUTJOBVIEWACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButJobNewcrdActive", ButJobNewcrdActive)) add(BUTJOBNEWCRDACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstSgeAvail", LstSgeAvail)) add(LSTSGEAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSgeViewActive", ButSgeViewActive)) add(BUTSGEVIEWACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSgeNewcrdActive", ButSgeNewcrdActive)) add(BUTSGENEWCRDACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstMtdAvail", LstMtdAvail)) add(LSTMTDAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButMtdViewActive", ButMtdViewActive)) add(BUTMTDVIEWACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButMtdNewcrdActive", ButMtdNewcrdActive)) add(BUTMTDNEWCRDACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstBlkAvail", LstBlkAvail)) add(LSTBLKAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButBlkViewActive", ButBlkViewActive)) add(BUTBLKVIEWACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButBlkNewcrdActive", ButBlkNewcrdActive)) add(BUTBLKNEWCRDACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstCalAvail", LstCalAvail)) add(LSTCALAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButCalViewActive", ButCalViewActive)) add(BUTCALVIEWACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButCalNewcrdActive", ButCalNewcrdActive)) add(BUTCALNEWCRDACTIVE); }; return basefound; }; set<uint> PnlWznmNavJob::StatShr::comm( const StatShr* comp ) { set<uint> items; if (LstJobAvail == comp->LstJobAvail) insert(items, LSTJOBAVAIL); if (ButJobViewActive == comp->ButJobViewActive) insert(items, BUTJOBVIEWACTIVE); if (ButJobNewcrdActive == comp->ButJobNewcrdActive) insert(items, BUTJOBNEWCRDACTIVE); if (LstSgeAvail == comp->LstSgeAvail) insert(items, LSTSGEAVAIL); if (ButSgeViewActive == comp->ButSgeViewActive) insert(items, BUTSGEVIEWACTIVE); if (ButSgeNewcrdActive == comp->ButSgeNewcrdActive) insert(items, BUTSGENEWCRDACTIVE); if (LstMtdAvail == comp->LstMtdAvail) insert(items, LSTMTDAVAIL); if (ButMtdViewActive == comp->ButMtdViewActive) insert(items, BUTMTDVIEWACTIVE); if (ButMtdNewcrdActive == comp->ButMtdNewcrdActive) insert(items, BUTMTDNEWCRDACTIVE); if (LstBlkAvail == comp->LstBlkAvail) insert(items, LSTBLKAVAIL); if (ButBlkViewActive == comp->ButBlkViewActive) insert(items, BUTBLKVIEWACTIVE); if (ButBlkNewcrdActive == comp->ButBlkNewcrdActive) insert(items, BUTBLKNEWCRDACTIVE); if (LstCalAvail == comp->LstCalAvail) insert(items, LSTCALAVAIL); if (ButCalViewActive == comp->ButCalViewActive) insert(items, BUTCALVIEWACTIVE); if (ButCalNewcrdActive == comp->ButCalNewcrdActive) insert(items, BUTCALNEWCRDACTIVE); return(items); }; set<uint> PnlWznmNavJob::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {LSTJOBAVAIL, BUTJOBVIEWACTIVE, BUTJOBNEWCRDACTIVE, LSTSGEAVAIL, BUTSGEVIEWACTIVE, BUTSGENEWCRDACTIVE, LSTMTDAVAIL, BUTMTDVIEWACTIVE, BUTMTDNEWCRDACTIVE, LSTBLKAVAIL, BUTBLKVIEWACTIVE, BUTBLKNEWCRDACTIVE, LSTCALAVAIL, BUTCALVIEWACTIVE, BUTCALNEWCRDACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmNavJob::Tag ******************************************************************************/ PnlWznmNavJob::Tag::Tag( const string& Cpt , const string& CptJob , const string& CptSge , const string& CptMtd , const string& CptBlk , const string& CptCal ) : Block() { this->Cpt = Cpt; this->CptJob = CptJob; this->CptSge = CptSge; this->CptMtd = CptMtd; this->CptBlk = CptBlk; this->CptCal = CptCal; mask = {CPT, CPTJOB, CPTSGE, CPTMTD, CPTBLK, CPTCAL}; }; bool PnlWznmNavJob::Tag::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagWznmNavJob"); else basefound = checkXPath(docctx, basexpath); string itemtag = "TagitemWznmNavJob"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Cpt", Cpt)) add(CPT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptJob", CptJob)) add(CPTJOB); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptSge", CptSge)) add(CPTSGE); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptMtd", CptMtd)) add(CPTMTD); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptBlk", CptBlk)) add(CPTBLK); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptCal", CptCal)) add(CPTCAL); }; return basefound; }; /****************************************************************************** class PnlWznmNavJob::DpchAppData ******************************************************************************/ PnlWznmNavJob::DpchAppData::DpchAppData( const string& scrJref , ContIac* contiac , const set<uint>& mask ) : DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMNAVJOBDATA, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, CONTIAC}; else this->mask = mask; if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac; }; string PnlWznmNavJob::DpchAppData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(CONTIAC)) ss.push_back("contiac"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmNavJob::DpchAppData::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmNavJobData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(CONTIAC)) contiac.writeXML(wr); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWznmNavJob::DpchAppDo ******************************************************************************/ PnlWznmNavJob::DpchAppDo::DpchAppDo( const string& scrJref , const uint ixVDo , const set<uint>& mask ) : DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMNAVJOBDO, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO}; else this->mask = mask; this->ixVDo = ixVDo; }; string PnlWznmNavJob::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmNavJob::DpchAppDo::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmNavJobDo"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo)); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWznmNavJob::DpchEngData ******************************************************************************/ PnlWznmNavJob::DpchEngData::DpchEngData() : DpchEngWznm(VecWznmVDpch::DPCHENGWZNMNAVJOBDATA) { feedFLstBlk.tag = "FeedFLstBlk"; feedFLstCal.tag = "FeedFLstCal"; feedFLstJob.tag = "FeedFLstJob"; feedFLstMtd.tag = "FeedFLstMtd"; feedFLstSge.tag = "FeedFLstSge"; }; string PnlWznmNavJob::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(CONTIAC)) ss.push_back("contiac"); if (has(FEEDFLSTBLK)) ss.push_back("feedFLstBlk"); if (has(FEEDFLSTCAL)) ss.push_back("feedFLstCal"); if (has(FEEDFLSTJOB)) ss.push_back("feedFLstJob"); if (has(FEEDFLSTMTD)) ss.push_back("feedFLstMtd"); if (has(FEEDFLSTSGE)) ss.push_back("feedFLstSge"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(TAG)) ss.push_back("tag"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmNavJob::DpchEngData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngWznmNavJobData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF); if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC); if (feedFLstBlk.readXML(docctx, basexpath, true)) add(FEEDFLSTBLK); if (feedFLstCal.readXML(docctx, basexpath, true)) add(FEEDFLSTCAL); if (feedFLstJob.readXML(docctx, basexpath, true)) add(FEEDFLSTJOB); if (feedFLstMtd.readXML(docctx, basexpath, true)) add(FEEDFLSTMTD); if (feedFLstSge.readXML(docctx, basexpath, true)) add(FEEDFLSTSGE); if (statapp.readXML(docctx, basexpath, true)) add(STATAPP); if (statshr.readXML(docctx, basexpath, true)) add(STATSHR); if (tag.readXML(docctx, basexpath, true)) add(TAG); } else { contiac = ContIac(); feedFLstBlk.clear(); feedFLstCal.clear(); feedFLstJob.clear(); feedFLstMtd.clear(); feedFLstSge.clear(); statapp = StatApp(); statshr = StatShr(); tag = Tag(); }; };
36.495667
269
0.693181
mpsitech
6cb79f7e758a5d04fe5e52a64dce35a1d3889185
5,718
cpp
C++
PCoreLib/PSpriteManager.cpp
bear1704/WindowsProgramming_Portfolio
83f1d763c73d08b82291aa894ef246558fdf0198
[ "Apache-2.0" ]
null
null
null
PCoreLib/PSpriteManager.cpp
bear1704/WindowsProgramming_Portfolio
83f1d763c73d08b82291aa894ef246558fdf0198
[ "Apache-2.0" ]
null
null
null
PCoreLib/PSpriteManager.cpp
bear1704/WindowsProgramming_Portfolio
83f1d763c73d08b82291aa894ef246558fdf0198
[ "Apache-2.0" ]
null
null
null
#include "PSpriteManager.h" PSpriteManager::~PSpriteManager() { } PSpriteManager::PSpriteManager() : kDamageFontLifetime(1.2f), kDamageFontGap(35.0f) { dmg_font_index_ = 0; } bool PSpriteManager::Init() { need_load_character_sprite_data_ = true; need_load_UI_sprite_data_ = true; need_load_map_sprite_data_ = true; return true; } bool PSpriteManager::Frame() { for (PSprite& sprite : render_wait_list_) { if (sprite.get_is_dmg()) { pPoint pos = sprite.get_position_(); sprite.SetPosition(pos.x, pos.y - 0.5f); } sprite.Frame(); } return false; } bool PSpriteManager::Render() { for (PSprite& sprite : render_wait_list_) { sprite.Render(); } return false; } bool PSpriteManager::Release() { for (auto iter = render_wait_list_.begin(); iter != render_wait_list_.end(); ) { PSprite& sprite = *iter; if (sprite.get_is_dead_()) { sprite.Release(); iter = render_wait_list_.erase(iter); } else { iter++; } } return false; } //SpriteDataInfo * PSpriteManager::get_sprite_data_list_from_map(std::wstring key) //{ // // auto iter = sprite_data_list_.find(key); // if (iter != sprite_data_list_.end()) // { // SpriteDataInfo* data = (*iter).second; // return data; // } // return nullptr; //} PSprite* PSpriteManager::get_sprite_from_map_ex(std::wstring key) { auto iter = sprite_list_.find(key); if (iter != sprite_list_.end()) { PSprite* data = (*iter).second; return data; } return nullptr; } PSprite* PSpriteManager::get_sprite_from_dmgfont_list(std::wstring key) { auto iter = damage_font_list_.find(key); if (iter != damage_font_list_.end()) { PSprite* data = (*iter).second; return data; } return nullptr; } void PSpriteManager::LoadSpriteDataFromScript(multibyte_string filepath, ObjectLoadType type) { if (!need_load_character_sprite_data_ && type == ObjectLoadType::CHARACTER) return; if (!need_load_UI_sprite_data_ && type == ObjectLoadType::UI) return; if (!need_load_map_sprite_data_ && type == ObjectLoadType::MAP) return; PParser parser; std::vector<std::pair<string, string>> ret_parse; std::string str; str.assign(filepath.begin(), filepath.end()); parser.XmlParse(str, &ret_parse); for (auto iter = ret_parse.begin() ; iter != ret_parse.end() ; iter++) { if (iter->second.compare("sprite") == 0) { SpriteDataInfo info; std::wstring sprite_name; while (true) { iter++; if (iter->first.compare("name") == 0) sprite_name.assign(iter->second.begin(), iter->second.end()); else if (iter->first.compare("max_frame") == 0) info.max_frame = std::atoi(iter->second.c_str()); else if (iter->first.compare("lifetime") == 0) info.lifetime = std::atof(iter->second.c_str()); else if (iter->first.compare("once_playtime") == 0) info.once_playtime = std::atof(iter->second.c_str()); else if (iter->first.compare("path") == 0) info.bitmap_path.assign(iter->second.begin(), iter->second.end()); else if (iter->first.compare("coord") == 0) { FLOAT_RECT rt; std::vector<string> coord_vec = parser.SplitString(iter->second, ','); rt.left = std::atof(coord_vec[0].c_str()); rt.top = std::atof(coord_vec[1].c_str()); rt.right = std::atof(coord_vec[2].c_str()); rt.bottom = std::atof(coord_vec[3].c_str()); info.rect_list.push_back(rt); } else if (iter->first.compare("END") == 0) break; } PSprite* sprite = new PSprite(); sprite->Set(info, 1.0, 1.0); sprite_list_.insert(std::make_pair(sprite_name, sprite)); } else if (iter->second.compare("dmg_sprite") == 0) { SpriteDataInfo info; std::wstring sprite_name; info.lifetime = kDamageFontLifetime; info.once_playtime = kDamageFontLifetime; while (true) { iter++; if (iter->first.compare("name") == 0) sprite_name.assign(iter->second.begin(), iter->second.end()); else if (iter->first.compare("max_frame") == 0) info.max_frame = std::atoi(iter->second.c_str()); else if (iter->first.compare("path") == 0) info.bitmap_path.assign(iter->second.begin(), iter->second.end()); else if (iter->first.compare("coord") == 0) { FLOAT_RECT rt; std::vector<string> coord_vec = parser.SplitString(iter->second, ','); rt.left = std::atof(coord_vec[0].c_str()); rt.top = std::atof(coord_vec[1].c_str()); rt.right = std::atof(coord_vec[2].c_str()); rt.bottom = std::atof(coord_vec[3].c_str()); info.rect_list.push_back(rt); } else if (iter->first.compare("END") == 0) break; } PSprite* sprite = new PSprite(); sprite->Set(info, 1.0, 1.0); damage_font_list_.insert(std::make_pair(sprite_name, sprite)); } } if (need_load_character_sprite_data_ && type == ObjectLoadType::CHARACTER) need_load_character_sprite_data_ = false; if (need_load_UI_sprite_data_ && type == ObjectLoadType::UI) need_load_UI_sprite_data_ = false; if (need_load_map_sprite_data_ && type == ObjectLoadType::MAP) need_load_map_sprite_data_ = false; } bool PSpriteManager::Delete(int key) { return false; } void PSpriteManager::AddRenderWaitList(PSprite sprite) { render_wait_list_.push_back(sprite); } void PSpriteManager::CreateDamageFontFromInteger(int damage, pPoint firstPos) { std::string damage_str = std::to_string(damage); float gap = 0; for (int i = 0; i < damage_str.size(); i++) { std::wstring nthstr(1, damage_str[i]); PSprite* sprite = get_sprite_from_dmgfont_list(nthstr); PSprite clone_sprite; clone_sprite.Clone(sprite, 1.0f, 1.5f); clone_sprite.SetPosition(firstPos.x + gap, firstPos.y); clone_sprite.set_is_dmg(true); gap += kDamageFontGap; AddRenderWaitList(clone_sprite); } }
24.331915
93
0.670689
bear1704
6cbc9c2dd04de352a7b0435adf9d09dc022d85f5
16,072
cpp
C++
C++/BitwiseAutomation/src/BitwiseDevice.cpp
jimwaschura/Automation
f655feeea74ff22ebe44d8b68374ba6983748f60
[ "BSL-1.0" ]
null
null
null
C++/BitwiseAutomation/src/BitwiseDevice.cpp
jimwaschura/Automation
f655feeea74ff22ebe44d8b68374ba6983748f60
[ "BSL-1.0" ]
null
null
null
C++/BitwiseAutomation/src/BitwiseDevice.cpp
jimwaschura/Automation
f655feeea74ff22ebe44d8b68374ba6983748f60
[ "BSL-1.0" ]
null
null
null
/* BitwiseDevice.cpp */ //================================================================================ // BOOST SOFTWARE LICENSE // // Copyright 2020 BitWise Laboratories Inc. // Author.......Jim Waschura // Contact......info@bitwiselabs.com // //Permission is hereby granted, free of charge, to any person or organization //obtaining a copy of the software and accompanying documentation covered by //this license (the "Software") to use, reproduce, display, distribute, //execute, and transmit the Software, and to prepare derivative works of the //Software, and to permit third-parties to whom the Software is furnished to //do so, all subject to the following: // //The copyright notices in the Software and this entire statement, including //the above license grant, this restriction and the following disclaimer, //must be included in all copies of the Software, in whole or in part, and //all derivative works of the Software, unless such copies or derivative //works are solely in the form of machine-executable object code generated by //a source language processor. // //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, TITLE AND NON-INFRINGEMENT. IN NO EVENT //SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE //FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, //ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //DEALINGS IN THE SOFTWARE. //================================================================================ #include <stdarg.h> /* va_list, va_start, va_end */ #include <stdio.h> /* vsnprintf,snprintf,fprintf */ #include <string.h> /* strcmp, strtok */ #include <unistd.h> /* usleep */ #include <stdlib.h> /* malloc, free */ #include <sys/stat.h> /* stat */ #include <utime.h> /* utimbuf */ #include "BitwiseDevice.h" //================================================================================ //================================================================================ void BitwiseDevice::Connect( const char *ipaddress, int port ) { base::Connect(ipaddress,port); } //================================================================================ //================================================================================ int BitwiseDevice::unpackIntegerByKey(const char *str, const char *key ) { char buffer[1024]; unpackValueByKey( buffer, 1024, str, key ); int retn=0.0; if( sscanf(buffer,"%i",&retn) != 1) throw "[No_Integer_Found]"; return retn; } double BitwiseDevice::unpackDoubleByKey(const char *str, const char *key ) { char buffer[1024]; unpackValueByKey( buffer, 1024, str, key ); double retn=0.0; if( sscanf(buffer,"%lf",&retn) != 1) throw "[No_Double_Found]"; return retn; } char *BitwiseDevice::unpackValueByKey( char *buffer, int buflen, const char *str, const char *key ) { int keylen=0; if( key==0|| (keylen=strlen(key))<1 ) throw("[Invalid_Key]"); if( buffer==0||buflen<1 ) throw "[Invalid_Buffer]"; char *ptr = (char*)malloc( strlen(str)+1 ); /* buffer because strtok changes contents */ bool found=false; try { memcpy( ptr, str, strlen(str)+1 ); char *tok = strtok(ptr,"\n"); while( tok && !found ) { if(!strncmp(tok,key,keylen) && (int)strlen(tok)>keylen && (tok[keylen]==' '||tok[keylen]=='\t'||tok[keylen]=='='||tok[keylen]==',' ) ) { snprintf(buffer,buflen,"%s",tok+keylen+1); found=true; } tok = strtok(0,"\n"); } free(ptr); } catch(...) { free(ptr); throw; } if( !found ) throw "[Key_Not_Found]"; return buffer; } //================================================================================ //================================================================================ /* add error-checking to SendCommand */ void BitwiseDevice::SendCommand( const char *command, ... ) { char outBuffer[4096+4] = "stc;"; va_list argptr; va_start(argptr,command); vsnprintf(outBuffer+4,4096,command,argptr); va_end(argptr); #ifdef DEBUG if(getDebugging()) fprintf(stderr,"BitwiseDevice::SendCommand(), command: %s", outBuffer ); #endif base::SendCommand(outBuffer); char inBuffer[4096]; base::QueryResponse(inBuffer,4096,(char*)"st?\n"); #ifdef DEBUG if(getDebugging()) fprintf(stderr,"BitwiseDevice::SendCommand(), Status Response is: [%s]\n", inBuffer ); #endif if( strcasecmp(inBuffer,"[none]") ) { static char static_throw_buffer[4096]; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-overflow" #pragma GCC diagnostic ignored "-Wformat-truncation" snprintf(static_throw_buffer,4096,"[%s]",inBuffer); #pragma GCC diagnostic pop throw (const char*)static_throw_buffer; } } /* add error-checking to QueryResponse */ char * BitwiseDevice::QueryResponse( char *buffer, int buflen, const char *command, ... ) { char outBuffer[4096+4] = "stc;"; va_list argptr; va_start(argptr,command); vsnprintf(outBuffer+4,4096,command,argptr); va_end(argptr); #ifdef DEBUG if(getDebugging()) fprintf(stderr,"BitwiseDevice::QueryResponse(), command: %s", outBuffer ); #endif base::QueryResponse(buffer,buflen,outBuffer); #ifdef DEBUG if(getDebugging()) fprintf(stderr,"BitwiseDevice::QueryResponse(), Response is: [%s]\n", buffer ); #endif char inBuffer[4096]; base::QueryResponse(inBuffer,4096,(char*)"st?\n"); #ifdef DEBUG if(getDebugging()) fprintf(stderr,"BitwiseDevice::QueryResponse(), Status Response is: [%s]\n", inBuffer ); #endif if( strcasecmp(inBuffer,"[none]") ) { static char static_throw_buffer[4096]; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-overflow" #pragma GCC diagnostic ignored "-Wformat-truncation" snprintf(static_throw_buffer,4096,"[%s]",inBuffer); #pragma GCC diagnostic pop throw (const char*)static_throw_buffer; } #ifdef DEBUG if(getDebugging()) fprintf(stderr,"BitwiseDevice::QueryResponse(), Returning: [%s]\n", buffer ); #endif return buffer; } //================================================================================ //================================================================================ /* specifying configurations: */ /* "[recent]" ... most recent settings */ /* "[factory]" ... factory settings */ /* "[startup]" ... settings from selectable startup configuration file */ /* full-path-name ... settings from fully-specified configuration file path */ /* filename-only ... settings from file located in configuration folder */ void BitwiseDevice::SaveConfiguration( const char *configuration ) { base::SendCommand( "save \"%s\"\n", configuration ); } void BitwiseDevice::RestoreConfiguration( const char *configuration, bool waitToComplete ) { App.Stop(); // just to make sure base::SendCommand( "stc; restore \"%s\"\n", configuration );/* use base: to avoid error checking */ if( waitToComplete ) WaitForRestoreToComplete(); } void BitwiseDevice::WaitForRestoreToComplete() { double now = timestamp(); double timeout = now + 30.0; #ifdef DEBUG double begin_time=now; #endif while( now < timeout ) { usleep(500*1000); now = timestamp(); #ifdef DEBUG if( getDebugging() ) fprintf(stderr,"Restoring configuration %.1lf\n",now-begin_time); #endif char buffer[4096]; base::QueryResponse(buffer,4096,"inprogress\n"); /* use base: to avoid error checking */ if( buffer[0]=='F'||buffer[0]=='0' ) break; } if( now >= timeout ) throw "[Timeout_Restoring_Configuration]"; #ifdef DEBUG if( getDebugging() ) fprintf(stderr,"Restoring configuration complete %.1lf\n",timestamp()-begin_time); #endif base::SendCommand( "stc\n");/* use base: to avoid error checking */ } //================================================================================ //================================================================================ bool BitwiseDevice::getIsRunning() { char buffer[4096]; if( App.getRunState(buffer,4096)==NULL ) throw "[Unable_To_Retrieve_Run_State]" ; char *ptr = strtok( buffer, "{}," ); bool onState = false; while ( ptr!= NULL && !onState ) { onState = onState || (strncasecmp(ptr, "Stop", 4) != 0); ptr = strtok(NULL,"{},"); } return onState ; } void BitwiseDevice::Run( double waitUntilRunningTimeout ) { App.Run(); if( waitUntilRunningTimeout>0 ) { double now = timestamp(); double timeout = now + waitUntilRunningTimeout; while( now<timeout && !getIsRunning() ) { usleep( 10*1000 ); now=timestamp(); } if( now>=timeout ) throw "[Run_Timeout]"; } } void BitwiseDevice::RunSingle( double waitUntilRunningTimeout ) { App.Run(true); if( waitUntilRunningTimeout>0 ) { double now = timestamp(); double timeout = now + waitUntilRunningTimeout; while( now<timeout && !getIsRunning() ) { usleep( 10*1000 ); now=timestamp(); } if( now>=timeout ) throw "[Run_Once_Timeout]"; } } void BitwiseDevice::WaitForRunToStart( double timeoutSec ) { double now = SocketDevice::timestamp(); double timeout = now + timeoutSec; while( now<timeout && !getIsRunning() ) { usleep( 200*1000 ); /* poll 5 times per second */ now=SocketDevice::timestamp(); } Stop(); if( now>=timeout ) throw "[Wait_Run_Start_Timeout]"; } void BitwiseDevice::WaitForRunToComplete( double timeoutSec ) { double now = SocketDevice::timestamp(); double timeout = now + timeoutSec; while( now<timeout && getIsRunning() ) { usleep( 200*1000 ); /* poll 5 times per second */ now=SocketDevice::timestamp(); } Stop(); if( now>=timeout ) throw "[Wait_Run_Complete_Timeout]"; } void BitwiseDevice::Stop() { App.Stop(); } void BitwiseDevice::Clear() { App.Clear(); } //================================================================================ //================================================================================ void BitwiseDevice::fileXferBuffer( char *buffer_bytes, int byte_count, const char *prefix ) /* use prefix "Same" for retry */ { if( buffer_bytes==NULL || byte_count<1 ) throw "[XferBuffer_Is_Empty]"; uint32_t cksum=0; for( int n=0; n<byte_count; n++ ) cksum += (uint8_t) buffer_bytes[n]; SendCommand( "stc; File:Xfer:%sBuffer %u 0x%x\n", prefix, byte_count, cksum ); Send( buffer_bytes, byte_count ); } void BitwiseDevice::SendFileAs( char *localFilePath, char *destinationFilePath ) { struct stat statbuf; if( localFilePath==NULL || localFilePath[0]==0 ) throw "[Local_Filename_Is_Missing]"; if( destinationFilePath==NULL || destinationFilePath[0]==0 ) throw "[Destination_Filename_Is_Missing]"; if(stat(localFilePath, &statbuf)!=0 ) throw "[Send_Unable_To_Stat_File]"; FILE *f = fopen(localFilePath,"rb"); if( f==NULL ) throw "[Send_Unable_To_Open_File]"; try { char timebuffer[128]; strftime( timebuffer, 128, "%Y/%m/%d %H:%M:%S", localtime( &statbuf.st_mtime )); SendCommand("File:Xfer:Put \"%s\" %s\n", destinationFilePath, timebuffer ); char buffer[4096]; char response_buffer[1024]; char *status; unsigned int count = fread(buffer,1,4096,f); while( count>0 ) { fileXferBuffer( buffer, count ); status = base::QueryResponse(response_buffer,1024,"st?\n"); unsigned int retry=0; while( retry<3 && !strcasecmp(status,"[Checksum_Error]")) { fileXferBuffer( buffer, count, "Same" ); status = base::QueryResponse(response_buffer,1024,"st?\n"); retry++ ; } if( strcasecmp(status,"[none]") ) throw "[File_Send_Failed]"; count = fread(buffer,1,4096,f); } SendCommand("File:Xfer:DonePut\n"); fclose(f); } catch(...) { if(f!=NULL ) fclose(f); SendCommand("File:Xfer:DonePut\n"); base::SendCommand("File:Del \"%s\"\n",destinationFilePath); throw; } } void BitwiseDevice::ReceiveFileAs( char *sourceFilePath, char *localFilePath ) { /* Todo: Is code-complete, needs testing */ if( sourceFilePath==NULL || sourceFilePath[0]==0 ) throw "[Source_Filename_Is_Missing]"; if( localFilePath==NULL || localFilePath[0]==0 ) throw "[Local_Filename_Is_Missing]"; char xfer[8192]; char *buffer; int n; /* returns with long string containing fields separated by space: */ /* "filename" .. including double quotes */ /* byte count */ /* year/month/day .. including forward slashes, year is 4 digits */ /* HH:MM:SS .. including colons */ buffer = base::QueryResponse( xfer, 8192, "File:Xfer:Get \"%s\"\n", sourceFilePath ); for( n=1; buffer[n]!=0 && buffer[n]!='"' && n<8192 ; n++) ; if( buffer[0]!='"' || buffer[n]!='"' ) throw "[Invalid_Response_From_Get_Command]"; unsigned int length, year, month, day, hour, minute, second; if( sscanf( buffer+n+1,"%u %u/%u/%u %u:%u:%u", &length, &year, &month, &day, &hour, &minute, &second ) != 7 ) throw "[Invalid_Response_Length_Date_Time]" ; FILE *f = fopen(localFilePath,"wb"); if( f==NULL ) throw "[Unable_To_Create_Local_File]"; try { struct { uint32_t magic; // 0x12345678 uint32_t bytes; uint32_t sum; } response ; unsigned int totalTransferred=0; unsigned int blen; while( totalTransferred<length ) { base::SendCommand( "File:Xfer:Next\n" ); blen = base::Receive( (char*) &response, sizeof(response) ); if( blen!=sizeof(response) ) throw "[No_Response_From_Next_Command]" ; if( response.magic != 0x12345678 ) throw "[Response_From_Next_Command_Is_Invalid]"; if( response.bytes==0 ) break; unsigned int cnt=0; if( response.bytes>8192 ) throw"[Individual_Transfer_Is_Too_Big]"; cnt=0; while( cnt<response.bytes ) { blen = base::Receive( xfer+cnt, response.bytes-cnt ); if( blen==0 ) throw "[Binary_Xfer_Unsuccessful]"; cnt += blen; } uint32_t sum=0; for( uint32_t i=0; i<response.bytes; i++ ) sum += (uint8_t) xfer[i]; int retry=3; while( sum != response.sum && retry>0 ) { base::SendCommand( "File:Xfer:Resend\n" ); blen = base::Receive( (char*) &response, sizeof(response) ); if( blen!=sizeof(response) ) throw "[No_Response_From_Resend_Command]" ; if( response.magic != 0x12345678 ) throw "[Response_From_Next_Command_Is_Invalid]"; if( response.bytes>8192 ) throw"[Individual_Transfer_Is_Too_Big]"; cnt=0; while( cnt<response.bytes ) { blen = base::Receive( xfer+cnt, response.bytes-cnt ); if( blen==0 ) throw "[Binary_Retry_Unsuccessful]"; cnt += blen; } uint32_t sum=0; for( uint32_t i=0; i<response.bytes; i++ ) sum += (uint8_t) xfer[i]; retry--; } if( retry==0 ) throw "[Binary_Xfer_Retries_Failed]"; if( fwrite(xfer,1,response.bytes,f) != response.bytes ) throw "[Failed_Writing_To_New_File]"; totalTransferred += response.bytes; } SendCommand("File:Xfer:DoneGet\n"); fclose(f); f=NULL; /* set resulting file to have appropriate date and time */ struct stat statbuf; if( stat(localFilePath,&statbuf)!=0 ) throw"[Unable_To_Stat_Destination_File]"; struct tm * timeinfo; timeinfo = localtime( &statbuf.st_mtime ); timeinfo->tm_year = year - 1900; timeinfo->tm_mon = month - 1; timeinfo->tm_mday = day; timeinfo->tm_hour = hour; timeinfo->tm_min = minute; timeinfo->tm_sec = second; struct utimbuf new_times; new_times.actime = mktime( timeinfo ); new_times.modtime = mktime( timeinfo ); if( utime( localFilePath, &new_times ) < 0 ) throw "[Unable_To_Set_Destination_File_Date_Time]"; } catch(...) { if(f!=NULL) fclose(f); unlink(localFilePath); throw; } } // EOF
26.048622
100
0.609072
jimwaschura
6cc06d6376bfecabe157288efb31d8bac3dbc359
4,483
cpp
C++
Game_exe/release_mode/windows/obj/src/LuaSprite.cpp
hisatsuga/Salty-Psyche-Engine-Port-Main
0c6afc6ef57f6f6a8b83ff23bb6a26bb05117ab7
[ "Apache-2.0" ]
null
null
null
Game_exe/release_mode/windows/obj/src/LuaSprite.cpp
hisatsuga/Salty-Psyche-Engine-Port-Main
0c6afc6ef57f6f6a8b83ff23bb6a26bb05117ab7
[ "Apache-2.0" ]
null
null
null
Game_exe/release_mode/windows/obj/src/LuaSprite.cpp
hisatsuga/Salty-Psyche-Engine-Port-Main
0c6afc6ef57f6f6a8b83ff23bb6a26bb05117ab7
[ "Apache-2.0" ]
null
null
null
#include <hxcpp.h> #ifndef INCLUDED_LuaSprite #include <LuaSprite.h> #endif #ifndef INCLUDED_flixel_FlxBasic #include <flixel/FlxBasic.h> #endif #ifndef INCLUDED_flixel_FlxObject #include <flixel/FlxObject.h> #endif #ifndef INCLUDED_flixel_FlxSprite #include <flixel/FlxSprite.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_14194ce63f52f33d_887_new,"LuaSprite","new",0x660a672f,"LuaSprite.new","FunkinLua.hx",887,0x00117937) void LuaSprite_obj::__construct( ::Dynamic X, ::Dynamic Y, ::Dynamic SimpleGraphic){ HX_STACKFRAME(&_hx_pos_14194ce63f52f33d_887_new) HXLINE( 890) this->isInFront = false; HXLINE( 889) this->wasAdded = false; HXLINE( 887) super::__construct(X,Y,SimpleGraphic); } Dynamic LuaSprite_obj::__CreateEmpty() { return new LuaSprite_obj; } void *LuaSprite_obj::_hx_vtable = 0; Dynamic LuaSprite_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< LuaSprite_obj > _hx_result = new LuaSprite_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2]); return _hx_result; } bool LuaSprite_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x40c918fd) { if (inClassId<=(int)0x2c01639b) { return inClassId==(int)0x00000001 || inClassId==(int)0x2c01639b; } else { return inClassId==(int)0x40c918fd; } } else { return inClassId==(int)0x7ccf8994 || inClassId==(int)0x7dab0655; } } ::hx::ObjectPtr< LuaSprite_obj > LuaSprite_obj::__new( ::Dynamic X, ::Dynamic Y, ::Dynamic SimpleGraphic) { ::hx::ObjectPtr< LuaSprite_obj > __this = new LuaSprite_obj(); __this->__construct(X,Y,SimpleGraphic); return __this; } ::hx::ObjectPtr< LuaSprite_obj > LuaSprite_obj::__alloc(::hx::Ctx *_hx_ctx, ::Dynamic X, ::Dynamic Y, ::Dynamic SimpleGraphic) { LuaSprite_obj *__this = (LuaSprite_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(LuaSprite_obj), true, "LuaSprite")); *(void **)__this = LuaSprite_obj::_hx_vtable; __this->__construct(X,Y,SimpleGraphic); return __this; } LuaSprite_obj::LuaSprite_obj() { } ::hx::Val LuaSprite_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"wasAdded") ) { return ::hx::Val( wasAdded ); } break; case 9: if (HX_FIELD_EQ(inName,"isInFront") ) { return ::hx::Val( isInFront ); } } return super::__Field(inName,inCallProp); } ::hx::Val LuaSprite_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"wasAdded") ) { wasAdded=inValue.Cast< bool >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"isInFront") ) { isInFront=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void LuaSprite_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("wasAdded",d7,ce,90,02)); outFields->push(HX_("isInFront",ba,6b,49,a7)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo LuaSprite_obj_sMemberStorageInfo[] = { {::hx::fsBool,(int)offsetof(LuaSprite_obj,wasAdded),HX_("wasAdded",d7,ce,90,02)}, {::hx::fsBool,(int)offsetof(LuaSprite_obj,isInFront),HX_("isInFront",ba,6b,49,a7)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *LuaSprite_obj_sStaticStorageInfo = 0; #endif static ::String LuaSprite_obj_sMemberFields[] = { HX_("wasAdded",d7,ce,90,02), HX_("isInFront",ba,6b,49,a7), ::String(null()) }; ::hx::Class LuaSprite_obj::__mClass; void LuaSprite_obj::__register() { LuaSprite_obj _hx_dummy; LuaSprite_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("LuaSprite",bd,a3,85,7d); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(LuaSprite_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< LuaSprite_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = LuaSprite_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = LuaSprite_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); }
32.251799
130
0.73366
hisatsuga
6cc1a112d67ec12acaf30219bc76756efd1f1df8
2,037
cpp
C++
Harbour.Space Scholarship Contest 2021-2022 (open for everyone, rated, Div. 1 + Div. 2)/Penalty.cpp
Yashdew/DSA
d211d3b53acd28879233e55b77745b60ff44410f
[ "MIT" ]
4
2021-04-13T11:04:45.000Z
2021-12-06T16:32:28.000Z
Harbour.Space Scholarship Contest 2021-2022 (open for everyone, rated, Div. 1 + Div. 2)/Penalty.cpp
Yashdew/DSA
d211d3b53acd28879233e55b77745b60ff44410f
[ "MIT" ]
null
null
null
Harbour.Space Scholarship Contest 2021-2022 (open for everyone, rated, Div. 1 + Div. 2)/Penalty.cpp
Yashdew/DSA
d211d3b53acd28879233e55b77745b60ff44410f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void solve() { string str; cin>>str; int countKick = 0; int TeamACount = 0; int TeamAMiss = 0; int TeamBCount = 0; int TeamBMiss = 0; for(int i=0;i<str.length();i++) { if(str[i]!='?') countKick++; if(i%2==0) { if(str[i]=='1') TeamACount++; else if(str[i]=='?') TeamAMiss++; } else if(i%2!=0) { if(str[i]=='1') TeamBCount++; else if(str[i]=='?') TeamBMiss++; } } if(countKick==10) cout<<10<<endl; else if(countKick==0) cout<<6<<endl; else { if(TeamACount > TeamBCount) { if(TeamAMiss > TeamBMiss) { } else if(TeamAMiss < TeamBMiss) { if( TeamACount + TeamAMiss >= 3 ) { countKick = countKick + TeamAMiss; } else { } } else if(TeamAMiss == TeamBMiss) { } } else if(TeamACount < TeamBCount) { if(TeamAMiss > TeamBMiss) { } else if(TeamAMiss < TeamBMiss) { } else if(TeamAMiss == TeamBMiss) { } } else if(TeamACount == TeamBCount) { if(TeamAMiss > TeamBMiss) { } else if(TeamAMiss < TeamBMiss) { } else if(TeamAMiss == TeamBMiss) { } } } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int testCases; cin >> testCases; while (testCases--) { solve(); } return 0; }
18.1875
55
0.355916
Yashdew
6cc7ebfc38ae550ad4e9b661c81ed1d1928a2211
1,676
cc
C++
mindspore/core/ops/sgd.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
2
2021-07-08T13:10:42.000Z
2021-11-08T02:48:57.000Z
mindspore/core/ops/sgd.cc
peixinhou/mindspore
fcb2ec2779b753e95c762cf292b23bd81d1f561b
[ "Apache-2.0" ]
null
null
null
mindspore/core/ops/sgd.cc
peixinhou/mindspore
fcb2ec2779b753e95c762cf292b23bd81d1f561b
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Huawei Technologies Co., Ltd * * 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 "ops/sgd.h" namespace mindspore { namespace ops { void SGD::Init(const float dampening, const float weight_decay, const bool nesterov) { set_nesterov(nesterov); set_dampening(dampening); set_weight_decay(weight_decay); } void SGD::set_dampening(const float dampening) { if (get_nesterov()) CheckAndConvertUtils::CheckValue<float>(kDampening, dampening, kEqual, 0.0, name()); AddAttr(kDampening, MakeValue(dampening)); } void SGD::set_weight_decay(const float weight_decay) { AddAttr(kWeightDecay, MakeValue(weight_decay)); } void SGD::set_nesterov(const bool nesterov) { AddAttr(kNesterov, MakeValue(nesterov)); } float SGD::get_dampening() const { auto value_ptr = GetAttr(kDampening); return GetValue<float>(value_ptr); } float SGD::get_weight_decay() const { auto value_ptr = GetAttr(kWeightDecay); return GetValue<float>(value_ptr); } bool SGD::get_nesterov() const { auto value_ptr = GetAttr(kNesterov); return GetValue<bool>(value_ptr); } REGISTER_PRIMITIVE_C(kNameSGD, SGD); } // namespace ops } // namespace mindspore
31.622642
106
0.75
Vincent34
6ccf736ce8c79a386b7fb782aeab63d50894f61e
17,669
cpp
C++
Samples/Audio/InGameChat/GameChatManager.cpp
acidburn0zzz/Xbox-GDK-Samples
0a998ca467f923aa04bd124a5e5ca40fe16c386c
[ "MIT" ]
1
2021-12-30T09:49:18.000Z
2021-12-30T09:49:18.000Z
Samples/Audio/InGameChat/GameChatManager.cpp
acidburn0zzz/Xbox-GDK-Samples
0a998ca467f923aa04bd124a5e5ca40fe16c386c
[ "MIT" ]
null
null
null
Samples/Audio/InGameChat/GameChatManager.cpp
acidburn0zzz/Xbox-GDK-Samples
0a998ca467f923aa04bd124a5e5ca40fe16c386c
[ "MIT" ]
null
null
null
//-------------------------------------------------------------------------------------- // GameChatManager.cpp // // Advanced Technology Group (ATG) // Copyright (C) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "pch.h" #include "GameChatManager.h" #include "InGameChat.h" // Suppress warnings from gamechat header until fixed #pragma warning(push) #pragma warning(disable : 5043) // This file must be included in a single compilation unit per: // https://docs.microsoft.com/en-us/gaming/xbox-live/features/multiplayer/chat/how-to/live-using-game-chat-2 #include "GameChat2Impl.h" #pragma warning(pop) using namespace xbox::services::game_chat_2; namespace { std::string RelationshipFlagsToString(game_chat_communication_relationship_flags flags) { std::string output = ""; if (flags == game_chat_communication_relationship_flags::none) { output = "none "; } else { if (int(flags) & int(game_chat_communication_relationship_flags::receive_audio)) { output += "receive_audio "; } if (int(flags) & int(game_chat_communication_relationship_flags::receive_text)) { output += "receive_text "; } if (int(flags) & int(game_chat_communication_relationship_flags::send_microphone_audio)) { output += "send_microphone_audio "; } if (int(flags) & int(game_chat_communication_relationship_flags::send_text)) { output += "send_text "; } if (int(flags) & int(game_chat_communication_relationship_flags::send_text_to_speech_audio)) { output += "send_text_to_speech_audio "; } } output.pop_back(); return output; } std::string RelationshipAdjusterToString(game_chat_communication_relationship_adjuster adjuster) { switch (adjuster) { case game_chat_communication_relationship_adjuster::none: return "none"; case game_chat_communication_relationship_adjuster::conflict_with_other_user: return "conflict_with_other_user"; case game_chat_communication_relationship_adjuster::initializing: return "initializing"; case game_chat_communication_relationship_adjuster::privacy: return "privacy"; case game_chat_communication_relationship_adjuster::privilege: return "privilege"; case game_chat_communication_relationship_adjuster::privilege_check_failure: return "privilege_check_failure"; case game_chat_communication_relationship_adjuster::reputation: return "reputation"; case game_chat_communication_relationship_adjuster::resolve_user_issue: return "resolve_user_issue"; case game_chat_communication_relationship_adjuster::service_unavailable: return "service_unavailable"; case game_chat_communication_relationship_adjuster::uninitialized: return "uninitialized"; default: return "unknown"; } } } GameChatManager::GameChatManager() noexcept : m_initialized(false) { } void GameChatManager::Initialize() { DebugTrace("Initialize GameChatManager"); if (!m_initialized) { auto &chatManager = chat_manager::singleton_instance(); // Hint where we'd like the STT window XSpeechToTextSetPositionHint( XSpeechToTextPositionHint::MiddleRight ); // Put the audio processing thread on core 5 chat_manager::set_thread_processor( game_chat_thread_id::audio, 4 ); // Put the network processing thread on core 6 chat_manager::set_thread_processor( game_chat_thread_id::networking, 5 ); // Initialize chat manager chatManager.initialize( Sample::MAXUSERS, // Max users 1.0f, // Default volume xbox::services::game_chat_2::c_communicationRelationshipSendAndReceiveAll, // Default to 'everyone can talk' game_chat_shared_device_communication_relationship_resolution_mode::restrictive, // Be restrictive for shared device (kinect) game_chat_speech_to_text_conversion_mode::automatic // Let GameChat perform perform accessibility actions ); m_initialized = true; } // Add the local users for (const auto& user : Sample::Instance()->GetUserManager()->GetUsers()) { uint64_t xuid = 0; auto hr = XUserGetId( user->UserHandle, &xuid ); if (SUCCEEDED(hr)) { AddLocalUser(xuid); } else { DebugTrace("Failed to get XUID for user %lu", user->UserHandle); } } } void GameChatManager::Shutdown() { DebugTrace("Shutdown GameChatManager"); if (m_initialized) { std::lock_guard<std::mutex> lock(m_lock); chat_manager::singleton_instance().cleanup(); m_initialized = false; } } void GameChatManager::AddRemoteUser( uint64_t chatUserXuid, uint64_t deviceId ) { if (m_initialized) { std::lock_guard<std::mutex> lock(m_lock); DebugTrace("Adding remote chat user: %lu, %lu", chatUserXuid, deviceId); chat_manager::singleton_instance().add_remote_user( std::to_wstring(chatUserXuid).c_str(), deviceId ); m_channels[chatUserXuid] = 1; RebuildRelationshipMap(); } } void GameChatManager::ProcessStateChanges() { if (!m_initialized) { return; } uint32_t count; game_chat_state_change_array changes; chat_manager::singleton_instance().start_processing_state_changes( &count, &changes ); for (uint32_t i = 0; i < count; i++) { auto change = changes[i]; switch (change->state_change_type) { case game_chat_state_change_type::communication_relationship_adjuster_changed: DebugTrace("GameChatManager: communication_relationship_adjuster_changed"); HandleRelationshipAdjusterChange(change); break; case game_chat_state_change_type::text_chat_received: DebugTrace("GameChatManager: text_chat_received"); HandleTextMessage(change, false); break; case game_chat_state_change_type::text_conversion_preference_changed: DebugTrace("GameChatManager: text_conversion_preference_changed"); break; case game_chat_state_change_type::transcribed_chat_received: DebugTrace("GameChatManager: transcribed_chat_received"); HandleTextMessage(change, true); break; } } chat_manager::singleton_instance().finish_processing_state_changes(changes); } void GameChatManager::ProcessDataFrames() { if (m_initialized) { std::lock_guard<std::mutex> lock(m_lock); uint32_t dataFrameCount; game_chat_data_frame_array dataFrames; chat_manager::singleton_instance().start_processing_data_frames( &dataFrameCount, &dataFrames ); for (uint32_t dataFrameIndex = 0; dataFrameIndex < dataFrameCount; ++dataFrameIndex) { auto dataFrame = dataFrames[dataFrameIndex]; auto dataBuffer = std::vector<uint8_t>(dataFrame->packet_buffer, dataFrame->packet_buffer + dataFrame->packet_byte_count); for (uint32_t targetIndex = 0; targetIndex < dataFrame->target_endpoint_identifier_count; ++targetIndex) { auto targetIdentifier = dataFrame->target_endpoint_identifiers[targetIndex]; Sample::Instance()->GetLiveManager()->SendNetworkMessage( targetIdentifier, dataBuffer, dataFrame->transport_requirement == game_chat_data_transport_requirement::guaranteed ); } } chat_manager::singleton_instance().finish_processing_data_frames(dataFrames); } } void GameChatManager::HandleTextMessage( const game_chat_state_change *change, bool transcribed ) { uint64_t xuid = 0; const wchar_t* message; if (transcribed) { auto event = static_cast<const game_chat_transcribed_chat_received_state_change*>(change); xuid = std::stoull(event->speaker->xbox_user_id()); message = event->message; } else { auto event = static_cast<const game_chat_text_chat_received_state_change*>(change); xuid = std::stoull(event->sender->xbox_user_id()); message = event->message; } std::wstring name; auto user = GetChatUserByXboxUserId(xuid); if (user != nullptr) { name = Sample::Instance()->GetLiveManager()->GetGamertagForXuid(xuid); } else { name = std::to_wstring(xuid); } DebugTrace("Text Message from %ws: %ws", name.c_str(), message); XSpeechToTextSendString( DX::WideToUtf8(name).c_str(), DX::WideToUtf8(message).c_str(), transcribed ? XSpeechToTextType::Voice : XSpeechToTextType::Text ); } void GameChatManager::HandleRelationshipAdjusterChange( const game_chat_state_change *change ) { auto event = static_cast<const game_chat_communication_relationship_adjuster_changed_state_change*>(change); game_chat_communication_relationship_flags relationship; game_chat_communication_relationship_adjuster adjuster; event->local_user->local()->get_effective_communication_relationship( event->target_user, &relationship, &adjuster ); DebugTrace("Relationship between %s and %s is [%s] with adjustment %s", DX::WideToUtf8(Sample::Instance()->GetLiveManager()->GetGamertagForXuid(std::stoull(event->local_user->xbox_user_id()))).c_str(), DX::WideToUtf8(Sample::Instance()->GetLiveManager()->GetGamertagForXuid(std::stoull(event->target_user->xbox_user_id()))).c_str(), RelationshipFlagsToString(relationship).c_str(), RelationshipAdjusterToString(adjuster).c_str() ); } void GameChatManager::AddLocalUser( uint64_t chatUserXuid ) { if (m_initialized) { std::lock_guard<std::mutex> lock(m_lock); DebugTrace("Adding local chat user: %lu", chatUserXuid); chat_manager::singleton_instance().add_local_user(std::to_wstring(chatUserXuid).c_str()); // Set users on channel 1 by default m_channels[chatUserXuid] = 1; RebuildRelationshipMap(); } } void GameChatManager::RebuildRelationshipMap() { auto users = Sample::Instance()->GetUserManager()->GetUsers(); for (auto xboxUser : users) { uint64_t xuid = 0; auto hr = XUserGetId( xboxUser->UserHandle, &xuid ); if (FAILED(hr)) { continue; } auto localUser = GetChatUserByXboxUserId(xuid); if (localUser == nullptr) { continue; } uint32_t chatUserCount; chat_user_array chatUsers; chat_manager::singleton_instance().get_chat_users( &chatUserCount, &chatUsers ); for (uint32_t chatUserIndex = 0; chatUserIndex < chatUserCount; ++chatUserIndex) { auto chatUser = chatUsers[chatUserIndex]; if (chatUser->local() == nullptr) { auto currentChannel = m_channels[std::stoull(chatUser->xbox_user_id())]; auto relationship = game_chat_communication_relationship_flags::none; // You can fully participate with users in the same channel if (m_channels[xuid] == currentChannel) { relationship = c_communicationRelationshipSendAndReceiveAll; } localUser->local()->set_communication_relationship( chatUser, relationship ); DebugTrace("SetrRelationship between %s and %s to [%s]", DX::WideToUtf8(Sample::Instance()->GetLiveManager()->GetGamertagForXuid(xuid)).c_str(), DX::WideToUtf8(Sample::Instance()->GetLiveManager()->GetGamertagForXuid(std::stoull(chatUser->xbox_user_id()))).c_str(), RelationshipFlagsToString(relationship).c_str() ); } } } } void GameChatManager::RemoveLocalUser( uint64_t chatUserXuid ) { DebugTrace("RemoveLocalUser: %lu", chatUserXuid); if (m_initialized) { chat_manager::singleton_instance().remove_user( GetChatUserByXboxUserId(chatUserXuid) ); } } void GameChatManager::RemoveRemoteUser( uint64_t chatUserXuid ) { if (m_initialized) { std::lock_guard<std::mutex> lock(m_lock); DebugTrace("GameChatManager::RemoveRemoteUser(%lu)", chatUserXuid); uint32_t chatUserCount; chat_user_array chatUsers; chat_manager::singleton_instance().get_chat_users( &chatUserCount, &chatUsers ); for (uint32_t chatUserIndex = 0; chatUserIndex < chatUserCount; ++chatUserIndex) { auto chatUser = chatUsers[chatUserIndex]; if (chatUserXuid == std::stoull(chatUser->xbox_user_id())) { chat_manager::singleton_instance().remove_user( chatUser ); DebugTrace("Removing remote user: %lu", chatUserXuid); break; } } } } chat_user* GameChatManager::GetChatUserByXboxUserId( uint64_t chatUserXuid ) { if (m_initialized) { uint32_t count; chat_user_array chatUsers; chat_manager::singleton_instance().get_chat_users( &count, &chatUsers ); for (uint32_t i = 0; i < count; ++i) { auto user = chatUsers[i]; auto uxuid = std::stoull(user->xbox_user_id()); if (chatUserXuid == uxuid) { return user; } } } return nullptr; } std::vector<uint64_t> GameChatManager::GetChatUsersXuids() { auto xuids = std::vector<uint64_t>(); if (m_initialized) { uint32_t chatUserCount; chat_user_array chatUsers; chat_manager::singleton_instance().get_chat_users( &chatUserCount, &chatUsers ); for (uint32_t chatUserIndex = 0; chatUserIndex < chatUserCount; ++chatUserIndex) { xuids.push_back(std::stoull(chatUsers[chatUserIndex]->xbox_user_id())); } } return xuids; } void GameChatManager::ChangeChannelForUser( uint64_t chatUserXuid, uint8_t newChatChannelIndex ) { std::lock_guard<std::mutex> lock(m_lock); m_channels[chatUserXuid] = newChatChannelIndex; RebuildRelationshipMap(); } void GameChatManager::ToggleChatUserMuteState( uint64_t chatUserXuid ) { // Helper function to swap the mute state of a specific chat user auto chatUser = GetChatUserByXboxUserId(chatUserXuid); if (chatUser->local() != nullptr) { chatUser->local()->set_microphone_muted( !chatUser->local()->microphone_muted() ); } else { auto users = Sample::Instance()->GetUserManager()->GetUsers(); for (auto xboxUser : users) { uint64_t xuid = 0; auto hr = XUserGetId( xboxUser->UserHandle, &xuid ); if (SUCCEEDED(hr)) { auto localUser = GetChatUserByXboxUserId(xuid); localUser->local()->set_remote_user_muted( chatUser, !localUser->local()->remote_user_muted(chatUser) ); } } } } uint8_t GameChatManager::GetChannelForUser( uint64_t chatUserXuid ) { std::lock_guard<std::mutex> lock(m_lock); return m_channels[chatUserXuid]; } void GameChatManager::ProcessChatPacket( uint64_t deviceId, const std::vector<uint8_t> &data ) { if (m_initialized) { std::lock_guard<std::mutex> lock(m_lock); chat_manager::singleton_instance().process_incoming_data( deviceId, // Remote console id static_cast<uint32_t>(data.size()), // Buffer size data.data() // Raw buffer pointer ); } }
30.04932
147
0.585715
acidburn0zzz
6cd8aa98628db3499b9e97bfc17f12997b10f1cd
5,353
cpp
C++
tests/test_rocketmodel.cpp
julienlopez/QRocketLaunchSimulator
132e979489b3b84a82c162df0209085d0a30fd8e
[ "MIT" ]
null
null
null
tests/test_rocketmodel.cpp
julienlopez/QRocketLaunchSimulator
132e979489b3b84a82c162df0209085d0a30fd8e
[ "MIT" ]
5
2015-02-19T09:25:15.000Z
2015-02-19T14:43:20.000Z
tests/test_rocketmodel.cpp
julienlopez/QRocketLaunchSimulator
132e979489b3b84a82c162df0209085d0a30fd8e
[ "MIT" ]
null
null
null
#include "rocketmodel.hpp" #include "external/json.h" #include <stdexcept> #include <gtest/gtest.h> using nlohmann::json; using boost::units::si::meters; using boost::units::si::kilograms; using boost::units::si::kilograms; using boost::units::si::newtons; using boost::units::si::seconds; TEST(TestRocketModel, TestParsingRocketWithNoStages) { const std::string name = "test"; std::stringstream ss; ss << R"({ "name": ")" + name + R"(", "stages": [], "fairings" : {"length" : 7.88, "diameter" : 2.6} } ")"; auto rocket = RocketModel::fromJson(ss); EXPECT_EQ(name, rocket.name); EXPECT_TRUE(rocket.stages.empty()); } TEST(TestRocketModel, TestParsingRocketWithoutName) { std::stringstream ss; ss << R"({ "stages": [] } ")"; ASSERT_THROW(RocketModel::fromJson(ss), std::runtime_error); } TEST(TestRocketModel, TestParsingRocketInvalidName) { std::stringstream ss; ss << R"({ "name": 2 , "stages": [] } ")"; ASSERT_THROW(RocketModel::fromJson(ss), std::runtime_error); } TEST(TestRocketModel, TestParsingRocketWithoutStages) { std::stringstream ss; ss << R"({ "name": "test" }")"; ASSERT_THROW(RocketModel::fromJson(ss), std::runtime_error); } TEST(TestRocketModel, TestParsingRocketInvalidStages) { std::stringstream ss; ss << R"({ "name": "test", "stages": "error" } ")"; ASSERT_THROW(RocketModel::fromJson(ss), std::runtime_error); } TEST(TestRocketModel, TestParsingRocketWithTwoStages) { const std::string name = "test"; std::stringstream ss; ss << R"({ "name": ")" + name + R"(", "stages": [ { "name": "Z9", "length" : 4.12, "diameter" : 1.9, "dry_mass" : 1315, "gross_mass" : 11815, "thrust" : 260000, "isp" : 296, "burn_time" : 120, "fuel" : "solid" }, { "name": "AVUM", "length" : 1.7, "diameter" : 2.31, "dry_mass" : 147, "gross_mass" : 697, "thrust" : 2420, "isp" : 315.5, "burn_time" : 6672, "fuel" : "UDMH/N204" }], "fairings" : {"length" : 7.88, "diameter" : 2.6} } } ")"; auto rocket = RocketModel::fromJson(ss); EXPECT_EQ(name, rocket.name); ASSERT_EQ(2, rocket.stages.size()); const auto s1 = rocket.stages.front(); EXPECT_EQ("Z9", s1.name); EXPECT_EQ(4.12 * meters, s1.length); EXPECT_EQ(1.9 * meters, s1.diameter); EXPECT_EQ(1315 * kilograms, s1.dry_mass); EXPECT_EQ(11815 * kilograms, s1.gross_mass); EXPECT_EQ(260000 * newtons, s1.thrust); EXPECT_EQ(296 * seconds, s1.isp); EXPECT_EQ(120 * seconds, s1.burn_time); EXPECT_EQ("solid", s1.fuel); EXPECT_EQ(1 * boost::units::si::si_dimensionless / s1.burn_time, s1.burnRate()); const auto s2 = rocket.stages.back(); EXPECT_EQ("AVUM", s2.name); EXPECT_EQ(1.7 * meters, s2.length); EXPECT_EQ(2.31 * meters, s2.diameter); EXPECT_EQ(147 * kilograms, s2.dry_mass); EXPECT_EQ(697 * kilograms, s2.gross_mass); EXPECT_EQ(2420 * newtons, s2.thrust); EXPECT_EQ(315.5 * seconds, s2.isp); EXPECT_EQ(6672 * seconds, s2.burn_time); EXPECT_EQ("UDMH/N204", s2.fuel); EXPECT_EQ(1 * boost::units::si::si_dimensionless / s2.burn_time, s2.burnRate()); } TEST(TestRocketModel, TestParsingRocketStagesInvalidType) { std::stringstream ss; ss << R"({ "name": "test", "stages": [ "error" ] } ")"; ASSERT_THROW(RocketModel::fromJson(ss), std::runtime_error); } TEST(TestRocketModel, TestParsingRocketStagesNumberInvalidType) { std::stringstream ss; ss << R"({ "name": "test", "stages": [ { "name": "AVUM", "length" : 1.7, "diameter" : 2.31, "dry_mass" : 147, "gross_mass" : "error", "thrust" : 2420, "isp" : 315.5, "burn_time" : 6672, "fuel" : "UDMH/N204" } ] } ")"; ASSERT_THROW(RocketModel::fromJson(ss), std::runtime_error); } TEST(TestRocketModel, TestParsingRocketStagesNumberMissing) { std::stringstream ss; ss << R"({ "name": "test", "stages": [ { "name": "AVUM", "length" : 1.7, "diameter" : 2.31, "dry_mass" : 147, "thrust" : 2420, "isp" : 315.5, "burn_time" : 6672, "fuel" : "UDMH/N204" } ] } ")"; ASSERT_THROW(RocketModel::fromJson(ss), std::runtime_error); } TEST(TestRocketModel, TestParsingRocketWithNoFairings) { const std::string name = "test"; std::stringstream ss; ss << R"({ "name": ")" + name + R"(", "stages": [] })"; ASSERT_THROW(RocketModel::fromJson(ss), std::runtime_error); } TEST(TestFairings, TestParsingInvalidFairings) { const std::string name = "test"; std::stringstream ss; ss << R"({ "name": ")" + name + R"(", "stages": [], "fairings" : 2 })"; json js; js >> ss; ASSERT_THROW(Fairings::fromJson(js["fairings"]), std::runtime_error); }
31.674556
93
0.545302
julienlopez
6cdbfdcc116bfd837cf2f2c7c3e4ea3c6133e282
2,863
cxx
C++
Testing/Code/Review/itkQuadEdgeMeshDeletePointAndReorderIDsTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
1
2018-04-15T13:32:43.000Z
2018-04-15T13:32:43.000Z
Testing/Code/Review/itkQuadEdgeMeshDeletePointAndReorderIDsTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
Testing/Code/Review/itkQuadEdgeMeshDeletePointAndReorderIDsTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkQuadEdgeMeshDeletePointAndReorderIDsTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkQuadEdgeMesh.h" #include "itkQuadEdgeMeshPolygonCell.h" #include "itkVTKPolyDataWriter.h" int itkQuadEdgeMeshDeletePointAndReorderIDsTest( int , char* [] ) { typedef double PixelType; const unsigned int Dimension = 3; typedef itk::QuadEdgeMesh< PixelType, Dimension > MeshType; typedef MeshType::CellTraits CellTraits; typedef CellTraits::QuadEdgeType QEType; typedef MeshType::CellType CellType; typedef itk::QuadEdgeMeshPolygonCell< CellType > QEPolygonCellType; typedef itk::VTKPolyDataWriter< MeshType > WriterType; MeshType::Pointer mesh = MeshType::New(); MeshType::PointType pts[ 5 ]; WriterType::Pointer writer = WriterType::New( ); pts[ 0 ][ 0 ] = -1.0; pts[ 0 ][ 1 ] = -1.0; pts[ 0 ][ 2 ] = 0.0; pts[ 1 ][ 0 ] = 1.0; pts[ 1 ][ 1 ] = -1.0; pts[ 1 ][ 2 ] = 0.0; pts[ 2 ][ 0 ] = 1.0; pts[ 2 ][ 1 ] = 1.0; pts[ 2 ][ 2 ] = 0.0; pts[ 3 ][ 0 ] = -1.0; pts[ 3 ][ 1 ] = 1.0; pts[ 3 ][ 2 ] = 0.0; pts[ 4 ][ 0 ] = 0.0; pts[ 4 ][ 1 ] = 0.0; pts[ 4 ][ 2 ] = 1.0; mesh->SetPoint( 0, pts[ 0 ] ); mesh->SetPoint( 1, pts[ 1 ] ); mesh->SetPoint( 2, pts[ 2 ] ); mesh->SetPoint( 3, pts[ 3 ] ); mesh->SetPoint( 4, pts[ 4 ] ); // create a tetahedra and one isolated point: id = 0 int specialCells[12] = { 4, 1, 2, 4, 2, 3, 3, 1, 4, 1, 3, 2 }; CellType::CellAutoPointer cellpointer; QEPolygonCellType *poly; for(int i=0; i<4; i++) { poly = new QEPolygonCellType( 3 ); cellpointer.TakeOwnership( poly ); cellpointer->SetPointId( 0, specialCells[3*i] ); cellpointer->SetPointId( 1, specialCells[3*i+1] ); cellpointer->SetPointId( 2, specialCells[3*i+2] ); mesh->SetCell( i, cellpointer ); } writer->SetInput( mesh ); writer->SetFileName( "BeforeDeletePoint.vtk" ); writer->Update( ); mesh->DeletePoint( 0 ); writer->SetFileName( "AfterDeletePoint.vtk" ); writer->Update( ); mesh->SqueezePointsIds( ); writer->SetFileName( "AfterSqueeze.vtk" ); writer->Update( ); return EXIT_SUCCESS; }
32.534091
76
0.592735
kiranhs
6ce00f14afefbfb0a2ae3437400170ca6b5116b9
1,983
cpp
C++
bionic/tests/getauxval_test.cpp
lihuibng/marshmallow
950cf8de3b4d63af9fc9699374e4ec45ad09b3a7
[ "Apache-2.0" ]
null
null
null
bionic/tests/getauxval_test.cpp
lihuibng/marshmallow
950cf8de3b4d63af9fc9699374e4ec45ad09b3a7
[ "Apache-2.0" ]
null
null
null
bionic/tests/getauxval_test.cpp
lihuibng/marshmallow
950cf8de3b4d63af9fc9699374e4ec45ad09b3a7
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2013 The Android Open Source Project * * 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 <errno.h> #include <sys/cdefs.h> #include <gtest/gtest.h> // getauxval() was only added as of glibc version 2.16. // See: http://lwn.net/Articles/519085/ // Don't try to compile this code on older glibc versions. #if defined(__BIONIC__) #define GETAUXVAL_CAN_COMPILE 1 #elif defined(__GLIBC_PREREQ) #if __GLIBC_PREREQ(2, 16) #define GETAUXVAL_CAN_COMPILE 1 #endif #endif #if defined(GETAUXVAL_CAN_COMPILE) #include <sys/auxv.h> #endif TEST(getauxval, expected_values) { #if defined(GETAUXVAL_CAN_COMPILE) ASSERT_EQ((unsigned long int) 0, getauxval(AT_SECURE)); ASSERT_EQ(getuid(), getauxval(AT_UID)); ASSERT_EQ(geteuid(), getauxval(AT_EUID)); ASSERT_EQ(getgid(), getauxval(AT_GID)); ASSERT_EQ(getegid(), getauxval(AT_EGID)); ASSERT_EQ((unsigned long int) getpagesize(), getauxval(AT_PAGESZ)); ASSERT_NE((unsigned long int) 0, getauxval(AT_PHDR)); ASSERT_NE((unsigned long int) 0, getauxval(AT_PHNUM)); ASSERT_NE((unsigned long int) 0, getauxval(AT_ENTRY)); ASSERT_NE((unsigned long int) 0, getauxval(AT_PAGESZ)); #else GTEST_LOG_(INFO) << "This test does nothing.\n"; #endif } TEST(getauxval, unexpected_values) { #if defined(GETAUXVAL_CAN_COMPILE) errno = 0; ASSERT_EQ((unsigned long int) 0, getauxval(0xdeadbeef)); ASSERT_EQ(ENOENT, errno); #else GTEST_LOG_(INFO) << "This test does nothing.\n"; #endif }
30.984375
75
0.734241
lihuibng
6ce29b8024f9b9ce202b983bc21c6a2e703c7274
1,674
cpp
C++
src/Parsers/Kusto/ParserKQLStatement.cpp
DevTeamBK/ClickHouse
f65b5d21594a07afb017a7cdaa718c5d1caa257d
[ "Apache-2.0" ]
null
null
null
src/Parsers/Kusto/ParserKQLStatement.cpp
DevTeamBK/ClickHouse
f65b5d21594a07afb017a7cdaa718c5d1caa257d
[ "Apache-2.0" ]
1
2021-12-22T12:08:09.000Z
2021-12-22T12:08:09.000Z
src/Parsers/Kusto/ParserKQLStatement.cpp
DevTeamBK/ClickHouse
f65b5d21594a07afb017a7cdaa718c5d1caa257d
[ "Apache-2.0" ]
null
null
null
#include <Parsers/IParserBase.h> #include <Parsers/ParserSetQuery.h> #include <Parsers/ASTExpressionList.h> #include <Parsers/ASTSelectWithUnionQuery.h> #include <Parsers/Kusto/ParserKQLQuery.h> #include <Parsers/Kusto/ParserKQLStatement.h> #include <Parsers/Kusto/KustoFunctions/KQLFunctionFactory.h> namespace DB { bool ParserKQLStatement::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) { ParserKQLWithOutput query_with_output_p(end, allow_settings_after_format_in_insert); ParserSetQuery set_p; bool res = query_with_output_p.parse(pos, node, expected) || set_p.parse(pos, node, expected); return res; } bool ParserKQLWithOutput::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) { ParserKQLWithUnionQuery kql_p; ASTPtr query; bool parsed = kql_p.parse(pos, query, expected); if (!parsed) return false; node = std::move(query); return true; } bool ParserKQLWithUnionQuery::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) { // will support union next phase ASTPtr kql_query; if (!ParserKQLQuery().parse(pos, kql_query, expected)) return false; if (kql_query->as<ASTSelectWithUnionQuery>()) { node = std::move(kql_query); return true; } auto list_node = std::make_shared<ASTExpressionList>(); list_node->children.push_back(kql_query); auto select_with_union_query = std::make_shared<ASTSelectWithUnionQuery>(); node = select_with_union_query; select_with_union_query->list_of_selects = list_node; select_with_union_query->children.push_back(select_with_union_query->list_of_selects); return true; } }
27
90
0.725806
DevTeamBK
6ce2f0bd1655dd8a190e542fbb5626c3d2c83037
4,051
cpp
C++
src/wanderers/WildwoodRangers.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
5
2019-02-01T01:41:19.000Z
2021-06-17T02:16:13.000Z
src/wanderers/WildwoodRangers.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
2
2020-01-14T16:57:42.000Z
2021-04-01T00:53:18.000Z
src/wanderers/WildwoodRangers.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
1
2019-03-02T20:03:51.000Z
2019-03-02T20:03:51.000Z
/* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <wanderers/WildwoodRangers.h> #include <UnitFactory.h> namespace Wanderers { static const int g_basesize = 32; static const int g_wounds = 1; static const int g_minUnitSize = 10; static const int g_maxUnitSize = 30; static const int g_pointsPerBlock = 140; static const int g_pointsMaxUnitSize = 420; bool WildwoodRangers::s_registered = false; WildwoodRangers::WildwoodRangers(int numModels, bool standardBearer, bool hornblower, int points) : Wanderer("Wildwood Rangers", 6, g_wounds, 7, 5, false, points), m_rangersDraich(Weapon::Type::Melee, "Ranger's Draich", 2, 2, 3, 3, -1, 1), m_wardensDraich(Weapon::Type::Melee, "Ranger's Draich", 2, 3, 3, 3, -1, 1) { m_keywords = {ORDER, AELF, WANDERER, WILDWOOD_RANGERS}; m_weapons = {&m_rangersDraich, &m_wardensDraich}; auto warden = new Model(g_basesize, wounds()); warden->addMeleeWeapon(&m_wardensDraich); addModel(warden); for (auto i = 1; i < numModels; i++) { auto model = new Model(g_basesize, wounds()); model->addMeleeWeapon(&m_rangersDraich); if (standardBearer) { model->setName(Model::StandardBearer); standardBearer = false; } else if (hornblower) { model->setName(Model::Hornblower); hornblower = false; } addModel(model); } } Unit *WildwoodRangers::Create(const ParameterList &parameters) { int numModels = GetIntParam("Models", parameters, g_minUnitSize); bool standardBearer = GetBoolParam("Standard Bearer", parameters, false); bool hornblower = GetBoolParam("Hornblower", parameters, false); return new WildwoodRangers(numModels, standardBearer, hornblower, ComputePoints(parameters)); } void WildwoodRangers::Init() { if (!s_registered) { static FactoryMethod factoryMethod = { WildwoodRangers::Create, nullptr, nullptr, WildwoodRangers::ComputePoints, { IntegerParameter("Models", g_minUnitSize, g_minUnitSize, g_maxUnitSize, g_minUnitSize), BoolParameter("Standard Bearer"), BoolParameter("Hornblower"), }, ORDER, {WANDERER} }; s_registered = UnitFactory::Register("Wildwood Rangers", factoryMethod); } } Wounds WildwoodRangers::weaponDamage(const Model* attackingModel, const Weapon *weapon, const Unit *target, int hitRoll, int woundRoll) const { // Guardians of the Kindreds if (target->hasKeyword(MONSTER)) { return {Dice::RollD3(), 0}; } return Wanderer::weaponDamage(attackingModel, weapon, target, hitRoll, woundRoll); } Rerolls WildwoodRangers::runRerolls() const { if (isNamedModelAlive(Model::Hornblower)) { return Rerolls::Failed; } return Wanderer::runRerolls(); } int WildwoodRangers::braveryModifier() const { int modifier = Wanderer::braveryModifier(); if (isNamedModelAlive(Model::StandardBearer)) { modifier += 1; // if (Board::Instance()->unitInCover(this)) { modifier += 1; } } return modifier; } int WildwoodRangers::ComputePoints(const ParameterList& parameters) { int numModels = GetIntParam("Models", parameters, g_minUnitSize); auto points = numModels / g_minUnitSize * g_pointsPerBlock; if (numModels == g_maxUnitSize) { points = g_pointsMaxUnitSize; } return points; } } // namespace Wanderers
37.509259
147
0.602074
rweyrauch
6ce582473817154716db84277cca72db93910d4f
6,679
cpp
C++
logview/emap.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
8
2015-11-16T19:15:55.000Z
2021-02-17T23:58:33.000Z
logview/emap.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
5
2015-11-12T00:19:59.000Z
2020-03-23T10:18:19.000Z
logview/emap.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
11
2015-03-15T23:02:48.000Z
2021-09-05T14:17:13.000Z
/************************************************************************************ * EMStudio - Open Source ECU tuning software * * Copyright (C) 2020 Michael Carpenter (malcom2073@gmail.com) * * * * This file is a part of EMStudio is licensed MIT as * * defined in LICENSE.md at the top level of this repository * ************************************************************************************/ #include "emap.h" #include <QPainter> EMap::EMap(QWidget *parent) : QWidget(parent) { m_mapImage = 0; m_redrawBackground = true; } void EMap::reDrawMap(QPainter *painter2) { if (!m_mapImage) { return; } QPainter painter(m_mapImage); QPen pen = painter.pen(); pen.setWidth(2); pen.setColor(QColor::fromRgb(0,0,0)); painter.setPen(pen); painter.fillRect(0,0,width(),height(),Qt::SolidPattern); if (m_x.size() == 0 || m_y.size() == 0 || m_z.size() == 0) { return; } double xrange = m_maxX - m_minX; double yrange = m_maxY - m_minY; double zrange = m_maxZ - m_minZ; if (zrange == 0) { zrange = 1; } painter.drawRect(0,0,width()-1,height()); int dataoffsetx = 40; int dataoffsety = 20; int datawidth = width() - (dataoffsetx * 2.0); int dataheight = height() - (dataoffsety * 2.0); painter.drawRect(dataoffsetx,dataoffsety,datawidth - 1,dataheight-1); pen.setWidth(1); painter.setPen(pen); for (int i=0;i<m_z.size();i++) { float percentx = (m_maxX - m_x.value(i)) / (xrange); float percenty = (m_maxY - m_y.value(i)) / (yrange); float percentz = (m_maxZ - m_z.value(i)) / (zrange); if (percentx < 0 || percentx > 1) { continue; } if (percenty < 0 || percenty > 1) { continue; } if (percentz < 0 || percentz > 1) { //continue; } QPen p = painter.pen(); p.setColor(QColor::fromRgb(255,255 * percentz,0)); p.setWidth(1); painter.setPen(p); painter.drawPoint(dataoffsetx + (datawidth - (datawidth * percentx)),dataoffsety + (dataheight * percenty)); } QPen p = painter.pen(); p.setColor(QColor::fromRgb(0,0,0)); p.setWidth(1); painter.setPen(p); for (int i=0;i<=10;i++) { double xval = m_minX + ((xrange / 10.0) * i); float percentx = (m_maxX - xval) / (xrange); //Position of values painter.drawText(dataoffsetx + (datawidth - (datawidth * percentx)),height()-5,QString::number(xval,'f',2)); double yval = m_minY + ((yrange / 10.0) * i); float percenty = (m_maxY - yval) / (yrange); //Position of values painter.drawText(5,dataheight * percenty,QString::number(yval,'f',2)); } } void EMap::resizeEvent(QResizeEvent *evt) { //Q_UNUSED(oldgeometry); delete m_mapImage; m_mapImage = new QImage(evt->size().width(),evt->size().height(),QImage::Format_ARGB32); m_redrawBackground = true; //drawBackground(); } void EMap::paintEvent(QPaintEvent *e) { QPainter painter(this); if (!m_mapImage) { return; } if (m_redrawBackground) { m_redrawBackground = false; reDrawMap(&painter); } painter.drawImage(0,0,*m_mapImage); } void EMap::passXData(QList<double> x) { //Automatically scale when new data is received. m_x = x; if (m_x.size() > 0) { m_minX = m_x.value(0); m_maxX = m_x.value(0); for (int i=0;i<m_x.size();i++) { if (m_minX > m_x.value(i)) { m_minX = m_x.value(i); } if (m_maxX < m_x.value(i)) { m_maxX = m_x.value(i); } } } m_autoMinX = m_minX; m_autoMaxX = m_maxX; emit rangesSet(m_minX,m_maxX,m_minY,m_maxY,m_minZ,m_maxZ); update(); } void EMap::passYData(QList<double> y) { //Automatically scale when new data is received. m_y = y; if (m_y.size() > 0) { m_minY = m_y.value(0); m_maxY = m_y.value(0); for (int i=0;i<m_y.size();i++) { if (m_minY > m_y.value(i)) { m_minY = m_y.value(i); } if (m_maxY < m_y.value(i)) { m_maxY = m_y.value(i); } } } m_autoMinY = m_minY; m_autoMaxY = m_maxY; emit rangesSet(m_minX,m_maxX,m_minY,m_maxY,m_minZ,m_maxZ); update(); } void EMap::passZData(QList<double> z) { //Automatically scale when new data is received. m_z = z; if (m_z.size() > 0) { m_minZ = m_z.value(0); m_maxZ = m_z.value(0); for (int i=0;i<m_z.size();i++) { if (m_minZ > m_z.value(i)) { m_minZ = m_z.value(i); } if (m_maxZ < m_z.value(i)) { m_maxZ = m_z.value(i); } } } m_autoMinZ = m_minZ; m_autoMaxZ = m_maxZ; emit rangesSet(m_minX,m_maxX,m_minY,m_maxY,m_minZ,m_maxZ); update(); } void EMap::passData(QList<double> x,QList<double> y,QList<double> z) { m_x = x; m_y = y; m_z = z; if (m_x.size() > 0) { m_minX = m_x.value(0); m_maxX = m_x.value(0); for (int i=0;i<m_x.size();i++) { if (m_minX > m_x.value(i)) { m_minX = m_x.value(i); } if (m_maxX < m_x.value(i)) { m_maxX = m_x.value(i); } } } if (m_y.size() > 0) { m_minY = m_y.value(0); m_maxY = m_y.value(0); for (int i=0;i<m_y.size();i++) { if (m_minY > m_y.value(i)) { m_minY = m_y.value(i); } if (m_maxY < m_y.value(i)) { m_maxY = m_y.value(i); } } } if (m_z.size() > 0) { m_minZ = m_z.value(0); m_maxZ = m_z.value(0); for (int i=0;i<m_z.size();i++) { if (m_minZ > m_z.value(i)) { m_minZ = m_z.value(i); } if (m_maxZ < m_z.value(i)) { m_maxZ = m_z.value(i); } } } m_autoMinX = m_minX; m_autoMaxX = m_maxX; m_autoMinY = m_minY; m_autoMaxY = m_maxY; m_autoMinZ = m_minZ; m_autoMaxZ = m_maxZ; emit rangesSet(m_minX,m_maxX,m_minY,m_maxY,m_minZ,m_maxZ); update(); } void EMap::setXMinMax(double min,double max) { m_minX = min; m_maxX = max; update(); } void EMap::setYMinMax(double min,double max) { m_minY = min; m_maxY = max; update(); } void EMap::setZMinMax(double min,double max) { m_minZ = min; m_maxZ = max; update(); } void EMap::autoScaleX() { m_minX = m_autoMinX; m_maxX = m_autoMaxX; emit rangesSet(m_minX,m_maxX,m_minY,m_maxY,m_minZ,m_maxZ); update(); } void EMap::autoScaleY() { m_minY = m_autoMinY; m_maxY = m_autoMaxY; emit rangesSet(m_minX,m_maxX,m_minY,m_maxY,m_minZ,m_maxZ); update(); } void EMap::autoScaleZ() { m_minZ = m_autoMinZ; m_maxZ = m_autoMaxZ; emit rangesSet(m_minX,m_maxX,m_minY,m_maxY,m_minZ,m_maxZ); update(); }
22.488215
110
0.558167
Hayesie88
6ce6f867d811db392a875497c7fc888e43bb14c8
1,637
cpp
C++
font.cpp
dbralir/ludum-dare-26
4fabf578ae73839cdf2d10c733138d4d6f8c6606
[ "Unlicense", "MIT" ]
null
null
null
font.cpp
dbralir/ludum-dare-26
4fabf578ae73839cdf2d10c733138d4d6f8c6606
[ "Unlicense", "MIT" ]
null
null
null
font.cpp
dbralir/ludum-dare-26
4fabf578ae73839cdf2d10c733138d4d6f8c6606
[ "Unlicense", "MIT" ]
null
null
null
#include "font.hpp" #include "game.hpp" #include "meta.hpp" #include "inugami/texture.hpp" using namespace Inugami; Font::Font(const Texture& img, int tw, int th, float cx, float cy) : Spritesheet(img, tw, th, cx, cy) , tileW(tw/8) , tileH(th/8) , centerX(1.f-cx) , centerY(1.f-cy) {} Font::Font(const Font& in) : Spritesheet(in) , tileW(in.tileW) , tileH(in.tileH) , centerX(in.centerX) , centerY(in.centerY) {} Font::Font(Font&& in) : Spritesheet(in) , tileW(in.tileW) , tileH(in.tileH) , centerX(in.centerX) , centerY(in.centerY) {} Font::~Font() {} void Font::drawString(const std::string& in, Transform mat) const { if (tilesX != 16 || tilesY != 16) throw GameError("Font: Invalid spritesheet."); Texture bgtex(Image(1,1,{{85,85,85,255}})); Mesh bgmesh(Geometry::fromRect(tileW,tileH,centerX,centerY)); mat.push(); for (char c : in) { if (c == '\n') { mat.pop(); mat.translate(Vec3{0.f, -tileH, 0.f}); mat.push(); continue; } bgtex.bind(0); Game::getInstance().modelMatrix(mat); bgmesh.draw(); if (c == ' ') { mat.translate(Vec3{tileW, 0.f, 0.f}); continue; } if (c == '\t') { mat.translate(Vec3{tileW*4, 0.f, 0.f}); continue; } mat.push(); mat.scale(Vec3{1.0/8.0, 1.0/8.0, 1.0}); Game::getInstance().modelMatrix(mat); draw(c/16, c%16); mat.pop(); mat.translate(Vec3{tileW, 0.f, 0.f}); } }
20.721519
84
0.516188
dbralir
6ce937255dfb16470a99f4e23daa5ed0d3f136b6
1,864
cpp
C++
examples/LIDAR_GTAV/lib/utils.cpp
edward0im/A-virtual-LiDAR-for-DeepGTAV
0d43000d0b23b33f378af839825455234d824f5c
[ "MIT" ]
1
2020-08-27T03:21:25.000Z
2020-08-27T03:21:25.000Z
examples/LIDAR_GTAV/lib/utils.cpp
edward0im/A-virtual-LiDAR-for-DeepGTAV
0d43000d0b23b33f378af839825455234d824f5c
[ "MIT" ]
null
null
null
examples/LIDAR_GTAV/lib/utils.cpp
edward0im/A-virtual-LiDAR-for-DeepGTAV
0d43000d0b23b33f378af839825455234d824f5c
[ "MIT" ]
null
null
null
/* THIS FILE IS A PART OF GTA V SCRIPT HOOK SDK http://dev-c.com (C) Alexander Blade 2015 */ #include "utils.h" #include "script.h" #include <windows.h> extern "C" IMAGE_DOS_HEADER __ImageBase; // MSVC specific, with other compilers use HMODULE from DllMain std::string cachedModulePath; std::string GetCurrentModulePath() { if (cachedModulePath.empty()) { // get module path char modPath[MAX_PATH]; memset(modPath, 0, sizeof(modPath)); GetModuleFileNameA((HMODULE)&__ImageBase, modPath, sizeof(modPath)); for (size_t i = strlen(modPath); i > 0; i--) { if (modPath[i - 1] == '\\') { modPath[i] = 0; break; } } cachedModulePath = modPath; } return cachedModulePath; } std::string statusText; DWORD statusTextDrawTicksMax; bool statusTextGxtEntry; void update_status_text() { if (GetTickCount() < statusTextDrawTicksMax) { UI::SET_TEXT_FONT(0); UI::SET_TEXT_SCALE(0.55, 0.55); UI::SET_TEXT_COLOUR(255, 255, 255, 255); UI::SET_TEXT_WRAP(0.0, 1.0); UI::SET_TEXT_CENTRE(1); UI::SET_TEXT_DROPSHADOW(0, 0, 0, 0, 0); UI::SET_TEXT_EDGE(1, 0, 0, 0, 205); if (statusTextGxtEntry) { UI::_SET_TEXT_ENTRY((char *)statusText.c_str()); } else { UI::_SET_TEXT_ENTRY("STRING"); UI::_ADD_TEXT_COMPONENT_STRING((char *)statusText.c_str()); } UI::_DRAW_TEXT(0.5, 0.5); } } void set_status_text(std::string str, DWORD time, bool isGxtEntry) { statusText = str; statusTextDrawTicksMax = GetTickCount() + time; statusTextGxtEntry = isGxtEntry; } float getFloatValue(Vehicle vehicle, int offset){ BYTE* pointerToData = getScriptHandleBaseAddress(vehicle) + offset; float* data = (float *)pointerToData; return *data; } void setFloatValue(Vehicle vehicle, int offset, float value) { BYTE* pointerToData = getScriptHandleBaseAddress(vehicle) + offset; *((float *)pointerToData) = value; }
23.012346
104
0.696888
edward0im
6cea6e5eee8d183f0ff1edaf91022bace48f3730
406
hpp
C++
include/CountingMutex.hpp
kamilturek/factory
6d74d3de53d6174e6e82e537be6dabd3ab5b3d9c
[ "MIT" ]
null
null
null
include/CountingMutex.hpp
kamilturek/factory
6d74d3de53d6174e6e82e537be6dabd3ab5b3d9c
[ "MIT" ]
2
2020-04-19T08:14:08.000Z
2020-04-19T11:05:10.000Z
include/CountingMutex.hpp
kamilturek/factory
6d74d3de53d6174e6e82e537be6dabd3ab5b3d9c
[ "MIT" ]
null
null
null
#pragma once #include <condition_variable> #include <mutex> // Inspired by C++20's std::counting_semaphore // Not available in any compiler on 15.05.2020 // Meets C++ BasicLockable requirements class CountingMutex { public: explicit CountingMutex(int max); void lock(); void unlock(); private: int count; const int maxCount; std::mutex mutex; std::condition_variable cv; };
17.652174
46
0.699507
kamilturek
6cea7a6f7f044c2dffb0ce01d450072af9b3382b
426
hpp
C++
vendor/cucumber-cpp/include/cucumber-cpp/deprecated-defs.hpp
AndreasAugustin/Gherkin-Demos-cpp
79a4be81ee1fffce56ac503760a48a2b77d6d03f
[ "MIT" ]
1
2016-07-21T10:10:33.000Z
2016-07-21T10:10:33.000Z
vendor/cucumber-cpp/include/cucumber-cpp/deprecated-defs.hpp
AndreasAugustin/Gherkin-Demos-cpp
79a4be81ee1fffce56ac503760a48a2b77d6d03f
[ "MIT" ]
null
null
null
vendor/cucumber-cpp/include/cucumber-cpp/deprecated-defs.hpp
AndreasAugustin/Gherkin-Demos-cpp
79a4be81ee1fffce56ac503760a48a2b77d6d03f
[ "MIT" ]
null
null
null
#ifndef CUKE_DEPRECATED_DEFS_HPP_ #define CUKE_DEPRECATED_DEFS_HPP_ // ************************************************************************** // // ************** USING_CONTEXT ************** // // ************************************************************************** // #define USING_CONTEXT(type, name) ::cucumber::ScenarioScope<type> name #endif /* CUKE_DEPRECATED_DEFS_HPP_ */
32.769231
80
0.377934
AndreasAugustin
6cec06062eb24cc327758d2dbb829c50c046fd6a
71,997
cpp
C++
lib/FixpointSSI.cpp
ucsb-seclab/sasi
a406bd69728f5502bc618fc01782a48db6c3d3ea
[ "MIT" ]
30
2019-07-04T02:26:13.000Z
2021-09-02T18:22:24.000Z
lib/FixpointSSI.cpp
ucsb-seclab/sasi
a406bd69728f5502bc618fc01782a48db6c3d3ea
[ "MIT" ]
null
null
null
lib/FixpointSSI.cpp
ucsb-seclab/sasi
a406bd69728f5502bc618fc01782a48db6c3d3ea
[ "MIT" ]
10
2019-08-05T21:15:47.000Z
2020-03-31T02:57:11.000Z
// Authors: Jorge. A Navas, Peter Schachte, Harald Sondergaard, and // Peter J. Stuckey. // The University of Melbourne 2012. ////////////////////////////////////////////////////////////////////////////// /// \file FixpointSSI.cpp /// Iterative Forward Abstract Interpreter ////////////////////////////////////////////////////////////////////////////// /// /// The fixpoint is intraprocedural and does not track any memory /// location. Thus, it considers only variables in SSA form. /// /// The precision of the fixpoint relies heavily on the effectiveness /// of the SSI form. That is, it is vital for the analysis that the /// SSI form pass is able to add as many sigma nodes as possible. /// - We have noticed that the use of CFGSimplify can avoid the SSI pass /// to add sigma nodes losing dramatically precision. /// - It is relative often code like the following: /// /// \verbatim /// %tmp7 = sext i8 %x to i32 /// %tmp8 = sext i8 -10 to i32 /// ... /// %tmp9 = icmp sge i32 %tmp7, %tmp8 /// ... in another block: /// %sigma = phi i8 [%x,..] /// \endverbatim /// /// Here there is type mismatch for %x. In these case, we do not call /// visitSigmaNode. /// /// Another source of imprecision is cast instructions from floating /// or pointers to integers which are not tracked by the analysis. /// /// \todo Make sure there is no memory leaks. /// /// The fixpoint is mostly designed for running a lattice. However, it /// can also run non-lattice abstract domains if some special care is /// taken. In particular: /// - if the abstract domain is not a lattice widening cannot be /// executed in a intermittent manner. Otherwise, the analysis may /// not terminate. /// - Specialized versions of joins to merge more than two abstract /// values are recommended to avoid losing precision since joins are /// not associative. ///////////////////////////////////////////////////////////////////////////////// #include "FixpointSSI.h" #include "AbstractValue.h" #include "ArrayIndexManager.h" using namespace llvm; using namespace unimelb; using namespace NEWEVAL; STATISTIC(NumOfAnalFuncs ,"Number of analyzed functions"); STATISTIC(NumOfAnalBlocks ,"Number of analyzed blocks"); STATISTIC(NumOfAnalInsts ,"Number of analyzed instructions"); STATISTIC(NumOfInfeasible ,"Number of infeasible branches"); STATISTIC(NumOfWideningPts ,"Number of widening locations"); STATISTIC(NumOfWidenings ,"Number of widen instructions"); STATISTIC(NumOfNarrowings ,"Number of narrowing passes"); STATISTIC(NumOfSkippedIns ,"Number of skipped instructions"); // Debugging void printValueInfo(Value *,Function*); void printUsersInst(Value *,SmallPtrSet<BasicBlock*, 16>,bool); inline void PRINTCALLER(std::string s){ /*dbgs() << s << "\n";*/ } FixpointSSI:: FixpointSSI(Module *M, unsigned WL, unsigned NL, AliasAnalysis *AA, OrderingTy ord): M(M), WideningLimit(WL), ConstSetOrder(ord), NarrowingLimit(NL), NarrowingPass(false), AA(AA), IsAllSigned(true){ if (WideningLimit == 0) dbgs() << "Warning: user selected no widening!\n"; if (NarrowingLimit == 0) dbgs() << "Warning: user selected no narrowing!\n"; } FixpointSSI:: FixpointSSI(Module *M, unsigned WL, unsigned NL, AliasAnalysis *AA, bool isSigned, OrderingTy ord): M(M), WideningLimit(WL), ConstSetOrder(ord), NarrowingLimit(NL), NarrowingPass(false), AA(AA), IsAllSigned(isSigned){ if (WideningLimit == 0) dbgs() << "Warning: user selected no widening!\n"; if (NarrowingLimit == 0) dbgs() << "Warning: user selected no narrowing!\n"; } FixpointSSI::~FixpointSSI(){ for (AbstractStateTy::iterator I = ValueState.begin(), E=ValueState.end(); I!=E; ++I) delete I->second; for (DenseMap<Value*,TBool*>::iterator I=TrackedCondFlags.begin(), E=TrackedCondFlags.end(); I!=E; ++I) delete I->second; ConstSet.clear(); } void FixpointSSI::init(Function *F){ Cleanup(); // Pessimistic assumption about trackable global variables. In this // case, no bother running an expensive alias analysis. // addTrackedGlobalVariablesPessimistically(M); unsigned Width; Type * Ty; if (Utilities::IsTrackableFunction(F)){ // Add formal parameters as definitions and initialize the // abstract value for (Function::arg_iterator argIt=F->arg_begin(),E=F->arg_end(); argIt != E; argIt++) { DEBUG(printValueInfo(argIt,F)); if (isCondFlag(argIt)){ DEBUG(dbgs() << "\trecording a Boolean flag:" << argIt->getName() << "\n"); TrackedCondFlags.insert(std::make_pair(&*argIt, new TBool())); } else{ if (Utilities::getTypeAndWidth(argIt, Ty, Width)){ AbstractValue *Top = initAbsValTop(argIt); Top->setBasicBlock(&F->getEntryBlock()); ValueState.insert(std::make_pair(&*argIt,Top)); } } } // end for ArrayIndexClassifier::setupFunction(F); // Add instructions as definitions and initialize the abstract value for (inst_iterator I = inst_begin(F), E=inst_end(F) ; I != E; ++I){ DEBUG(printValueInfo(&*I,F)); if (HasLeftHandSide(*I)){ if (Value * V = dyn_cast<Value>(&*I)){ if (isCondFlag(V)){ DEBUG(dbgs() << "\trecording a Boolean flag:" << V->getName() << "\n"); TrackedCondFlags.insert(std::make_pair(&*V, new TBool())); } else{ if (Utilities::getTypeAndWidth(V, Ty, Width)){ AbstractValue *Bot = initAbsValBot(V); Bot->setBasicBlock(I->getParent()); ValueState.insert(std::make_pair(&*V,Bot)); } } } } } // end for /// Record all constant integers that appear in the program. /// We put them into a set first to eliminate duplicates. std::set<int64_t> Set; Utilities::recordIntegerConstants(F,Set); std::copy(Set.begin(), Set.end(), std::back_inserter(ConstSet)); // Sort them if (ConstSetOrder == LESS_THAN){ // Since Set is ordered already using signed < we don't need to // do anything here. // std::sort(ConstSet.begin(), ConstSet.end()); } else if (ConstSetOrder == LEX_LESS_THAN) std::sort(ConstSet.begin(), ConstSet.end(), Utilities::Lex_LessThan_Comp); else llvm_unreachable("Unsupported ordering"); DEBUG(Utilities::printIntConstants(ConstSet)); /// Create an abstract value for each integer constant in the /// program. std::vector<std::pair<Value*,ConstantInt*> > NewAbsVals; Utilities::addTrackedIntegerConstants(F, IsAllSigned, NewAbsVals); for (unsigned int i=0; i<NewAbsVals.size(); i++){ ValueState.insert(std::make_pair(NewAbsVals[i].first, initAbsIntConstant(NewAbsVals[i].second))); } // Record widening points. addTrackedWideningPoints(F); #ifdef SKIP_TRAP_BLOCKS for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B){ for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I){ if (CallInst *CI = dyn_cast<CallInst>(&*I)){ if (Function *F = CI->getCalledFunction()){ if (F->getName().endswith("trap_handler")) TrackedTrapBlocks.insert(std::make_pair(B,0)); } } } } #endif } } // Iterative intraprocedural fixpoint + narrowing. void FixpointSSI::solve(Function *F){ solveLocal(F); computeNarrowing(F); } // Compute a intraprocedural fixpoint until no change applying the // corresponding transfer function. void FixpointSSI::solveLocal(Function *F){ DEBUG(dbgs () << "Starting fixpoint for " << F->getName() << " ... \n"); NumOfAnalFuncs++; // Confirm this: no needed for intraprocedural analysis // We need to cleanup BBExecutable and KnownFeasibleEdges in case // the function is analyzed more than once. Otherwise, after the // first time all blocks are kept as processed so nothing will be // done. //cleanupPreviousFunctionAnalysis(F); markBlockExecutable(&F->getEntryBlock()); computeFixpo(); DEBUG(dbgs () << "Fixpoint reached for " << F->getName() << ".\n"); } void FixpointSSI::computeFixpo(){ // Process the work lists until they are empty! while (!BBWorkList.empty() || !InstWorkList.empty()) { // Process the instruction work list. while (!InstWorkList.empty()) { std::set<Value*>::iterator It = InstWorkList.begin(); InstWorkList.erase(It); Value *I = *It; // "I" got into the work list because it made a transition. See // if any users are both live and in need of updating. DEBUG(dbgs() << "\n*** Popped off I-WL: " << *I << "\n"); DEBUG(printUsersInst(I,BBExecutable,true)); for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) { Instruction *U = cast<Instruction>(*UI); // We check that the instruction U is defined in an executable // block if (BBExecutable.count(U->getParent()) && U != I) { DEBUG(dbgs() << "\n***Visiting: " << *U << " as user of " << *I << "\n"); visitInst(*U); } } // end for /// We need to pay special attention to sigma nodes for two /// reasons. For code like this: /// \verbatim /// i = phi [tmp6,...] [0,...] /// ... /// sigma = phi [i,...] /// tmp6 = add sigma, 1 /// \endverbatim /// Assume that tmp6 changes from [0,0] to [1,1]. As a result, /// we push tmp6 into IWorklist. Then, we analyze i and infer /// than i=[0,1], and push i also in the IWorklist. If we pop /// first tmp6 from IWorklist then tmp6 is again [1,1] since /// sigma was not updated. This suggests that we should visit /// first sigma nodes. Another issue arises with code like this: /// \verbatim /// tmp4 = icmp slt i, j /// .... /// sigma = phi [i,..] /// \endverbatim /// Here sigma is an user of i. However, sigma is also indirectly /// an user of j. That is, if j is modified we should re-analyze /// sigma. However, this dependency between j and sigma does not /// appear in the def-use information. We solve in a bit clumsy /// way these two issues by tracking a map from V to set(V) that /// keeps track of for a given variable V which is the set of /// sigma nodes that should be re-analyzed. /// /// \bug: we are visiting twice the number of sigma nodes. if (SmallValueSet * SigmaSet = TrackedValuesUsedSigmaNode[I]){ for( SmallValueSet::iterator UI = SigmaSet->begin(), UE = SigmaSet->end(); UI != UE; ++UI){ Instruction * U = cast<Instruction>(*UI); if (BBExecutable.count(U->getParent())) { DEBUG(dbgs() << "\n***Forcing the visit of: " << *U << " as user of " << *I << "\n"); visitInst(*U); } } // end inner for } } // end while // Process the basic block work list. while (!BBWorkList.empty()) { std::set<BasicBlock*>::iterator BBIt = BBWorkList.begin(); BBWorkList.erase(BBIt); BasicBlock *BB = *BBIt; DEBUG(dbgs() << "\n***Popped off BBWL: " << *BB); // Notify all instructions in this basic block that they are newly // executable. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I){ visitInst(*I); } } // end while } // end outer while } /// Iterate over all instructions in the function and apply the /// corresponding transfer function for every one without /// widening. The instructions must be visited preserving the original /// order in the program. /// \lambda x. x /\ F(x) void FixpointSSI::computeOneNarrowingIter(Function *F){ markBlockExecutable(&F->getEntryBlock()); // Iterator dfs over the basic blocks in the function for (df_iterator<BasicBlock*> DFI = df_begin(&F->getEntryBlock()), DFE = df_end(&F->getEntryBlock()); DFI != DFE; ++DFI) { BasicBlock * BB = *DFI; if (BBExecutable.count(BB)){ for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I){ visitInst(*I); } } } } // Narrowing is implemented by making a arbitrary number of passes // applying the transfer functions **without** applying widening. void FixpointSSI::computeNarrowing(Function *EntryF){ if (NarrowingLimit == 0) return; unsigned N = NarrowingLimit; NarrowingPass=true; // We should clear these datastructures before starting narrowing. // Otherwise, narrowing cannot make unreachable a block that was // reachable for the fixpoint. // BBExecutable.clear(); // KnownFeasibleEdges.clear(); while (N-- > 0){ DEBUG(dbgs () << "\nStarting narrowing ... \n"); NumOfNarrowings++; assert(InstWorkList.empty() && "The worklist should be empty"); computeOneNarrowingIter(EntryF); assert(InstWorkList.empty() && "The worklist should be empty"); } NarrowingPass=false; DEBUG(dbgs () << "Narrowing finished.\n"); } bool FixpointSSI:: isEdgeFeasible(BasicBlock *From, BasicBlock *To){ std::set<Edge>::iterator I = KnownFeasibleEdges.find(std::make_pair(From,To)); if (I != KnownFeasibleEdges.end()) return true; else{ NumOfInfeasible++; return false; } } // Check if the new value is contained by the old value. If yes, then // return and do nothing. Otherwise, add the instruction in the // worklist and apply widening if widening conditions are // applicable. If we are doing a narrowing pass then widening is // disabled and we don't add anything in the worklist. void FixpointSSI::updateState(Instruction &Inst, AbstractValue * NewV) { assert(NewV != NULL && "updateState: instruction not defined"); AbstractStateTy::iterator I = ValueState.find(&Inst); AbstractValue* OldV = I->second; // DEBUG(dbgs() << "Old value: " ); // DEBUG(OldV->print(dbgs())); // DEBUG(dbgs() << "\n" ); // DEBUG(dbgs() << "New value: " ); // DEBUG(NewV->print(dbgs())); // DEBUG(dbgs() << "\n" ); if (NarrowingPass){ DEBUG(dbgs() << "***[Narrowing] from "); DEBUG(OldV->print(dbgs())); DEBUG(dbgs() << " to " ); DEBUG(NewV->print(dbgs())); DEBUG(dbgs() << "\n" ); assert(NewV); delete ValueState[&Inst]; ValueState[&Inst] = NewV; } else{ //////////////////////////////////////////////////////////////////// // Widening: // bottom if n=0 // f^{n}_{w} = f^{n-1}_{w} if n>0 and // f(f^{n-1}_{w}) \subseteq f^{n-1}_{w} // widening(f^{n-1}_{w},f(f^{n-1}_{w})) otherwise // Here OldV = f^{n-1}_{w} and NewV = f(f^{n-1}_{w}) //////////////////////////////////////////////////////////////////// if (I != ValueState.end() && NewV->lessOrEqual(OldV)){ // No change DEBUG(dbgs() << "\nThere is no change\n"); // If uncommented then we produce a seg fault if debugging mode // delete NewV return; } NewV->incNumOfChanges(); if (Widen(&Inst,NewV->getNumOfChanges())){ //dbgs() << "WIDENING " << Inst << "\n"; NumOfWidenings++; NewV->widening(OldV,ConstSet); // We reset the counter because we don't want to apply widening // if not really needed. E.g., after a widening we can have a // casting operation. If the counter is not reset then we will // do widening again with potential catastrophic losses. if (NewV->isLattice()) NewV->resetNumOfChanges(); } // there is change: visit uses of I. assert(NewV); delete ValueState[&Inst]; ValueState[&Inst] = NewV; DEBUG(dbgs() << "***Added into I-WL: " << Inst << "\n"); InstWorkList.insert(&Inst); } } // Special case for Boolean flags. void FixpointSSI::updateCondFlag(Instruction &I, TBool * New){ assert(isTrackedCondFlag(&I)); if (NarrowingPass){ delete TrackedCondFlags[&I]; TrackedCondFlags[&I] = New; return; } TBool * Old = TrackedCondFlags.lookup(&I); if (Old->isEqual(New)){ // No change DEBUG(dbgs() << "\nThere is no change\n"); //delete New; return; } // There is change: visit uses of I. delete TrackedCondFlags[&I]; TrackedCondFlags[&I] = New; DEBUG(dbgs() << "***Added into I-WL: " << I << "\n"); InstWorkList.insert(&I); } // Mark the edge Source-Dest as executable and mark Dest as an // executable block. Moreover, we revisit the phi nodes of Dest. void FixpointSSI::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) { if (!KnownFeasibleEdges.insert(std::make_pair(Source, Dest)).second) return; // This edge is already known to be executable! DEBUG(dbgs() << "***Marking Edge Executable: " << Source->getName() << " -> " << Dest->getName() << "\n"); if (BBExecutable.count(Dest) && !NarrowingPass) { // The destination is already executable, but we just made an edge // feasible that wasn't before. Revisit the PHI nodes in the block // because they have potentially new operands. for (BasicBlock::iterator I = Dest->begin(), E = Dest->end(); I!=E ; ++I){ if (isa<PHINode>(I)){ DEBUG(dbgs() << "Triggering the analysis of " << *I << "\n"); visitPHINode(*cast<PHINode>(I)); } } } else markBlockExecutable(Dest); } // Mark a basic block as executable, adding it to the BB worklist if // it is not already executable. void FixpointSSI::markBlockExecutable(BasicBlock *BB) { DEBUG(dbgs() << "***Marking Block Executable: " << BB->getName() << "\n"); NumOfAnalBlocks++; BBExecutable.insert(BB); // Basic block is executable #ifdef SKIP_TRAP_BLOCKS DenseMap<BasicBlock*,unsigned int>::iterator It = TrackedTrapBlocks.find(BB); if (It != TrackedTrapBlocks.end()) return; #endif BBWorkList.insert(BB); // Add the block to the work list } // visitInst - Execute the instruction void FixpointSSI::visitInst(Instruction &I) { NumOfAnalInsts++; // First, special instructions handled directly by the fixpoint // algorithm, never passed into the underlying abstract domain // because they can be defined in terms of join, meet, etc. if (StoreInst *SI = dyn_cast<StoreInst>(&I)) return visitStoreInst(*SI); if (LoadInst *LI = dyn_cast<LoadInst>(&I)) return visitLoadInst(*LI); if (CallInst *CI = dyn_cast<CallInst>(&I)) return visitCallInst(*CI); if (ReturnInst *RI = dyn_cast<ReturnInst>(&I)) return visitReturnInst(*RI); if (PHINode *PN = dyn_cast<PHINode>(&I)) return visitPHINode(*PN); if (SelectInst *SelI = dyn_cast<SelectInst>(&I)) return visitSelectInst(*SelI); if (TerminatorInst *TI = dyn_cast<TerminatorInst>(&I)) return visitTerminatorInst(*TI); if (ICmpInst *ICmpI = dyn_cast<ICmpInst>(&I)) return visitComparisonInst(*ICmpI); if (IsBooleanLogicalOperator(&I)) return visitBooleanLogicalInst(I); // Otherwise, we pass the transfer function to the abstract domain. if (Value *V = dyn_cast<Value>(&I)){ if (AbstractValue * AbsV = ValueState.lookup(V)){ // New is going to keep a pointer to a derived class. The // methods visitArithBinaryOp, visitBitwiseBinaryOp, and // visitCast ensure that it is new allocated memory. AbstractValue *New = NULL; switch (I.getOpcode()){ case Instruction::Add: case Instruction::Sub: case Instruction::Mul: case Instruction::SDiv: case Instruction::UDiv: case Instruction::SRem: case Instruction::URem: { DEBUG(dbgs() << "Arithmetic instruction: " << I << "\n"); /// // We can have instructions like // %tmp65 = sub i32 %tmp64, ptrtoint ([6 x %struct._IO_FILE*]* @xgets.F to i32) // Therefore, we need to check if the operands are in // ValueState. If not, just top. //// AbstractValue * Op1 = Lookup(I.getOperand(0), false); AbstractValue * Op2 = Lookup(I.getOperand(1), false); if (Op1 && Op2) New = AbsV->visitArithBinaryOp(Op1,Op2, I.getOpcode(),I.getOpcodeName()); else{ New = AbsV->clone(); New->makeTop(); } } break; case Instruction::Shl: // logical left shift case Instruction::LShr: // logical right shift case Instruction::AShr: // arithmetic right shift case Instruction::And: // bitwise and case Instruction::Or: // bitwise or case Instruction::Xor: // bitwise xor { DEBUG(dbgs() << "Bitwise instruction: " << I << "\n"); AbstractValue * Op1 = Lookup(I.getOperand(0), false); AbstractValue * Op2 = Lookup(I.getOperand(1), false); if (Op1 && Op2) New = AbsV->visitBitwiseBinaryOp(Op1, Op2, I.getOperand(0)->getType(), I.getOperand(1)->getType(), I.getOpcode(), I.getOpcodeName()); else{ New = AbsV->clone(); New->makeTop(); } } break; case Instruction::BitCast: // no-op cast from one type to another case Instruction::ZExt: // zero extend integers case Instruction::SExt: // sign extend integers case Instruction::Trunc: // truncate integers { DEBUG(dbgs() << "Casting instruction: " << I << "\n"); // Tricky step: the source of the casting instruction may be // a Boolean Flag. If yes, we need to convert the Boolean // flag into an abstract value. This must be done by the // class that implements AbstractValue. TBool * SrcFlag = NULL; AbstractValue *SrcAbsV = NULL; if (isTrackedCondFlag(I.getOperand(0))) SrcFlag = TrackedCondFlags.lookup(I.getOperand(0)); else SrcAbsV = Lookup(I.getOperand(0), false); if (SrcFlag || SrcAbsV) New = AbsV->visitCast(I, SrcAbsV, SrcFlag, IsAllSigned); else{ New = AbsV->clone(); New->makeTop(); } } break; default: #ifdef WARNINGS dbgs() << "Warning: transfer function not implemented: " << I << "\n"; #endif /* WARNINGS */ assert(New == NULL); New = AbsV->clone(); New->makeTop(); NumOfSkippedIns++; break; } // end switch assert(New && "ERROR: something wrong during the transfer function "); PRINTCALLER("visitInst"); // We do not delete New since it will be stored in a map // manipulated by updateState. Instead, updateState will free // the old value if it is replaced with New. updateState(I,New); } } } // Function calls /// Conservative assumptions if the code of the called function will /// not be analyzed. void FixpointSSI:: FunctionWithoutCode(CallInst *CInst, Function * Callee, Instruction *I){ // Make top the return value if it's trackable by the analysis if (!I->getType()->isVoidTy()) { if (isTrackedCondFlag(I)){ TBool * LHSFlag = TrackedCondFlags[I]; assert(LHSFlag && "ERROR: flag not found in TrackedCondFlags"); LHSFlag->makeMaybe(); DEBUG(dbgs() << "\tMaking the return value maybe: "); DEBUG(LHSFlag->print(dbgs())); DEBUG(dbgs() << "\n"); } else{ if (AbstractValue * LHS = ValueState[I]){ DEBUG(dbgs() << "\tMaking the return value top: "); LHS->makeTop(); DEBUG(LHS->print(dbgs())); DEBUG(dbgs() << "\n"); } } } if (Callee){ // Make top all global variables that may be touched by the // function (CInst). for (SmallPtrSet<GlobalVariable*, 64>::iterator I = TrackedGlobals.begin(), E = TrackedGlobals.end(); I != E; ++I){ GlobalVariable *Gv = *I; AliasAnalysis::ModRefResult IsModRef = AA->getModRefInfo(CInst,Gv,AliasAnalysis::UnknownSize); if ( (IsModRef == AliasAnalysis::Mod) || (IsModRef == AliasAnalysis::ModRef) ){ if (TrackedGlobals.count(Gv)){ if (isTrackedCondFlag(Gv)){ TBool * GvFlag = TrackedCondFlags[Gv]; assert(GvFlag && "ERROR: flag not found in TrackedCondFlags"); GvFlag->makeMaybe(); DEBUG(dbgs() <<"\tGlobal Boolean flag " << Gv->getName() << " may be modified by " << Callee->getName() <<".\n"); } else{ AbstractValue * AbsGv = ValueState.lookup(Gv); assert(AbsGv && "ERROR: entry not found in ValueState"); AbsGv->makeTop(); DEBUG(dbgs() <<"\tGlobal variable " << Gv->getName() << " may be modified by " << Callee->getName() <<".\n"); } } } } } } /// Since the analysis is intraprocedural we don't analysis the /// callee. We just consider the most pessimistic assumptions about /// the callee: top for the return value and anything memory location /// may-touched by the callee. void FixpointSSI::visitCallInst(CallInst &CI) { CallSite *CS = new CallSite(&CI); Function *F = CS->getCalledFunction(); Instruction *I = CS->getInstruction(); DEBUG(dbgs() << "Function call " << *I << "\n"); FunctionWithoutCode(&CI,F,I); delete CS; } /// Do nothing. void FixpointSSI::visitReturnInst(ReturnInst &I){ return; } /// Inform the analysis that it should track loads and stores to the /// specified global variable if it can and it gives an initial /// abstract value for each global variable. Note we following C /// semantics we assign 0 to all uninitialized integer scalar global /// variables. void FixpointSSI::addTrackedGlobalVariables(Module *M) { /// Keep track only integer scalar global variables whose addresses /// have not been taken. In LLVM, if the address has not been taken /// then they memory object still has its def-use chains. for (Module::global_iterator Gv = M->global_begin(), E = M->global_end(); Gv != E; ++Gv){ if (!Utilities::AddressIsTaken(Gv) && Gv->getType()->isPointerTy() && Gv->getType()->getContainedType(0)->isIntegerTy()) { DEBUG(printValueInfo(Gv,NULL)); // Initialize the global variable if (Gv->hasInitializer()){ if (ConstantInt * GvInitVal = dyn_cast<ConstantInt>(Gv->getInitializer())){ if (isCondFlag(Gv)){ DEBUG(dbgs() << "\trecording a Boolean flag for global:" << Gv->getName() << "\n"); // FIXME: we ignore the initialized value and assume "maybe" TrackedCondFlags.insert(std::make_pair(&*Gv, new TBool())); } else ValueState.insert(std::make_pair(&*Gv, initAbsValIntConstant(Gv,GvInitVal))); } } else{ if (isCondFlag(Gv)){ DEBUG(dbgs() << "\trecording a Boolean flag for global:" << Gv->getName() << "\n"); TBool * GvFlag = new TBool(); GvFlag->makeFalse(); TrackedCondFlags.insert(std::make_pair(&*Gv,GvFlag)); } else{ ConstantInt * Zero = cast<ConstantInt>(ConstantInt:: get(Gv->getType()->getContainedType(0), 0, IsAllSigned)); ValueState.insert(std::make_pair(&*Gv,initAbsValIntConstant(Gv,Zero))); } } TrackedGlobals.insert(Gv); } } } /// Here we keep track of global variables but we always initialize /// with top so that each function is analyzed with correct /// assumption. void FixpointSSI::addTrackedGlobalVariablesPessimistically(Module *M) { /// Keep track only integer scalar global variables whose addresses /// have not been taken. In LLVM, if the address has not been taken /// then they memory object still has its def-use chains. for (Module::global_iterator Gv = M->global_begin(), E = M->global_end(); Gv != E; ++Gv){ if (!Utilities::AddressIsTaken(Gv) && Gv->getType()->isPointerTy() && Gv->getType()->getContainedType(0)->isIntegerTy()) { DEBUG(printValueInfo(Gv,NULL)); // Initialize the global variable if (isCondFlag(Gv)){ DEBUG(dbgs() << "\trecording a Boolean flag for global:" << Gv->getName() << "\n"); TrackedCondFlags.insert(std::make_pair(&*Gv,new TBool())); } else ValueState.insert(std::make_pair(&*Gv,initAbsValTop(Gv))); TrackedGlobals.insert(Gv); } } } /// The store instruction is special since the destination is a /// pointer which is not in SSA. We perform weak updates and also very /// importantly, notify widening points about the change. void FixpointSSI::visitStoreInst(StoreInst &I){ // We care only about store related to tracked global variables Value *ptrOper = I.getPointerOperand(); AbstractValue *checkZAbsValue = Lookup(ptrOper, false); if(checkZAbsValue && checkZAbsValue->hasNoZero()) { if(checkZAbsValue->getValueID() == 1) { // HERE Wrapped range is non-zero dbgs() << "Wrapped Range non-zero for:" << I << "\n"; } if(checkZAbsValue->getValueID() == 2) { dbgs() << "Strided Range non-zero for:" << I << "\n"; } } if (GlobalVariable *Gv = dyn_cast<GlobalVariable>(I.getPointerOperand())){ if (TrackedGlobals.count(Gv)){ // Special case if a Boolean Flag if (isTrackedCondFlag(Gv)){ TBool * MemAddFlag = TrackedCondFlags[I.getPointerOperand()]; assert(MemAddFlag && "Memory location not mapped to a Boolean flag"); DEBUG(dbgs() << "Memory store " << I << "\n"); if (isTrackedCondFlag(I.getValueOperand())){ TBool * FlagToStore = TrackedCondFlags[I.getValueOperand()]; // weak update using disjunction MemAddFlag->Or(MemAddFlag,FlagToStore); } else MemAddFlag->makeMaybe(); DEBUG(dbgs() <<"\t[RESULT] "); DEBUG(MemAddFlag->print(dbgs())); DEBUG(dbgs() <<"\n"); return; } AbstractValue * MemAddr = Lookup(I.getPointerOperand(), true); assert(MemAddr && "Memory location is not mapped in ValueState"); DEBUG(dbgs() << "Memory store " << I << "\n"); // Weak update MemAddr->join(Lookup(I.getValueOperand(), true)); DEBUG(dbgs() <<"\t[RESULT] "); DEBUG(MemAddr->print(dbgs())); DEBUG(dbgs() <<"\n"); // Notify widening points about new change. // FIXME: In fact we could test here if there is actually a // change. Otherwise, we don't need to notify anybody. // FIXME: maybe also other load instructions which postdominate I? for (Value::use_iterator UI = I.getPointerOperand()->use_begin(), E = I.getPointerOperand()->use_end(); UI != E; ++UI) { Instruction *U = cast<Instruction>(*UI); if (BBExecutable.count(U->getParent())){ if (WideningPoints.count(U)){ DEBUG(dbgs() << "***Added into I-WL: " << *U << "\n"); visitInst(*U); } } } return; } } DEBUG(dbgs() << "Ignored memory store " << I << "\n"); } // To avoid problems during narrowing void ResetAbstractValue(AbstractValue * V){ V->makeBot(); } /// Load the abstract value from the memory pointer to the lhs of the /// instruction and insert into the worklist all its users. We care /// only about tracked global variables. void FixpointSSI::visitLoadInst(LoadInst &I){ Value *ptrOper = I.getPointerOperand(); AbstractValue *checkZAbsValue = Lookup(ptrOper, false); if(checkZAbsValue && checkZAbsValue->hasNoZero()) { if(checkZAbsValue->getValueID() == 1) { // HERE Wrapped range is non-zero dbgs() << "Wrapped Range non-zero for:" << I << "\n"; } if(checkZAbsValue->getValueID() == 2) { dbgs() << "Strided Range non-zero for:" << I << "\n"; } } /// We care only about store related to tracked global variables if (GlobalVariable *Gv = dyn_cast<GlobalVariable>(I.getPointerOperand())){ if (TrackedGlobals.count(Gv)){ // Special case if a Boolean Flag if (isTrackedCondFlag(Gv)){ TBool * LHSFlag = new TBool(*TrackedCondFlags[&I]); assert(LHSFlag && "Memory location not mapped to a Boolean flag"); if (isTrackedCondFlag(I.getPointerOperand())){ TBool * MemAddFlag = TrackedCondFlags[I.getPointerOperand()]; LHSFlag->makeTrue(); LHSFlag->And(LHSFlag,MemAddFlag); } else LHSFlag->makeMaybe(); // We do not delete LHSFlag since it will be stored in a map // manipulated by updateCondFlag. Instead, updateCondFlag will // free the old value if it is replaced with LHSFlag. updateCondFlag(I,LHSFlag); DEBUG(dbgs() << "\t[RESULT] "); DEBUG(LHSFlag->print(dbgs())); DEBUG(dbgs() << "\n"); return; } AbstractValue * LHS = Lookup(&I, false); if (!LHS) return; DEBUG(dbgs() << "Memory Load " << I << "\n"); // Clone LHS in order to compare with old value in updateState AbstractValue * NewLHS = LHS->clone(); // Assign from memory to lhs ResetAbstractValue(NewLHS); NewLHS->join(Lookup(I.getPointerOperand(), true)); DEBUG(dbgs() << "\t[RESULT] "); DEBUG(NewLHS->print(dbgs())); DEBUG(dbgs() << "\n"); // Compare if it loads a new value and then add I into the // worklist PRINTCALLER("visitLoadInst"); // We do not delete NewLHS since it will be stored in a map // manipulated by updateState. Instead, updateState will free // the old value if it is replaced with NewLHS. updateState(I,NewLHS); return; } } DEBUG(dbgs() << "Ignored memory load " << I << "\n"); AbstractValue * LHS = Lookup(&I, false); // No need to call updateState since it's top from the beginning. if (LHS) LHS->makeTop(); } // Execution of sigma nodes /// Helper to add the map from V to Sigma in /// TrackedValuesUsedSigmaNode. void insertTrackedValuesUsedSigmaNode(SigmaUsersTy &TrackedValuesUsedSigmaNode, Value *V, Value *LHSSigma){ if (!isa<ConstantInt>(V)){ DEBUG(dbgs() << "Adding " << V->getName() << " -> " << LHSSigma->getName() << "\n"); if (SmallValueSet * SigmaSet = TrackedValuesUsedSigmaNode[V]){ SigmaSet->insert(LHSSigma); } else{ SmallValueSet * NSigmaSet = new SmallValueSet; NSigmaSet->insert(LHSSigma); TrackedValuesUsedSigmaNode[V] = NSigmaSet; } } } /// Add the entry LHSSigma --> (Op1 'pred' Op2) /// Pre: there is no entry for LHSSigma. void genConstraint(unsigned pred, Value *Op1, Value *Op2, SigmaFiltersTy &filters, Value * LHSSigma, SigmaUsersTy &TrackedValuesUsedSigmaNode){ BinaryConstraintPtr C(new BinaryConstraint(pred,Op1,Op2)); // Sanity check // SigmaFiltersTy::iterator It = filters.find(LHSSigma); // assert(It == filters.end()); filters.insert(std::make_pair(LHSSigma, C)); DEBUG(dbgs() << "\t"; C->print(); dbgs() << "\n"); // Key step for correctness of the fixpoint. insertTrackedValuesUsedSigmaNode(TrackedValuesUsedSigmaNode,Op1, LHSSigma); insertTrackedValuesUsedSigmaNode(TrackedValuesUsedSigmaNode,Op2, LHSSigma); } // /// Generate the constraint Op1 'pred' Op2 and record that the // /// constraint is a filter for both Op1 and Op2. // void genConstraint(unsigned pred, Value *Op1, Value *Op2, // FiltersTy &filters, // Value * LHSSigma, // SigmaUsersTy &TrackedValuesUsedSigmaNode){ // BinaryConstraintPtr C(new BinaryConstraint(pred,Op1,Op2)); // if (!C->isConstantOperand(0)){ // FiltersTy::iterator It = filters.find(Op1); // if (It != filters.end()){ // BinaryConstraintSetTy *Rhs = It->second; // assert(Rhs); // Rhs->insert(C); // filters[Op1]=Rhs; // DEBUG(dbgs() << "\t" ; C->print(); dbgs() << "\n"); // } // else{ // BinaryConstraintSetTy * Rhs = new BinaryConstraintSetTy(); // Rhs->insert(C); // filters.insert(std::make_pair(Op1, Rhs)); // DEBUG(dbgs() << "\t"; C->print(); dbgs() << "\n"); // } // } // if (!C->isConstantOperand(1)){ // FiltersTy::iterator It = filters.find(Op2); // if (It != filters.end()){ // BinaryConstraintSetTy *Rhs = It->second; // assert(Rhs); // Rhs->insert(C); // filters[Op2]=Rhs; // DEBUG(dbgs() << "\t"; C->print(); dbgs() << "\n"); // } // else{ // BinaryConstraintSetTy *Rhs = new BinaryConstraintSetTy(); // Rhs->insert(C); // filters.insert(std::make_pair(Op2, Rhs)); // DEBUG(dbgs() << "\t"; C->print(); dbgs() << "\n"); // } // } // // Key step for correctness of the fixpoint. // insertTrackedValuesUsedSigmaNode(TrackedValuesUsedSigmaNode,Op1, LHSSigma); // insertTrackedValuesUsedSigmaNode(TrackedValuesUsedSigmaNode,Op2, LHSSigma); // } void visitInstrToFilter(Value * LHSSigma, Value * RHSSigma, BranchInst *BI, BasicBlock *SigmaBB, ICmpInst* CI, SigmaFiltersTy &filters, SigmaUsersTy &TrackedValuesUsedSigmaNode){ if (CI->getOperand(0) == RHSSigma || CI->getOperand(1) == RHSSigma){ assert((BI->getSuccessor(0) == SigmaBB || BI->getSuccessor(1) == SigmaBB ) && "This should not happen"); // Figure out whether it is a "then" or "else" block. if (BI->getSuccessor(0) == SigmaBB) genConstraint(CI->getSignedPredicate(), CI->getOperand(0), CI->getOperand(1), filters, LHSSigma, TrackedValuesUsedSigmaNode); else genConstraint(CI->getInversePredicate(CI->getSignedPredicate()), CI->getOperand(0), CI->getOperand(1), filters, LHSSigma, TrackedValuesUsedSigmaNode); } else{ // Case to improve #ifdef WARNINGS dbgs() << "Searching for " << RHSSigma->getName() << "in: \n"; dbgs() << *(BI->getParent()) << "\n"; dbgs() << *(SigmaBB) << "\n"; #endif return; // no filtering here! } } /// Key method for precision: refine RHSSigma using information from /// the branch condition BI. void FixpointSSI::generateFilters(Value *LHSSigma, Value *RHSSigma, BranchInst *BI, BasicBlock *SigmaBB /*, FiltersTy &filters*/){ unsigned width; DEBUG(dbgs() << "Generating filters for " << SigmaBB->getName() << ":" << RHSSigma->getName() << ":\n"); if (ICmpInst * CI = dyn_cast<ICmpInst>(BI->getCondition())){ // If it is not of the type and width that we can track then // no bother if (Utilities::getIntegerWidth(CI->getType(),width)) visitInstrToFilter(LHSSigma, RHSSigma, BI, SigmaBB, CI, SigmaFilters, TrackedValuesUsedSigmaNode); } #ifdef WARNINGS else if (SelectInst * SI = dyn_cast<SelectInst>(BI->getCondition())){ // if (Utilities::getIntegerWidth(SI->getType(),width)) dbgs() << "Warning: no filter generated for " << *SI << "\n"; //visitInstrToFilter(RHSSigma, BI, SI); } else if (IsBooleanLogicalOperator(dyn_cast<Instruction>(BI->getCondition()))){ Instruction * BoolI = dyn_cast<Instruction>(BI->getCondition()); dbgs() << "Warning: no filter generated for " << *BoolI << "\n"; //visitInstrToFilter(RHSSigma, BI, cast<Instruction>(BI->getCondition()), // TrackedCondFlags); } else if (PHINode *PHI = dyn_cast<PHINode>(BI->getCondition())){ dbgs() << "Warning: no filter generated for " << *PHI << "\n"; // For instance, we can have instructions like: // bb1: // tmp2.pre-phi = phi i1 [false, %bb3], [%tmp2.pre, %bb] // br i1, %tmp2.pre-phi, label %bb6, label %bb3 // bb3: // ... // br label %bb1 // // This is coming from code like while(*){ } so there is not // much to do here. I think we do not lose too much if we // leave uncovered this case. } else if (FCmpInst * FCI = dyn_cast<FCmpInst>(BI->getCondition())){ // We do not reason at all about floating numbers even if they // can become integer after some casting. dbgs() << "Warning: no filter generated for " << *FCI << "\n"; } else if (LoadInst *LI = dyn_cast<LoadInst>(BI->getCondition())){ dbgs() << "Warning: no filter generated for " << *LI << "\n"; } else{ dbgs() << "Uncovered case by visitInstrToFilter: \n\t"; dbgs() << *(BI->getCondition()) << "\n"; dbgs() << "We may avoid the analysis losing precision!\n"; // Temporary raise exception to be aware of the unsupported case. llvm_unreachable("Unsupported case") } #endif /*WARNINGS*/ } /// For reducing the number of cases, normalize the constraint with /// respect to V. V appears always as the first argument in F. void normalizeConstraint(BinaryConstraintPtr & FPtr, Value *V){ bool isOp1Constant = isa<ConstantInt>(FPtr.get()->getOperand(0)); bool isOp2Constant = isa<ConstantInt>(FPtr.get()->getOperand(1)); assert(!(isOp1Constant && isOp2Constant)); if (isOp1Constant && !isOp2Constant){ // We swap operands to have first operand the variable and the // second the constant FPtr.get()->swap(); } else if (!isOp1Constant && !isOp2Constant){ assert( (FPtr.get()->getOperand(0) == V) || (FPtr.get()->getOperand(1) == V)); if (FPtr.get()->getOperand(1) == V){ // We swap operands to have first operand the variable that we // want to refine. FPtr.get()->swap(); } } } /// Execute the filters generated for RHSSigma and store the result in /// LHSSigma. bool FixpointSSI::evalFilter(AbstractValue * &LHSSigma, Value *RHSSigma){ bool FilteredDone=false; SigmaFiltersTy::iterator I = SigmaFilters.find(LHSSigma->getValue()); if (I != SigmaFilters.end()){ BinaryConstraintPtr C = (*I).second; DEBUG(dbgs() << "Evaluating filter constraints: "; C.get()->print(); dbgs() << "\n"); normalizeConstraint(C,RHSSigma); DEBUG(dbgs() << "After normalization : "; C.get()->print(); dbgs() << "\n"); // After normalization we know that Op1 is the default value for // LHS which we hope to refine by using Op2. AbstractValue * Op1 = Lookup(C.get()->getOperand(0), true); AbstractValue * Op2 = Lookup(C.get()->getOperand(1), true); // This is too restrictive: If Op1 is already top then we do not // bother. // if (Op1->IsTop()){ LHSSigma->makeTop(); break; } // Here we cannot filter since Op2 is top. if (Op2->IsTop()) return false; if (Op2->isBot()) return false; unsigned pred = C.get()->getPred(); DEBUG( LHSSigma->print(dbgs()); dbgs() << "\n"); DEBUG( Op1->print(dbgs()); dbgs() << "\n"); DEBUG( Op2->print(dbgs()); dbgs() << "\n"); // Do not remember why I cloned here but it does not make sense. // LHSSigma->filterSigma(pred, Op1->clone(), Op2->clone()); LHSSigma->filterSigma(pred, Op1, Op2); DEBUG( LHSSigma->print(dbgs()); dbgs() << "\n"); FilteredDone=true; } return FilteredDone; } // /// Execute the filters generated for RHSSigma and store the result in // /// LHSSigma. // bool FixpointSSI::evalFilter(AbstractValue * &LHSSigma, Value *RHSSigma, // const FiltersTy filters){ // bool FilteredDone=false; // FiltersTy::const_iterator I = filters.find(RHSSigma); // if (I != filters.end()){ // BinaryConstraintSetTy * Rhs = I->second; // assert(Rhs->size() < 2); // for (BinaryConstraintSetTy::iterator II=Rhs->begin(), EE=Rhs->end(); II!=EE; ++II){ // BinaryConstraintPtr C = *II; // DEBUG(dbgs() << "Evaluating filter constraints: "; C.get()->print(); dbgs() << "\n"); // normalizeConstraint(C,RHSSigma); // DEBUG(dbgs() << "After normalization : "; C.get()->print(); dbgs() << "\n"); // AbstractValue * Op1 = Lookup(C.get()->getOperand(0), true); // AbstractValue * Op2 = Lookup(C.get()->getOperand(1), true); // // After normalization we know that Op1 is the default value for // // LHS which we hope to refine by using Op2. // // (This is too restrictive: If Op1 is already top then we do not // // bother) // //if (Op1->IsTop()){ LHSSigma->makeTop(); break; } // // Here we cannot filter since Op2 is top. // if (Op2->IsTop()) return false; // if (Op2->isBot()) return false; // unsigned pred = C.get()->getPred(); // DEBUG( LHSSigma->print(dbgs()); dbgs() << "\n"); // DEBUG( Op1->print(dbgs()); dbgs() << "\n"); // DEBUG( Op2->print(dbgs()); dbgs() << "\n"); // LHSSigma->filterSigma(pred, Op1->clone(), Op2->clone()); // DEBUG( LHSSigma->print(dbgs()); dbgs() << "\n"); // FilteredDone=true; // } // } // return FilteredDone; // } /// Simply assign RHSSigma to LHSSigma. void FixpointSSI::visitSigmaNode(AbstractValue *LHSSigma, Value * RHSSigma){ // In programs like 176.gcc we have things like: // %.01.i = phi i32 [ ptrtoint (double* getelementptr inbounds // (%struct.fooalign* null, i32 0, i32 1) to i32), // %bb3.i ] // Thus, we can raise an exception if RHSSigma is not found. ResetAbstractValue(LHSSigma); if (AbstractValue *AbsVal = Lookup(RHSSigma,false)) LHSSigma->join(AbsVal); else LHSSigma->makeTop(); } // Execute a sigma node in two steps. The execution consists of // assigning RHSSigma to LHSSigma. Additionally, knowledge from BI is // used to improve LHSSigma. First it generates any filter that it can // be inferred from the branch condition. Second, it actually executes // the filter. void FixpointSSI::visitSigmaNode(AbstractValue *LHSSigma, Value * RHSSigma, BasicBlock *SigmaBB, BranchInst * BI){ // FiltersTy filters; // generateFilters(LHSSigma->getValue(), RHSSigma, BI, SigmaBB, filters); SigmaFiltersTy::iterator I = SigmaFilters.find(LHSSigma->getValue()); if (I == SigmaFilters.end()) generateFilters(LHSSigma->getValue(), RHSSigma, BI, SigmaBB); if (!evalFilter(LHSSigma, RHSSigma /*, filters*/)){ // Assign RHSSigma to LHSSigma ResetAbstractValue(LHSSigma); // LHSSigma->join(Lookup(RHSSigma,true)); if (AbstractValue * AbsVal = Lookup(RHSSigma,false)) LHSSigma->join(AbsVal); else LHSSigma->makeTop(); } } /// Special case if the underlying domain is a non-lattice. The /// implementation of visitPHINode assumes that the underlying /// abstract domain is associative. That is, join(join(x,y)),z) = /// join(x, join(y,z)). However, non-lattice joins are not /// associative. In that case, we prefer not to join directly all the /// incoming values since different orders although sound may give /// different levels of precision. Instead, we just collect all /// incoming values and put them into a vector which is passed /// directly to the non-lattice domain which knows how to deal with /// this lack of associativity. void FixpointSSI::visitPHINode(AbstractValue *&AbsValNew, PHINode &PN){ bool must_be_top=false; std::vector<AbstractValue*> AbsIncVals; for (unsigned i=0, num_vals=PN.getNumIncomingValues(); i != num_vals;i++) { if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()) && (PN.getIncomingValue(i)->getValueID() != Value::UndefValueVal)){ AbstractValue * AbsIncVal = Lookup(PN.getIncomingValue(i),false); if (!AbsIncVal){ must_be_top = true; break; } else AbsIncVals.push_back(AbsIncVal); } } // end for if (must_be_top) AbsValNew->makeTop(); else AbsValNew->GeneralizedJoin(AbsIncVals); PRINTCALLER("visitPHI"); updateState(PN,AbsValNew); DEBUG(dbgs() << "\t[RESULT] "); DEBUG(AbsValNew->print(dbgs())); DEBUG(dbgs() << "\n"); } /// This method covers actually two different instructions. A sigma /// node is represented as a phi node but with a single incoming /// block. /// /// If a sigma node then it attempts at improving the precision of the /// value by restricting it using information from the conditional /// branch of the incoming block of the sigma node. /// /// If a phi node then it merges the values only from feasible /// predecessors. void FixpointSSI::visitPHINode(PHINode &PN) { if (Value *V = dyn_cast<Value>(&PN)){ if (AbstractValue * AbsVal = Lookup(V, false)){ if (PN.getNumIncomingValues() == 1){ // Sigma node is represented as a phi node with exactly one // incoming value. DEBUG(dbgs() << "Sigma node " << PN << "\n"); AbstractValue * NewAbsVal = AbsVal->clone(); if (TerminatorInst * TI = PN.getIncomingBlock(0)->getTerminator()){ if (BranchInst * BI = dyn_cast<BranchInst>(TI)){ //assert(BI->isConditional()); if (BI->isConditional()) visitSigmaNode(NewAbsVal, PN.getIncomingValue(0), PN.getParent(), BI); else visitSigmaNode(NewAbsVal, PN.getIncomingValue(0)); } } PRINTCALLER("visitSigmaNode"); // We do not delete NewAbsVal since it will be stored in a map // manipulated by updateState. Instead, updateState will free // the old value if it is replaced with NewAbsVal. updateState(PN,NewAbsVal); DEBUG(dbgs() << "\t[RESULT] "); DEBUG(NewAbsVal->print(dbgs())); DEBUG(dbgs() << "\n"); } else{ // PHI node AbstractValue *AbsValNew = AbsVal->clone(); //ResetAbstractValue(AbsValNew); AbsValNew->makeBot(); DEBUG(dbgs() << "PHI node " << PN << "\n"); // If the abstract domain is not a lattice then we call go // GeneralizedJoin, a special version, for joining multiple // abstract values. If the abstract domain is a lattice we // don't need such a specialized method since we can use the // binary join repeatedly without losing precision. For a // non-lattice domain is not the case (see our SAS'13 paper). if (!(AbsValNew->isLattice())) visitPHINode(AbsValNew,PN); else{ for (unsigned i=0, num_vals=PN.getNumIncomingValues(); i != num_vals;i++) { // if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) // dbgs() << PN.getIncomingBlock(i)->getName() // << " --> " << PN.getParent()->getName() << " IS UNREACHABLE\n"; // else{ // dbgs() << PN.getIncomingBlock(i)->getName() // << " --> " << PN.getParent()->getName() << " IS REACHABLE\n"; // } if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()) && (PN.getIncomingValue(i)->getValueID() != Value::UndefValueVal)){ /// Merging values: since join can only lose precision /// we stop if we already reach top. if (AbsValNew->IsTop()){ DEBUG(dbgs() << "Skipped " << *(PN.getIncomingValue(i)) << " because already top!\n"); break; } AbstractValue * AbsIncVal = Lookup(PN.getIncomingValue(i),false); DEBUG(dbgs() << "Merging " << *(PN.getIncomingValue(i)) << "\n"); if (!AbsIncVal){ AbsValNew->makeTop(); DEBUG(dbgs() << "Could not find " << *(PN.getIncomingValue(i)) << " in the lookup table. \n"); break; } else AbsValNew->join(AbsIncVal); } } // end for PRINTCALLER("visitPHI"); // We do not delete NewAbsVal since it will be stored in a map // manipulated by updateState. Instead, updateState will free // the old value if it is replaced with NewAbsVal. updateState(PN,AbsValNew); DEBUG(dbgs() << "\t[RESULT] "); DEBUG(AbsValNew->print(dbgs())); DEBUG(dbgs() << "\n"); } } } } } /// Join the abstract values of the two operands and store it in the /// lhs. If it is known whether the condition is true or false the /// join can be refined. We have a separate treatment if the operands /// are Boolean flags. void FixpointSSI::visitSelectInst(SelectInst &Ins){ DEBUG(dbgs() << "Select Instruction " << Ins << "\n"); // Special case: SelectInst involves only Boolean flags if (TrackedCondFlags.lookup(&Ins)){ // Make sure we make a copy here TBool *LHS = new TBool(*TrackedCondFlags.lookup(&Ins)); if (TBool * Cond = TrackedCondFlags.lookup(Ins.getCondition())){ if (TBool * True = getTBoolfromValue(Ins.getTrueValue())){ if (TBool * False = getTBoolfromValue(Ins.getFalseValue())){ if (Cond->isTrue()){ LHS->makeTrue(); LHS->And(LHS,True); } else{ if (Cond->isFalse()){ LHS->makeTrue(); LHS->And(LHS,False); } else LHS->Or(True,False); } goto BOOL_END; } } } // Some of the operands is not trackable but LHS is LHS->makeMaybe(); BOOL_END: // We do not delete LHS since it will be stored in a map // manipulated by updateCondFlag. Instead, updateCondFlag will // free the old value if it is replaced with LHS. updateCondFlag(Ins,LHS); DEBUG(dbgs() << "\t[RESULT] "); DEBUG(LHS->print(dbgs())); DEBUG(dbgs() << "\n"); return; } // General case: all the operands are AbstractValue objects // Important: clone here to be able to compare old value later. AbstractValue * OldLHS = Lookup(&Ins, false); if (!OldLHS) return; AbstractValue * LHS = OldLHS->clone(); AbstractValue * True = Lookup(Ins.getTrueValue(), false); AbstractValue * False = Lookup(Ins.getFalseValue(), false); // FIXME: we can have instructions like: // %tmp128 = select i1 %tmp126, i32 -1, i32 %tmp127 // where %tmp127 is untrackable. if (!True || !False){ LHS->makeTop(); goto END_GENERAL; } ResetAbstractValue(LHS); if (!isTrackedCondFlag(Ins.getCondition())){ // The condition is not trackable as a Boolean Flag so we join // both LHS->join(True); LHS->join(False); } else{ TBool * Cond = TrackedCondFlags.lookup(Ins.getCondition()); if (Cond->isTrue()) // must be true LHS->join(True); else{ if (Cond->isFalse()) // must be false LHS->join(False); else{ // maybe LHS->join(True); LHS->join(False); } } } END_GENERAL: PRINTCALLER("visitSelectInst"); // We do not delete LHS since it will be stored in a map // manipulated by updateState. Instead, updateState will free // the old value if it is replaced with LHS. updateState(Ins,LHS); DEBUG(dbgs() << "\t[RESULT] "); DEBUG(LHS->print(dbgs())); DEBUG(dbgs() << "\n"); } // visitTerminatorInst - Mark all possible executable transitions from // the terminator. We cover for now IndirectBrInst (we always add all // successors), SwitchInst, and BranchInst. This procedure is vital to // improve accuracy of the analysis. void FixpointSSI::visitTerminatorInst(TerminatorInst &TI){ assert(! (isa<SwitchInst>(&TI)) && "The program should not have switch (-lowerswitch)"); assert(! (isa<IndirectBrInst>(&TI)) && "The program should not have indirect branches"); if (BranchInst * Branch = dyn_cast<BranchInst>(&TI)){ if (Branch->isUnconditional()){ DEBUG(dbgs() << "Unconditional branch: " << *Branch << "\n") ; assert(Branch->getNumSuccessors() == 1); markEdgeExecutable(Branch->getParent(),Branch->getSuccessor(0)); return; } // End Unconditional Branch DEBUG(dbgs() << "Conditional branch: " << *Branch << "\n") ; assert(Branch->getNumSuccessors() == 2); // Special cases if constants true or false if (isTrueConstant(Branch->getCondition())){ DEBUG(dbgs() << "\tthe branch condition is MUST BE TRUE.\n") ; markEdgeExecutable(Branch->getParent(),Branch->getSuccessor(0)); return; } if (isFalseConstant(Branch->getCondition())){ DEBUG(dbgs() << "\tthe branch condition is MUST BE FALSE.\n") ; markEdgeExecutable(Branch->getParent(),Branch->getSuccessor(1)); return; } // We do not keep track of the flag so everything can happen if (!isTrackedCondFlag(Branch->getCondition())){ DEBUG(dbgs() << "\tthe branch condition is MAY-TRUE/MAY-FALSE.\n") ; markEdgeExecutable(Branch->getParent(),Branch->getSuccessor(0)); markEdgeExecutable(Branch->getParent(),Branch->getSuccessor(1)); return; } TBool * Cond = TrackedCondFlags.lookup(Branch->getCondition()); if (Cond->isBottom()){ DEBUG(dbgs() << "\tthe branch condition is BOTTOM!\n") ; DEBUG(dbgs() << "\tthe successors are UNREACHABLE!\n") ; return; } if (Cond->isMaybe()){ DEBUG(dbgs() << "\tthe branch condition is MAYBE TRUE OR FALSE.\n") ; markEdgeExecutable(Branch->getParent(),Branch->getSuccessor(0)); markEdgeExecutable(Branch->getParent(),Branch->getSuccessor(1)); return; } if (Cond->isTrue()){ DEBUG(dbgs() << "\tthe branch condition is MUST BE TRUE.\n") ; markEdgeExecutable(Branch->getParent(),Branch->getSuccessor(0)); return; } if (Cond->isFalse()){ DEBUG(dbgs() << "\tthe branch condition is MUST BE FALSE.\n") ; markEdgeExecutable(Branch->getParent(),Branch->getSuccessor(1)); return; } } // End BranchInst // UnreachableInst if (isa<UnreachableInst>(&TI)){ // FIXME: all the abstract values should be bottom! DEBUG(dbgs() << "Unreachable instruction. \n") ; return; } dbgs() << TI << "\n"; llvm_unreachable("Found an unsupported terminator instruction."); } // Reduce the number of cases. After calling getPredicate and // swap, only six cases: EQ, NEQ, SLE, ULE, ULT, and SLT // // Important: for some reason if an instruction is swap it may disable // some def-use chains. This causes to reach too early fixpoints // (e.g., test-unbounded-loop-3.c). This weird behaviour is not // documented so it's hard to see why. Our solution is to clone the // instruction which we want to swap. However, we have to be careful // since if we try to lookup in one of our tables using that cloned // instruction the search will fail. ICmpInst * normalizeCmpInst(ICmpInst &I){ ICmpInst *II = cast<ICmpInst>(I.clone()); switch (II->getPredicate()){ case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_SGT: II->swapOperands(); break; case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_SGE: II->swapOperands(); break; default: ; } return II; } void comparisonEqInst(TBool &LHS, AbstractValue *I1, AbstractValue *I2, bool meetIsBottom, unsigned OpCode){ // Pre: this method cannot be called if V1 or V2 is bottom switch (OpCode){ case ICmpInst::ICMP_EQ: if (!meetIsBottom){ // must be true or maybe if(I1->isGammaSingleton() && I1->isIdentical(I2)) LHS.makeTrue(); // must be true else LHS.makeMaybe(); } else // must be false LHS.makeFalse(); break; case ICmpInst::ICMP_NE: if (meetIsBottom){ // LHS.makeMaybe(); // must be true // 13/05/2013: if intersection is empty I1 and I2 are for sure // not equal. LHS.makeTrue() ; } else{ // must be false or maybe if(I1->isGammaSingleton() && I1->isIdentical(I2)) LHS.makeFalse(); else LHS.makeMaybe(); } break; llvm_unreachable("ERROR: undefined argument in predEquality "); } } void comparisonSleInst(TBool &LHS, AbstractValue* V1, AbstractValue *V2){ // Pre: this method cannot be called if V1 or V2 is bottom if (V1->comparisonSle(V2)){ if (V2->comparisonSlt(V1)) LHS.makeMaybe(); else LHS.makeTrue(); // must be true } else LHS.makeFalse(); // must be false } void comparisonSltInst(TBool &LHS, AbstractValue *V1, AbstractValue*V2){ // Pre: this method cannot be called if V1 or V2 is bottom if (V1->comparisonSlt(V2)){ if (V2->comparisonSle(V1)) LHS.makeMaybe(); else LHS.makeTrue(); // must be true } else LHS.makeFalse(); // must be false } void comparisonUleInst(TBool &LHS, AbstractValue* V1, AbstractValue *V2){ if (V1->comparisonUle(V2)){ if (V2->comparisonUlt(V1)) LHS.makeMaybe(); else LHS.makeTrue(); // must be true } else LHS.makeFalse(); // must be false } void comparisonUltInst(TBool &LHS, AbstractValue *V1, AbstractValue*V2){ if (V1->comparisonUlt(V2)){ if (V2->comparisonUle(V1)) LHS.makeMaybe(); else LHS.makeTrue(); // must be true } else LHS.makeFalse(); // must be false } /// Wrapper to call the meet operation and returns true iff the meet /// between the two abstract values is bottom. The wrapper is needed /// to make sure that the meet method is called by a non-constant /// value. bool IsMeetEmpty(AbstractValue *V1,AbstractValue* V2){ if (V1->isConstant() && V2->isConstant()) return (!V1->isIdentical(V2)); else{ if (!V1->isConstant()){ AbstractValue *Meet = V1->clone(); Meet->meet(V1,V2); bool result = Meet->isBot(); delete Meet; return result; } else{ AbstractValue *Meet = V2->clone(); Meet->meet(V1,V2); bool result = Meet->isBot(); delete Meet; return result; } } } /// Execute a comparison instruction and store the result: "must /// true", "must false", or "maybe" in the abstract value of the lhs /// which must be a TBool object. void FixpointSSI::visitComparisonInst(ICmpInst &I){ DEBUG(dbgs() << "Comparison instruction: " << I << "\n"); if (!isTrackedCondFlag(&I)) return; // May swap operands of I: don't do lookups using ClonedI as a base // pointer !! ICmpInst* ClonedI = normalizeCmpInst(I); // Make sure we make a copy here TBool *LHS = new TBool(*TrackedCondFlags.lookup(&I)); /////////////////////////////////////////////////////////////////////////////// // The operands of the ICmpInst could be actually anything. E.g., // // %tmp37 = icmp ult double* %table.0, getelementptr inbounds ([544 // x double]* @decwin, i32 0, i32 528) // // Here the operands are not in ValueState. Thus, we cannot raise an // assertion in that case. Instead, we just make "maybe" the lhs of // the instruction. /////////////////////////////////////////////////////////////////////////////// if (AbstractValue *Op1 = Lookup(ClonedI->getOperand(0), false)){ if (AbstractValue *Op2 = Lookup(ClonedI->getOperand(1), false)){ if (Op1->isBot() || Op2->isBot()){ // LHS->makeBottom(); // It is more conservative this: LHS->makeMaybe(); goto END; } if (Op1->IsTop() || Op2->IsTop()){ // Here is one of the operands is top we just say maybe. LHS->makeMaybe(); goto END; } // Cloned has been already normalized (removed some cases) switch (ClonedI->getPredicate()){ case ICmpInst::ICMP_EQ: comparisonEqInst(*LHS,Op1,Op2,IsMeetEmpty(Op1,Op2),ICmpInst::ICMP_EQ); break; case ICmpInst::ICMP_NE: comparisonEqInst(*LHS,Op1,Op2,IsMeetEmpty(Op1,Op2),ICmpInst::ICMP_NE); break; case ICmpInst::ICMP_ULE: comparisonUleInst(*LHS,Op1, Op2); break; case ICmpInst::ICMP_ULT: comparisonUltInst(*LHS,Op1, Op2); break; case ICmpInst::ICMP_SLE: comparisonSleInst(*LHS,Op1, Op2); break; case ICmpInst::ICMP_SLT: comparisonSltInst(*LHS,Op1, Op2); break; default: llvm_unreachable("ERROR: uncovered comparison operator"); } goto END; } } // If this point is reachable is because either V1 or v2 were not // found in ValueState. LHS->makeMaybe(); END: delete ClonedI; DEBUG(dbgs() << "\t[RESULT]"); DEBUG(LHS->print(dbgs())); DEBUG(dbgs() << "\n"); // We do not delete LHS since it will be stored in a map manipulated // by updateCondFlag. Instead, updateCondFlag will free the old // value if it is replaced with LHS. updateCondFlag(I,LHS); } /// Execute logical operations (and, or, xor) on 1-bit variables /// (i.e., Boolean flag) using three-valued logic. void FixpointSSI::visitBooleanLogicalInst(Instruction &I){ DEBUG(dbgs() << "Boolean Logical instruction: " << I << "\n"); if (isTrackedCondFlag(&I)){ // Make sure we make a copy here TBool * LHS = new TBool(*TrackedCondFlags[&I]); if (TBool *Op1 = getTBoolfromValue(I.getOperand(0))){ if (TBool *Op2 = getTBoolfromValue(I.getOperand(1))){ switch(I.getOpcode()){ case Instruction::And: LHS->And(Op1,Op2); break; case Instruction::Or: LHS->Or(Op1,Op2); break; case Instruction::Xor: LHS->Xor(Op1,Op2); break; default: llvm_unreachable("Wrong instruction in visitBooleanLogicalInst"); } // We do not delete LHS since it will be stored in a map manipulated // by updateCondFlag. Instead, updateCondFlag will free the old // value if it is replaced with LHS. updateCondFlag(I,LHS); DEBUG(dbgs() << "\t[RESULT]"); DEBUG(LHS->print(dbgs())); DEBUG(dbgs() << "\n"); return; } } // FIXME: // Here we don't consider an error yet because we have things like: // %tmp547.i = fcmp ugt float %tmp13.i83.i, 0.000000e+00 // %tmp551.i = fcmp ult float %tmp13.i83.i, 1.000000e+00 // %or.cond = and i1 %tmp547.i, %tmp551.i // where the lhs is a Boolean flag but the operands not. LHS->makeMaybe(); return; } /* if (isCondFlag(I.getOperand(0))) dbgs() << I.getOperand(0)->getName() << " is a boolean flag\n"; else dbgs() << I.getOperand(0)->getName() << " is NOT a boolean flag\n"; if (isCondFlag(I.getOperand(1))) dbgs() << I.getOperand(1)->getName() << " is a boolean flag\n"; else dbgs() << I.getOperand(1)->getName() << " is NOT a boolean flag\n"; if (isTrackedCondFlag(I.getOperand(0))) dbgs() << I.getOperand(0)->getName() << " is tracked \n"; else dbgs() << I.getOperand(0)->getName() << " is NOT tracked\n"; if (isTrackedCondFlag(I.getOperand(1))) dbgs() << I.getOperand(1)->getName() << " is tracked\n"; else dbgs() << I.getOperand(1)->getName() << " is NOT tracked\n"; */ llvm_unreachable("All operands must be Boolean flags that are being tracked"); } // Return true iff widening can be applied bool FixpointSSI::Widen(Instruction* I, unsigned NumChanges){ return ( (WideningLimit > 0) && WideningPoints.count(I) && (NumChanges >= WideningLimit)); } /// This procedure is vital for the termination of the analysis since /// it decides which points must be widen so that the analysis can /// terminate. If we miss a point then we are in trouble. We /// consider mainly for widening points phi nodes that are in /// destination blocks of backedges (arc whose tail dominates its /// head). /// /// Moreover, we also consider some load instructions done in the /// destination block of backedges. In particular, where global /// variables of interest are involved. void FixpointSSI::addTrackedWideningPoints(Function * F){ if (WideningLimit > 0){ SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> BackEdges; FindFunctionBackedges(*F, BackEdges); // DestBackEdgeBB - Set of destination blocks of backedges SmallPtrSet<const BasicBlock*,16> DestBackEdgeBB; for (SmallVector<std::pair<const BasicBlock*,const BasicBlock*>,32>::iterator I = BackEdges.begin(),E = BackEdges.end(); I != E; ++I){ // DEBUG(dbgs() << "backedge from" << I->first->getName() << " to " << // I->second->getName() << "\n"); DestBackEdgeBB.insert(I->second); } DEBUG(dbgs() << "Widening points: \n"); for (inst_iterator I = inst_begin(F), E=inst_end(F) ; I != E; ++I){ // A phi node that is in the destination block of a backedge if (PHINode *PN = dyn_cast<PHINode>(&*I)){ if (PN->getNumIncomingValues() > 1){ if (DestBackEdgeBB.count(PN->getParent())){ DEBUG(dbgs() << "\t" << *I << "\n"); NumOfWideningPts++; WideningPoints.insert(&*I); } } } // A load of a global variable of interest done in the // destination block of a backedge if (LoadInst *LoadI = dyn_cast<LoadInst>(&*I)){ if (GlobalVariable * Gv = dyn_cast<GlobalVariable>(LoadI->getPointerOperand())){ if (TrackedGlobals.count(Gv) && DestBackEdgeBB.count(I->getParent())){ DEBUG(dbgs() << "\t" << *I << "\n"); NumOfWideningPts++; WideningPoints.insert(&*I); } } } } DEBUG(dbgs() << "\n"); } } /////////////////////////////////////////////////////////////////////////// // Printing utililties /////////////////////////////////////////////////////////////////////////// // Helper to make easier the printing of results and stats. void sortByBasicBlock(Function *F, AbstractStateTy ValMap, DenseMap<BasicBlock*, std::set<AbstractValue*> * > & BlockMap){ for (AbstractStateTy::iterator I=ValMap.begin(), E=ValMap.end(); I != E; ++I){ AbstractValue * AbsVal = I->second; if (!AbsVal) continue; // I think this should not happen! BasicBlock * BB = AbsVal->getBasicBlock(); if (!BB) continue; DenseMap<BasicBlock*, std::set<AbstractValue*> * >::iterator II = BlockMap.find(BB); if (II != BlockMap.end()){ std::set<AbstractValue*> *S = II->second; S->insert(AbsVal); BlockMap[BB] = S; } else{ std::set<AbstractValue*> *S = new std::set<AbstractValue*>(); S->insert(AbsVal); BlockMap.insert(std::make_pair(BB,S)); } } // end for } /// Print analysis results for global variables. void FixpointSSI::printResultsGlobals(raw_ostream &Out){ Out <<"\n===-------------------------------------------------------------------------===\n" ; Out << " Analysis Results for global variables \n" ; Out <<"===-------------------------------------------------------------------------===\n" ; // Iterate over all global variables of interest defined in the module for (Module::global_iterator Gv = M->global_begin(), E = M->global_end(); Gv != E; ++Gv){ if (TrackedGlobals.count(Gv)){ ValueState[Gv]->print(Out); Out << "\n"; } } Out << "\n"; } /// Print results of the analysis for the particular function F. void FixpointSSI::printResultsFunction(Function *F, raw_ostream &Out){ Out <<"\n===-------------------------------------------------------------------------===\n" ; Out << " Analysis Results for " << F->getName() << "\n" ; Out << " (Only local variables are displayed) \n" ; Out <<"===-------------------------------------------------------------------------===\n" ; DenseMap<BasicBlock*, std::set<AbstractValue*> * > BlockMap; sortByBasicBlock(F, ValueState, BlockMap); // Iterate over each basic block. for (Function::iterator BB = F->begin(), EE = F->end(); BB != EE; ++BB){ DenseMap<BasicBlock*, std::set<AbstractValue*> * >::iterator It = BlockMap.find(BB); if (BBExecutable.count(BB) == 0){ Out << "Block " << BB->getName() << " is unreachable\n"; continue; } if (It == BlockMap.end()) Out << "Block " << BB->getName() << " {}\n"; else{ std::set<AbstractValue*> *Values = It->second; Out << "Block " << BB->getName() << " { "; // Print abstract values of the block for(std::set<AbstractValue*>::iterator I_I = Values->begin(), I_E = Values->end(); I_I != I_E ; ++I_I){ AbstractValue *AbsV = (*I_I); AbsV->print(Out); Out << "; "; } Out << "}\n"; } } // Boolean flags // for (DenseMap<Value*,TBool*>::iterator I=TrackedCondFlags.begin(), // E=TrackedCondFlags.end(); I!=E;++I){ // if (VST->lookup(I->first->getName())) // Out << " " << I->first->getName() << "=" << I->second->getValue() << "; "; // } } /// Print the results of the analysis for the whole module. void FixpointSSI::printResults(raw_ostream &Out){ // Iterate over all functions defined in the module. for (Module::iterator F = M->begin(), E=M->end() ; F != E; ++F) printResultsFunction(F,Out); } void printValueInfo(Value *v, Function *F){ if (Argument *Arg = dyn_cast<Argument>(v)) dbgs() << F->getName() << "." << Arg->getParent()->getName() << "." << Arg->getName() << " type(" << *Arg->getType() << ")\n"; else{ if (GlobalVariable *Gv = dyn_cast<GlobalVariable>(v)){ dbgs() << "global." << Gv->getName() << " type(" << *Gv->getType() << ")\n"; } else{ if (Instruction *Inst = dyn_cast<Instruction>(v)){ if (Inst->hasName()){ dbgs() << F->getName() << "." << Inst->getParent()->getName() << "." << Inst->getName() << " type(" << *Inst->getType() << ")\n"; } } } } } void printUsersInst(Value *I,SmallPtrSet<BasicBlock*, 16> BBExecutable, bool OnlyExecutable){ dbgs() << "USERS of" << *I << ": \n"; for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) { Instruction *U = cast<Instruction>(*UI); if (OnlyExecutable){ if (BBExecutable.count(U->getParent())) dbgs() << "\t" << *U << "\n"; } else dbgs() << "\t" << *U << "\n"; } }
35.309956
99
0.618095
ucsb-seclab
6ced20f0600803efff41094c392434fd0bb6d9b4
749
hpp
C++
fuji/inc/m4c0/fuji/main_loop_thread.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
fuji/inc/m4c0/fuji/main_loop_thread.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
fuji/inc/m4c0/fuji/main_loop_thread.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
#pragma once #include "m4c0/fuji/main_loop.hpp" #include "m4c0/log.hpp" #include "m4c0/vulkan/surface.hpp" #include <thread> namespace m4c0::fuji { /// \brief Convenience for running a main_loop in a different thread template<class MainLoopTp> class main_loop_thread { MainLoopTp m_loop; std::thread m_thread; public: template<typename... Args> void start(Args &&... args) { if (m_thread.joinable()) { interrupt(); } m_thread = std::thread { &MainLoopTp::run_global, &m_loop, std::forward<Args>(args)... }; m4c0::log::info("Vulkan thread starting"); } void interrupt() { m4c0::log::info("Vulkan thread ending"); m_loop.interrupt(); m_thread.join(); } }; }
22.69697
95
0.631509
m4c0
6ceeacdb54036d96fb8d83ffd01f48958a18a5f3
5,652
hpp
C++
private/inc/avb_streamhandler/IasLocalVideoBuffer.hpp
tnishiok/AVBStreamHandler
7621daf8c9238361e030fe35188b921ee8ea2466
[ "BSL-1.0", "BSD-3-Clause" ]
13
2018-09-26T13:32:35.000Z
2021-05-20T10:01:12.000Z
private/inc/avb_streamhandler/IasLocalVideoBuffer.hpp
keerockl/AVBStreamHandler
c0c9aa92656ae0acd0f57492d4f325eee2f7d13b
[ "BSD-3-Clause" ]
23
2018-10-03T22:45:21.000Z
2020-03-05T23:40:12.000Z
private/inc/avb_streamhandler/IasLocalVideoBuffer.hpp
keerockl/AVBStreamHandler
c0c9aa92656ae0acd0f57492d4f325eee2f7d13b
[ "BSD-3-Clause" ]
22
2018-09-14T03:55:34.000Z
2021-12-07T01:13:27.000Z
/* * Copyright (C) 2018 Intel Corporation. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ /** * @file IasLocalVideoBuffer.hpp * @brief This class contains all methods to access the ring buffers * @details Each local Video stream handles its data via a * separate ring buffer. * * @date 2014 */ #ifndef IASLOCALVIDEOBUFFER_HPP_ #define IASLOCALVIDEOBUFFER_HPP_ #include "avb_streamhandler/IasAvbTypes.hpp" #include "IasAvbPacketPool.hpp" #include <cstring> namespace IasMediaTransportAvb { class IasLocalVideoBuffer { public: typedef unsigned char VideoData; enum IasVideoBufferState { eIasVideoBufferStateInit = 0, eIasVideoBufferStateOk, eIasVideoBufferStateUnderrun, eIasVideoBufferStateOverrun, }; /** * @brief Constructor. */ IasLocalVideoBuffer(); /** * @brief Destructor, virtual by default. */ virtual ~IasLocalVideoBuffer(); struct IasVideoDesc { /*! * @brief mpegts - number of TSPs in AVB packet */ uint32_t tspsInAvbPacket; /*! * @brief source packet header indicator. */ bool hasSph; /*! * @brief Iec 61883 indicator. */ bool isIec61883Packet; /*! * @brief presentation timestamp, in NS */ uint64_t pts; /*! * @brief decoding timestamp, in NS */ uint64_t dts; /*! * @brief rtp timestamp */ uint32_t rtpTimestamp; /*! * @brief rtp sequence number */ uint16_t rtpSequenceNumber; /*! * @brief rtp marker bit and payload type M|PT */ uint8_t mptField; /*! * @brief rtp marker bit and payload type M|PT */ void * rtpPacketPtr; /*! * @brief pointer to an avbPacket */ IasAvbPacket *avbPacket; /*! * @brief the real payload */ Buffer buffer; /*! * @brief default constructor */ IasVideoDesc() : tspsInAvbPacket(0u) , hasSph(false) , isIec61883Packet(false) , pts(0u) , dts(0u) , rtpTimestamp(0u) , rtpSequenceNumber(0u) , mptField(0u) , rtpPacketPtr(NULL) , avbPacket(NULL) { } }; /** * @brief Initialize method. * * Pass component specific initialization parameter. * * @param[in] numPackets This has a minimum value of 2 as a packet is needed internally to separate the start * and end of the ring buffer. */ IasAvbProcessingResult init(uint16_t numPackets, uint16_t maxPacketSize, bool internalBuffers); /** * @brief Reset functionality for the channel buffers */ IasAvbProcessingResult reset(uint32_t optimalFillLevel); /** * @brief Writes H.264 data into the local ring buffer */ uint32_t writeH264(IasLocalVideoBuffer::IasVideoDesc * packet); /** * @brief Writes MPEG2-TS data into the local ring buffer */ uint32_t writeMpegTS(IasLocalVideoBuffer::IasVideoDesc * packet); /** * @brief Reads data from the local ring buffer */ uint32_t read(void * buffer, IasVideoDesc * descPacket); /** * @brief Clean up all allocated resources. */ void cleanup(); /** * @brief get current fill level */ inline uint32_t getFillLevel() const; /** * @brief get maximum fill level (i.e. total size) */ inline uint32_t getTotalSize() const; /** * @brief set the avbPacketPool pointer for payload pointer access */ inline void setAvbPacketPool(IasAvbPacketPool * avbPacketPool); /** * @brief get info whether internal buffers or dma were used */ inline bool getInternalBuffers() const; private: /** * @brief Constant used to define the measurement window for calculating packets/s value for debug */ static const uint64_t cObservationInterval = 1000000000u; /** * @brief Copy constructor, private unimplemented to prevent misuse. */ IasLocalVideoBuffer(IasLocalVideoBuffer const &other); /** * @brief Assignment operator, private unimplemented to prevent misuse. */ IasLocalVideoBuffer& operator=(IasLocalVideoBuffer const &other); uint32_t mReadIndex; uint32_t mWriteIndex; uint32_t mReadCnt; uint32_t mWriteCnt; uint16_t mRtpSequNrLast; uint32_t mNumPacketsTotal; //in samples (IasLocalVideoBuffer::VideoData) uint16_t mNumPackets; uint16_t mMaxPacketSize; uint16_t mMaxFillLevel; IasVideoBufferState mBufferState; IasVideoBufferState mBufferStateLast; bool mInternalBuffers; std::mutex mLock; unsigned char *mBuffer; IasAvbPacketPool *mPool; IasVideoDesc *mRing; uint32_t mLastRead; DltContext *mLog; uint32_t mMsgCount; uint32_t mMsgCountMax; uint64_t mLocalTimeLast; }; inline uint32_t IasLocalVideoBuffer::getFillLevel() const { uint32_t ret = mWriteIndex - mReadIndex; if (ret > mNumPacketsTotal) { ret += mNumPacketsTotal; } return ret; } inline void IasLocalVideoBuffer::setAvbPacketPool(IasAvbPacketPool * avbPacketPool) { (void) mLock.lock(); mPool = avbPacketPool; (void) mLock.unlock(); } inline uint32_t IasLocalVideoBuffer::getTotalSize() const { return mNumPacketsTotal; } inline bool IasLocalVideoBuffer::getInternalBuffers() const { return mBuffer == nullptr; } } // namespace IasMediaTransportAvb #endif /* IASLOCALVIDEOBUFFER_HPP_ */
21.992218
114
0.633404
tnishiok
6cf02ece223febeaa7f366cf4feb5c65d3df9889
2,963
cpp
C++
flexcore/extended/base_node.cpp
vacing/flexcore
08c08e98556f92d1993e2738cbcb975b3764fa2d
[ "Apache-2.0" ]
47
2016-09-23T10:27:17.000Z
2021-12-14T07:31:40.000Z
flexcore/extended/base_node.cpp
vacing/flexcore
08c08e98556f92d1993e2738cbcb975b3764fa2d
[ "Apache-2.0" ]
10
2016-12-04T16:40:29.000Z
2020-04-28T08:46:50.000Z
flexcore/extended/base_node.cpp
vacing/flexcore
08c08e98556f92d1993e2738cbcb975b3764fa2d
[ "Apache-2.0" ]
20
2016-09-23T17:14:41.000Z
2021-10-09T18:24:47.000Z
#include <boost/algorithm/string/join.hpp> #include <boost/format.hpp> #include <flexcore/extended/base_node.hpp> #include <flexcore/extended/visualization/visualization.hpp> #include <stack> namespace fc { static forest_t::iterator find_self(forest_t& forest, const tree_node& node) { auto node_id = node.graph_info().get_id(); auto self = std::find_if(forest.begin(), forest.end(), [=](auto& other_uniq_ptr) { return node_id == other_uniq_ptr->graph_info().get_id(); }); assert(self != forest.end()); return adobe::trailing_of(self); } std::string full_name(forest_t& forest, const tree_node& node) { auto position = find_self(forest, node); // push names of parent / grandparent ... to stack to later reverse order. std::stack<std::string> name_stack; for (auto parent = adobe::find_parent(position); parent != forest.end(); parent = adobe::find_parent(parent)) { name_stack.emplace((*parent)->name()); } std::string full_name; while (!name_stack.empty()) { full_name += (name_stack.top() + name_seperator); name_stack.pop(); } full_name += (*position)->name(); return full_name; } tree_base_node::tree_base_node(const node_args& args) : fg_(args.fg), region_(args.r), graph_info_(args.graph_info) { assert(region_); } std::string tree_base_node::name() const { return graph_info_.name(); } graph::graph_node_properties tree_base_node::graph_info() const { return graph_info_; } graph::connection_graph& tree_base_node::get_graph() { return fg_.graph; } forest_t::iterator owning_base_node::self() const { return self_; } forest_t::iterator owning_base_node::add_child(std::unique_ptr<tree_node> child) { assert(child); auto& forest = fg_.forest; auto child_it = adobe::trailing_of(forest.insert(self(), std::move(child))); assert(adobe::find_parent(child_it) == self()); assert(adobe::find_parent(child_it) != forest.end()); return child_it; } node_args owning_base_node::new_node(node_args args) { const auto proxy_iter = add_child(std::make_unique<tree_base_node>(args)); args.self = proxy_iter; return args; } forest_owner::forest_owner( graph::connection_graph& graph, std::string n, std::shared_ptr<parallel_region> r) : fg_(std::make_unique<forest_graph>(graph)) , tree_root(nullptr) , viz_(std::make_unique<visualization>(fg_->graph, fg_->forest)) { assert(r); assert(fg_); auto& forest = fg_->forest; auto args = node_args{*fg_, std::move(r), std::move(n)}; //first place a proxy node in the forest to create tree_node const auto iter = adobe::trailing_of( forest.insert(forest.begin(), std::make_unique<tree_base_node>(args))); args.self = iter; // replace proxy with actual node *iter = std::make_unique<owning_base_node>(args); tree_root = dynamic_cast<owning_base_node*>(iter->get()); assert(tree_root); assert(fg_); assert(viz_); } forest_owner::~forest_owner() { } void forest_owner::visualize(std::ostream& out) const { assert(viz_); viz_->visualize(out); } }
25.324786
91
0.724603
vacing
6cf0ccc637228ad480b380bce5cd15bc2eef2864
1,944
cpp
C++
CodeForces-Contest/1404/E.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-01-23T07:18:07.000Z
2022-01-23T07:18:07.000Z
CodeForces-Contest/1404/E.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
null
null
null
CodeForces-Contest/1404/E.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-02-05T11:53:04.000Z
2022-02-05T11:53:04.000Z
#include<bits/stdc++.h> using namespace std; mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); struct Kuhn { int n; vector<vector<int>> g; vector<int> l, r; vector<bool> vis; Kuhn(int _n, int _m) { n = _n; g.resize(n + 1); vis.resize(n + 1, false); l.resize(n + 1, -1); r.resize(_m + 1, -1); } void add_edge(int a, int b) { g[a].push_back(b); } bool yo(int u) { if (vis[u]) return false; vis[u] = true; for (auto v : g[u]) { if (r[v] == -1 || yo(r[v])) { l[u] = v; r[v] = u; return true; } } return false; } int maximum_matching() { for (int i = 1; i <= n; i++) shuffle(g[i].begin(), g[i].end(), rnd); vector<int> p(n); iota(p.begin(), p.end(), 1); shuffle(p.begin(), p.end(), rnd); bool ok = true; while (ok) { ok = false; vis.assign(n + 1, false); for (auto &i: p) if(l[i] == -1) ok |= yo(i); } int ans = 0; for (int i = 1; i <= n; i++) ans += l[i] != -1; return ans; } }; string s[300]; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; s[0] = string(m + 2, '.'); for (int i = 1; i <= n; i++) { cin >> s[i]; s[i] = "." + s[i] + "."; } s[n + 1] = string(m + 2, '.'); Kuhn F(n * m, n * m); int black = 0, vertex = 0; #define id(i, j) (i - 1) * m + j for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i][j] == '#') { black++; if (s[i][j - 1] == '#') { vertex++; if (s[i - 1][j - 1] == '#') { F.add_edge(id(i - 1, j - 1), id(i, j - 1)); } if (s[i - 1][j] == '#') { F.add_edge(id(i - 1, j), id(i, j - 1)); } } if (s[i + 1][j] == '#') { vertex++; if (s[i][j - 1] == '#') { F.add_edge(id(i, j), id(i, j - 1)); } if (s[i][j + 1] == '#') { F.add_edge(id(i, j), id(i, j)); } } } } } int MIS = vertex - F.maximum_matching(); cout << black - MIS << '\n'; return 0; }
22.604651
70
0.437757
Tech-Intellegent
6cf20e6a0c6bfa2a1cc03258925e629a65d2741f
343
cpp
C++
lib/libc/tests/string/strstr.cpp
otaviopace/ananas
849925915b0888543712a8ca625318cd7bca8dd9
[ "Zlib" ]
52
2015-11-27T13:56:00.000Z
2021-12-01T16:33:58.000Z
lib/libc/tests/string/strstr.cpp
otaviopace/ananas
849925915b0888543712a8ca625318cd7bca8dd9
[ "Zlib" ]
4
2017-06-26T17:59:51.000Z
2021-09-26T17:30:32.000Z
lib/libc/tests/string/strstr.cpp
otaviopace/ananas
849925915b0888543712a8ca625318cd7bca8dd9
[ "Zlib" ]
8
2016-08-26T09:42:27.000Z
2021-12-04T00:21:05.000Z
#include <gtest/gtest.h> #include <string.h> TEST(string, strstr) { char s[] = "abcabcabcdabcde"; EXPECT_EQ(NULL, strstr(s, "x")); EXPECT_EQ(NULL, strstr(s, "xyz")); EXPECT_EQ(&s[0], strstr(s, "a")); EXPECT_EQ(&s[0], strstr(s, "abc")); EXPECT_EQ(&s[6], strstr(s, "abcd")); EXPECT_EQ(&s[10], strstr(s, "abcde")); }
24.5
42
0.577259
otaviopace
6cfc5b92610a663f5c95a611c96c5a7fdf5253b6
2,385
cpp
C++
modules/skottie/src/effects/DirectionalBlur.cpp
fourgrad/skia
b9b550e9bb1b73001088ba89483e2f9bbe46c3db
[ "BSD-3-Clause" ]
6,304
2015-01-05T23:45:12.000Z
2022-03-31T09:48:13.000Z
modules/skottie/src/effects/DirectionalBlur.cpp
Wal1e/skia
eda97288bdc8e87afea817b25d561724c2b6a2f8
[ "BSD-3-Clause" ]
67
2016-04-18T13:30:02.000Z
2022-03-31T23:06:55.000Z
modules/skottie/src/effects/DirectionalBlur.cpp
Wal1e/skia
eda97288bdc8e87afea817b25d561724c2b6a2f8
[ "BSD-3-Clause" ]
1,231
2015-01-05T03:17:39.000Z
2022-03-31T22:54:58.000Z
/* * Copyright 2021 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "modules/skottie/src/effects/Effects.h" #include "modules/skottie/src/Adapter.h" #include "modules/skottie/src/SkottieValue.h" #include "modules/sksg/include/SkSGPaint.h" #include "modules/sksg/include/SkSGRenderEffect.h" #include "src/utils/SkJSON.h" namespace skottie::internal { namespace { class DirectionalBlurAdapter final : public DiscardableAdapterBase<DirectionalBlurAdapter, sksg::ExternalImageFilter> { public: DirectionalBlurAdapter(const skjson::ArrayValue& jprops, const AnimationBuilder& abuilder) : INHERITED(sksg::ExternalImageFilter::Make()) { enum : size_t { kDirection_Index = 0, kBlurLength_Index = 1, }; EffectBinder(jprops, abuilder, this) .bind( kDirection_Index, fDirection) .bind( kBlurLength_Index, fBlurLength); } private: void onSync() override { const auto rot = fDirection - 90; auto filter = SkImageFilters::MatrixTransform(SkMatrix::RotateDeg(rot), SkSamplingOptions(SkFilterMode::kLinear), SkImageFilters::Blur(fBlurLength * kBlurSizeToSigma, 0, SkImageFilters::MatrixTransform(SkMatrix::RotateDeg(-rot), SkSamplingOptions(SkFilterMode::kLinear), nullptr))); this->node()->setImageFilter(std::move(filter)); } ScalarValue fDirection = 0; ScalarValue fBlurLength = 0; using INHERITED = DiscardableAdapterBase<DirectionalBlurAdapter, sksg::ExternalImageFilter>; }; } // namespace sk_sp<sksg::RenderNode> EffectBuilder::attachDirectionalBlurEffect(const skjson::ArrayValue& jprops, sk_sp<sksg::RenderNode> layer) const { auto imageFilterNode = fBuilder->attachDiscardableAdapter<DirectionalBlurAdapter>(jprops, *fBuilder); return sksg::ImageFilterEffect::Make(std::move(layer), std::move(imageFilterNode)); } } // namespace skottie::internal
36.692308
100
0.605451
fourgrad
6cfd7c07617b5395d93ef91c3bdd05c50a445289
8,712
cpp
C++
src/phreeqcpp/smalldense.cpp
AbelHeinsbroek/VIPhreeqc
30d6e10ed9c7f375a5d8f9cdeccfc1c2353d3604
[ "Apache-2.0" ]
5
2017-08-07T19:35:30.000Z
2021-01-27T04:30:49.000Z
src/phreeqcpp/smalldense.cpp
AbelHeinsbroek/VIPhreeqc
30d6e10ed9c7f375a5d8f9cdeccfc1c2353d3604
[ "Apache-2.0" ]
2
2020-04-28T15:59:17.000Z
2021-06-24T21:10:32.000Z
src/phreeqcpp/smalldense.cpp
AbelHeinsbroek/VIPhreeqc
30d6e10ed9c7f375a5d8f9cdeccfc1c2353d3604
[ "Apache-2.0" ]
3
2018-11-26T12:08:07.000Z
2020-09-03T20:00:49.000Z
/************************************************************************** * * * File : smalldense.c * * Programmers : Scott D. Cohen and Alan C. Hindmarsh @ LLNL * * Version of : 26 June 2002 * *------------------------------------------------------------------------* * Copyright (c) 2002, The Regents of the University of California * * Produced at the Lawrence Livermore National Laboratory * * All rights reserved * * For details, see LICENSE below * *------------------------------------------------------------------------* * This is the implementation file for a generic DENSE linear * * solver package, intended for small dense matrices. * * * *------------------------------------------------------------------------* * LICENSE * *------------------------------------------------------------------------* * Copyright (c) 2002, The Regents of the University of California. * * Produced at the Lawrence Livermore National Laboratory. * * Written by S.D. Cohen, A.C. Hindmarsh, R. Serban, * * D. Shumaker, and A.G. Taylor. * * UCRL-CODE-155951 (CVODE) * * UCRL-CODE-155950 (CVODES) * * UCRL-CODE-155952 (IDA) * * UCRL-CODE-237203 (IDAS) * * UCRL-CODE-155953 (KINSOL) * * All rights reserved. * * * * This file is part of SUNDIALS. * * * * 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 disclaimer below. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the disclaimer (as noted below) * * in the documentation and/or other materials provided with the * * distribution. * * * * 3. Neither the name of the UC/LLNL nor the names of its contributors * * may be used to endorse or promote products derived from this software * * without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * * REGENTS OF THE UNIVERSITY OF CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY * * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "smalldense.h" #include "sundialstypes.h" #include "sundialsmath.h" /* WARNING don`t include any headers below here */ #define ZERO RCONST(0.0) #define ONE RCONST(1.0) /* Implementation */ realtype ** denalloc(integertype n) { integertype j; realtype **a; if (n <= 0) return (NULL); a = (realtype **) malloc(n * sizeof(realtype *)); if (a == NULL) return (NULL); a[0] = (realtype *) malloc(n * n * sizeof(realtype)); if (a[0] == NULL) { free(a); return (NULL); } for (j = 1; j < n; j++) a[j] = a[0] + j * n; return (a); } integertype * denallocpiv(integertype n) { if (n <= 0) return (NULL); return ((integertype *) malloc(n * sizeof(integertype))); } integertype gefa(realtype ** a, integertype n, integertype * p) { integertype i, j, k, l; realtype *col_j, *col_k, *diag_k; realtype temp, mult, a_kj; booleantype swap; /* k = elimination step number */ for (k = 0; k < n - 1; k++, p++) { col_k = a[k]; diag_k = col_k + k; /* find l = pivot row number */ l = k; for (i = k + 1; i < n; i++) if (ABS(col_k[i]) > ABS(col_k[l])) l = i; *p = l; /* check for zero pivot element */ if (col_k[l] == ZERO) return (k + 1); /* swap a(l,k) and a(k,k) if necessary */ /*if ( (swap = (l != k) )) { */ swap = (l != k); if (swap) { temp = col_k[l]; col_k[l] = *diag_k; *diag_k = temp; } /* Scale the elements below the diagonal in */ /* column k by -1.0 / a(k,k). After the above swap, */ /* a(k,k) holds the pivot element. This scaling */ /* stores the pivot row multipliers -a(i,k)/a(k,k) */ /* in a(i,k), i=k+1, ..., n-1. */ mult = -ONE / (*diag_k); for (i = k + 1; i < n; i++) col_k[i] *= mult; /* row_i = row_i - [a(i,k)/a(k,k)] row_k, i=k+1, ..., n-1 */ /* row k is the pivot row after swapping with row l. */ /* The computation is done one column at a time, */ /* column j=k+1, ..., n-1. */ for (j = k + 1; j < n; j++) { col_j = a[j]; a_kj = col_j[l]; /* Swap the elements a(k,j) and a(k,l) if l!=k. */ if (swap) { col_j[l] = col_j[k]; col_j[k] = a_kj; } /* a(i,j) = a(i,j) - [a(i,k)/a(k,k)]*a(k,j) */ /* a_kj = a(k,j), col_k[i] = - a(i,k)/a(k,k) */ if (a_kj != ZERO) { for (i = k + 1; i < n; i++) col_j[i] += a_kj * col_k[i]; } } } /* set the last pivot row to be n-1 and check for a zero pivot */ *p = n - 1; if (a[n - 1][n - 1] == ZERO) return (n); /* return 0 to indicate success */ return (0); } void gesl(realtype ** a, integertype n, integertype * p, realtype * b) { integertype k, l, i; realtype mult, *col_k; /* Solve Ly = Pb, store solution y in b */ for (k = 0; k < n - 1; k++) { l = p[k]; mult = b[l]; if (l != k) { b[l] = b[k]; b[k] = mult; } col_k = a[k]; for (i = k + 1; i < n; i++) b[i] += mult * col_k[i]; } /* Solve Ux = y, store solution x in b */ for (k = n - 1; k >= 0; k--) { col_k = a[k]; b[k] /= col_k[k]; mult = -b[k]; for (i = 0; i < k; i++) b[i] += mult * col_k[i]; } } void denzero(realtype ** a, integertype n) { integertype i, j; realtype *col_j; for (j = 0; j < n; j++) { col_j = a[j]; for (i = 0; i < n; i++) col_j[i] = ZERO; } } void dencopy(realtype ** a, realtype ** b, integertype n) { integertype i, j; realtype *a_col_j, *b_col_j; for (j = 0; j < n; j++) { a_col_j = a[j]; b_col_j = b[j]; for (i = 0; i < n; i++) b_col_j[i] = a_col_j[i]; } } void denscale(realtype c, realtype ** a, integertype n) { integertype i, j; realtype *col_j; for (j = 0; j < n; j++) { col_j = a[j]; for (i = 0; i < n; i++) col_j[i] *= c; } } void denaddI(realtype ** a, integertype n) { integertype i; for (i = 0; i < n; i++) a[i][i] += ONE; } void denfreepiv(integertype * p) { free(p); } void denfree(realtype ** a) { free(a[0]); free(a); } void denprint(realtype ** a, integertype n) { #if !defined(R_SO) integertype i, j; printf("\n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%10g", (double) a[j][i]); } printf("\n"); } printf("\n"); #endif }
27.56962
76
0.451102
AbelHeinsbroek
6cff754810119c9cfaa074251913a35b52ca0014
2,187
cpp
C++
src/helpers/getLocation.cpp
HerrEurobeat/nodemcu-clock
1afda078d522ad676aaf5a0717ae9a30a1b24438
[ "MIT" ]
null
null
null
src/helpers/getLocation.cpp
HerrEurobeat/nodemcu-clock
1afda078d522ad676aaf5a0717ae9a30a1b24438
[ "MIT" ]
null
null
null
src/helpers/getLocation.cpp
HerrEurobeat/nodemcu-clock
1afda078d522ad676aaf5a0717ae9a30a1b24438
[ "MIT" ]
null
null
null
/* * File: getLocation.cpp * Project: nodemcu-clock * Created Date: 05.09.2021 14:16:00 * Author: 3urobeat * * Last Modified: 30.12.2021 22:24:01 * Modified By: 3urobeat * * Copyright (c) 2021 3urobeat <https://github.com/HerrEurobeat> * * Licensed under the MIT license: https://opensource.org/licenses/MIT * Permission is granted to use, copy, modify, and redistribute the work * Full license information available in the project LICENSE file. */ #include <string.h> #include "helpers.h" void getLocation(LiquidCrystal_PCF8574 lcd, const char *openweathermaptoken, char *lat, char *lon, char *city, char *country, int *timeoffset) { DynamicJsonDocument locationResult(256); //If the user didn't provide a lat & lon value then get values from geocoding api if (strlen(lat) == 0 && strlen(lon) == 0) { StaticJsonDocument<0> filter; filter.set(true); httpGetJson("http://ip-api.com/json?fields=lat,lon,offset,city,countryCode", &locationResult, filter); char temp[8]; dtostrf(locationResult["lat"], 6, 4, temp); //convert double to string strcpy(lat, temp); dtostrf(locationResult["lon"], 6, 4, temp); strcpy(lon, temp); strcpy(city, locationResult["city"]); strcpy(country, locationResult["countryCode"]); *timeoffset = locationResult["offset"]; } else { //...otherwise ping openweathermap once with the coords to get the city name and timeoffset StaticJsonDocument<128> filter; filter["name"] = true; filter["sys"]["country"] = true; filter["timezone"] = true; char fullstr[200] = "http://api.openweathermap.org/data/2.5/weather?lat="; char *p = fullstr; p = mystrcat(p, lat); p = mystrcat(p, "&lon="); p = mystrcat(p, lon); p = mystrcat(p, "&appid="); p = mystrcat(p, openweathermaptoken); *(p) = '\0'; //add null char to the end httpGetJson(fullstr, &locationResult, filter); strcpy(city, locationResult["name"]); strcpy(country, locationResult["sys"]["country"]); *timeoffset = locationResult["timezone"]; } }
31.695652
142
0.633745
HerrEurobeat
6cff97a54bf00789f0a3adb0720012d0d3fee4b6
794
hpp
C++
include/gba/display/background_control.hpp
felixjones/gba-plusplus
79dce6c3095b52de72f96a17871b4d6c8b9aaf2f
[ "Zlib" ]
33
2020-11-02T22:03:27.000Z
2022-03-25T04:40:29.000Z
include/gba/display/background_control.hpp
felixjones/gbaplusplus
79dce6c3095b52de72f96a17871b4d6c8b9aaf2f
[ "Zlib" ]
21
2019-09-05T15:10:52.000Z
2020-06-21T15:08:54.000Z
include/gba/display/background_control.hpp
felixjones/gba-plusplus
79dce6c3095b52de72f96a17871b4d6c8b9aaf2f
[ "Zlib" ]
3
2020-11-02T21:44:46.000Z
2022-02-23T17:37:00.000Z
#ifndef GBAXX_DISPLAY_BACKGROUND_CONTROL_HPP #define GBAXX_DISPLAY_BACKGROUND_CONTROL_HPP #include <gba/types/color.hpp> #include <gba/types/int_type.hpp> #include <gba/types/screen_size.hpp> namespace gba { enum class affine_background_wrap : bool { transparent = false, wrap = true, clamp = false, repeat = true }; struct background_control { uint16 priority : 2, character_base_block : 2, : 2; bool mosaic : 1; gba::color_depth color_depth : 1; uint16 screen_base_block : 5; gba::affine_background_wrap affine_background_wrap : 1; gba::screen_size screen_size : 2; }; static_assert( sizeof( background_control ) == 2, "background_control must be tightly packed" ); } // gba #endif // define GBAXX_DISPLAY_BACKGROUND_CONTROL_HPP
24.060606
96
0.722922
felixjones
9f02574ed31b8ce06e711ad832160f351f0901ea
1,294
cpp
C++
lang/C++/man-or-boy-test-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
5
2021-01-29T20:08:05.000Z
2022-03-22T06:16:05.000Z
lang/C++/man-or-boy-test-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
null
null
null
lang/C++/man-or-boy-test-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2018-11-09T22:08:40.000Z
2018-11-09T22:08:40.000Z
#include <iostream> #include <tr1/memory> using std::tr1::shared_ptr; using std::tr1::enable_shared_from_this; struct Arg { virtual int run() = 0; virtual ~Arg() { }; }; int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>); class B : public Arg, public enable_shared_from_this<B> { private: int k; const shared_ptr<Arg> x1, x2, x3, x4; public: B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3, shared_ptr<Arg> _x4) : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { } int run() { return A(--k, shared_from_this(), x1, x2, x3, x4); } }; class Const : public Arg { private: const int x; public: Const(int _x) : x(_x) { } int run () { return x; } }; int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3, shared_ptr<Arg> x4, shared_ptr<Arg> x5) { if (k <= 0) return x4->run() + x5->run(); else { shared_ptr<Arg> b(new B(k, x1, x2, x3, x4)); return b->run(); } } int main() { std::cout << A(10, shared_ptr<Arg>(new Const(1)), shared_ptr<Arg>(new Const(-1)), shared_ptr<Arg>(new Const(-1)), shared_ptr<Arg>(new Const(1)), shared_ptr<Arg>(new Const(0))) << std::endl; return 0; }
23.962963
74
0.588872
ethansaxenian
9f0502de3c1f7649968da6bd920fce2ccec5cad6
7,608
cpp
C++
query_execution/PolicyEnforcer.cpp
craig-chasseur/incubator-quickstep
00ca1e4b3a9c9838dcb9509058b8a40b0f573617
[ "Apache-2.0" ]
null
null
null
query_execution/PolicyEnforcer.cpp
craig-chasseur/incubator-quickstep
00ca1e4b3a9c9838dcb9509058b8a40b0f573617
[ "Apache-2.0" ]
null
null
null
query_execution/PolicyEnforcer.cpp
craig-chasseur/incubator-quickstep
00ca1e4b3a9c9838dcb9509058b8a40b0f573617
[ "Apache-2.0" ]
1
2021-12-04T18:48:44.000Z
2021-12-04T18:48:44.000Z
/** * Copyright 2016, Quickstep Research Group, Computer Sciences Department, * University of Wisconsin—Madison. * * 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 "query_execution/PolicyEnforcer.hpp" #include <cstddef> #include <memory> #include <queue> #include <utility> #include <unordered_map> #include <vector> #include "catalog/CatalogTypedefs.hpp" #include "query_execution/QueryExecutionMessages.pb.h" #include "query_execution/QueryManager.hpp" #include "query_execution/WorkerDirectory.hpp" #include "query_optimizer/QueryHandle.hpp" #include "relational_operators/WorkOrder.hpp" #include "gflags/gflags.h" #include "glog/logging.h" namespace quickstep { DEFINE_uint64(max_msgs_per_dispatch_round, 20, "Maximum number of messages that" " can be allocated in a single round of dispatch of messages to" " the workers."); bool PolicyEnforcer::admitQuery(QueryHandle *query_handle) { if (admitted_queries_.size() < kMaxConcurrentQueries) { // Ok to admit the query. const std::size_t query_id = query_handle->query_id(); if (admitted_queries_.find(query_id) == admitted_queries_.end()) { // Query with the same ID not present, ok to admit. admitted_queries_[query_id].reset( new QueryManager(foreman_client_id_, num_numa_nodes_, query_handle, catalog_database_, storage_manager_, bus_)); return true; } else { LOG(ERROR) << "Query with the same ID " << query_id << " exists"; return false; } } else { // This query will have to wait. waiting_queries_.push(query_handle); return false; } } void PolicyEnforcer::processMessage(const TaggedMessage &tagged_message) { // TODO(harshad) : Provide processXMessage() public functions in // QueryManager, so that we need to extract message from the // TaggedMessage only once. std::size_t query_id; switch (tagged_message.message_type()) { case kWorkOrderCompleteMessage: { serialization::NormalWorkOrderCompletionMessage proto; // Note: This proto message contains the time it took to execute the // WorkOrder. It can be accessed in this scope. CHECK(proto.ParseFromArray(tagged_message.message(), tagged_message.message_bytes())); query_id = proto.query_id(); worker_directory_->decrementNumQueuedWorkOrders( proto.worker_thread_index()); break; } case kRebuildWorkOrderCompleteMessage: { serialization::RebuildWorkOrderCompletionMessage proto; // Note: This proto message contains the time it took to execute the // rebuild WorkOrder. It can be accessed in this scope. CHECK(proto.ParseFromArray(tagged_message.message(), tagged_message.message_bytes())); query_id = proto.query_id(); worker_directory_->decrementNumQueuedWorkOrders( proto.worker_thread_index()); break; } case kCatalogRelationNewBlockMessage: { serialization::CatalogRelationNewBlockMessage proto; CHECK(proto.ParseFromArray(tagged_message.message(), tagged_message.message_bytes())); query_id = proto.query_id(); break; } case kDataPipelineMessage: { serialization::DataPipelineMessage proto; CHECK(proto.ParseFromArray(tagged_message.message(), tagged_message.message_bytes())); query_id = proto.query_id(); break; } case kWorkOrdersAvailableMessage: { serialization::WorkOrdersAvailableMessage proto; CHECK(proto.ParseFromArray(tagged_message.message(), tagged_message.message_bytes())); query_id = proto.query_id(); break; } case kWorkOrderFeedbackMessage: { WorkOrder::FeedbackMessage msg( const_cast<void *>(tagged_message.message()), tagged_message.message_bytes()); query_id = msg.header().query_id; break; } default: LOG(FATAL) << "Unknown message type found in PolicyEnforcer"; } DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end()); const QueryManager::QueryStatusCode return_code = admitted_queries_[query_id]->processMessage(tagged_message); if (return_code == QueryManager::QueryStatusCode::kQueryExecuted) { removeQuery(query_id); if (!waiting_queries_.empty()) { // Admit the earliest waiting query. QueryHandle *new_query = waiting_queries_.front(); waiting_queries_.pop(); admitQuery(new_query); } } } void PolicyEnforcer::getWorkerMessages( std::vector<std::unique_ptr<WorkerMessage>> *worker_messages) { // Iterate over admitted queries until either there are no more // messages available, or the maximum number of messages have // been collected. DCHECK(worker_messages->empty()); // TODO(harshad) - Make this function generic enough so that it // works well when multiple queries are getting executed. std::size_t per_query_share = 0; if (!admitted_queries_.empty()) { per_query_share = FLAGS_max_msgs_per_dispatch_round / admitted_queries_.size(); } else { LOG(WARNING) << "Requesting WorkerMessages when no query is running"; return; } DCHECK_GT(per_query_share, 0u); std::vector<std::size_t> finished_queries_ids; for (const auto &admitted_query_info : admitted_queries_) { QueryManager *curr_query_manager = admitted_query_info.second.get(); DCHECK(curr_query_manager != nullptr); std::size_t messages_collected_curr_query = 0; while (messages_collected_curr_query < per_query_share) { WorkerMessage *next_worker_message = curr_query_manager->getNextWorkerMessage(0, kAnyNUMANodeID); if (next_worker_message != nullptr) { ++messages_collected_curr_query; worker_messages->push_back(std::unique_ptr<WorkerMessage>(next_worker_message)); } else { // No more work ordes from the current query at this time. // Check if the query's execution is over. if (curr_query_manager->getQueryExecutionState().hasQueryExecutionFinished()) { // If the query has been executed, remove it. finished_queries_ids.push_back(admitted_query_info.first); } break; } } } for (const std::size_t finished_qid : finished_queries_ids) { removeQuery(finished_qid); } } void PolicyEnforcer::removeQuery(const std::size_t query_id) { DCHECK(admitted_queries_.find(query_id) != admitted_queries_.end()); if (!admitted_queries_[query_id]->getQueryExecutionState().hasQueryExecutionFinished()) { LOG(WARNING) << "Removing query with ID " << query_id << " that hasn't finished its execution"; } admitted_queries_.erase(query_id); } bool PolicyEnforcer::admitQueries( const std::vector<QueryHandle*> &query_handles) { for (QueryHandle *curr_query : query_handles) { if (!admitQuery(curr_query)) { return false; } } return true; } } // namespace quickstep
37.850746
91
0.694664
craig-chasseur
9f056c274055ac5533d8fff55f5979150c2b13b3
964
cpp
C++
2017-09-17/D-2.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
3
2018-04-02T06:00:51.000Z
2018-05-29T04:46:29.000Z
2017-09-17/D-2.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
2
2018-03-31T17:54:30.000Z
2018-05-02T11:31:06.000Z
2017-09-17/D-2.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
2
2018-10-07T00:08:06.000Z
2021-06-28T11:02:59.000Z
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> using namespace std; int T, K; struct Fraction { long long x; long long y; Fraction(long long __x = 0, long long __y = 1) { x = __x; y = __y; } }; int main() { int t; long long d; Fraction l, r, mid, ans; scanf("%d", &T); for(t = 0;t < T;t += 1) { scanf("%d", &K); l = Fraction(max(0, (int)pow((long long)K * K, 1/3.0) - 1), 1); r = Fraction(1, 0); while(1) { mid = Fraction(l.x + r.x, l.y + r.y); if(mid.y > 100000) break; if((__int128)mid.x * mid.x * mid.x < (__int128)mid.y * mid.y * mid.y * K * K) l = mid; else r = mid; } mid = Fraction(l.x * r.y + r.x * l.y, 2 * l.y * r.y); d = __gcd(mid.x, mid.y); mid = Fraction(mid.x / d, mid.y / d); if((__int128)mid.x * mid.x * mid.x < (__int128)mid.y * mid.y * mid.y * K * K) ans = r; else ans = l; printf("%lld/%lld\n", ans.x, ans.y); } exit(0); }
17.851852
80
0.524896
tangjz
9f083dee33d20b80dd0731e3157afa9da2fe7a69
4,011
cxx
C++
repro/SiloStore.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
1
2019-04-15T14:10:58.000Z
2019-04-15T14:10:58.000Z
repro/SiloStore.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
null
null
null
repro/SiloStore.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
2
2019-10-31T09:11:09.000Z
2021-09-17T01:00:49.000Z
#include "rutil/Logger.hxx" #include "rutil/ParseBuffer.hxx" #include "rutil/Lock.hxx" #include "resip/stack/SipMessage.hxx" #include "repro/SiloStore.hxx" #include "rutil/WinLeakCheck.hxx" using namespace resip; using namespace repro; using namespace std; #define RESIPROCATE_SUBSYSTEM Subsystem::REPRO SiloStore::SiloStore(AbstractDb& db): mDb(db) { } SiloStore::~SiloStore() { } bool SiloStore::addMessage(const resip::Data& destUri, const resip::Data& sourceUri, time_t originalSendTime, const resip::Data& tid, const resip::Data& mimeType, const resip::Data& messageBody) { AbstractDb::SiloRecord rec; rec.mDestUri = destUri; rec.mSourceUri = sourceUri; rec.mOriginalSentTime = originalSendTime; rec.mTid = tid; rec.mMimeType = mimeType; rec.mMessageBody = messageBody; Key key = buildKey(originalSendTime, tid); return mDb.addToSilo(key, rec); } bool SiloStore::getSiloRecords(const Data& uri, AbstractDb::SiloRecordList& recordList) { // Note: This fn uses the secondary cursor, and cleanupExpiredSiloRecords uses the // primary cursor, so there should be no need to provide locking at this level (at // least that's the theory - assuming the db performs it's own locking properly) return mDb.getSiloRecords(uri, recordList); } void SiloStore::deleteSiloRecord(time_t originalSendTime, const resip::Data& tid) { Key key = buildKey(originalSendTime, tid); mDb.eraseSiloRecord(key); } void SiloStore::cleanupExpiredSiloRecords(UInt64 now, unsigned long expirationTime) { mDb.cleanupExpiredSiloRecords(now, expirationTime); } SiloStore::Key SiloStore::buildKey(time_t originalSendTime, const resip::Data& tid) const { Key key((UInt64)originalSendTime); key += ":" + tid; return key; } /* ==================================================================== * The Vovida Software License, Version 1.0 * * Copyright (c) 2000 Vovida Networks, 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. * * 3. The names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact vocal@vovida.org. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY 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. * * ==================================================================== */
33.425
86
0.697332
dulton
9f0bbb1f514b772b02dc52b0f80f48a23c247cc1
2,251
hpp
C++
stan/math/prim/prob/discrete_range_rng.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/prob/discrete_range_rng.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/prob/discrete_range_rng.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_PROB_DISCRETE_RANGE_RNG_HPP #define STAN_MATH_PRIM_PROB_DISCRETE_RANGE_RNG_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/max_size.hpp> #include <stan/math/prim/fun/scalar_seq_view.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <boost/random/variate_generator.hpp> namespace stan { namespace math { /** \ingroup prob_dists * Return an integer random variate between the given lower and upper bounds * (inclusive) using the specified random number generator. * * `lower` and `upper` can each be a scalar or a one-dimensional container. * Any non-scalar inputs must be the same size. * * @tparam T_lower type of lower bound, either int or std::vector<int> * @tparam T_upper type of upper bound, either int or std::vector<int> * @tparam RNG type of random number generator * * @param lower lower bound * @param upper upper bound * @param rng random number generator * @return A (sequence of) integer random variate(s) between `lower` and * `upper`, both bounds included. * @throw std::domain_error if upper is smaller than lower. * @throw std::invalid_argument if non-scalar arguments are of different * sizes. */ template <typename T_lower, typename T_upper, class RNG> inline typename VectorBuilder<true, int, T_lower, T_upper>::type discrete_range_rng(const T_lower& lower, const T_upper& upper, RNG& rng) { static const char* function = "discrete_range_rng"; using boost::variate_generator; using boost::random::uniform_int_distribution; check_consistent_sizes(function, "Lower bound parameter", lower, "Upper bound parameter", upper); check_greater_or_equal(function, "Upper bound parameter", upper, lower); scalar_seq_view<T_lower> lower_vec(lower); scalar_seq_view<T_upper> upper_vec(upper); size_t N = max_size(lower, upper); VectorBuilder<true, int, T_lower, T_upper> output(N); for (size_t n = 0; n < N; ++n) { variate_generator<RNG&, uniform_int_distribution<>> discrete_range_rng( rng, uniform_int_distribution<>(lower_vec[n], upper_vec[n])); output[n] = discrete_range_rng(); } return output.data(); } } // namespace math } // namespace stan #endif
36.306452
76
0.742781
LaudateCorpus1
9f0f72787fa59a95a1a6c61bb5720d1c74cddc27
17,993
cpp
C++
c++/tools/zenbutools.cpp
jessica-severin/ZENBU_2.11.1
694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7
[ "Unlicense" ]
null
null
null
c++/tools/zenbutools.cpp
jessica-severin/ZENBU_2.11.1
694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7
[ "Unlicense" ]
null
null
null
c++/tools/zenbutools.cpp
jessica-severin/ZENBU_2.11.1
694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7
[ "Unlicense" ]
null
null
null
/* $Id: zenbutools.cpp,v 1.20 2015/11/13 09:03:34 severin Exp $ */ /**** NAME zdxtools - DESCRIPTION of Object DESCRIPTION zdxtools is a ZENBU system command line tool to access and process data both remotely on ZENBU federation servers and locally with ZDX file databases. The API is designed to both enable ZENBU advanced features, but also to provide a backward compatibility to samtools and bedtools so that zdxtools can be a "drop in" replacement for these other tools. CONTACT Jessica Severin <jessica.severin@gmail.com> LICENSE * Software License Agreement (BSD License) * MappedQueryDB [MQDB] toolkit * copyright (c) 2006-2009 Jessica Severin * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Jessica Severin nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS 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. APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _ ***/ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string> #include <iostream> #include <math.h> #include <sys/time.h> #include <sys/dir.h> #include <sys/types.h> #include <pwd.h> #include <curl/curl.h> #include <openssl/hmac.h> #include <rapidxml.hpp> //rapidxml must be include before boost #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #include <MQDB/Database.h> #include <MQDB/MappedQuery.h> #include <MQDB/DBStream.h> #include <EEDB/Assembly.h> #include <EEDB/Chrom.h> #include <EEDB/Metadata.h> #include <EEDB/Symbol.h> #include <EEDB/MetadataSet.h> #include <EEDB/Datatype.h> #include <EEDB/FeatureSource.h> #include <EEDB/Experiment.h> #include <EEDB/EdgeSource.h> #include <EEDB/Peer.h> #include <EEDB/Feature.h> #include <EEDB/SPStream.h> #include <EEDB/SPStreams/Dummy.h> #include <EEDB/SPStreams/SourceStream.h> #include <EEDB/SPStreams/MultiMergeStream.h> #include <EEDB/SPStreams/FederatedSourceStream.h> #include <EEDB/SPStreams/FeatureEmitter.h> #include <EEDB/SPStreams/TemplateCluster.h> #include <EEDB/SPStreams/OSCFileDB.h> #include <EEDB/SPStreams/BAMDB.h> #include <EEDB/SPStreams/RemoteServerStream.h> #include <EEDB/Tools/OSCFileParser.h> #include <EEDB/Tools/RemoteUserTool.h> #include <EEDB/User.h> #include <EEDB/Collaboration.h> #include <EEDB/Feature.h> #include <EEDB/WebServices/WebBase.h> #include <EEDB/WebServices/MetaSearch.h> #include <EEDB/WebServices/RegionServer.h> #include <EEDB/WebServices/ConfigServer.h> #include <math.h> #include <sys/time.h> using namespace std; using namespace MQDB; map<string,string> _parameters; EEDB::WebServices::WebBase *webservice; EEDB::User *_user_profile=NULL; void usage(); bool get_cmdline_user(); //bool verify_remote_user(); void list_datasources(); void list_peers(); void show_object(); void show_config(); int main(int argc, char *argv[]) { //seed random with usec of current time struct timeval starttime; gettimeofday(&starttime, NULL); srand(starttime.tv_usec); if(argc==1) { usage(); } for(int argi=1; argi<argc; argi++) { if(argv[argi][0] != '-') { continue; } string arg = argv[argi]; vector<string> argvals; while((argi+1<argc) and (argv[argi+1][0] != '-')) { argi++; argvals.push_back(argv[argi]); } if(arg == "-help") { usage(); } if(arg == "-ids") { string ids; for(unsigned int j=0; j<argvals.size(); j++) { ids += " "+ argvals[j]; } _parameters["ids"] += ids; } if(arg == "-mode") { _parameters["mode"] = argvals[0]; } if(arg == "-file") { _parameters["_input_file"] = argvals[0]; } if(arg == "-f") { _parameters["_input_file"] = argvals[0]; } if(arg == "-url") { _parameters["_url"] = argvals[0]; } if(arg == "-hashkey") { _parameters["hashkey"] = argvals[0]; } if(arg == "-buildtime") { _parameters["buildtime"] = argvals[0]; } if(arg == "-jobid") { _parameters["jobid"] = argvals[0]; _parameters["mode"] = "jobid"; } if(arg == "-assembly") { _parameters["asmb"] = argvals[0]; } if(arg == "-asm") { _parameters["asmb"] = argvals[0]; } if(arg == "-asmb") { _parameters["asmb"] = argvals[0]; } if(arg == "-assembly_name") { _parameters["asmb"] = argvals[0]; } if(arg == "-chr") { _parameters["chrom"] = argvals[0]; } if(arg == "-chrom") { _parameters["chrom"] = argvals[0]; } if(arg == "-chrom_name") { _parameters["chrom"] = argvals[0]; } if(arg == "-start") { _parameters["start"] = argvals[0]; } if(arg == "-end") { _parameters["end"] = argvals[0]; } if(arg == "-sources") { _parameters["mode"] = "sources"; } if(arg == "-experiments") { _parameters["mode"] = "sources"; _parameters["source"] = "Experiment"; } if(arg == "-exps") { _parameters["mode"] = "sources"; _parameters["source"] = "Experiment"; } if(arg == "-fsrc") { _parameters["mode"] = "sources"; _parameters["source"] = "FeatureSource"; } if(arg == "-peers") { _parameters["mode"] = "peers"; } if(arg == "-id") { _parameters["mode"] = "object"; _parameters["id"] = argvals[0]; } if(arg == "-config") { _parameters["mode"] = "config"; _parameters["id"] = argvals[0]; } if(arg == "-chroms") { _parameters["mode"] = "chroms"; } if(arg == "-format") { _parameters["format"] = argvals[0]; } if(arg == "-filter") { _parameters["filter"] = argvals[0]; } if(arg == "-collab") { _parameters["collab"] = argvals[0]; } } webservice = new EEDB::WebServices::WebBase(); webservice->parse_config_file("/etc/zenbu/zenbu.conf"); webservice->init_service_request(); map<string,string>::iterator param; for(param = _parameters.begin(); param != _parameters.end(); param++) { webservice->set_parameter((*param).first, (*param).second); } webservice->postprocess_parameters(); get_cmdline_user(); webservice->set_user_profile(_user_profile); //execute the mode if(_parameters["mode"] == "sources") { list_datasources(); } else if(_parameters["mode"] == "peers") { list_peers(); } else if(_parameters["mode"] == "object") { show_object(); } else if(_parameters["mode"] == "config") { show_config(); } else { usage(); } exit(1); } void usage() { printf("zenbutools [options]\n"); printf(" -help : print this help\n"); printf(" -collab <collab_uuid> : filter searches to specific collaboaration\n"); printf(" -filter <keyword logix> : filter searches with keyword expression\n"); printf(" -sources : data sources query\n"); printf(" -exps : data sources query for only Experiments\n"); printf(" -fsrc : data sources query for only FeatureSources\n"); printf(" -peers : peers query\n"); printf(" -id <zenbu_id> : fetch specific object\n"); printf(" -config <uuid> : fetch specific configuration\n"); printf("zenbutools v%s\n", EEDB::WebServices::WebBase::zenbu_version); exit(1); } //////////////////////////////////////////////////////////////////////////// // // user query methods // //////////////////////////////////////////////////////////////////////////// bool get_cmdline_user() { //reads ~/.zenbu/id_hmac to get hmac authentication secret int fildes; off_t cfg_len; char* config_text; if(_user_profile) { return true; } struct passwd *pw = getpwuid(getuid()); string path = pw->pw_dir; path += "/.zenbu/id_hmac"; fildes = open(path.c_str(), O_RDONLY, 0x700); if(fildes<0) { return false; } //error cfg_len = lseek(fildes, 0, SEEK_END); //printf("config file %lld bytes long\n", (long long)cfg_len); lseek(fildes, 0, SEEK_SET); config_text = (char*)malloc(cfg_len+1); memset(config_text, 0, cfg_len+1); read(fildes, config_text, cfg_len); char* email = strtok(config_text, " \t\n"); char* secret = strtok(NULL, " \t\n"); printf("[%s] -> [%s]\n", email, secret); _user_profile = new EEDB::User(); if(email) { _user_profile->email_address(email); } if(secret) { _user_profile->hmac_secretkey(secret); } free(config_text); close(fildes); return true; } /* bool verify_remote_user() { //collaborations user is member/owner of //might also need to cache peers, but for now try to do without caching rapidxml::xml_document<> doc; rapidxml::xml_node<> *root_node; CURL *curl = curl_easy_init(); if(!curl) { return false; } struct RSS_curl_buffer chunk; chunk.memory = NULL; // will be grown as needed chunk.size = 0; // no data at this point chunk.alloc_size = 0; // no data at this point string paramXML = "<zenbu_query>"; if(_user_profile) { paramXML += "<authenticate><email>"+ _user_profile->email_identity() +"</email>"; struct timeval expiretime; gettimeofday(&expiretime, NULL); //set to 5min in the future long value = expiretime.tv_sec+300; paramXML += "<expires>" +l_to_string(value) + "</expires>"; paramXML += "</authenticate>"; } paramXML += "<mode>user</mode>"; paramXML += "</zenbu_query>"; //fprintf(stderr, "POST: %s\n", paramXML.c_str()); string url = _server_url + "/cgi/eedb_user.cgi"; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, paramXML.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, paramXML.length()); struct curl_slist *slist = NULL; slist = curl_slist_append(NULL, "Content-Type: text/xml; charset=utf-8"); // or whatever charset your XML is really using... if(_user_profile) { string key = _user_profile->hmac_secretkey(); unsigned int md_len; unsigned char* result = HMAC(EVP_sha256(), (const unsigned char*)key.c_str(), key.length(), (const unsigned char*)paramXML.c_str(), paramXML.length(), NULL, &md_len); static char res_hexstring[64]; //expect 32 so this is safe bzero(res_hexstring, 64); for(unsigned i = 0; i < md_len; i++) { sprintf(&(res_hexstring[i * 2]), "%02x", result[i]); } string credentials = string("x-zenbu-magic: ") + res_hexstring; slist = curl_slist_append(slist, credentials.c_str()); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _rss_curl_writeMemoryCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0"); curl_easy_perform(curl); if(slist) { curl_slist_free_all(slist); } curl_easy_cleanup(curl); //fprintf(stderr, "returned-----\n%s\n", chunk.memory); char *start_ptr = strstr(chunk.memory, "<user"); if(!start_ptr) { free(chunk.memory); return false; } doc.parse<rapidxml::parse_declaration_node | rapidxml::parse_no_data_nodes>(start_ptr); root_node = doc.first_node(); if(!root_node) { free(chunk.memory); return false; } rapidxml::xml_node<> *node = root_node->first_node("eedb_user"); EEDB::User *user = NULL; if(node) { user = new EEDB::User(node); } if(!user) { return false; } //fprintf(stderr, "%s\n", user->xml().c_str()); free(chunk.memory); doc.clear(); return true; } */ // ///////////////////////////////////////////////////////////////////////////////////////////////// // void list_datasources() { if(_parameters.find("format") == _parameters.end()) { _parameters["format"] = "list"; } map<string, EEDB::Peer*> peer_map; long exp_count=0; long fsrc_count=0; if(_parameters.find("collab") != _parameters.end()) { webservice->set_parameter("collab", _parameters["collab"]); webservice->postprocess_parameters(); } EEDB::SPStream *stream = webservice->source_stream(); // sources string source_type = ""; if(_parameters.find("source") != _parameters.end()) { source_type = _parameters["source"]; } if(_parameters.find("filter") != _parameters.end()) { stream->stream_data_sources(source_type, _parameters["filter"]); } else { stream->stream_data_sources(source_type); } while(MQDB::DBObject* obj = stream->next_in_stream()) { if(obj->classname() == EEDB::Peer::class_name) { EEDB::Peer *peer = (EEDB::Peer*)obj; peer_map[peer->uuid()] = peer; continue; } string uuid, objClass; long int objID; MQDB::unparse_dbid(obj->db_id(), uuid, objID, objClass); //printf(" uuid: %s\n", uuid.c_str()); EEDB::Peer *peer = EEDB::Peer::check_cache(uuid); EEDB::DataSource* source = (EEDB::DataSource*)obj; if(obj->classname() == EEDB::Experiment::class_name) { exp_count++; } if(obj->classname() == EEDB::FeatureSource::class_name) { fsrc_count++; } if(_parameters["format"] == "xml") { printf("%s\n", source->xml().c_str()); } if((_parameters["format"] == "simplexml") || (_parameters["format"] == "simple_xml")) { printf("%s", source->simple_xml().c_str()); } if(_parameters["format"] == "list") { printf("%60s %s\n", obj->db_id().c_str(),source->display_name().c_str()); } if(_parameters["format"] == "detail") { printf("-------\n"); printf(" db_id: %s\n", obj->db_id().c_str()); printf(" name: %s\n", source->display_name().c_str()); printf(" description: %s\n", source->description().c_str()); if(peer) { printf(" peer: %s\n", peer->db_url().c_str()); } } source->release(); } fprintf(stderr, "%ld peers --- %ld featuresources --- %ld experiments --- [%ld total sources]\n", peer_map.size(), fsrc_count, exp_count, fsrc_count+exp_count); stream->disconnect(); } void list_peers() { map<string, EEDB::Peer*> peer_map; if(_parameters.find("collab") != _parameters.end()) { webservice->set_parameter("collab", _parameters["collab"]); webservice->postprocess_parameters(); } EEDB::SPStream *stream = webservice->source_stream(); // peers stream->stream_peers(); while(MQDB::DBObject* obj = stream->next_in_stream()) { if(!obj) { continue; } EEDB::Peer *peer = (EEDB::Peer*)obj; if(!(peer->is_valid())) { continue; } peer_map[peer->uuid()] = peer; printf("%s\n", peer->xml().c_str()); } fprintf(stderr, "%ld peers\n", peer_map.size()); stream->disconnect(); } void show_object() { if(_parameters.find("format") == _parameters.end()) { _parameters["format"] = "xml"; } if(_parameters.find("collab") != _parameters.end()) { webservice->set_parameter("collab", _parameters["collab"]); webservice->postprocess_parameters(); } EEDB::SPStream *stream = webservice->source_stream(); MQDB::DBObject* object = stream->fetch_object_by_id(_parameters["id"]); if(object) { printf("\n"); if(_parameters["format"] == "xml") { printf("%s\n", object->xml().c_str()); } if((_parameters["format"] == "simplexml") || (_parameters["format"] == "simple_xml")) { printf("%s", object->simple_xml().c_str()); } } else { printf("unable to fetch id [%s]\n", _parameters["id"].c_str()); } stream->disconnect(); } void show_config() { if(_parameters.find("format") == _parameters.end()) { _parameters["format"] = "xml"; } EEDB::WebServices::ConfigServer *configservice = new EEDB::WebServices::ConfigServer(); configservice->parse_config_file("/etc/zenbu/zenbu.conf"); configservice->init_service_request(); map<string,string>::iterator param; for(param = _parameters.begin(); param != _parameters.end(); param++) { configservice->set_parameter((*param).first, (*param).second); } configservice->postprocess_parameters(); get_cmdline_user(); configservice->set_user_profile(_user_profile); EEDB::Configuration* config = configservice->get_config_uuid(_parameters["id"]); if(config) { printf("\n"); if(_parameters["format"] == "xml") { printf("%s\n", config->xml().c_str()); } if((_parameters["format"] == "simplexml") || (_parameters["format"] == "simple_xml")) { printf("%s", config->simple_xml().c_str()); } } else { printf("unable to fetch config [%s]\n", _parameters["id"].c_str()); } }
34.142315
162
0.626355
jessica-severin
9f10e30ec2a1f9806dc52f5ce9250a407db25fb0
5,841
cpp
C++
Source/VectorShapeEditor/Private/SplineVisualizer/VectorMeshComponentVisualizer.cpp
mhousse1247/UE4-VectorShapeWidgetPlugin
12c4d5507e32551d8e54c405de7f6d64ba6745ba
[ "MIT" ]
7
2020-12-05T21:07:41.000Z
2021-09-08T21:43:24.000Z
Source/VectorShapeEditor/Private/SplineVisualizer/VectorMeshComponentVisualizer.cpp
mhousse1247/UE4-VectorShapeWidgetPlugin
12c4d5507e32551d8e54c405de7f6d64ba6745ba
[ "MIT" ]
null
null
null
Source/VectorShapeEditor/Private/SplineVisualizer/VectorMeshComponentVisualizer.cpp
mhousse1247/UE4-VectorShapeWidgetPlugin
12c4d5507e32551d8e54c405de7f6d64ba6745ba
[ "MIT" ]
2
2021-08-18T16:05:27.000Z
2021-09-11T00:15:02.000Z
//==========================================================================// // Copyright Elhoussine Mehnik (ue4resources@gmail.com). All Rights Reserved. //================== http://unrealengineresources.com/ =====================// #include "VectorMeshComponentVisualizer.h" #include "VectorMeshComponent.h" #include "VectorShapeActor.h" #include "SceneManagement.h" #include "ComponentVisualizer.h" #define LOCTEXT_NAMESPACE "VectorMeshComponentVisualizer" FVectorMeshComponentVisualizer::FVectorMeshComponentVisualizer() : VectorShapeActorPtr(nullptr) { } FVectorMeshComponentVisualizer::~FVectorMeshComponentVisualizer() { } void FVectorMeshComponentVisualizer::OnRegister() { } void FVectorMeshComponentVisualizer::DrawVisualization(const UActorComponent* Component, const FSceneView* View, FPrimitiveDrawInterface* PDI) { if (const UVectorMeshComponent* SplineComp = Cast<const UVectorMeshComponent>(Component)) { if (AVectorShapeActor* VectorShapeActor = Cast<AVectorShapeActor>(SplineComp->GetOwner())) { if (!VectorShapeActor->bDrawSpawnRect) { return; } const FVector SpawnRectLocation = VectorShapeActor->GetActorTransform().TransformPosition(VectorShapeActor->NewSplineSpawnPoint); const FVector2D& RectExtent = VectorShapeActor->NewSplineExtent; const FVector ActorLocation = VectorShapeActor->GetActorLocation(); const FVector2D& WorldExtent = VectorShapeActor->WorldSize / 2.0f; const FVector ActorRight = VectorShapeActor->GetActorRightVector(); const FVector ActorForward = VectorShapeActor->GetActorForwardVector(); const FColor& RectColor = VectorShapeActor->SpawnRectColor; if (SplineComp == VectorShapeActor->GetMeshComponent()) { PDI->SetHitProxy(new HComponentVisProxy(Component)); } PDI->DrawLine(SpawnRectLocation - ActorForward* RectExtent.X + ActorRight * RectExtent.Y, SpawnRectLocation + ActorForward*RectExtent.X + ActorRight *RectExtent.Y, RectColor, SDPG_Foreground); PDI->DrawLine(SpawnRectLocation + ActorForward*RectExtent.X + ActorRight *RectExtent.Y, SpawnRectLocation + ActorForward*RectExtent.X - ActorRight *RectExtent.Y, RectColor, SDPG_Foreground); PDI->DrawLine(SpawnRectLocation + ActorForward* RectExtent.X - ActorRight *RectExtent.Y, SpawnRectLocation - ActorForward*RectExtent.X - ActorRight *RectExtent.Y, RectColor, SDPG_Foreground); PDI->DrawLine(SpawnRectLocation - ActorForward*RectExtent.X - ActorRight *RectExtent.Y, SpawnRectLocation - ActorForward*RectExtent.X + ActorRight *RectExtent.Y, RectColor, SDPG_Foreground); PDI->DrawLine(SpawnRectLocation - ActorForward* RectExtent.X, SpawnRectLocation + ActorForward * RectExtent.X, RectColor, SDPG_Foreground); PDI->DrawLine(SpawnRectLocation - ActorRight * RectExtent.Y, SpawnRectLocation + ActorRight *RectExtent.Y, RectColor, SDPG_Foreground); PDI->DrawPoint(SpawnRectLocation - ActorForward* RectExtent.X + ActorRight * RectExtent.Y, RectColor, 10.0f, SDPG_Foreground); PDI->DrawPoint(SpawnRectLocation + ActorForward*RectExtent.X + ActorRight *RectExtent.Y, RectColor, 10.0f, SDPG_Foreground); PDI->DrawPoint(SpawnRectLocation + ActorForward* RectExtent.X - ActorRight *RectExtent.Y, RectColor, 10.0f, SDPG_Foreground); PDI->DrawPoint(SpawnRectLocation - ActorForward*RectExtent.X - ActorRight *RectExtent.Y, RectColor, 10.0f, SDPG_Foreground); PDI->SetHitProxy(nullptr); } } } bool FVectorMeshComponentVisualizer::VisProxyHandleClick(FEditorViewportClient* InViewportClient, HComponentVisProxy* VisProxy, const FViewportClick& Click) { if (VisProxy && VisProxy->Component.IsValid()) { if(const UVectorMeshComponent* SplineComp = CastChecked<const UVectorMeshComponent>(VisProxy->Component.Get())) { if (AVectorShapeActor* VectorShapeActor = Cast<AVectorShapeActor>(SplineComp->GetOwner())) { VectorShapeActorPtr = VectorShapeActor; return true; } } } return false; } void FVectorMeshComponentVisualizer::EndEditing() { VectorShapeActorPtr = nullptr; } bool FVectorMeshComponentVisualizer::GetWidgetLocation(const FEditorViewportClient* ViewportClient, FVector& OutLocation) const { if (AVectorShapeActor* VectorShapeActor = VectorShapeActorPtr.Get()) { OutLocation = VectorShapeActor->GetActorTransform().TransformPosition(VectorShapeActor->NewSplineSpawnPoint ); return true; } return false; } bool FVectorMeshComponentVisualizer::GetCustomInputCoordinateSystem(const FEditorViewportClient* ViewportClient, FMatrix& OutMatrix) const { if (AVectorShapeActor* VectorShapeActor = VectorShapeActorPtr.Get()) { OutMatrix = FRotationMatrix::Make(VectorShapeActor->GetActorQuat()); return true; } return false; } bool FVectorMeshComponentVisualizer::HandleInputDelta(FEditorViewportClient* ViewportClient, FViewport* Viewport, FVector& DeltaTranslate, FRotator& DeltaRotate, FVector& DeltaScale) { if (AVectorShapeActor* VectorShapeActor = VectorShapeActorPtr.Get()) { VectorShapeActor->Modify(); if (!DeltaTranslate.IsZero()) { VectorShapeActor->NewSplineSpawnPoint += VectorShapeActor->GetActorTransform().InverseTransformVector(DeltaTranslate); VectorShapeActor->NewSplineSpawnPoint.Z = FMath::Max<float>(VectorShapeActor->NewSplineSpawnPoint.Z, 0.0f); } if (!DeltaScale.IsZero()) { VectorShapeActor->NewSplineExtent += FVector2D(DeltaScale.X, DeltaScale.Y) * 100.0f; VectorShapeActor->NewSplineExtent.X = FMath::Max<float>(VectorShapeActor->NewSplineExtent.X, 5.0f); VectorShapeActor->NewSplineExtent.Y = FMath::Max<float>(VectorShapeActor->NewSplineExtent.Y, 5.0f); } if (!DeltaRotate.IsZero()) { } return true; } return false; } bool FVectorMeshComponentVisualizer::HandleInputKey(FEditorViewportClient* ViewportClient, FViewport* Viewport, FKey Key, EInputEvent Event) { return false; } #undef LOCTEXT_NAMESPACE
36.50625
195
0.77093
mhousse1247
9f12738041481119b2f0e69bd9383e9c13e10fb3
307
hpp
C++
PP/view/destroy.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
3
2019-07-12T23:12:24.000Z
2019-09-05T07:57:45.000Z
PP/view/destroy.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
null
null
null
PP/view/destroy.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
null
null
null
#pragma once #include <PP/get_type.hpp> #include <PP/partial_.hpp> #include <PP/view/for_each.hpp> namespace PP::detail::functors { PP_CIA destroy_helper = [](auto&& x) { using T = PP_GT(~PP_DT(x)); x.~T(); }; } namespace PP::view { PP_CIA destroy = for_each * detail::functors::destroy_helper; }
16.157895
61
0.674267
Petkr
9f12e5aed7c73cc52bbd723374683f5422411fca
2,393
cpp
C++
src/Shader.cpp
cjuniet/simpleGL
719c1152d9085f1612c3e0b8ce2ee25fe3ad22dd
[ "MIT" ]
null
null
null
src/Shader.cpp
cjuniet/simpleGL
719c1152d9085f1612c3e0b8ce2ee25fe3ad22dd
[ "MIT" ]
null
null
null
src/Shader.cpp
cjuniet/simpleGL
719c1152d9085f1612c3e0b8ce2ee25fe3ad22dd
[ "MIT" ]
null
null
null
#include "Shader.hpp" #include <glm/gtc/type_ptr.hpp> #include <fstream> #include <sstream> #include <stdexcept> namespace { void compile_glsl(const std::string& filename, GLuint shader) { std::ifstream ifs(filename); if (!ifs) { throw std::runtime_error("compile_glsl(): unable to open " + filename); } std::ostringstream oss; oss << ifs.rdbuf(); ifs.close(); const std::string glsl = oss.str(); const char* str = glsl.c_str(); glShaderSource(shader, 1, &str, nullptr); glCompileShader(shader); GLint success; glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { char buf[512]; glGetShaderInfoLog(shader, sizeof(buf), nullptr, buf); throw std::runtime_error("compile_glsl('" + filename + "'): " + buf); } } } Shader::Shader(const std::string& vertex_file, const std::string& fragment_file) : _vertex(glCreateShader(GL_VERTEX_SHADER)), _fragment(glCreateShader(GL_FRAGMENT_SHADER)), _program(glCreateProgram()) { load(vertex_file, fragment_file); } Shader::~Shader() { glDeleteShader(_vertex); glDeleteShader(_fragment); glDeleteProgram(_program); } void Shader::load(const std::string& vertex_file, const std::string& fragment_file) { compile_glsl(vertex_file, _vertex); compile_glsl(fragment_file, _fragment); glAttachShader(_program, _vertex); glAttachShader(_program, _fragment); glLinkProgram(_program); GLint success; glGetProgramiv(_program, GL_LINK_STATUS, &success); if (!success) { char buf[512]; glGetProgramInfoLog(_program, sizeof(buf), nullptr, buf); throw std::runtime_error(std::string("Shader::Shader(): ") + buf); } } void Shader::attach() const { glUseProgram(_program); } void Shader::detach() const { glUseProgram(0); } void Shader::set_uniform(const GLchar* name, GLfloat value) const { glUniform1f(glGetUniformLocation(_program, name), value); } void Shader::set_uniform(const GLchar* name, const glm::vec2& value) const { glUniform2fv(glGetUniformLocation(_program, name), 1, glm::value_ptr(value)); } void Shader::set_uniform(const GLchar* name, const glm::vec4& value) const { glUniform4fv(glGetUniformLocation(_program, name), 1, glm::value_ptr(value)); } void Shader::set_uniform(const GLchar* name, const glm::mat4& value) const { glUniformMatrix4fv(glGetUniformLocation(_program, name), 1, GL_FALSE, glm::value_ptr(value)); }
24.171717
95
0.717509
cjuniet
2f58ddcaef4c917882ccfd0aacf47bcf7c72072a
1,395
cpp
C++
Codeforces/C++/Dima-Sereja_problem.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
289
2021-05-15T22:56:03.000Z
2022-03-28T23:13:25.000Z
Codeforces/C++/Dima-Sereja_problem.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
1,812
2021-05-09T13:49:58.000Z
2022-01-15T19:27:17.000Z
Codeforces/C++/Dima-Sereja_problem.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
663
2021-05-09T16:57:58.000Z
2022-03-27T14:15:07.000Z
/* Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins. Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move. Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her. */ #include <iostream> using namespace std; int main() { int n; cin >> n; int a[n]; for(int turns = 0; turns < n; turns++) { cin >> a[turns]; } int sum1 = 0, sum2 = 0; int front = 0, back = n-1; for(int turns = 0; turns < n; turns++) { int ans = max(a[front], a[back]); if(a[front] >= a[back]) { front++; } else { back--; } if(turns % 2 == 1) sum1 += ans; else sum2 += ans; } cout << sum2 << " " << sum1; return 0; } /* Input: 4 4 1 2 10 Output: 12 5 */
25.363636
171
0.580645
abdzitter
2f5ce7acde58c43615729d6d9e4bf6ccdfd6b8b4
316
hpp
C++
include/TypeHelpers.hpp
ChoppinBlockParty/perq
2442e33b230c81c9f6e971ffcb35499b2f248cbd
[ "BSD-3-Clause" ]
3
2018-06-30T09:09:38.000Z
2020-06-05T22:46:23.000Z
include/TypeHelpers.hpp
ChoppinBlockParty/perq
2442e33b230c81c9f6e971ffcb35499b2f248cbd
[ "BSD-3-Clause" ]
null
null
null
include/TypeHelpers.hpp
ChoppinBlockParty/perq
2442e33b230c81c9f6e971ffcb35499b2f248cbd
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <cinttypes> #include <cstddef> namespace perq { struct NoPrefix { using Type = uint8_t; }; namespace internal { template <typename T> struct PrefixSize { static constexpr size_t size = sizeof(T); }; template <> struct PrefixSize<NoPrefix> { static constexpr size_t size = 0; }; } }
12.64
43
0.705696
ChoppinBlockParty
2f5d08138fe49f3963a0ab10237b4bd888778970
7,550
cpp
C++
module-apps/application-settings/windows/network/SimContactsImportWindow.cpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
369
2021-11-10T09:20:29.000Z
2022-03-30T06:36:58.000Z
module-apps/application-settings/windows/network/SimContactsImportWindow.cpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
149
2021-11-10T08:38:35.000Z
2022-03-31T23:01:52.000Z
module-apps/application-settings/windows/network/SimContactsImportWindow.cpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
41
2021-11-10T08:30:37.000Z
2022-03-29T08:12:46.000Z
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "SimContactsImportWindow.hpp" #include <application-settings/windows/WindowNames.hpp> #include <InputEvent.hpp> #include <service-appmgr/Controller.hpp> namespace gui { SimContactsImportWindow::SimContactsImportWindow( app::ApplicationCommon *app, std::unique_ptr<SimContactsImportWindowContract::Presenter> simImportPresenter) : AppWindow(app, gui::window::name::import_contacts), presenter(std::move(simImportPresenter)) { presenter->attach(this); preventsAutoLock = true; buildInterface(); } void SimContactsImportWindow::buildInterface() { AppWindow::buildInterface(); setTitle(utils::translate("app_settings_network_import_contacts")); navBar->setText(gui::nav_bar::Side::Right, utils::translate(::style::strings::common::back)); navBar->setText(gui::nav_bar::Side::Center, utils::translate(::style::strings::common::import)); list = new ListView(this, style::window::default_left_margin, style::window::default_vertical_pos, style::listview::body_width_with_scroll, style::window::default_body_height, presenter->getSimContactsProvider(), listview::ScrollBarType::Fixed); emptyListIcon = new gui::Icon(this, ::style::window::default_left_margin, ::style::window::default_vertical_pos, ::style::window::default_body_width, ::style::window::default_body_height, "info_128px_W_G", utils::translate("app_settings_network_import_contacts_from_sim_card_reading")); emptyListIcon->setAlignment(Alignment::Horizontal::Center); emptyListIcon->setVisible(false); list->emptyListCallback = [this]() { emptyListIcon->setVisible(true); }; list->notEmptyListCallback = [this]() { emptyListIcon->setVisible(false); }; setFocusItem(list); } void SimContactsImportWindow::onBeforeShow(ShowMode mode, SwitchData *data) { emptyListIcon->text->setRichText( utils::translate("app_settings_network_import_contacts_from_sim_card_reading")); emptyListIcon->image->set("progress_128px_W_G"); navBar->setActive(nav_bar::Side::Right, true); navBar->setActive(nav_bar::Side::Center, false); navBar->setActive(nav_bar::Side::Left, false); presenter->requestSimContacts(); } void SimContactsImportWindow::onClose(CloseReason reason) { if (reason != CloseReason::PhoneLock) { presenter->eraseProviderData(); } } bool SimContactsImportWindow::onInput(const InputEvent &inputEvent) { if (inputEvent.isKeyRelease(gui::KeyCode::KEY_LF) && !navBar->isActive(nav_bar::Side::Left)) { return false; } if (inputEvent.isKeyRelease(gui::KeyCode::KEY_ENTER) && !navBar->isActive(nav_bar::Side::Center)) { return false; } if (inputEvent.isKeyRelease(gui::KeyCode::KEY_RF) && !navBar->isActive(nav_bar::Side::Right)) { return false; } if (inputEvent.isKeyRelease(gui::KeyCode::KEY_LF) && presenter->isRequestCompleted() && onLFInputCallback) { onLFInputCallback(); return true; } if (inputEvent.isKeyRelease(gui::KeyCode::KEY_ENTER) && presenter->isRequestCompleted() && onEnterInputCallback) { onEnterInputCallback(); return true; } return AppWindow::onInput(inputEvent); } void SimContactsImportWindow::contactsReady() noexcept { navBar->setActive(nav_bar::Side::Center, true); list->rebuildList(); if (list->isEmpty()) { navBar->setActive(nav_bar::Side::Center, false); emptyListIcon->text->setRichText( utils::translate("app_settings_network_import_contacts_from_sim_card_no_contacts")); emptyListIcon->image->set("info_128px_W_G"); } else { setTitle(utils::translate("app_settings_network_import_contacts_from_sim_card")); onEnterInputCallback = [&]() { displayProgressInfo(); presenter->saveImportedContacts(); }; } } void SimContactsImportWindow::displayDuplicatesCount(unsigned int duplicatesCount) noexcept { list->rebuildList(); setTitle(utils::translate("app_settings_network_import_contacts")); emptyListIcon->text->setRichText( utils::translate("app_settings_network_import_contacts_from_sim_card_duplicates"), {{"$DUPLICATES", std::to_string(duplicatesCount)}}); emptyListIcon->image->set("info_128px_W_G"); navBar->setActive(nav_bar::Side::Right, true); navBar->setText(gui::nav_bar::Side::Center, utils::translate(::style::strings::common::show)); navBar->setText(gui::nav_bar::Side::Left, utils::translate(::style::strings::common::skip)); onLFInputCallback = [&]() { displayProgressInfo(); presenter->saveImportedContacts(); }; onEnterInputCallback = [&]() { presenter->requestDuplicates(); }; } void SimContactsImportWindow::displayDuplicates() noexcept { navBar->setText(gui::nav_bar::Side::Center, utils::translate(::style::strings::common::replace)); list->rebuildList(); setTitle(utils::translate("app_settings_network_import_contacts_duplicates")); navBar->setActive(nav_bar::Side::Right, true); onLFInputCallback = nullptr; onEnterInputCallback = [&]() { displayProgressInfo(); presenter->saveImportedContacts(); }; } void SimContactsImportWindow::contactsImported() noexcept { list->rebuildList(); setTitle(utils::translate("app_settings_network_import_contacts_from_sim_card")); emptyListIcon->text->setRichText( utils::translate("app_settings_network_import_contacts_from_sim_card_success")); emptyListIcon->image->set("success_128px_W_G"); navBar->setActive(nav_bar::Side::Right, false); navBar->setText(gui::nav_bar::Side::Center, utils::translate(::style::strings::common::ok)); navBar->setText(gui::nav_bar::Side::Left, utils::translate(::style::strings::common::contacts)); onLFInputCallback = [&]() { app::manager::Controller::sendAction(application, app::manager::actions::ShowContacts); }; onEnterInputCallback = [&]() { application->switchWindow(gui::window::name::sim_cards); }; } void SimContactsImportWindow::displayProgressInfo() { list->clear(); list->emptyListCallback(); emptyListIcon->text->setRichText( utils::translate("app_settings_network_import_contacts_from_sim_card_reading")); emptyListIcon->image->set("progress_128px_W_G"); navBar->setActive(nav_bar::Side::Right, false); navBar->setActive(nav_bar::Side::Center, false); navBar->setActive(nav_bar::Side::Left, false); } } // namespace gui
40.591398
118
0.627285
bitigchi
2f63d060dc3774088e6c783814004b1f1a3aa58b
1,925
hpp
C++
include/zax/stringcat.hpp
fcharlie/zax
041ad510635df85e5842036cd0319ea92f7f56ba
[ "MIT" ]
null
null
null
include/zax/stringcat.hpp
fcharlie/zax
041ad510635df85e5842036cd0319ea92f7f56ba
[ "MIT" ]
null
null
null
include/zax/stringcat.hpp
fcharlie/zax
041ad510635df85e5842036cd0319ea92f7f56ba
[ "MIT" ]
null
null
null
#ifndef ZAX_STRINGCAT_HPP #define ZAX_STRINGCAT_HPP #include <string> #include <string_view> #include <charconv> #include "unicode.hpp" namespace zax { // class AlphaNum { static constexpr const int suggest_size = 32; public: AlphaNum(bool x) { piece_ = x ? "true" : "false"; // true or false } AlphaNum(int x) { auto ret = std::to_chars(digits_, digits_ + suggest_size, x); piece_ = std::string_view{digits_, ret.ptr - digits_}; } AlphaNum(unsigned int x) { auto ret = std::to_chars(digits_, digits_ + suggest_size, x); piece_ = std::string_view{digits_, ret.ptr - digits_}; } AlphaNum(long x) { auto ret = std::to_chars(digits_, digits_ + suggest_size, x); piece_ = std::string_view{digits_, ret.ptr - digits_}; } AlphaNum(unsigned long x) { auto ret = std::to_chars(digits_, digits_ + suggest_size, x); piece_ = std::string_view{digits_, ret.ptr - digits_}; } AlphaNum(long long x) { auto ret = std::to_chars(digits_, digits_ + suggest_size, x); piece_ = std::string_view{digits_, ret.ptr - digits_}; } AlphaNum(unsigned long long x) { auto ret = std::to_chars(digits_, digits_ + suggest_size, x); piece_ = std::string_view{digits_, ret.ptr - digits_}; } AlphaNum(char32_t rune) { // convert utf-8 auto n = zax::text::RuneEncode(rune, digits_, suggest_size); piece_ = std::string_view{digits_, n}; } AlphaNum(const char *c_str) : piece_(c_str == nullptr ? "(nullptr)" : c_str) {} AlphaNum(std::string_view pc) : piece_(pc) {} AlphaNum(char c) = delete; AlphaNum(const AlphaNum &) = delete; AlphaNum &operator=(const AlphaNum &) = delete; std::string_view::size_type size() const { return piece_.size(); } const char *data() const { return piece_.data(); } std::string_view Piece() const { return piece_; } private: std::string_view piece_; char digits_[suggest_size]; }; } // namespace zax #endif
29.615385
81
0.66961
fcharlie
2f66883e0e5b390bdac4311a8bd1b23c41be1dcd
46,972
cpp
C++
applis/OLD-MICMAC-OLD/cModeleAnalytiqueComp.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
451
2016-11-25T09:40:28.000Z
2022-03-30T04:20:42.000Z
applis/OLD-MICMAC-OLD/cModeleAnalytiqueComp.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
143
2016-11-25T20:35:57.000Z
2022-03-01T11:58:02.000Z
applis/OLD-MICMAC-OLD/cModeleAnalytiqueComp.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
139
2016-12-02T10:26:21.000Z
2022-03-10T19:40:29.000Z
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ #include "general/all.h" #include "MICMAC.h" #include "im_tpl/image.h" // #include "XML_GEN/all.h" // using namespace NS_ParamChantierPhotogram; /* --------------------------------------------------------------------------------- cMatrCorresp : contient une correspondance "moyennee" entre deux images. Elle contient : mImX1, mImY1 : P1 = mImX1(i,j),mImY1(i,j) est un point "moyenne" de l'image mImPds(i,j) est le poids associe a ce point mXY2 est la parallaxe moyennee de Normalize : va utiliser mImX1,mImY1,mImPds,mXY2 pour creer des points homologues. mPackHomInit : "vrais" points homologues issus de l'appariements mPackHomCorr : point homologues corriges du maxim de modele a priori (ie si le modele etait parfait, on aurait P1=P2); cMatrCorresp * cModeleAnalytiqueComp::GetMatr(int aPas) cree une telle matrice avec les deux "paquets" initialises. void cModeleAnalytiqueComp::MakeExport() { * cree le paquet avec GetMatr (eventuellement si UseHomologueReference est vrai, on lui subsititue a des fin de mise au point un paquet stocke sur fichier par ReadPackHom) * le filtre eventuellement avec FiltragePointHomologues (pour enlever les point hors image ou trop tres du bord); * Ensuite on a un embranchement suivant que l'on est DHD ou en Ori : - DHD SolveHomographie(*aPackIn); // En general aPackIn vaut mPackHomCorr SauvHom(*aPackIn); - Ori // En general aPackIn vaut mPackHomCorr==mPackHomInit filtre cMA_AffineOrient ... (a Documenter + tard) } cModeleAnalytiqueComp en tant que Dist22Gen , sa fonction ::Direct est le modele analytique calcule soit : 1 Pt2dr aQ = mGeom2.CorrigeDist1(aP); // Distorsion images 1 2 aQ = CorrecDirecte(aQ); // Modele complementaire (Hom+ ? Polynome) 3 aQ = mGeom2.InvCorrDist2(aQ); // Homographie de base + Distosion Image 2 void cModeleAnalytiqueComp::SolveHomographie(const ElPackHomologue & aPackHom) { 1- estime un modele analytique de la deformation aPackHom; ce modele est fait : d'une homographie (calculee par L1) composee eventuellement par un polynome de degre N (!! Attention le polynome est aussi estime en L1 par Barrodale, Pb potentiel si degre eleve et Le modele est modifie ce qui fait que lui 2- le mode est sauvegarde en XML, il sera reutilise a l'etape suivante (? a documenter .. avec "LoadMA" qui va charger le modele); 3- Sauvegarde Image si (mModele.ExportImage().Val() || mModele.ReuseResiduelle().Val() ) On calcule la paralaxe (a valeur reelle) qui aurait donne exactement la valeur du modele analytique Apparament (a eclaircir !) ReuseResiduelle n'a pas d'effet sur l'etape d'apres. BUG ?? 4- Sauvegarde du modele sous forme de grille "prete" a l'emploi if (mExpModeleGlobal) ... } */ namespace NS_ParamMICMAC { void AssertAutomSelExportOriIsInit(const cOneModeleAnalytique & aM) { ELISE_ASSERT ( aM.AutomSelExportOri().IsInit(), "AutomNamesExportOri non init; avec AutomSelExportOri init" ); } /**********************************************************************/ /* */ /* cMC_PairIm */ /* */ /**********************************************************************/ cMC_PairIm::cMC_PairIm ( int aDZ, const cGeomDiscFPx & aGDF, cPriseDeVue & aPDV1, cPriseDeVue & aPDV2 ) : mDZ (aDZ), mResolZ1 (aGDF.ResolZ1()), mPDV1 (aPDV1), mPDV2 (aPDV2), mI1 (CreateAllImAndLoadCorrel<Im2D_REAL4>(mPDV1.IMIL(),aDZ)), mTI1 (mI1), mI2 (CreateAllImAndLoadCorrel<Im2D_REAL4>(mPDV2.IMIL(),aDZ)), mTI2 (mI2) { } double cMC_PairIm::Correl(Pt2dr aPTER,int aSzW,double * aVPx) { RMat_Inertie aMat; Pt2di aDP; for (aDP.x=-aSzW ; aDP.x<=aSzW; aDP.x++) { for (aDP.y=-aSzW ; aDP.y<=aSzW; aDP.y++) { Pt2dr aQTer = aPTER + (Pt2dr(aDP) * double(mDZ*mResolZ1)); Pt2dr aPI1 = mPDV1.Geom().Objet2ImageInit_Euclid(aQTer,aVPx) / double(mDZ); Pt2dr aPI2 = mPDV2.Geom().Objet2ImageInit_Euclid(aQTer,aVPx) / double(mDZ); if (mTI1.Rinside_bilin(aPI1) && (mTI2.Rinside_bilin(aPI2))) { aMat.add_pt_en_place(mTI1.getr(aPI1),mTI2.getr(aPI2)); } else return -1; } } return aMat.correlation(); } /**********************************************************************/ /* */ /* cMatrCorresp */ /* */ /**********************************************************************/ cMatrCorresp::cMatrCorresp(cAppliMICMAC & anAppli,Pt2di aSz,int aNBXY2) : mAppli (anAppli), mNBXY2 (aNBXY2), mSz (aSz), mImPds (aSz.x,aSz.y,0.0), mTImPds (mImPds), mImX1 (aSz.x,aSz.y,0.0), mTImX1 (mImX1), mImY1 (aSz.x,aSz.y,0.0), mTImY1 (mImY1), mImZ (1,1,0.0), mTImZ (mImZ) { for (int aK=0 ; aK<aNBXY2 ; aK++) { mXY2.push_back(Im2D_REAL4(aSz.x,aSz.y,0.0)); mVYY2.push_back(mXY2.back().data()); } mDXY2 = &(mVYY2[0]); } bool cMatrCorresp::IsOK(const Pt2di & aPRas) const { return mTImPds.get(aPRas,0) > 0; } Pt2dr cMatrCorresp::P1(const Pt2di & aPRas) const { return Pt2dr ( mTImX1.get(aPRas), mTImY1.get(aPRas) ); } void cMatrCorresp::SetXY2(const Pt2di & aPRas,double * aVXY2) const { for (int aK=0 ; aK<mNBXY2 ; aK++) aVXY2[aK] = mDXY2[aK][aPRas.y][aPRas.x]; } // Pt2dr P1 (const Pt2di & aPRas) const; // void SetXY2(const Pt2di &,double *) const; const Pt2di & cMatrCorresp::Sz() const { return mSz; } Output cMatrCorresp::StdHisto() { Output aRes = Virgule(mImPds.histo(),mImX1.histo(),mImY1.histo()); for (int aK=0 ; aK<int(mXY2.size()) ; aK++) aRes = Virgule(aRes,mXY2[aK].histo()); return aRes; } void cMatrCorresp::Normalize ( const cOneModeleAnalytique & aModele, const cGeomDiscFPx & aGT, cPriseDeVue & aPDV1, const cGeomImage & aGeom1, cPriseDeVue & aPDV2, const cGeomImage & aGeom2 ) { const cReCalclCorrelMultiEchelle * aRCCME=GetOnlyUseIt(aModele.ReCalclCorrelMultiEchelle()); bool isNuage3D = (aModele.TypeModele() == eTMA_Nuage3D); // A voir, sans doute un peu severe pour eTMA_Nuage3D if (isNuage3D) { mImZ = Im2D_REAL4(mSz.x,mSz.y,0.0); mTImZ = TIm2D<REAL4,REAL8>(mImZ); } else { ELISE_ASSERT ( aGeom1.IsId(), "Modele Analytique supose Geom1=Identite " ); } double aVXY2[theDimPxMax]; Pt2di aPRas; Im2D_REAL4 aIRCC(mSz.x,mSz.y,0.0); for (aPRas.x=0 ; aPRas.x<mSz.x ; aPRas.x++) { for (aPRas.y=0 ; aPRas.y<mSz.y ; aPRas.y++) { double aPds = mTImPds.get(aPRas); if ( aPds > 0) { Pt2dr aPTer ( mTImX1.get(aPRas)/aPds, mTImY1.get(aPRas)/aPds ); for (int aK=0; aK<mNBXY2; aK++) { aVXY2[aK] = mDXY2[aK][aPRas.y][aPRas.x]/ aPds; } aGT.PxDisc2PxReel(aVXY2,aVXY2); aPTer = aGT.RDiscToR2(aPTer); if (isNuage3D) { Pt3dr aPE = aGeom1.Restit2Euclid(aPTer,aVXY2); mTImX1.oset(aPRas,aPE.x); mTImY1.oset(aPRas,aPE.y); mTImZ.oset(aPRas,aPE.z); if (aPRas.y==0) std::cout << aPRas.x << "\n"; } else { Pt2dr aQ1 = aGeom1.Objet2ImageInit_Euclid(aPTer,aVXY2); Pt2dr aQ2 = aGeom2.Objet2ImageInit_Euclid(aPTer,aVXY2); if (aRCCME!=0) { bool aMMin = aRCCME->AgregMin().Val(); double aCorAgr = aMMin ? 1e10 : 0; int aNb=0; for ( std::list<Pt2di>::const_iterator itScSz=aRCCME->ScaleSzW().begin(); itScSz!=aRCCME->ScaleSzW().end(); itScSz++ ) { aNb++; cMC_PairIm * aPair = mPairs[itScSz->x]; if (aPair==0) { mPairs[itScSz->x] = new cMC_PairIm(itScSz->x,aGT,aPDV1,aPDV2); aPair = mPairs[itScSz->x]; } double aCor = aPair->Correl(aPTer,itScSz->y,aVXY2); if (aMMin) ElSetMin(aCorAgr,aCor); else aCorAgr += aCor; } if (! aMMin) aCorAgr /= aNb; aIRCC.data()[aPRas.y][aPRas.x] = aCorAgr; // std::cout << "COR = " << aCorAgr << "\n"; if (aCorAgr < aRCCME->Seuil() ) { aPds = 0; mTImPds.oset(aPRas,0); } } if (aPds > 0) { mPackHomInit.Cple_Add(ElCplePtsHomologues(aQ1,aQ2,aPds)); aQ1 = aGeom2.CorrigeDist1(aQ1); aQ2 = aGeom2.CorrigeDist2(aQ2); mPackHomCorr.Cple_Add(ElCplePtsHomologues(aQ1,aQ2,aPds)); } } } } } if (aRCCME && (aRCCME->DoImg().Val())) { std::string aName= mAppli.FullDirResult() + std::string("CorME_") + mAppli.NameChantier() + std::string(".tif"); Tiff_Im::Create8BFromFonc(aName,aIRCC.sz(),Max(0,Min(255,128*(1+aIRCC.in())))); } } const ElPackHomologue & cMatrCorresp::PackHomCorr() const { return mPackHomCorr; } const ElPackHomologue & cMatrCorresp::PackHomInit() const { return mPackHomInit; } Im2D_REAL4 cMatrCorresp::ImPds() {return mImPds;} Im2D_REAL4 cMatrCorresp::ImAppX() {return mImX1;} Im2D_REAL4 cMatrCorresp::ImAppY() {return mImY1;} Im2D_REAL4 cMatrCorresp::ImAppZ() {return mImZ;} /*****************************************************************/ /* */ /* cMA_AffineOrient */ /* */ /*****************************************************************/ class cMA_AffineOrient { public : cMA_AffineOrient ( cAppliMICMAC & anAppli, cModeleAnalytiqueComp &, const cGeomDiscFPx & mGeoTer, bool L1, const Pt2di & aP, const ElPackHomologue & aPackHom ); void NoOp() {} void OneItere(bool isLast); void StateOri2(const std::string & aMes); void TestOri1Ori2(bool ShowAll,CamStenope &,CamStenope &); const ElPackHomologue & PackHom() const; Pt3dr CalcPtMoy(CamStenope &,CamStenope &); // Calcul une image de px tranverse "ideale", c.a.d celle obenue // si la realite etait l'ori void MakeImagePxRef(); private : cAppliMICMAC & mAppli; Pt2di mSzM; Im2D_REAL4 mImResidu; TIm2D<REAL4,REAL8> mTImResidu; Im2D_REAL4 mImPds; TIm2D<REAL4,REAL8> mTImPds; const cGeomDiscFPx & mGeoTer; int mPas; CamStenope * mOri1; CamStenope * mOri2; cOrientationConique * mOC1; cOrientationConique * mOC2; int mNbPtMin; CamStenope & mNewOri1; CamStenope & mNewOri2; CamStenope & mCam1; CamStenope & mCam2; ElPackHomologue mPack; cSetEqFormelles mSetEq; ElRotation3D mChR; cParamIntrinsequeFormel * mPIF; cCameraFormelle * mCamF1; cCameraFormelle * mCamF2; cCpleCamFormelle * mCpl12; double mFocale; }; const ElPackHomologue & cMA_AffineOrient::PackHom() const { return mPack; } Pt3dr cMA_AffineOrient::CalcPtMoy(CamStenope & anOri1,CamStenope & anOri2) { Pt3dr aSPt(0,0,0); double aSPds =0.0; for ( ElPackHomologue::iterator iT = mPack.begin(); iT != mPack.end(); iT++ ) { double aD; Pt3dr aP = anOri1.PseudoInter(iT->P1(),anOri2,iT->P2(),&aD); aSPds += iT->Pds(); aSPt = aSPt + aP * iT->Pds(); } return aSPt/aSPds; } void cMA_AffineOrient::TestOri1Ori2(bool ShowAll,CamStenope & anOri1,CamStenope & anOri2) { double aSEc2 =0; double aSEc =0; double aSP =0; for ( ElPackHomologue::iterator iT = mPack.begin(); iT != mPack.end(); iT++ ) { Pt2dr aQ1 = mCam1.F2toPtDirRayonL3(iT->P1()); Pt2dr aQ2 = mCam2.F2toPtDirRayonL3(iT->P2()); double aL = mCpl12->ResiduSigneP1P2(aQ1,aQ2); aL = ElAbs(aL*mFocale); double aD; anOri1.PseudoInter(iT->P1(),anOri2,iT->P2(),&aD); aSEc2 += ElSquare(aD)*iT->Pds(); aSEc += ElAbs(aD)*iT->Pds(); aSP += iT->Pds(); // double aRatio = aL/aD; // Pt2dr aP1 = mGeoTer.R2ToRDisc(iT->P1()); // Pt2di aI1 = round_down(aP1/mPas); /* { if (ShowAll) std::cout << aL << aP << "\n"; << iT->Pds() << " " << iT->P1() << " " << iT->P2() << " " << " RATIO = " << aL/aD << " " << " Ec Ang " << aL << " " << " D INTER = " << aD << "\n"; } */ } std::cout << "EC2 = " << sqrt(aSEc2/aSP) << " ECAbs = " << (aSEc/aSP) << "\n"; for ( std::list<cListTestCpleHomol>::iterator itC=mAppli.ListTestCpleHomol().begin(); itC !=mAppli.ListTestCpleHomol().end(); itC++ ) { // Pt2dr aP1 = itC->PtIm1(); // Pt2dr aP2 = itC->PtIm2(); double aD; Pt3dr aP = anOri1.PseudoInter(itC->PtIm1(),anOri2,itC->PtIm2(),&aD); std::cout << "VERIF " << aP << " " << aD << "\n"; } } void cMA_AffineOrient::StateOri2(const std::string & aMes) { // OO Pt3dr aSom = mOri2->orsommet_de_pdv_terrain(); Pt3dr aSom = mOri2->PseudoOpticalCenter(); Pt3dr aTr = mCamF2->RF().CurRot().tr(); std::cout << aMes << (aSom-aTr) << " " << aSom << " " << aTr << "\n"; } void cMA_AffineOrient::OneItere(bool isLast) { ElRotation3D aR1 = mCamF1->RF().CurRot(); ElRotation3D aR2 = mCamF2->RF().CurRot(); std::cout << "TR = " << (aR2.tr()-aR1.tr()) << "\n"; std::cout << "I = " << aR2.ImVect(Pt3dr(1,0,0)) << euclid(aR2.ImVect(Pt3dr(1,0,0))) << "\n"; std::cout << "J = " << aR2.ImVect(Pt3dr(0,1,0)) << euclid(aR2.ImVect(Pt3dr(0,1,0))) << "\n"; std::cout << "K = " << aR2.ImVect(Pt3dr(0,0,1)) << euclid(aR2.ImVect(Pt3dr(0,0,1))) << "\n"; mSetEq.AddContrainte(mPIF->StdContraintes(),true); mSetEq.AddContrainte(mCamF1->RF().StdContraintes(),true); mSetEq.AddContrainte(mCamF2->RF().StdContraintes(),true); double aSEc2 =0; double aSEc =0; double aSP =0; int aNbP=0; for ( ElPackHomologue::iterator iT = mPack.begin(); iT != mPack.end(); iT++ ) { // double aD = mCam1.EcartProj(iT->P1(),mCam2,iT->P2()); Pt2dr aQ1 = mCam1.F2toPtDirRayonL3(iT->P1()); Pt2dr aQ2 = mCam2.F2toPtDirRayonL3(iT->P2()); //double aL = mCpl12->ResiduSigneP1P2(aQ1,aQ2); double aL2 = mCpl12->AddLiaisonP1P2(aQ1,aQ2,iT->Pds(),false); aSEc2 += ElSquare(aL2)*iT->Pds(); aSEc += ElAbs(aL2)*iT->Pds(); aSP += iT->Pds(); Pt2dr aP1 = mGeoTer.R2ToRDisc(iT->P1()); Pt2di aI1 = round_down(aP1/mPas); mTImResidu.oset(aI1,aL2*mFocale); mTImPds.oset(aI1,iT->Pds()); if (iT->Pds() > 1e-5) aNbP++; } if (aNbP < mNbPtMin) { mAppli.MicMacErreur ( eErrNbPointInEqOriRel, "Pas assez de point pour equation d'orientation relative", "Zone de recouvrement trop faible" ); } mSetEq.SolveResetUpdate(); // if (isLast) { std::cout << aSEc2 << " " << aSP << " " << mPack.size() << " EQuad = " << (sqrt(aSEc2/aSP)*mFocale) << " EAbs = " << ((aSEc/aSP)*mFocale) << "\n"; } } void cMA_AffineOrient::MakeImagePxRef() { int aSsRes = 20; Pt2di aSzGlob = mAppli.SzOfResol(1); Pt2di aPRes1; Pt2di aPInd; cGeomDiscFPx aGDF = mAppli.GeomDFPxInit(); const cGeomImage & aGeom2 = mAppli.PDV2()->Geom(); double aZ0 = mNewOri2.GetAltiSol(); Pt2di aSzSR = (aSzGlob+Pt2di(aSsRes-1,aSsRes-1))/aSsRes; Im2D_REAL4 mImRes(aSzSR.x,aSzSR.y,0.0); TIm2D<REAL4,REAL8> mTImRes(mImRes); for (aPRes1.x=aPInd.x=0 ; aPRes1.x<aSzGlob.x ; aPRes1.x+=aSsRes,aPInd.x++) { for (aPRes1.y=aPInd.y=0 ; aPRes1.y<aSzGlob.y ; aPRes1.y+=aSsRes,aPInd.y++) { Pt2dr aPIm1 = aGDF.DiscToR2(aPRes1); Pt3dr aPTer = mNewOri1.ImEtZ2Terrain(aPIm1,aZ0); Pt2dr aPIm2 = mNewOri2.R3toF2(aPTer); Pt2dr aPx = aGeom2.P1P2ToPx(aPIm1,aPIm2); mTImRes.oset(aPInd,aPx.y); // std::cout << aPx.y << "\n"; // (aP2Ter.x,aP2Ter.y,mNewOri2.altisol()); // Pt2dr aPIm2 = mNewOri2.to_photo(aP3Ter); } } Tiff_Im::Create8BFromFonc ( "toto.tif", aSzGlob, Max(0,Min(255,120+100.0*mImRes.in(0)[Virgule(FX,FY)/double(aSsRes)])) ); } tParamAFocal aNoPAF; cMA_AffineOrient::cMA_AffineOrient ( cAppliMICMAC & anAppli, cModeleAnalytiqueComp & aModele, const cGeomDiscFPx & aGeoTer, bool L1, const Pt2di & aSzM, const ElPackHomologue & aPackHom ) : mAppli (anAppli), mSzM (aSzM), mImResidu (mSzM.x,mSzM.y), mTImResidu (mImResidu), mImPds (mSzM.x,mSzM.y), mTImPds (mImPds), mGeoTer (aGeoTer), mPas (aModele.Modele().PasCalcul()), mOri1 (aModele.mGeom1.GetOriNN()), mOri2 (aModele.mGeom2.GetOriNN()), mOC1 (new cOrientationConique(mOri1->StdExportCalibGlob())), mOC2 (new cOrientationConique(mOri2->StdExportCalibGlob())), // OO mOC1 (mOri1->OC() ? new cOrientationConique(*(mOri1->OC())) : 0), // OO mOC2 (mOri2->OC() ? new cOrientationConique(*(mOri2->OC())) : 0), mNbPtMin (aModele.Modele().NbPtMinValideEqOriRel().Val()), mNewOri1 (*(mOri1->Dupl())), mNewOri2 (*(mOri2->Dupl())), mCam1 (*mOri1), mCam2 (*mOri2), mPack (aPackHom), mSetEq ( (L1 ? cNameSpaceEqF::eSysL1Barrodale : cNameSpaceEqF::eSysPlein), mPack.size() ), mChR (Pt3dr(0,0,0),0,0,0), // mSetEq (cNameSpaceEqF::eSysL1Barrodale,mPack.size()), // On va donner des points corriges de la dist : // mPIF (mSetEq.NewParamIntrNoDist(1.0,Pt2dr(0,0))), mPIF (mSetEq.NewParamIntrNoDist(true,new CamStenopeIdeale(true,1.0,Pt2dr(0,0),aNoPAF))), mCamF1 (mPIF->NewCam ( cNameSpaceEqF::eRotFigee, mChR * mCam1.Orient().inv() ) ), mCamF2 (mPIF->NewCam ( cNameSpaceEqF::eRotBaseU, mChR * mCam2.Orient().inv(), mCamF1 ) ), mCpl12 (mSetEq.NewCpleCam(*mCamF1,*mCamF2)), mFocale (mOri1->Focale()) { mSetEq.SetClosed(); mPIF->SetFocFree(false); mPIF->SetPPFree(false); int aNbEtape = 9; int aFlag = 0; for ( std::list<int>::const_iterator itB = aModele.Modele().NumsAngleFiges().begin(); itB != aModele.Modele().NumsAngleFiges().end(); itB++ ) aFlag |= 1 << *itB; for (int aK=0 ; aK<aNbEtape ; aK++) { mCamF2->RF().SetFlagAnglFige(aFlag); /* mCamF2->RF().SetModeRot ( (aK<3) ? cNameSpaceEqF::eRotCOptFige : cNameSpaceEqF::eRotBaseU ); */ OneItere(aK==(aNbEtape-1)); } std::string aName = mAppli.FullDirResult() + std::string("Residus_Dz") + ToString(round_ni(mGeoTer.DeZoom())) + std::string("_") + mAppli.NameChantier() + std::string(".tif"); Tiff_Im aFileResidu ( aName.c_str(), mSzM, GenIm::u_int1, Tiff_Im::No_Compr, Tiff_Im::RGB ); mNewOri2.SetOrientation(mCamF2->RF().CurRot()); Pt3dr aPMoy = CalcPtMoy(mNewOri1,mNewOri2); mNewOri1.SetAltiSol(aPMoy.z); mNewOri2.SetAltiSol(aPMoy.z); std::string aNAu = aModele.Modele().AutomSelExportOri().Val(); std::string aNEx1 = aModele.Modele().AutomNamesExportOri1().Val(); std::string aNEx2 = aModele.Modele().AutomNamesExportOri2().Val(); std::string aNI1 = mAppli.PDV1()->Name(); std::string aNI2 = mAppli.PDV2()->Name(); std::string aNOri1 = mAppli.FullDirGeom() + StdNameFromCple(aModele.AutomExport(),aNAu,aNEx1,"@",aNI1,aNI2); std::string aNOri2 = mAppli.FullDirGeom() + StdNameFromCple(aModele.AutomExport(),aNAu,aNEx2,"@",aNI1,aNI2); bool aXmlRes = false; if (StdPostfix(aNOri1)== "xml") { aXmlRes = true; ELISE_ASSERT ( (StdPostfix(aNOri2)=="xml") && (mOC1!=0) && (mOC2!=0), "Incoherence in XML export for cMA_AffineOrient" ); // Les points de verifs, si ils existent n'ont pas de raison d'etre transposables mOC1->Verif().SetNoInit(); mOC2->Verif().SetNoInit(); ElRotation3D aR1 = mCamF1->RF().CurRot(); ElRotation3D aR2 = mCamF2->RF().CurRot(); mOC2->Externe() = From_Std_RAff_C2M(aR2,mOC2->Externe().ParamRotation().CodageMatr().IsInit()); mOC1->Externe().AltiSol().SetVal(aPMoy.z); mOC2->Externe().AltiSol().SetVal(aPMoy.z); mOC1->Externe().Profondeur().SetVal(ProfFromCam(aR1.inv(),aPMoy)); mOC2->Externe().Profondeur().SetVal(ProfFromCam(aR2.inv(),aPMoy)); } TestOri1Ori2(true,*mOri1,*mOri2); TestOri1Ori2(true,mNewOri1,mNewOri2); std::cout << "ZMoyen = " << aPMoy.z << "\n"; Fonc_Num aFoK = (mImPds.in()>0); Fonc_Num aFRes = Max(0,Min(255,128.0 +mImResidu.in()*20)); ELISE_COPY ( aFileResidu.all_pts(), aFoK*its_to_rgb(Virgule(aFRes,3.14,32*Abs(mImResidu.in()>0.5))) + (1-aFoK)*Virgule(255,0,0), aFileResidu.out() ); bool Exp1 = aModele.Modele().AutomNamesExportOri1().IsInit(); bool Exp2 = aModele.Modele().AutomNamesExportOri2().IsInit(); ELISE_ASSERT(Exp1 == Exp2,"Incoherence in AutomNamesExportOri"); if (Exp1) { std::cout << "EXPORT OOOOOOOOOOOOOOORI\n"; AssertAutomSelExportOriIsInit(aModele.Modele()); if(aXmlRes) { MakeFileXML(*mOC1,aNOri1,"MicMacForAPERO"); MakeFileXML(*mOC2,aNOri2,"MicMacForAPERO"); } else { ELISE_ASSERT(false,"Cannot write ori "); // OO mNewOri1.write_txt(aNOri1.c_str()); // OO mNewOri2.write_txt(aNOri2.c_str()); } } if (aModele.Modele().SigmaPixPdsExport().ValWithDef(-1) > 0) { double aPds = aModele.Modele().SigmaPixPdsExport().Val(); for ( ElPackHomologue::iterator iT = mPack.begin(); iT != mPack.end(); iT++ ) { Pt2dr aQ1 = mCam1.F2toPtDirRayonL3(iT->P1()); Pt2dr aQ2 = mCam2.F2toPtDirRayonL3(iT->P2()); double aL = ElAbs(mCpl12->ResiduSigneP1P2(aQ1,aQ2))*mFocale; double aP = ElSquare(aPds)/(ElSquare(aPds)+ElSquare(aL)); iT->Pds() *= aP; } } } /**********************************************************************/ /* */ /* cModeleAnalytiqueComp */ /* */ /**********************************************************************/ cModeleAnalytiqueComp::cModeleAnalytiqueComp ( cAppliMICMAC & anAppli, const cOneModeleAnalytique & aModele, cEtapeMecComp & anEtape ) : mSz (-1,-1), mAppli (anAppli), mModele (aModele), mEtape (&anEtape), mNbPx (anAppli.DimPx()), mPDV1 (*mAppli.PDV1()), mGeom1 (mPDV1.Geom()), mPDV2 (*mAppli.PDV2()), mGeom2 (mPDV2.Geom()), mGeoTer (mEtape->GeomTer()), mHomogr (cElHomographie::Id()), mHomogrInv (cElHomographie::Id()), mPolX (1,1.0), mPolY (1,1.0), mDegrPolAdd (mModele.DegrePol().ValWithDef(-1)), mPolXInv (1,1.0), mPolYInv (1,1.0), mNameXML (NameFile(true,"Homographie","xml")), mNameImX (NameFile(true,"ImageX","tif")), mNameImY (NameFile(true,"ImageY","tif")), mNameResX (NameFile(true,"ResiduX","tif")), mNameResY (NameFile(true,"ResiduY","tif")), mExpModeleGlobal ( mModele.FCND_ExportModeleGlobal().IsInit()), mAutomExport (0) { mGeoTer.SetClip(Pt2di(0,0),mGeoTer.SzDz()); } bool cModeleAnalytiqueComp::ExportGlob() const { return mExpModeleGlobal; } void cModeleAnalytiqueComp::MakeInverseModele() { mHomogrInv = mHomogr.Inverse(); if (mDegrPolAdd>0) { ElDistortionPolynomiale aDPol(mPolX,mPolY); ElDistortionPolynomiale aDPolInv = aDPol.NewPolynLeastSquareInverse ( mBoxPoly, mPolX.DMax() + 2 ); mPolXInv = aDPolInv.DistX(); mPolYInv = aDPolInv.DistY(); } } void cModeleAnalytiqueComp::LoadMA() { cElXMLTree aTree(mNameXML); mHomogr = aTree.GetUnique("Homographie")->GetElHomographie(); if (mDegrPolAdd>0) { mPolX = aTree.GetUnique("XPoly")->GetPolynome2D(); mPolY = aTree.GetUnique("YPoly")->GetPolynome2D(); mBoxPoly._p0 = aTree.GetUnique("PMinBox")->GetPt2dr(); mBoxPoly._p1 = aTree.GetUnique("PMaxBox")->GetPt2dr(); } MakeInverseModele(); } Pt2dr cModeleAnalytiqueComp::CorrecDirecte(const Pt2dr & aP) const { Pt2dr aQ = mHomogr.Direct(aP); if (mDegrPolAdd>0) { aQ = Pt2dr(mPolX(aQ),mPolY(aQ)); } return aQ; } Pt2dr cModeleAnalytiqueComp::CorrecInverse(const Pt2dr & aP) const { Pt2dr aQ = aP; if (mDegrPolAdd>0) { aQ = Pt2dr(mPolXInv(aQ),mPolYInv(aQ)); } return mHomogrInv.Direct(aQ); } Pt2dr cModeleAnalytiqueComp::Direct(Pt2dr aP) const { Pt2dr aQ = mGeom2.CorrigeDist1(aP); aQ = CorrecDirecte(aQ); aQ = mGeom2.InvCorrDist2(aQ); return aQ; } bool cModeleAnalytiqueComp::OwnInverse(Pt2dr & aP) const { aP = mGeom2.CorrigeDist2(aP); aP = CorrecInverse(aP); aP = mGeom2.InvCorrDist1(aP); return true; } std::string cModeleAnalytiqueComp::NameFile ( bool aDirMEc, const std::string & aName, const std::string & aPost ) { return (aDirMEc ? mAppli.FullDirMEC() : mAppli.FullDirGeom()) + mModele.NameExport().Val() + std::string("_") + mAppli.NameChantier() + std::string("_") + aName + std::string("_Num") + ToString(mEtape->Num()) + std::string(".") + aPost; } static Fonc_Num ToUC(Fonc_Num aF) { return Max(0,Min(255,128+aF)); } Fonc_Num cModeleAnalytiqueComp::ImPx(int aK) { return mEtape->KPx(aK).FileIm().in(); } void cModeleAnalytiqueComp::SolveHomographie(const ElPackHomologue & aPackHom) { mHomogr = cElHomographie(aPackHom,mModele.HomographieL2().Val()); mBoxPoly = Box2dr(Pt2dr(0,0),Pt2dr(0,0)); if (mDegrPolAdd >0) { ElPackHomologue aPck2 = aPackHom; Pt2dr aPMin(1e5,1e5); Pt2dr aPMax(-1e5,-1e5); for ( ElPackHomologue::iterator iT = aPck2.begin(); iT != aPck2.end(); iT++ ) { iT->P1() = mHomogr.Direct(iT->P1()); aPMin.SetInf(iT->P1()); aPMax.SetSup(iT->P1()); } double anAmpl = ElMax(dist8(aPMin),dist8(aPMax)); mBoxPoly = Box2dr(aPMin,aPMax); bool aPL2 = mModele.PolynomeL2().Val(); mPolX = aPck2.FitPolynome(aPL2,mDegrPolAdd,anAmpl,true); mPolY = aPck2.FitPolynome(aPL2,mDegrPolAdd,anAmpl,false); } // Polynome2dReal ElPackHomologue::FitPolynome { cElXMLFileIn aFileXML(mNameXML); aFileXML.PutElHomographie(mHomogr,"Homographie"); if (mDegrPolAdd >0) { cElXMLFileIn::cTag aTag(aFileXML,"PolynomeCompl"); aTag.NoOp(); aFileXML.PutPoly(mPolX,"XPoly"); aFileXML.PutPoly(mPolY,"YPoly"); aFileXML.PutPt2dr(mBoxPoly._p0,"PMinBox"); aFileXML.PutPt2dr(mBoxPoly._p1,"PMaxBox"); } } MakeInverseModele(); // Verification de la correction du calcul de l'inverse if (0) { int aNb=10; double aEps = 0.05; for (int aKx=0 ; aKx<= aNb ; aKx++) { double aPdsX = ElMax(aEps,ElMin(1-aEps,aKx/double(aNb))); for (int aKy=0 ; aKy<= aNb ; aKy++) { double aPdsY = ElMax(aEps,ElMin(1-aEps,aKy/double(aNb))); Pt2dr aPRas = Pt2dr (mSzGl.x*aPdsX, mSzGl.x*aPdsY); Pt2dr aPTer = mGeoTer.RDiscToR2(aPRas); Pt2dr aP1 = Direct(Pt2dr(aPTer)); Pt2dr aQ2 = Inverse(aP1); double anEr = euclid(aPTer,aQ2); if (anEr>0.05) { std::cout << "Erreur = " << anEr << "\n"; std::cout << aPRas << aPTer << "\n"; Pt2dr aP0 = aPTer; Pt2dr aP1 = mGeom2.CorrigeDist1(aP0); Pt2dr aP2 = CorrecDirecte(aP1); Pt2dr aP3 = mGeom2.InvCorrDist2(aP2); Pt2dr aQ0 = mGeom2.InvCorrDist1(aP1); std::cout << "pq0= " << euclid(aP0,aQ0) << aP0 << aQ0 << "\n"; Pt2dr aQ1 = CorrecInverse(aP2); std::cout << "pq1= " << euclid(aP1,aQ1) << aP1 << aQ1 << "\n"; Pt2dr aQ2 = mGeom2.CorrigeDist2(aP3); std::cout << "pq2= " << euclid(aP2,aQ2) << aP2 << aQ2 << "\n"; std::cout << "P3 " << aP3 << "\n"; ELISE_ASSERT(false,"MakeInverseModele Pb!!"); } } } } if (mModele.ExportImage().Val() || mModele.ReuseResiduelle().Val() ) { Im2D_REAL4 anImX(mSzGl.x,mSzGl.y); TIm2D<REAL4,REAL8> aTImX(anImX); Im2D_REAL4 anImY(mSzGl.x,mSzGl.y); TIm2D<REAL4,REAL8> aTImY(anImY); Pt2di aPRas; double aPX0[2] = {0.0,0.0}; for (aPRas.x=0 ; aPRas.x<mSzGl.x ; aPRas.x++) { for (aPRas.y=0 ; aPRas.y<mSzGl.y ; aPRas.y++) { Pt2dr aPTer = mGeoTer.DiscToR2(aPRas); Pt2dr aP1 = Direct(Pt2dr(aPTer)); Pt2dr aP2 ; if (mModele.ReuseResiduelle().Val()) aP2 = mGeom2.Objet2ImageInit_Euclid(Pt2dr(aPTer),aPX0); else aP2 = mGeom2.InvCorrDist2(mGeom2.CorrigeDist1(aPTer)); double aPx[2]; aPx[0] = aP1.x- aP2.x; aPx[1] = aP1.y- aP2.y; mGeoTer.PxReel2PxDisc(aPx,aPx); aTImX.oset(aPRas,aPx[0]); aTImY.oset(aPRas,aPx[1]); } } if (mModele.ExportImage().Val()) { Tiff_Im::Create8BFromFonc(mNameImX,mSzGl,ToUC(anImX.in())); Tiff_Im::Create8BFromFonc(mNameImY,mSzGl,ToUC(anImY.in())); } if (mModele.ReuseResiduelle().Val()) { Tiff_Im::Create8BFromFonc(mNameResX,mSzGl,ToUC(anImX.in()-ImPx(0))); Tiff_Im::Create8BFromFonc(mNameResY,mSzGl,ToUC(anImY.in()-ImPx(1))); } } if (mExpModeleGlobal) { const cGeomDiscFPx & aG = mAppli.GeomDFPxInit() ; Box2dr aBox = aG.BoxEngl(); double aME =mModele.MailleExport().Val(); cDbleGrid aGrid ( true, aBox._p0,aBox._p1, Pt2dr(aME,aME), *this, "toto" ); std::string aNameXML = mAppli.ICNM()->Assoc1To2 ( mModele.FCND_ExportModeleGlobal().Val(), mAppli.PDV1()->Name(), mAppli.PDV2()->Name(), true ); aGrid.SaveXML(mAppli.FullDirResult() + aNameXML); } } cMatrCorresp * cModeleAnalytiqueComp::GetMatr(int aPas,bool PointUnique) { int aDz = mEtape->DeZoomTer(); mSzGl = mAppli.SzOfResol(aDz); mSz = (mSzGl+Pt2di(aPas-1,aPas-1))/aPas; cMatrCorresp * pMatr = new cMatrCorresp (mAppli,mSz,mNbPx); Fonc_Num aFPds = mAppli.FoncMasqOfResol(aDz); if (mAppli.OneDefCorAllPxDefCor().Val()) aFPds = aFPds && mEtape->FileMasqOfNoDef().in(); if (PointUnique) { aFPds = aFPds * ((FX%aPas)==(aPas/2)) * ((FY%aPas)==(aPas/2)); } // std::cout << "AAAAAAAAAa\n"; if (mModele.FiltreByCorrel().Val()) { Im1D_REAL8 aLut(256); double aS = mModele.SeuilFiltreCorrel().Val(); double anExp = mModele.ExposantPondereCorrel().Val(); Fonc_Num FC = FX/128.0-1; ELISE_COPY ( aLut.all_pts(), (mModele.UseFCBySeuil().Val()) ? (FC>=aS) : pow(Max(0.0,FC-aS),anExp), aLut.out() ); aFPds = aFPds * aLut.in()[mEtape->LastFileCorrelOK().in()]; /* double aS = mModele.SeuilFiltreCorrel().Val(); Fonc_Num FC = mEtape->LastFileCorrelOK().in()/128.0-1; if (mModele.UseFCBySeuil().Val()) aFPds = aFPds * (FC>=aS); else aFPds = aFPds * Max(0.0,(FC-aS)); */ } Symb_FNum fM(aFPds); /* { double aSom; ELISE_COPY ( rectangle(Pt2di(0,0),mSzGl), fM, sigma(aSom) ); std::cout << "SssDSOM = " << aSom << "\n"; getchar(); } */ Fonc_Num aFonc = Virgule(fM,fM*FX,fM*FY); for (int aK=0; aK<mNbPx ; aK++) { aFonc = Virgule(aFonc,fM*ImPx(aK)); } ELISE_COPY ( rectangle(Pt2di(0,0),mSzGl), aFonc, pMatr->StdHisto().chc(Virgule(FX,FY)/aPas) ); pMatr->Normalize(mModele,mGeoTer,mPDV1,mGeom1,mPDV2,mGeom2); return pMatr; } void cModeleAnalytiqueComp::TifSauvHomologues(const ElPackHomologue & aPack) { int aPas = mModele.PasCalcul(); if (! mModele.AutomNamesExportHomTif().IsInit()) return; ELISE_ASSERT ( mAppli.ExportForMultiplePointsHomologues().Val(), "TifSauvHom, No::ExportForMultiplePointsHomologues" ); if (mAppli.EchantillonagePtsInterets().IsInit()) { ELISE_ASSERT ( mAppli.EchantillonagePtsInterets().IsInit(), "TifSauvHom, No::EchantillonagePtsInterets" ); ELISE_ASSERT ( mAppli.EchantillonagePtsInterets().Val().FreqEchantPtsI()==aPas, "TifSauvHom, PasCalcul!=FreqEchantPtsI" ); } Pt2di aSzR = (mAppli.PDV1()->SzIm() + Pt2di(aPas-1,aPas-1)) / aPas; cElImPackHom aImPack(aPack,aPas,aSzR); std::string aNameTif = StdNameFromCple ( mAutomExport, mModele.AutomSelExportOri().Val(), mModele.AutomNamesExportHomTif().Val(), "@", mAppli.PDV1()->Name(), mAppli.PDV2()->Name() ); aImPack.SauvFile(mAppli.FullDirResult()+aNameTif); } // cDbleGrid void cModeleAnalytiqueComp::SauvHomologues(const ElPackHomologue & aPack) { TifSauvHomologues(aPack); if (mModele.AutomNamesExportHomXml().IsInit()) { AssertAutomSelExportOriIsInit(mModele); std::string aNameXML = StdNameFromCple ( mAutomExport, mModele.AutomSelExportOri().Val(), mModele.AutomNamesExportHomXml().Val(), "@", mAppli.PDV1()->Name(), mAppli.PDV2()->Name() ); cElXMLFileIn aFileXML(mAppli.FullDirResult()+aNameXML); aFileXML.PutPackHom(aPack); } if (mModele.KeyNamesExportHomXml().IsInit()) { std::string aNameXML = mAppli.ICNM()->Assoc1To2 ( mModele.KeyNamesExportHomXml().Val(), mAppli.PDV1()->Name(), mAppli.PDV2()->Name(), true ); // cElXMLFileIn aFileXML(mAppli.WorkDir()+aNameXML); // aFileXML.PutPackHom(aPack); aPack.StdPutInFile(mAppli.WorkDir()+aNameXML); } if (mModele.AutomNamesExportHomBin().IsInit()) { AssertAutomSelExportOriIsInit(mModele); std::string aNameBin = mAppli.FullDirResult() + StdNameFromCple ( mAutomExport, mModele.AutomSelExportOri().Val(), mModele.AutomNamesExportHomBin().Val(), "@", mAppli.PDV1()->Name(), mAppli.PDV2()->Name() ); ELISE_fp aFP (aNameBin.c_str(),ELISE_fp::WRITE); aPack.write(aFP); aFP.close(); } } bool cModeleAnalytiqueComp::FiltragePointHomologues ( const ElPackHomologue & aPackInit, ElPackHomologue & aNewPack, double aTol, double aFiltre ) { bool GotOut = false; Box2dr aBox1 = mAppli.PDV1()->BoxIm().AddTol(aTol); Box2dr aBox2 = mAppli.PDV2()->BoxIm().AddTol(aTol); Box2dr aBoxF1 = mAppli.PDV1()->BoxIm().AddTol(aFiltre); Box2dr aBoxF2 = mAppli.PDV2()->BoxIm().AddTol(aFiltre); for ( ElPackHomologue::const_iterator iT = aPackInit.begin(); iT != aPackInit.end(); iT++ ) { if ( ( aBoxF1.inside(iT->P1())) && ( aBoxF2.inside(iT->P2())) ) { bool thisOut = (! aBox1.inside(iT->P1())) || (! aBox2.inside(iT->P2())); if (thisOut) { std::cout << aBox1._p1 << aBox2._p1 << "\n"; std::cout << "OUT " << iT->P1() << " " << iT->P2() << " " << iT->Pds()<< "\n"; } GotOut = GotOut || thisOut; aNewPack.Cple_Add(iT->ToCple()); } } return GotOut; } void cModeleAnalytiqueComp::MakeExport() { if (!mModele.MakeExport().Val()) return; cMatrCorresp * pMatr = GetMatr(mModele.PasCalcul(),mModele.PointUnique().Val()); const ElPackHomologue * aPackIn =0; ElPackHomologue aPackRef; ElPackHomologue aNewPack; if (mModele.UseHomologueReference().Val()) { aPackRef = mAppli.PDV1()->ReadPackHom(mAppli.PDV2()); aPackIn = & aPackRef; } else { aPackIn = & pMatr->PackHomCorr(); } /* * FILTRAGE EVENTUEL DES POINTS HOMOLOGUES */ double aTol = mAppli.TolerancePointHomInImage().Val(); double aFiltre = mAppli.FiltragePointHomInImage().Val(); bool GotOut = false; switch (mModele.TypeModele()) { case eTMA_Homologues : SauvHomologues(pMatr->PackHomInit()); break; case eTMA_DHomD : // std::cout << "PKS = " << aPackIn->size() << "\n"; getchar(); SolveHomographie(*aPackIn); SauvHomologues(pMatr->PackHomInit()); break; case eTMA_Ori : { if ((aTol<1e10) || (aFiltre !=0)) { GotOut = FiltragePointHomologues(pMatr->PackHomInit(),aNewPack,aTol,aFiltre); aPackIn = & aNewPack; } SauvHomologues(pMatr->PackHomInit()); if (mModele.AffineOrient().Val()) { cMA_AffineOrient aMAAO ( mAppli, *this, mGeoTer, mModele.L1CalcOri().Val(), pMatr->Sz(), *aPackIn ); // SauvHomologues(*aPackIn); if (mModele.MakeImagePxRef().Val()) { aMAAO.MakeImagePxRef(); } } } break; case eTMA_Nuage3D : { std::string aNameRes = std::string("Nuage3D") + mAppli.NameChantier() + std::string(".tif"); if (mModele.KeyNuage3D().IsInit()) { aNameRes = mAppli.ICNM()->Assoc1To1 ( mModele.KeyNuage3D().Val(), mAppli.NameChantier(), true ); } aNameRes = mAppli.FullDirResult() + aNameRes; Tiff_Im aFile ( aNameRes.c_str(), pMatr->ImAppX().sz(), GenIm::real4, Tiff_Im::No_Compr, Tiff_Im::PtDAppuisDense ); ELISE_COPY ( aFile.all_pts(), Virgule ( pMatr->ImPds().in(), pMatr->ImAppX().in(), pMatr->ImAppY().in(), pMatr->ImAppZ().in() ), aFile.out() ); } break; default : ELISE_ASSERT(false,"TypeModeleAnalytique Non Traite"); break; } delete pMatr; if (GotOut) { mAppli.MicMacErreur ( eErrPtHomHorsImage, "Point Homologue Hors Image", "Specification Utilisateur sur la Tolerance : <TolerancePointHomInImage>" ); } } const cOneModeleAnalytique & cModeleAnalytiqueComp::Modele() const { return mModele; } // ACCESSEURS cElRegex_Ptr & cModeleAnalytiqueComp::AutomExport() { return mAutomExport; } }; /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant à la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. A cet égard l'attention de l'utilisateur est attirée sur les risques associés au chargement, à l'utilisation, à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant donné sa spécificité de logiciel libre, qui peut le rendre complexe à manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques approfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. Footer-MicMac-eLiSe-25/06/2007*/
29.52357
106
0.529102
kikislater
2f6690a81d5df2120c51d4a1ebb6a5acf2372a48
67
cpp
C++
cnd/cnd.modelimpl/test/unit/data/org/netbeans/modules/cnd/modelimpl/trace/FileModel2Test/bug256281.cpp
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
cnd/cnd.modelimpl/test/unit/data/org/netbeans/modules/cnd/modelimpl/trace/FileModel2Test/bug256281.cpp
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
cnd/cnd.modelimpl/test/unit/data/org/netbeans/modules/cnd/modelimpl/trace/FileModel2Test/bug256281.cpp
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
namespace bug256281 { typedef __sun_va_list __builtin_va_list; }
16.75
42
0.820896
leginee
2f6cdb5e6273277a1c0c07cd305f0dded94c81bc
340
cpp
C++
Competitive Programing Problem Solutions/Other/Sust Intra Contest/a.cpp
BIJOY-SUST/ACM---ICPC
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
1
2022-02-27T12:07:59.000Z
2022-02-27T12:07:59.000Z
Competitive Programing Problem Solutions/Other/Sust Intra Contest/a.cpp
BIJOY-SUST/Competitive-Programming
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
null
null
null
Competitive Programing Problem Solutions/Other/Sust Intra Contest/a.cpp
BIJOY-SUST/Competitive-Programming
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); set<int>s; int n; cin>>n; for(int i=0;i<n;i++){ int k; cin>>k; s.insert(k); } int a=n-s.size()+1; int b=n-a+1; cout<<a<<" "<<b<<"\n"; return 0; }
17
38
0.447059
BIJOY-SUST
2f6faf12900ebdb89f6dbcc3d6388523428b9eaa
6,097
cpp
C++
ivmpServer/networkManager.cpp
WuskieFTW1113/IV-MP-T4
ec4f193c90d23e07e6200dcb061ec8773be6bedc
[ "MIT" ]
2
2021-07-18T17:37:32.000Z
2021-08-04T12:33:51.000Z
ivmpServer/networkManager.cpp
VittorioC97/IV-MP-T4
ec4f193c90d23e07e6200dcb061ec8773be6bedc
[ "MIT" ]
1
2022-02-22T03:26:50.000Z
2022-02-22T03:26:50.000Z
ivmpServer/networkManager.cpp
WuskieFTW1113/IV-MP-T4
ec4f193c90d23e07e6200dcb061ec8773be6bedc
[ "MIT" ]
5
2021-06-17T06:41:00.000Z
2022-02-17T09:37:40.000Z
#include "networkManager.h" #include "RakPeer.h" #include <map> #include "../SharedDefines/easylogging++.h" #include "../SharedDefines/packetsIds.h" #include "playerConnectionState.h" #include "receiveFootSync.h" #include "receiveClientCredentials.h" #include "sendClientRequestedData.h" #include "vehicleSyncDeclarations.h" #include "receivePlayerChat.h" #include "vehStreamConfirmation.h" #include "checkPointsController.h" #include "objectsController.h" #include "dialogManager.h" #include "blipController.h" #include <time.h> typedef void (*ScriptFunction)(networkManager::connection* con, RakNet::BitStream &bsIn); std::map<int, ScriptFunction> handlers; std::map<int, ScriptFunction> conStates; networkManager::connection* cCon = NULL; void networkManager::initNetwork(int port) { cCon = new networkManager::connection; cCon->connectStat = 0; cCon->cTime = clock(); cCon->peer = RakNet::RakPeerInterface::GetInstance(); RakNet::SocketDescriptor r(port, 0); int rs = cCon->peer->Startup(50, &r, 1); if(rs != RakNet::RAKNET_STARTED) { mlog("Network startup failed: %i", rs); return; } cCon->peer->SetMaximumIncomingConnections(1000); conStates.insert(std::make_pair(ID_REMOTE_NEW_INCOMING_CONNECTION, playerConnected)); conStates.insert(std::make_pair(ID_NEW_INCOMING_CONNECTION, playerConnected)); conStates.insert(std::make_pair(ID_REMOTE_CONNECTION_LOST, playerDisconnected)); conStates.insert(std::make_pair(ID_REMOTE_DISCONNECTION_NOTIFICATION, playerDisconnected)); conStates.insert(std::make_pair(ID_CONNECTION_LOST, playerDisconnected)); handlers.insert(std::make_pair(ID_REMOTE_DISCONNECTION_NOTIFICATION, playerDisconnected)); //This is actually right, needed for /q handlers.insert(std::make_pair(FOOT_SYNC_TO_SERVER, clientFootSync)); handlers.insert(std::make_pair(WEAPON_CHANGE, clientChangedWeapon)); handlers.insert(std::make_pair(CHAR_DUCK_STATE, clientDuckStateChanged)); handlers.insert(std::make_pair(CLIENT_DEATH, clientDeath)); handlers.insert(std::make_pair(CLIENT_HAS_RESPAWNED, clientRespawned)); handlers.insert(std::make_pair(SET_HEALTH, clientHpChanged)); handlers.insert(std::make_pair(PLAYER_UPDATED_INTERIOR, clientInteriorChanged)); handlers.insert(std::make_pair(PLAYER_WEAPONS_INVENT, clientWeaponsRecieved)); handlers.insert(std::make_pair(GIVE_WEAPON, clientAmmoUpdated)); handlers.insert(std::make_pair(ARMOR_CHANGE, clientArmorUpdated)); handlers.insert(std::make_pair(CUSTOM_CHAT, clientChatUpdated)); handlers.insert(std::make_pair(ENTERING_VEHICLE, clientEnteringVehicle)); handlers.insert(std::make_pair(SEND_NICK_TO_SERVER, receiveClientNickName)); handlers.insert(std::make_pair(RUN_CHECKSUM, receiveCheckSum)); handlers.insert(std::make_pair(RUN_HACK_CHECK, receiveHackCheck)); handlers.insert(std::make_pair(REQUEST_PLAYER_DATA, sendPlayerFullData)); handlers.insert(std::make_pair(CLIENT_SPAWNED_PLAYER, playerSpawnedPlayer)); handlers.insert(std::make_pair(CLIENT_DELETED_PLAYER, playerDeletedPlayer)); handlers.insert(std::make_pair(SERVER_RECEIVE_VEHICLE_SYNC, clientVehicleSync)); handlers.insert(std::make_pair(SERVER_RECEIVE_PASSANGER_SYNC, clientVehiclePassangerSync)); handlers.insert(std::make_pair(PASSENGER_SYNC_WITH_POSITION, clientVehiclePassangerSyncWithPos)); handlers.insert(std::make_pair(CLIENT_REQUEST_VEHICLE_DATA, vehicleDataRequested)); handlers.insert(std::make_pair(CLIENT_SPAWNED_VEHICLE, clientSpawnedVehicle)); handlers.insert(std::make_pair(CLIENT_DELETED_VEHICLE, clientDeletedVehicle)); handlers.insert(std::make_pair(SINGLE_TYRE_POPPED, clientVehicleTyrePopped)); handlers.insert(std::make_pair(CAR_HP_UPDATE, clientVehicleHealth)); handlers.insert(std::make_pair(SIREN_STATE_CHANGED, clientVehicleSiren)); handlers.insert(std::make_pair(HORN_STATE_CHANGED, clientVehicleHorn)); handlers.insert(std::make_pair(VEHICLE_DIRT_LEVEL, clientVehicleDirt)); handlers.insert(std::make_pair(BILATERAL_MESSAGE, receivePlayerChat)); handlers.insert(std::make_pair(CHECK_POINT_CREATE, checkPointsController::checkPointSpawned)); handlers.insert(std::make_pair(CHECK_POINT_DELETE, checkPointsController::checkPointDeleted)); handlers.insert(std::make_pair(CHECK_POINT_ENTER, checkPointsController::checkPointEntered)); handlers.insert(std::make_pair(CHECK_POINT_EXIT, checkPointsController::checkPointExit)); handlers.insert(std::make_pair(OBJECT_CREATE, objectsController::spawnedObject)); handlers.insert(std::make_pair(OBJECT_DELETE, objectsController::deletedObject)); handlers.insert(std::make_pair(CLIENT_DIALOG_LIST_RESPONSE, dialogManager::listResponse)); handlers.insert(std::make_pair(BIND_PLAYER_KEY, clientKeyPress)); handlers.insert(std::make_pair(SPAWN_BLIP, blipController::blipSpawned)); handlers.insert(std::make_pair(DELETE_BLIP, blipController::blipRemoved)); handlers.insert(std::make_pair(TS_CONNECT, playerTeamSpeak)); cCon->connectStat = 1; } void networkManager::closeNetwork() { cCon->peer->~RakPeerInterface(); cCon->connectStat = 0; delete cCon; } networkManager::connection* networkManager::getConnection() { return cCon; } void networkManager::handlePackts() { cCon->cTime = clock(); for(cCon->packet = cCon->peer->Receive(); cCon->packet; cCon->peer->DeallocatePacket(cCon->packet), cCon->packet=cCon->peer->Receive()) { RakNet::BitStream bsIn(cCon->packet->data, cCon->packet->length, false); bsIn.IgnoreBytes(sizeof(MessageID)); if(conStates.find(cCon->packet->data[0]) != conStates.end()) { conStates.at(cCon->packet->data[0])(cCon, bsIn); continue; } else if(cCon->packet->data[0] != IVMP) { mlog("Message with invalid identifier %i has arrived", (int)cCon->packet->data[0]); continue; } int messageId = -1; bsIn.Read(messageId); try { if(handlers.find(messageId) != handlers.end()) handlers.at(messageId)(cCon, bsIn); } catch(std::exception&) { mlog("Message with invalid IVMP identifier %i has arrived", messageId); } } } bool networkManager::isNetworkActive() { if(cCon != NULL && cCon->connectStat > 0) { return true; } return false; }
38.345912
136
0.788257
WuskieFTW1113
2f75bbb51c6aed4aeb49d91246c363a2ec02c30d
1,266
cpp
C++
Apps/Examples/e08_OrbitManipulator/main.cpp
dormon/FitGL
de24984067f5307d01aebbc16ea366ce50e3c224
[ "CC0-1.0" ]
4
2016-09-19T13:32:58.000Z
2022-03-03T09:00:44.000Z
Apps/Examples/e08_OrbitManipulator/main.cpp
dormon/FitGL
de24984067f5307d01aebbc16ea366ce50e3c224
[ "CC0-1.0" ]
null
null
null
Apps/Examples/e08_OrbitManipulator/main.cpp
dormon/FitGL
de24984067f5307d01aebbc16ea366ce50e3c224
[ "CC0-1.0" ]
5
2016-10-21T12:33:52.000Z
2021-01-03T14:36:01.000Z
#include <BaseApp.h> int main(int /*argc*/, char ** /*argv*/) { BaseApp app; ProgramObject program; auto mainWindow = app.getMainWindow(); std::string prefix = app.getResourceDir() + "Shaders/Examples/e06_ModelLoader/"; PerspectiveCamera cam; OrbitManipulator manipulator(&cam); manipulator.setupCallbacks(app); NodeShared root; app.addInitCallback([&]() { auto vs = compileShader(GL_VERTEX_SHADER, Loader::text(prefix + "phong.vert")); auto fs = compileShader(GL_FRAGMENT_SHADER, Loader::text(prefix + "phong.frag")); program = createProgram(vs, fs); root = Loader::scene(app.getResourceDir() + "Models/sponza/sponza.fbx"); }); app.addResizeCallback([&](int w, int h) { glViewport(0, 0, w, h); cam.setAspect(float(w) / float(h)); }); app.addDrawCallback([&]() { glClearColor(0.2, 0.2, 0.2, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); //bunny program.use(); program.setMatrix4fv("p", value_ptr(cam.getProjection())); program.setMatrix4fv("v", value_ptr(cam.getView())); drawNode(program, root); fpsLabel(); label("Orbit manipulator:\nWSAD - Move center\nEQ - Up/Down\nRMB/LMB drag - rotate\nMMB drag - move center\nWheel - zoom",0,20,200,200); }); return app.run(); }
27.521739
138
0.690363
dormon
2f7859a389e4bcd6ad85854a663f5110d69c6448
459
cpp
C++
SourceCode/C++/Misc/LargestTest.cpp
dwgillies/OpenDSA
e012925896070a86bd7c3a4cbb75fa5682d9b9e2
[ "MIT" ]
200
2015-02-08T05:27:52.000Z
2022-03-23T02:44:38.000Z
SourceCode/C++/Misc/LargestTest.cpp
dwgillies/OpenDSA
e012925896070a86bd7c3a4cbb75fa5682d9b9e2
[ "MIT" ]
119
2015-03-22T22:38:21.000Z
2022-03-15T04:38:52.000Z
SourceCode/C++/Misc/LargestTest.cpp
dwgillies/OpenDSA
e012925896070a86bd7c3a4cbb75fa5682d9b9e2
[ "MIT" ]
105
2015-01-03T08:55:00.000Z
2022-03-19T00:51:45.000Z
/* *** ODSATag: Largest *** */ /** Return position of largest value in integer array A */ int largest(int A[], int size) { int currlarge = 0; // Position of largest element seen for (int i=1; i<size; i++) // For each element if (A[currlarge] < A[i]) // if A[i] is larger currlarge = i; // remember its position return currlarge; // Return largest position } /* *** ODSAendTag: Largest *** */
41.727273
68
0.555556
dwgillies
2f78bd027784244532019c8987c91101af0bbfe6
3,081
cpp
C++
http/alias.cpp
linbc/appweb2-win
ed9b55079cd427751e21ebdf122d5e3a1228f65c
[ "BSD-3-Clause" ]
null
null
null
http/alias.cpp
linbc/appweb2-win
ed9b55079cd427751e21ebdf122d5e3a1228f65c
[ "BSD-3-Clause" ]
null
null
null
http/alias.cpp
linbc/appweb2-win
ed9b55079cd427751e21ebdf122d5e3a1228f65c
[ "BSD-3-Clause" ]
1
2019-12-11T02:29:49.000Z
2019-12-11T02:29:49.000Z
/// /// @file alias.cpp /// @brief Alias service for aliasing URLs to file storage. /// @overview This module supports the alias directives and mapping /// URLs to physical locations. It also performs redirections. // ////////////////////////////////// Copyright /////////////////////////////////// // // @copy default // // Copyright (c) Mbedthis Software LLC, 2003-2007. All Rights Reserved. // // This software is distributed under commercial and open source licenses. // You may use the GPL open source license described below or you may acquire // a commercial license from Mbedthis Software. You agree to be fully bound // by the terms of either license. Consult the LICENSE.TXT distributed with // this software for full details. // // This software is open source; 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. See the GNU General Public License for more // details at: http://www.mbedthis.com/downloads/gplLicense.html // // This program is distributed WITHOUT ANY WARRANTY; without even the // implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // // This GPL license does NOT permit incorporating this software into // proprietary programs. If you are unable to comply with the GPL, you must // acquire a commercial license to use this software. Commercial licenses // for this software and support services are available from Mbedthis // Software at http://www.mbedthis.com // // @end // ////////////////////////////////// Includes //////////////////////////////////// #include "http.h" //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////// MaAlias /////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // WARNING: Note that the aliasName is a URL if a code is specified // (non-zero). Otherwise, the aliasName should be a document path // MaAlias::MaAlias(char *prefix, char *aliasName, int code) { this->prefix = mprStrdup(prefix); this->prefixLen = strlen(prefix); this->aliasName = mprStrdup(aliasName); redirectCode = code; inherited = false; #if WIN // // Windows is case insensitive for file names. Always map to lower case. // mprStrLower(this->prefix); mprStrLower(this->aliasName); #endif } //////////////////////////////////////////////////////////////////////////////// MaAlias::MaAlias(MaAlias *ap) { this->prefix = mprStrdup(ap->prefix); this->prefixLen = ap->prefixLen; this->aliasName = mprStrdup(ap->aliasName); redirectCode = ap->redirectCode; inherited = true; } //////////////////////////////////////////////////////////////////////////////// MaAlias::~MaAlias() { mprFree(prefix); mprFree(aliasName); } //////////////////////////////////////////////////////////////////////////////// // // Local variables: // tab-width: 4 // c-basic-offset: 4 // End: // vim: sw=4 ts=4 //
33.129032
80
0.580656
linbc
2f7e35c9080f2d52951a9c6d953e85d8844f565f
3,356
cpp
C++
old/src/resources/Material.cpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
5
2018-08-16T00:55:33.000Z
2020-06-19T14:30:17.000Z
old/src/resources/Material.cpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
null
null
null
old/src/resources/Material.cpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
null
null
null
#include "resources/Material.hpp" #include "core/LogicalDevice.hpp" #include "command/TransferPool.hpp" #include "resource/DescriptorSetLayout.hpp" #include "resource/DescriptorSet.hpp" #include "resource/Buffer.hpp" using namespace vpr; namespace vpsk { Material::Material(Material&& other) noexcept : ambient(std::move(other.ambient)), diffuse(std::move(other.diffuse)), specular(std::move(other.specular)), specularHighlight(std::move(other.specularHighlight)), bumpMap(std::move(other.bumpMap)), displacementMap(std::move(other.displacementMap)), alpha(std::move(other.alpha)), reflection(std::move(other.reflection)), ubo(std::move(other.ubo)), uboData(std::move(other.uboData)), setLayout(std::move(other.setLayout)), descriptorSet(std::move(other.descriptorSet)), pbrTextures(std::move(other.pbrTextures)), activeTextures(std::move(other.activeTextures)) {} Material & Material::operator=(Material && other) noexcept { ambient = std::move(other.ambient); diffuse = std::move(other.diffuse); specular = std::move(other.specular); specularHighlight = std::move(other.specularHighlight); bumpMap = std::move(other.bumpMap); displacementMap = std::move(other.displacementMap); alpha = std::move(other.alpha); reflection = std::move(other.reflection); ubo = std::move(other.ubo); uboData = std::move(other.uboData); descriptorSet = std::move(other.descriptorSet); pbrTextures = std::move(other.pbrTextures); activeTextures = std::move(other.activeTextures); setLayout = std::move(other.setLayout); return *this; } void Material::UploadToDevice(TransferPool* transfer_pool) { std::mutex transfer_mutex; std::lock_guard<std::mutex> transfer_guard(transfer_mutex); auto& cmd = transfer_pool->Begin(); while(!activeTextures.empty()) { auto& texture_to_transfer = activeTextures.front(); activeTextures.pop_front(); texture_to_transfer->TransferToDevice(cmd); } ubo->CopyTo(&uboData, cmd, sizeof(uboData), 0); if(pbrTextures) { pbrTextures->ubo->CopyTo(&pbrTextures->uboData, cmd, sizeof(pbrTextures->uboData), 0); } transfer_pool->Submit(); } void Material::BindMaterial(const VkCommandBuffer & cmd, const VkPipelineLayout& pipeline_layout) const noexcept { std::vector<VkDescriptorSet> descriptor_sets; descriptor_sets.push_back(descriptorSet->vkHandle()); if (pbrTextures) { descriptor_sets.push_back(pbrTextures->descriptorSet->vkHandle()); } vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, static_cast<uint32_t>(descriptor_sets.size()), descriptor_sets.data(), 0, nullptr); } VkDescriptorSetLayout Material::GetSetLayout() const noexcept { return setLayout->vkHandle(); } VkDescriptorSetLayout Material::GetPbrSetLayout() const noexcept { if (pbrTextures) { return pbrTextures->setLayout->vkHandle(); } else { return VK_NULL_HANDLE; } } void Material::createHashCode() { if (ambient != nullptr) { } if (diffuse != nullptr) { } } }
36.879121
321
0.661502
fuchstraumer
2f7ec922c705b640039c32fba114291b86f5e990
1,359
cpp
C++
aws-cpp-sdk-ssm/source/model/SessionFilter.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-ssm/source/model/SessionFilter.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-ssm/source/model/SessionFilter.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ssm/model/SessionFilter.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SSM { namespace Model { SessionFilter::SessionFilter() : m_key(SessionFilterKey::NOT_SET), m_keyHasBeenSet(false), m_valueHasBeenSet(false) { } SessionFilter::SessionFilter(JsonView jsonValue) : m_key(SessionFilterKey::NOT_SET), m_keyHasBeenSet(false), m_valueHasBeenSet(false) { *this = jsonValue; } SessionFilter& SessionFilter::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("key")) { m_key = SessionFilterKeyMapper::GetSessionFilterKeyForName(jsonValue.GetString("key")); m_keyHasBeenSet = true; } if(jsonValue.ValueExists("value")) { m_value = jsonValue.GetString("value"); m_valueHasBeenSet = true; } return *this; } JsonValue SessionFilter::Jsonize() const { JsonValue payload; if(m_keyHasBeenSet) { payload.WithString("key", SessionFilterKeyMapper::GetNameForSessionFilterKey(m_key)); } if(m_valueHasBeenSet) { payload.WithString("value", m_value); } return payload; } } // namespace Model } // namespace SSM } // namespace Aws
17.881579
91
0.71376
Neusoft-Technology-Solutions
2f8404b0da8d5dadac8a40e90321f91cb4f6f568
5,987
cpp
C++
src/common/MspImage.cpp
radiantbluetechnologies/ossim-msp-plugin
dd258ae54fd10cb5f3812b4e55e27ab1756b36ab
[ "MIT" ]
null
null
null
src/common/MspImage.cpp
radiantbluetechnologies/ossim-msp-plugin
dd258ae54fd10cb5f3812b4e55e27ab1756b36ab
[ "MIT" ]
null
null
null
src/common/MspImage.cpp
radiantbluetechnologies/ossim-msp-plugin
dd258ae54fd10cb5f3812b4e55e27ab1756b36ab
[ "MIT" ]
null
null
null
//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include "MspImage.h" #include <ossim/base/ossimException.h> #include <ossim/base/ossimString.h> #include <SensorModel/SensorModelService.h> #include <SupportData/SupportDataService.h> #include <common/csm/BytestreamIsd.h> using namespace std; using namespace ossim; namespace ossimMsp { MspImage::MspImage(const std::string& imageId, const std::string& filename, const std::string& modelName, unsigned int entryIndex, unsigned int band) : Image(imageId, filename, modelName, entryIndex, band), m_csmModel (0) { } MspImage::MspImage(const Json::Value& json_node) : Image(json_node), m_csmModel (0) { loadJSON(json_node); } MspImage::~MspImage() { //m_handler.reset(); } void MspImage::getAvailableModels(std::vector< pair<string, string> >& availableModels) const { // Fetch models from MSP: csm::Isd isd (m_filename); // TODO: Note entry index ignored here MSP::SMS::SensorModelService sms; sms.setPluginPreferencesRigorousBeforeRpc(); availableModels = sms.getAllSupportedModels(isd); } void MspImage::loadJSON(const Json::Value& json_node) { ostringstream xmsg; xmsg<<__FILE__<<": loadJSON(JSON) -- "; ossim::Image::loadJSON(json_node); // Entry index defaults to 0 if not present: if (json_node["imageIndex"].isUInt()) m_entryIndex = json_node["imageIndex"].asUInt(); // Sensor model defaults to most accurate available if not provided (indicated by blank name): if (json_node.isMember("pluginID")) m_modelName = json_node["pluginID"].asString(); // The imageName here corresponds to imageId: if (json_node.isMember("imageName")) m_imageId = json_node["imageName"].asString(); // The model state may have also defined an image ID. Id so, it must be the same as the name: if (json_node.isMember("imageID")) { string id_check = json_node["imageID"].asString(); if (id_check.compare(m_imageId)) { xmsg<<"The image name and model's imageID do not correspond!. Cannot load image from JSON."; throw ossimException(xmsg.str()); } } // Establish the sensor model. This also sets the official image ID, which will be overwritten // if JSON field provided string modelState = json_node["modelState"].asString(); if (modelState.empty()) modelState = json_node["stateData"].asString(); string isdData = json_node["imageSupportData"].asString(); if (modelState.size()) { MSP::SMS::SensorModelService sms; csm::Model* base = sms.createModelFromState(modelState.c_str()); m_csmModel = dynamic_cast<csm::RasterGM*>(base); string id = m_csmModel->getImageIdentifier(); if (id.compare("UNKNOWN")) m_imageId = id; else m_csmModel->setImageIdentifier(m_imageId); } else if (isdData.size()) { csm::BytestreamIsd isd (isdData); MSP::SMS::SensorModelService sms; csm::Model* base = sms.createModelFromISD(isd, m_modelName.c_str()); m_csmModel = dynamic_cast<csm::RasterGM*>(base); string id = m_csmModel->getImageIdentifier(); if (id.compare("UNKNOWN")) m_imageId = id; else m_csmModel->setImageIdentifier(m_imageId); } else { // Rely on image file for geometry info: getCsmSensorModel(); } } void MspImage::saveJSON(Json::Value& json_node) const { json_node.clear(); json_node["imageId"] = m_imageId; json_node["filename"] = m_filename.string(); json_node["entryIndex"] = m_entryIndex; if (m_modelName.size()) json_node["sensorModel"] = m_modelName; if (m_csmModel) { string state = m_csmModel->getModelState(); json_node["modelState"] = state; } } void MspImage::setCsmSensorModel(const csm::RasterGM* model) { ostringstream xmsg; xmsg<<__FILE__<<": getCsmSensorModel() -- "; try { MSP::SMS::SensorModelService sms; csm::Model* base = sms.createModelFromState(model->getModelState().c_str()); m_csmModel = dynamic_cast<csm::RasterGM*>(base); if (m_csmModel) { // Fetch the ID according to CSM, checking for "UNKNOWN": string id = m_csmModel->getImageIdentifier(); if (id.compare("UNKNOWN")) m_imageId = id; else m_csmModel->setImageIdentifier(m_imageId); } } catch (exception& e) { xmsg<<"Caught exception: "<<e.what(); throw ossimException(xmsg.str()); } m_modelName = model->getModelName(); } const csm::RasterGM* MspImage::getCsmSensorModel() { ostringstream xmsg; xmsg<<__FILE__<<": getCsmSensorModel() -- "; // May already be instantiated: if (m_csmModel) return m_csmModel; try { MSP::SMS::SensorModelService sms; const char* modelName = 0; if (m_modelName.size()) modelName = m_modelName.c_str(); MSP::ImageIdentifier entry ("IMAGE_INDEX", ossimString::toString(m_entryIndex).string()); sms.setPluginPreferencesRigorousBeforeRpc(); csm::Model* base = sms.createModelFromFile(m_filename.c_str(), modelName, &entry); m_csmModel = dynamic_cast<csm::RasterGM*>(base); if (m_csmModel) { // Fetch the ID according to CSM, checking for "UNKNOWN": string id = m_csmModel->getImageIdentifier(); if (id.compare("UNKNOWN")) m_imageId = id; else m_csmModel->setImageIdentifier(m_imageId); } } catch (exception& e) { xmsg<<"Caught exception: "<<e.what(); throw ossimException(xmsg.str()); } return m_csmModel; } } // end namespace ossimMsp
29.063107
101
0.632036
radiantbluetechnologies
2f89410f228523d1b2026468cb1b52dfb84de315
2,082
cc
C++
Common/View/Frustum.cc
mnrn/ReGL
922b36716ff29fa5ed8f18c078d2369ef9fba6a9
[ "MIT" ]
null
null
null
Common/View/Frustum.cc
mnrn/ReGL
922b36716ff29fa5ed8f18c078d2369ef9fba6a9
[ "MIT" ]
null
null
null
Common/View/Frustum.cc
mnrn/ReGL
922b36716ff29fa5ed8f18c078d2369ef9fba6a9
[ "MIT" ]
null
null
null
/** * @brief 視錐台クラス */ #include "View/Frustum.h" #include <boost/assert.hpp> #include <glm/gtc/constants.hpp> #include <glm/gtc/matrix_transform.hpp> #include <iostream> #include <vector> void Frustum::SetupPerspective(float fovy, float aspectRatio, float near, float far) { fovy_ = fovy; ar_ = aspectRatio; near_ = near; far_ = far; type_ = ProjectionType::Perspective; } void Frustum::SetupOrtho(float left, float right, float bottom, float top, float near, float far) { left_ = left; right_ = right; bottom_ = bottom; top_ = top; near_ = near; far_ = far; type_ = ProjectionType::Ortho; } void Frustum::SetupCorners(const glm::vec3 &eyePt, const glm::vec3 &lookatPt, const glm::vec3 &upVec) { corners_[0] = glm::vec3(-1.0, 1.0, 1.0); corners_[1] = glm::vec3(1.0, 1.0, 1.0); corners_[2] = glm::vec3(1.0, -1.0, 1.0); corners_[3] = glm::vec3(-1.0, -1.0, 1.0); corners_[4] = glm::vec3(-1.0, 1.0, -1.0); corners_[5] = glm::vec3(1.0, 1.0, -1.0); corners_[6] = glm::vec3(1.0, -1.0, -1.0); corners_[7] = glm::vec3(-1.0, -1.0, -1.0); const auto kView = glm::lookAt(eyePt, lookatPt, upVec); const auto kProj = GetProjectionMatrix(); const auto kInvVP = glm::inverse(kProj * kView); for (int i = 0; i < 8; i++) { const auto corner = kInvVP * glm::vec4(corners_[i], 1.0f); corners_[i] = glm::vec3(corner) / corner.w; } } BSphere Frustum::ComputeBSphere() const { glm::vec3 center = glm::vec3(0.0f); for (int i = 0; i < 8; i++) { center += corners_[i]; } center /= 8.0f; float radius = 0.0f; for (int i = 0; i < 8; i++) { float len = glm::length(corners_[i] - center); radius = glm::max(radius, len); } radius = std::ceil(radius * 16.0f) / 16.0f; return {center, radius}; } glm::mat4 Frustum::GetProjectionMatrix() const { if (type_ == ProjectionType::Perspective) { return glm::perspective(fovy_, ar_, near_, far_); } else { return glm::ortho(left_, right_, bottom_, top_, near_, far_); } }
26.025
77
0.596542
mnrn
2f900b25c6bce0c15327dda6fb0de9251ad3ea7a
22,028
cpp
C++
src/GUI/ServerBrowser.cpp
Olddies710/The-Forgotten-Client
8b7979619ea76bc29581122440d09f241afc175d
[ "Zlib" ]
1
2022-01-15T00:00:27.000Z
2022-01-15T00:00:27.000Z
src/GUI/ServerBrowser.cpp
Olddies710/The-Forgotten-Client
8b7979619ea76bc29581122440d09f241afc175d
[ "Zlib" ]
null
null
null
src/GUI/ServerBrowser.cpp
Olddies710/The-Forgotten-Client
8b7979619ea76bc29581122440d09f241afc175d
[ "Zlib" ]
3
2021-10-14T02:36:56.000Z
2022-03-22T21:03:31.000Z
/* The Forgotten Client Copyright (C) 2020 Saiyans King This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ // If some owner of otservlist wants to cooperate and will send me api then I can reimplement it #include "GUI_UTIL.h" #include "../engine.h" #include "../GUI_Elements/GUI_Window.h" #include "../GUI_Elements/GUI_Button.h" #include "../GUI_Elements/GUI_Separator.h" #include "../GUI_Elements/GUI_Grouper.h" #include "../game.h" #include "../http.h" #include "ServerBrowser.h" #define SERVERBROWSER_TITLE "Server Browser (Experimental)" #define SERVERBROWSER_WIDTH 636 #define SERVERBROWSER_HEIGHT 398 #define SERVERBROWSER_CANCEL_EVENTID 1000 #define SERVERBROWSER_OK_EVENTID 1001 #define SERVERBROWSER_LIST_EVENTID 1002 #define SERVERBROWSER_IP_TEXT "IP" #define SERVERBROWSER_IP_X 18 #define SERVERBROWSER_IP_Y 32 #define SERVERBROWSER_IP_W 100 #define SERVERBROWSER_IP_H 20 #define SERVERBROWSER_NAME_TEXT "Server Name" #define SERVERBROWSER_NAME_X 118 #define SERVERBROWSER_NAME_Y 32 #define SERVERBROWSER_NAME_W 100 #define SERVERBROWSER_NAME_H 20 #define SERVERBROWSER_PLAYERS_TEXT "Players/Max" #define SERVERBROWSER_PLAYERS_X 218 #define SERVERBROWSER_PLAYERS_Y 32 #define SERVERBROWSER_PLAYERS_W 100 #define SERVERBROWSER_PLAYERS_H 20 #define SERVERBROWSER_PVP_TEXT "PvP Type" #define SERVERBROWSER_PVP_X 318 #define SERVERBROWSER_PVP_Y 32 #define SERVERBROWSER_PVP_W 100 #define SERVERBROWSER_PVP_H 20 #define SERVERBROWSER_EXP_TEXT "EXP Ratio" #define SERVERBROWSER_EXP_X 418 #define SERVERBROWSER_EXP_Y 32 #define SERVERBROWSER_EXP_W 100 #define SERVERBROWSER_EXP_H 20 #define SERVERBROWSER_CLIENT_TEXT "Client Version" #define SERVERBROWSER_CLIENT_X 518 #define SERVERBROWSER_CLIENT_Y 32 #define SERVERBROWSER_CLIENT_W 100 #define SERVERBROWSER_CLIENT_H 20 #define SERVERBROWSER_BROWSER_EVENTID 1003 #define SERVERBROWSER_BROWSER_X 18 #define SERVERBROWSER_BROWSER_Y 52 #define SERVERBROWSER_BROWSER_W 600 #define SERVERBROWSER_BROWSER_H 300 extern Engine g_engine; extern Game g_game; extern Http g_http; extern Uint32 g_frameTime; struct Server_List { Server_List(std::string ip, std::string name, std::string type, Uint32 players, Uint32 playersMax, Uint32 expRatio, Uint32 version) : serverIp(std::move(ip)), serverName(std::move(name)), serverType(std::move(type)), serverPlayers(players), serverPlayersMax(playersMax), serverExpRatio(expRatio), serverVersion(version) {} // non-copyable Server_List(const Server_List&) = delete; Server_List& operator=(const Server_List&) = delete; // non-moveable Server_List(Server_List&& rhs) noexcept : serverIp(std::move(rhs.serverIp)), serverName(std::move(rhs.serverName)), serverType(std::move(rhs.serverType)), serverPlayers(rhs.serverPlayers), serverPlayersMax(rhs.serverPlayersMax), serverExpRatio(rhs.serverExpRatio), serverVersion(rhs.serverVersion) {} Server_List& operator=(Server_List&& rhs) noexcept { if(this != &rhs) { serverIp = std::move(rhs.serverIp); serverName = std::move(rhs.serverName); serverType = std::move(rhs.serverType); serverPlayers = rhs.serverPlayers; serverPlayersMax = rhs.serverPlayersMax; serverExpRatio = rhs.serverExpRatio; serverVersion = rhs.serverVersion; } return (*this); } std::string serverIp; std::string serverName; std::string serverType; Uint32 serverPlayers; Uint32 serverPlayersMax; Uint32 serverExpRatio; Uint32 serverVersion; }; std::vector<Server_List> g_serverList; Uint32 g_requestPage = 0; Uint32 g_requestId = 0; Uint32 g_selectedServer = SDL_static_cast(Uint32, -1); Uint32 g_lastServerClick = 0; void ServerBrowser_Recreate(GUI_ServerBrowserContainer* container); void serverbrowser_Events(Uint32 event, Sint32 status) { switch(event) { case SERVERBROWSER_CANCEL_EVENTID: { GUI_Window* pWindow = g_engine.getCurrentWindow(); if(pWindow && pWindow->getInternalID() == GUI_WINDOW_SERVERBROWSER) { g_engine.removeWindow(pWindow); g_serverList.clear(); g_serverList.shrink_to_fit(); if(g_requestId != 0) { g_http.removeRequest(g_requestId); g_requestId = 0; } } } break; case SERVERBROWSER_OK_EVENTID: { GUI_Window* pWindow = g_engine.getCurrentWindow(); if(pWindow && pWindow->getInternalID() == GUI_WINDOW_SERVERBROWSER) { g_engine.removeWindow(pWindow); if(g_selectedServer != SDL_static_cast(Uint32, -1)) { if(g_selectedServer < SDL_static_cast(Uint32, g_serverList.size())) { Server_List& serverList = g_serverList[g_selectedServer]; g_engine.setClientHost(serverList.serverIp); g_engine.setClientPort("7171");//TODO - detect port g_clientVersion = serverList.serverVersion; g_game.clientChangeVersion(g_clientVersion, g_clientVersion); } } g_serverList.clear(); g_serverList.shrink_to_fit(); if(g_requestId != 0) { g_http.removeRequest(g_requestId); g_requestId = 0; } } } break; case SERVERBROWSER_LIST_EVENTID: { if(g_requestId == SDL_static_cast(Uint32, status)) { HttpRequest* request = g_http.getRequest(SDL_static_cast(Uint32, status)); if(request) //Don't depend on result here because for some reason curl return recv error for otservlist.org even when we actually received data { SDL_snprintf(g_buffer, sizeof(g_buffer), "%sbrowser.dat", g_prefPath.c_str()); SDL_RWops* fp = SDL_RWFromFile(g_buffer, "rb"); if(fp) { size_t sizeData = SDL_static_cast(size_t, SDL_RWsize(fp)); if(sizeData <= 0) { SDL_RWclose(fp); #ifdef SDL_FILESYSTEM_WINDOWS DeleteFileA(g_buffer); #elif HAVE_STDIO_H remove(g_buffer); #endif return; } std::vector<char> msgData(sizeData); SDL_RWread(fp, &msgData[0], 1, sizeData); SDL_RWclose(fp); #ifdef SDL_FILESYSTEM_WINDOWS DeleteFileA(g_buffer); #elif HAVE_STDIO_H remove(g_buffer); #endif char* readData = &msgData[0]; //Check whether the page we are in exist Sint32 len = SDL_snprintf(g_buffer, sizeof(g_buffer), "class=\"b highlight\">%u</a>", g_requestPage); if(UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)) != std::string::npos) { std::string serverIp; std::string serverName; std::string serverType; Uint32 serverPlayers = 0; Uint32 serverPlayersMax = 0; Uint32 serverExpRatio = 0; Uint32 serverVersion = 0; while(true) { len = SDL_snprintf(g_buffer, sizeof(g_buffer), "<th class=\"pl-15\"><a href"); size_t searchData = UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)); if(searchData == std::string::npos) break; readData += searchData + len; sizeData -= searchData + len; len = SDL_snprintf(g_buffer, sizeof(g_buffer), "\">"); searchData = UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)); if(searchData == std::string::npos) break; readData += searchData + len; sizeData -= searchData + len; len = SDL_snprintf(g_buffer, sizeof(g_buffer), "</a></th>"); searchData = UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)); if(searchData == std::string::npos) break; serverIp = std::string(readData, searchData); readData += searchData + len; sizeData -= searchData + len; len = SDL_snprintf(g_buffer, sizeof(g_buffer), "</th><th>"); searchData = UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)); if(searchData == std::string::npos) break; readData += searchData + len; sizeData -= searchData + len; len = SDL_snprintf(g_buffer, sizeof(g_buffer), "</th><th>"); searchData = UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)); if(searchData == std::string::npos) break; serverName = std::string(readData, searchData); readData += searchData + len; sizeData -= searchData + len; len = SDL_snprintf(g_buffer, sizeof(g_buffer), " / "); searchData = UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)); if(searchData == std::string::npos) break; serverPlayers = SDL_static_cast(Uint32, SDL_strtoul(readData, NULL, 10)); readData += searchData + len; sizeData -= searchData + len; serverPlayersMax = SDL_static_cast(Uint32, SDL_strtoul(readData, NULL, 10)); len = SDL_snprintf(g_buffer, sizeof(g_buffer), "</th><th>"); searchData = UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)); if(searchData == std::string::npos) break; readData += searchData + len; sizeData -= searchData + len; len = SDL_snprintf(g_buffer, sizeof(g_buffer), "</th><th>"); searchData = UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)); if(searchData == std::string::npos) break; readData += searchData + len; sizeData -= searchData + len; len = SDL_snprintf(g_buffer, sizeof(g_buffer), "</th><th>"); searchData = UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)); if(searchData == std::string::npos) break; readData += searchData + len; sizeData -= searchData + len; serverExpRatio = SDL_static_cast(Uint32, SDL_strtoul(readData + 1, NULL, 10)); len = SDL_snprintf(g_buffer, sizeof(g_buffer), "</th><th>"); searchData = UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)); if(searchData == std::string::npos) break; readData += searchData + len; sizeData -= searchData + len; len = SDL_snprintf(g_buffer, sizeof(g_buffer), "</th><th>[ "); searchData = UTIL_Faststrstr(readData, sizeData, g_buffer, SDL_static_cast(size_t, len)); if(searchData == std::string::npos) break; serverType = std::string(readData, searchData); readData += searchData + len; sizeData -= searchData + len; serverVersion = SDL_static_cast(Uint32, SDL_strtoul(readData, &readData, 10)) * 100; Uint32 lowerVersion = SDL_static_cast(Uint32, SDL_strtoul(readData + 1, NULL, 10)); if(lowerVersion < 10) lowerVersion *= 10; serverVersion += lowerVersion; if(serverVersion != 0) // Only non-custom servers g_serverList.emplace_back(std::move(serverIp), std::move(serverName), std::move(serverType), serverPlayers, serverPlayersMax, serverExpRatio, serverVersion); } ServerBrowser_Recreate(NULL); void ServerBrowser_RequestPage(); ServerBrowser_RequestPage(); } } } } } break; default: break; } } void ServerBrowser_RequestPage() { std::stringExtended website(1024); website << "https://otservlist.org/list-server_players_online-desc-" << (++g_requestPage) << ".html"; SDL_snprintf(g_buffer, sizeof(g_buffer), "%sbrowser.dat", g_prefPath.c_str()); g_requestId = g_http.addRequest(website, g_buffer, std::string(), &serverbrowser_Events, SERVERBROWSER_LIST_EVENTID); } void ServerBrowser_Recreate(GUI_ServerBrowserContainer* container) { std::sort(g_serverList.begin(), g_serverList.end(), [](Server_List& a, Server_List& b) -> bool {return a.serverPlayers > b.serverPlayers;}); if(!container) { GUI_Window* pWindow = g_engine.getWindow(GUI_WINDOW_SERVERBROWSER); if(pWindow) container = SDL_static_cast(GUI_ServerBrowserContainer*, pWindow->getChild(SERVERBROWSER_BROWSER_EVENTID)); if(!container) return; } container->clearChilds(false); Sint32 PosY = -9; for(std::vector<Server_List>::iterator it = g_serverList.begin(), end = g_serverList.end(); it != end; ++it) { Server_List& serverList = (*it); GUI_ServerBrowserEntry* newServerBrowserEntry = new GUI_ServerBrowserEntry(iRect(SERVERBROWSER_IP_X - 13, PosY, SERVERBROWSER_BROWSER_W - 12, 20), SDL_static_cast(Uint32, std::distance(g_serverList.begin(), it))); newServerBrowserEntry->setServerIp(serverList.serverIp); newServerBrowserEntry->setServerName(serverList.serverName); SDL_snprintf(g_buffer, sizeof(g_buffer), "%u / %u", serverList.serverPlayers, serverList.serverPlayersMax); newServerBrowserEntry->setServerPlayers(g_buffer); newServerBrowserEntry->setServerType(serverList.serverType); SDL_snprintf(g_buffer, sizeof(g_buffer), "X%u", serverList.serverExpRatio); newServerBrowserEntry->setServerExp(g_buffer); SDL_snprintf(g_buffer, sizeof(g_buffer), "%u.%02u", (serverList.serverVersion / 100), (serverList.serverVersion % 100)); newServerBrowserEntry->setServerVersion(g_buffer); newServerBrowserEntry->startEvents(); container->addChild(newServerBrowserEntry, false); PosY += 20; } container->validateScrollBar(); } void UTIL_createServerBrowser() { GUI_Window* pWindow = g_engine.getWindow(GUI_WINDOW_SERVERBROWSER); if(pWindow) g_engine.removeWindow(pWindow); g_serverList.clear(); g_requestPage = 0; g_requestId = 0; g_selectedServer = SDL_static_cast(Uint32, -1); GUI_Window* newWindow = new GUI_Window(iRect(0, 0, SERVERBROWSER_WIDTH, SERVERBROWSER_HEIGHT), SERVERBROWSER_TITLE, GUI_WINDOW_SERVERBROWSER); GUI_Grouper* newGrouper = new GUI_Grouper(iRect(SERVERBROWSER_IP_X, SERVERBROWSER_IP_Y, SERVERBROWSER_IP_W, SERVERBROWSER_IP_H)); newWindow->addChild(newGrouper); newGrouper = new GUI_Grouper(iRect(SERVERBROWSER_NAME_X, SERVERBROWSER_NAME_Y, SERVERBROWSER_NAME_W, SERVERBROWSER_NAME_H)); newWindow->addChild(newGrouper); newGrouper = new GUI_Grouper(iRect(SERVERBROWSER_PLAYERS_X, SERVERBROWSER_PLAYERS_Y, SERVERBROWSER_PLAYERS_W, SERVERBROWSER_PLAYERS_H)); newWindow->addChild(newGrouper); newGrouper = new GUI_Grouper(iRect(SERVERBROWSER_PVP_X, SERVERBROWSER_PVP_Y, SERVERBROWSER_PVP_W, SERVERBROWSER_PVP_H)); newWindow->addChild(newGrouper); newGrouper = new GUI_Grouper(iRect(SERVERBROWSER_EXP_X, SERVERBROWSER_EXP_Y, SERVERBROWSER_EXP_W, SERVERBROWSER_EXP_H)); newWindow->addChild(newGrouper); newGrouper = new GUI_Grouper(iRect(SERVERBROWSER_CLIENT_X, SERVERBROWSER_CLIENT_Y, SERVERBROWSER_CLIENT_W, SERVERBROWSER_CLIENT_H)); newWindow->addChild(newGrouper); newGrouper = new GUI_Grouper(iRect(SERVERBROWSER_BROWSER_X, SERVERBROWSER_BROWSER_Y, SERVERBROWSER_BROWSER_W, SERVERBROWSER_BROWSER_H)); newWindow->addChild(newGrouper); GUI_DynamicLabel* newDynamicLabel = new GUI_DynamicLabel(iRect(SERVERBROWSER_IP_X + 5, SERVERBROWSER_IP_Y + 5, SERVERBROWSER_IP_W - 10, 12), SERVERBROWSER_IP_TEXT); newWindow->addChild(newDynamicLabel); newDynamicLabel = new GUI_DynamicLabel(iRect(SERVERBROWSER_NAME_X + 5, SERVERBROWSER_NAME_Y + 5, SERVERBROWSER_NAME_W - 10, 12), SERVERBROWSER_NAME_TEXT); newWindow->addChild(newDynamicLabel); newDynamicLabel = new GUI_DynamicLabel(iRect(SERVERBROWSER_PLAYERS_X + 5, SERVERBROWSER_PLAYERS_Y + 5, SERVERBROWSER_PLAYERS_W - 10, 12), SERVERBROWSER_PLAYERS_TEXT); newWindow->addChild(newDynamicLabel); newDynamicLabel = new GUI_DynamicLabel(iRect(SERVERBROWSER_PVP_X + 5, SERVERBROWSER_PVP_Y + 5, SERVERBROWSER_PVP_W - 10, 12), SERVERBROWSER_PVP_TEXT); newWindow->addChild(newDynamicLabel); newDynamicLabel = new GUI_DynamicLabel(iRect(SERVERBROWSER_EXP_X + 5, SERVERBROWSER_EXP_Y + 5, SERVERBROWSER_EXP_W - 10, 12), SERVERBROWSER_EXP_TEXT); newWindow->addChild(newDynamicLabel); newDynamicLabel = new GUI_DynamicLabel(iRect(SERVERBROWSER_CLIENT_X + 5, SERVERBROWSER_CLIENT_Y + 5, SERVERBROWSER_CLIENT_W - 10, 12), SERVERBROWSER_CLIENT_TEXT); newWindow->addChild(newDynamicLabel); GUI_ServerBrowserContainer* newContainer = new GUI_ServerBrowserContainer(iRect(SERVERBROWSER_BROWSER_X + 1, SERVERBROWSER_BROWSER_Y + 1, SERVERBROWSER_BROWSER_W - 2, SERVERBROWSER_BROWSER_H - 2), SERVERBROWSER_BROWSER_EVENTID); newContainer->startEvents(); newWindow->addChild(newContainer); GUI_Button* newButton = new GUI_Button(iRect(SERVERBROWSER_WIDTH - 56, SERVERBROWSER_HEIGHT - 30, GUI_UI_BUTTON_43PX_GRAY_UP_W, GUI_UI_BUTTON_43PX_GRAY_UP_H), "Cancel", CLIENT_GUI_ESCAPE_TRIGGER); newButton->setButtonEventCallback(&serverbrowser_Events, SERVERBROWSER_CANCEL_EVENTID); newButton->startEvents(); newWindow->addChild(newButton); newButton = new GUI_Button(iRect(SERVERBROWSER_WIDTH - 109, SERVERBROWSER_HEIGHT - 30, GUI_UI_BUTTON_43PX_GRAY_UP_W, GUI_UI_BUTTON_43PX_GRAY_UP_H), "Ok", CLIENT_GUI_ENTER_TRIGGER); newButton->setButtonEventCallback(&serverbrowser_Events, SERVERBROWSER_OK_EVENTID); newButton->startEvents(); newWindow->addChild(newButton); GUI_Separator* newSeparator = new GUI_Separator(iRect(13, SERVERBROWSER_HEIGHT - 40, SERVERBROWSER_WIDTH - 26, 2)); newWindow->addChild(newSeparator); g_engine.addWindow(newWindow); ServerBrowser_RequestPage(); } void GUI_ServerBrowserContainer::render() { GUI_Container::render(); Sint32 startX = m_tRect.x1 + SERVERBROWSER_IP_W - 2; auto& render = g_engine.getRender(); render->drawPictureRepeat(GUI_UI_IMAGE, GUI_UI_ICON_VERTICAL_SEPARATOR_X, GUI_UI_ICON_VERTICAL_SEPARATOR_Y, GUI_UI_ICON_VERTICAL_SEPARATOR_W, GUI_UI_ICON_VERTICAL_SEPARATOR_H, startX, m_tRect.y1, 2, m_tRect.y2); startX += SERVERBROWSER_NAME_W; render->drawPictureRepeat(GUI_UI_IMAGE, GUI_UI_ICON_VERTICAL_SEPARATOR_X, GUI_UI_ICON_VERTICAL_SEPARATOR_Y, GUI_UI_ICON_VERTICAL_SEPARATOR_W, GUI_UI_ICON_VERTICAL_SEPARATOR_H, startX, m_tRect.y1, 2, m_tRect.y2); startX += SERVERBROWSER_PLAYERS_W; render->drawPictureRepeat(GUI_UI_IMAGE, GUI_UI_ICON_VERTICAL_SEPARATOR_X, GUI_UI_ICON_VERTICAL_SEPARATOR_Y, GUI_UI_ICON_VERTICAL_SEPARATOR_W, GUI_UI_ICON_VERTICAL_SEPARATOR_H, startX, m_tRect.y1, 2, m_tRect.y2); startX += SERVERBROWSER_PVP_W; render->drawPictureRepeat(GUI_UI_IMAGE, GUI_UI_ICON_VERTICAL_SEPARATOR_X, GUI_UI_ICON_VERTICAL_SEPARATOR_Y, GUI_UI_ICON_VERTICAL_SEPARATOR_W, GUI_UI_ICON_VERTICAL_SEPARATOR_H, startX, m_tRect.y1, 2, m_tRect.y2); startX += SERVERBROWSER_EXP_W; render->drawPictureRepeat(GUI_UI_IMAGE, GUI_UI_ICON_VERTICAL_SEPARATOR_X, GUI_UI_ICON_VERTICAL_SEPARATOR_Y, GUI_UI_ICON_VERTICAL_SEPARATOR_W, GUI_UI_ICON_VERTICAL_SEPARATOR_H, startX, m_tRect.y1, 2, m_tRect.y2); } GUI_ServerBrowserEntry::GUI_ServerBrowserEntry(iRect boxRect, Uint32 internalID) : m_serverIp(iRect(0, 0, 0, 0), std::string()), m_serverName(iRect(0, 0, 0, 0), std::string()), m_serverPlayers(iRect(0, 0, 0, 0), std::string()), m_serverType(iRect(0, 0, 0, 0), std::string()), m_serverExp(iRect(0, 0, 0, 0), std::string()), m_serverVersion(iRect(0, 0, 0, 0), std::string()) { setRect(boxRect); m_internalID = internalID; } void GUI_ServerBrowserEntry::setRect(iRect& NewRect) { m_tRect = NewRect; iRect nRect = iRect(NewRect.x1 + SERVERBROWSER_IP_X - 18, NewRect.y1 + 5, SERVERBROWSER_IP_W - 10, NewRect.y2 - 6); m_serverIp.setRect(nRect); nRect = iRect(NewRect.x1 + SERVERBROWSER_NAME_X - 18, NewRect.y1 + 5, SERVERBROWSER_NAME_W - 10, NewRect.y2 - 6); m_serverName.setRect(nRect); nRect = iRect(NewRect.x1 + SERVERBROWSER_PLAYERS_X - 18, NewRect.y1 + 5, SERVERBROWSER_PLAYERS_W - 10, NewRect.y2 - 6); m_serverPlayers.setRect(nRect); nRect = iRect(NewRect.x1 + SERVERBROWSER_PVP_X - 18, NewRect.y1 + 5, SERVERBROWSER_PVP_W - 10, NewRect.y2 - 6); m_serverType.setRect(nRect); nRect = iRect(NewRect.x1 + SERVERBROWSER_EXP_X - 18, NewRect.y1 + 5, SERVERBROWSER_EXP_W - 10, NewRect.y2 - 6); m_serverExp.setRect(nRect); nRect = iRect(NewRect.x1 + SERVERBROWSER_CLIENT_X - 18, NewRect.y1 + 5, SERVERBROWSER_CLIENT_W - 10, NewRect.y2 - 6); m_serverVersion.setRect(nRect); } void GUI_ServerBrowserEntry::onLMouseDown(Sint32, Sint32) { if(g_frameTime < g_lastServerClick && g_selectedServer == m_internalID) m_doubleClicked = true; g_lastServerClick = g_frameTime + 1000; g_selectedServer = m_internalID; } void GUI_ServerBrowserEntry::onLMouseUp(Sint32, Sint32) { if(m_doubleClicked) { m_doubleClicked = false; SDL_snprintf(g_buffer, sizeof(g_buffer), "http://%s/", m_serverIp.getName().c_str()); UTIL_OpenURL(g_buffer); } } void GUI_ServerBrowserEntry::onMouseMove(Sint32 x, Sint32 y, bool isInsideParent) { if(m_serverIp.getRect().isPointInside(x, y)) m_serverIp.onMouseMove(x, y, isInsideParent); else if(m_serverName.getRect().isPointInside(x, y)) m_serverName.onMouseMove(x, y, isInsideParent); else if(m_serverPlayers.getRect().isPointInside(x, y)) m_serverPlayers.onMouseMove(x, y, isInsideParent); else if(m_serverType.getRect().isPointInside(x, y)) m_serverType.onMouseMove(x, y, isInsideParent); else if(m_serverExp.getRect().isPointInside(x, y)) m_serverExp.onMouseMove(x, y, isInsideParent); else if(m_serverVersion.getRect().isPointInside(x, y)) m_serverVersion.onMouseMove(x, y, isInsideParent); } void GUI_ServerBrowserEntry::render() { if(g_selectedServer == m_internalID) g_engine.getRender()->fillRectangle(m_tRect.x1 - 4, m_tRect.y1, m_tRect.x2 - 4, m_tRect.y2, 112, 112, 112, 255); m_serverIp.render(); m_serverName.render(); m_serverPlayers.render(); m_serverType.render(); m_serverExp.render(); m_serverVersion.render(); }
41.878327
229
0.744235
Olddies710
2f907a44951bc887589ca3ebb4f13802f1233e85
1,088
cpp
C++
hardwork/sicily_datastructure/ans.cpp
jskyzero/Cplusplus.Playground
b4a82bb32af04efcffb6e251ac8956a3cc316174
[ "MIT" ]
null
null
null
hardwork/sicily_datastructure/ans.cpp
jskyzero/Cplusplus.Playground
b4a82bb32af04efcffb6e251ac8956a3cc316174
[ "MIT" ]
null
null
null
hardwork/sicily_datastructure/ans.cpp
jskyzero/Cplusplus.Playground
b4a82bb32af04efcffb6e251ac8956a3cc316174
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <string> #include <cstdio> using namespace std; struct data { int a; int b; int c; int all; int num; }; int cmp1(data a, data b) { return a.all < b.all; } void _swap(data *a, data *b) { data tmp; tmp = *a; *a = *b; *b = tmp; } void com(data *a, data *b) { if ((*a).a < (*b).a) _swap(a, b); else if ((*a).a > (*b).a) return; else { if ((*a).num < (*b).num) return; else _swap(a, b); } } int main() { int N; int flag = 1; while (scanf("%d", &N) != EOF) { data tmp[N + 1]; for (int n = 1; n <= N; n++) { scanf("%d%d%d", &tmp[n].a, &tmp[n].b, &tmp[n].c); tmp[n].all = tmp[n].a + tmp[n].b + tmp[n].c; tmp[n].num = n; } sort(tmp + 1, tmp + N + 1, cmp1); if (flag == 0) printf("\n"); else flag = 0; for (int n = N, m = 5; m > 0; m--, n--) { int i = n - 1; while (tmp[n].all == tmp[i].all) { com(&tmp[n], &tmp[i]); i--; } printf("%d %d\n", tmp[n].num, tmp[n].all); } } return 0; }
19.087719
55
0.441176
jskyzero
2f9585256e855b315ad798992ec97f3dc1d8a063
754
hpp
C++
src/LibKyra/Typing/TypeContext.hpp
LukasPietzschmann/Slanguage
c00cc4712e24a201ab5ce55659d1ce38a3d8df41
[ "MIT" ]
7
2021-08-16T07:18:47.000Z
2021-09-28T08:03:00.000Z
src/LibKyra/Typing/TypeContext.hpp
LukasPietzschmann/Slanguage
c00cc4712e24a201ab5ce55659d1ce38a3d8df41
[ "MIT" ]
null
null
null
src/LibKyra/Typing/TypeContext.hpp
LukasPietzschmann/Slanguage
c00cc4712e24a201ab5ce55659d1ce38a3d8df41
[ "MIT" ]
null
null
null
#pragma once #include <iosfwd> #include <memory> #include <string> #include <unordered_map> #include <vector> #include "../Context.hpp" #include "../HasPtrAlias.hpp" #include "../Values/Value.hpp" #include "../Variable.hpp" #include "Type.hpp" #include "TypeProvider.hpp" namespace Kyra { class TypeContext : public Context<TypeContext, Variable<Type::Repr>, Type::Repr> { public: explicit TypeContext(TypeContext::Ptr parent = nullptr) : Context<TypeContext, Variable<Type::Repr>, Type::Repr>(parent) { for(const auto& nt : TypeProvider::nativeTypes()) m_types.try_emplace(TypeProvider::the().decode(nt)->getName(), nt); } using Context::declareVar; bool declareVar(const std::string& name, const Type::Repr& varType, bool isMutable); }; }
27.925926
85
0.724138
LukasPietzschmann
2f96afcd1571e2be24b84580bc7e71730b27405c
10,320
cpp
C++
src/prob_quadratico_cp.cpp
salvatore-punzo/dogbot_tesi
8bf521df5e16b517dce6746361e35c0b437b7e3e
[ "MIT" ]
null
null
null
src/prob_quadratico_cp.cpp
salvatore-punzo/dogbot_tesi
8bf521df5e16b517dce6746361e35c0b437b7e3e
[ "MIT" ]
null
null
null
src/prob_quadratico_cp.cpp
salvatore-punzo/dogbot_tesi
8bf521df5e16b517dce6746361e35c0b437b7e3e
[ "MIT" ]
null
null
null
#include "prob_quadratico_cp.h" //#include "traj_planner.h" using namespace std; PROB_QUAD_CP::PROB_QUAD_CP(){ }; void PROB_QUAD_CP::CalcoloProbOttimoCP(VectorXd &b, Matrix<double,18,18> &M, Matrix<double,24,18> &Jc, Matrix<double,24,1> &Jcdqd, Matrix<double,18,18> &T, Matrix<double,18,18> &T_dot,Matrix<double, 18,1> &q_joints_total, Matrix<double, 18,1> &dq_joints_total, Matrix<double,6,1> &composdes, Matrix<double,6,1> &comveldes, MatrixXd &com_pos, MatrixXd &com_vel, Eigen::Matrix<double,6,18> Jt1, Eigen::Matrix<double,6,18> Jcomdot, float &x_inf, float &x_sup, float&y_inf, float &y_sup) { //eigenfrequency w=sqrt(9.81/com_zdes); /* cout<<"m: "<<m<<endl; cout<<"qs: "<<qs<<endl; cout<<"qr: "<<qr<<endl; */ //vincoli superiori e inferiori per il poligono di supporto tnp = 2*w/(pow(Dt,2)*w + 2 * Dt) * (x_sup - com_pos(0) - com_vel(0) * Dt -com_pos(0)/w); tnn = 2*w/(pow(Dt,2)*w + 2 * Dt) * (x_inf - com_pos(0) - com_vel(0) * Dt -com_pos(0)/w); tnp = 2*w/(pow(Dt,2)*w + 2 * Dt) * (y_inf - com_pos(1) - com_vel(1) * Dt -com_pos(1)/w); tnp = 2*w/(pow(Dt,2)*w + 2 * Dt) * (y_sup - com_pos(1) - com_vel(1) * Dt -com_pos(1)/w); /* // vincoli per il caso in cui i lati del poligono di supporto non sono paralleli agli assi di riferimento di gazebo tnp = 2*w/(pow(Dt,2)*w + 2 * Dt) * (q_frbr +m_frbr * com_pos(0) +m_frbr * com_vel(0) * Dt +m_frbr *com_pos(0)/w - com_pos(1) - com_vel(1) * Dt - com_vel(1)/w); tnn = 2*w/(pow(Dt,2)*w + 2 * Dt) * (q_blfl +m_blfl * com_pos(0) +m_blfl * com_vel(0) * Dt +m_blfl *com_pos(0)/w - com_pos(1) - com_vel(1) * Dt - com_vel(1)/w); tnr = 2*w/(pow(Dt,2)*w + 2 * Dt) * (q_flfr +m_flfr * com_pos(0) +m_flfr * com_vel(0) * Dt +m_flfr *com_pos(0)/w - com_pos(1) - com_vel(1) * Dt - com_vel(1)/w); tns = 2*w/(pow(Dt,2)*w + 2 * Dt) * (q_brbl +m_brbl * com_pos(0) +m_brbl * com_vel(0) * Dt +m_brbl *com_pos(0)/w - com_pos(1) - com_vel(1) * Dt - com_vel(1)/w); */ // Matrici Jacobiane Jt1_dot_dq<<Jcomdot * dq_joints_total; //Sn è la matrice che seleziona le componenti sull'asse z delle forze di contatto Sn<<0,0,1,Matrix<double,1,9>::Zero(), Matrix<double,1,5>::Zero(),1,Matrix<double,1,6>::Zero(), Matrix<double,1,8>::Zero(),1,Matrix<double,1,3>::Zero(), Matrix<double,1,11>::Zero(),1; Matrix<double,3,3> I = Matrix<double,3,3>::Identity(3,3); Matrix<double,3,3> zero = Matrix<double,3,3>::Zero(3,3); B<< I,zero,zero,zero, zero,zero,zero,zero, zero,I,zero,zero, zero,zero,zero,zero, zero,zero,I,zero, zero,zero,zero,zero, zero,zero,zero,I, zero,zero,zero,zero; S << MatrixXd::Zero(12,6), MatrixXd::Identity(12,12); S_T = S.transpose(); Jc_T_B = Jc.transpose() * B; B_T_Jc = B.transpose() * Jc; // errore e<<com_pos - composdes;//posizione corrente - posizione desiderata e_dot<<com_vel - comveldes; //velocità corrente asse z - velocità desiderata Eigen::Matrix<double,6,1> matrixb= -Jt1_dot_dq -kd*e_dot - kp * e; // Termine quadratico, minimizza l'equazione relativa all'errore, motion task Eigen::Matrix<double,18,42> Sigma= Eigen::Matrix<double,18,42>::Zero(); Sigma.block(0,0,18,18)= Eigen::Matrix<double,18,18>::Identity(); Eigen::Matrix<double,6,42> matrixA=Jt1*Sigma; Eigen::Matrix<double,6,6> eigenQ= Eigen::Matrix<double,6,6>::Identity(); Eigen::Matrix<double,42,42> eigenQ1= matrixA.transpose()*eigenQ* matrixA; //imposto il problema quadratico /*Matrix<double,43,43> aa; aa<<Matrix<double,43,43>::Identity(); aa(42,42)=1;*/ real_2d_array a; a.setlength(42,42); //a.setcontent(42,42,&eigenQ1(0,0)); for ( int i = 0; i < eigenQ1.rows(); i++ ){ for ( int j = 0; j < eigenQ1.cols(); j++ ) a(i,j) = eigenQ1(i,j); } // Termine lineare real_1d_array lineartermalglib; lineartermalglib.setlength(42); Eigen::Matrix<double,42,1> linearterm= -matrixA.transpose()*eigenQ.transpose()*matrixb; for ( int i = 0; i < linearterm.rows(); i++ ){ for ( int j = 0; j < linearterm.cols(); j++ ) lineartermalglib(i) = linearterm(i,j); } real_1d_array s; s.setlength(42); for(int i = 0; i< 42; i++){ s(0)=1; } //Friction cones double mu=1; Eigen::Matrix<double,3, 1> n= Eigen::Matrix<double,3,1>::Zero(); n<< 0, 0, 1; Eigen::Matrix<double,3, 1> t1= Eigen::Matrix<double,3,1>::Zero(); t1<< 1, 0, 0; Eigen::Matrix<double,3, 1> t2= Eigen::Matrix<double,3,1>::Zero(); t2<<0, 1, 0; Eigen::Matrix<double,5,3> cfr=Eigen::Matrix<double,5,3>::Zero(); cfr<<(-mu*n+t1).transpose(), (-mu*n+t2).transpose(), -(mu*n+t1).transpose(), -(mu*n+t2).transpose(), -n.transpose(); Eigen::Matrix<double,20,12> Dfr=Eigen::Matrix<double,20,12>::Zero(); for(int i=0; i<4; i++) { Dfr.block(0+5*i,0+3*i,5,3)=cfr; } //limiti della posizione dei giunti VectorXd qmin(12); VectorXd qmax(12); double dt=0.001; double Dt=10*dt; qmin<<-1.7453,-1.7453,-1.7453,-1.7453,-3.14159265359,-0.02,-1.57079632679,-2.61795,-1.57079632679,-2.61795,-3.14159265359,-0.02; qmax<<1.7453, 1.7453, 1.7453, 1.7453, 1.57079632679, 2.61795, 3.14159265359, 0.02, 3.14159265359, 0.02, 1.57079632679, 2.61795; Eigen::Matrix<double,12, 1> ddqmin=(2/pow(Dt,2)) * (qmin-q_joints_total.block(6,0,12,1)- Dt * dq_joints_total.block(6,0,12,1)); Eigen::Matrix<double,12, 1> ddqmax=(2/pow(Dt,2)) * (qmax-q_joints_total.block(6,0,12,1)- Dt * dq_joints_total.block(6,0,12,1)); Eigen::Matrix<double,12,1> tau_max=60*Eigen::Matrix<double,12,1>::Ones(); Eigen::Matrix<double,12,1> tau_min=-60*Eigen::Matrix<double,12,1>::Ones(); real_2d_array c; //vincoli del problema quadratico Matrix<double,102,43> A; /*//controlla i segni di kp e kd, controlla i segni della matrice A, verifica Jt1 Matrix<double,1,6>cps1,cps2,cps3,cps4; cps1<<-m_frbr,1,0,0,0,0; cps2<<-m_blfl,1,0,0,0,0; cps3<<-m_flfr,1,0,0,0,0; cps4<<-m_brbl,1,0,0,0,0; */ A<< M,-Jc_T_B,-S_T, -b, B_T_Jc, Matrix<double,12,24>::Zero(),-B.transpose()*Jcdqd, Matrix<double,20,18>::Zero(), Dfr, Matrix<double,20,13>::Zero(), Matrix<double,12,6>::Zero(), Eigen::Matrix<double,12,12>::Identity(), Matrix<double,12,24>::Zero(), ddqmax, Matrix<double,12,6>::Zero(), -Eigen::Matrix<double,12,12>::Identity(), Matrix<double,12,24>::Zero(), -ddqmin, Matrix<double,12,30>::Zero(), Eigen::Matrix<double,12,12>::Identity(),tau_max, Matrix<double,12,30>::Zero(), -Eigen::Matrix<double,12,12>::Identity(),-tau_min, 1,Matrix<double,1,41>::Zero(),tnp, 1,Matrix<double,1,41>::Zero(), tnn, 0,1, Matrix<double,1,40>::Zero(),tnr, 0,1, Matrix<double,1,40>::Zero(),tns; /* vincoli per lati poligono di supporto non paralleli cps1*Jt1, Matrix<double,1,24>::Zero(),cps1*Jt1_dot_dq + tnp, cps2*Jt1, Matrix<double,1,24>::Zero(),cps1*Jt1_dot_dq + tnn, cps3*Jt1, Matrix<double,1,24>::Zero(),cps2*Jt1_dot_dq + tnr, cps4*Jt1, Matrix<double,1,24>::Zero(),cps2*Jt1_dot_dq + tns; */ //cout<<"A:"<<endl; //cout<<A<<endl; c.setlength(102,43); //c.setcontent(98,43, &A(0,0)); for ( int i = 0; i < A.rows(); i++ ){ for ( int j = 0; j < A.cols(); j++ ) c(i,j) = A(i,j); } //parametro che imposta la tipologia del vincolo integer_1d_array ct; ct.setlength(102); for(int i = 0; i <30; i++){ ct(i) = 0; } /*for(int i = 30; i<33; i++){ ct(i) = 1; }*/ //metti dis for(int i = 30; i<98; i++){ ct(i) = -1; } ct(98)= -1; ct(99)= 1; ct(100)= -1; ct(101)= 1; //box constrain real_1d_array bndl; bndl.setlength(43); real_1d_array bndu; bndu.setlength(43); /*VectorXd qmin(12); VectorXd qmax(12); double dt=0.001; double Dt=10*dt; //limiti della posizione dei giunti qmin<<-1.7453,-1.7453,-1.7453,-1.7453,-3.14159265359,-0.02,-1.57079632679,-2.61795,-1.57079632679,-2.61795,-3.14159265359,-0.02; qmax<<1.7453, 1.7453, 1.7453, 1.7453, 1.57079632679, 2.61795, 3.14159265359, 0.02, 3.14159265359, 0.02, 1.57079632679, 2.61795;*/ //Vincoli sulle accelerazioni ai giunti virtuali /*for(int i = 0; i<6; i++){ bndl(i)=fp_neginf;//-INFINITY bndu(i)=fp_posinf;//+INFINITY } //Vincoli sulle accelerazioni for(int i = 6; i<18; i++){ bndl(i)=(2/pow(Dt,2)) * (qmin(i-6)-q_joints_total(i)- Dt * dq_joints_total(i));// fp_neginf;//-INFINITY bndu(i)=(2/pow(Dt,2)) * (qmax(i-6)-q_joints_total(i)- Dt * dq_joints_total(i));// fp_posinf;//+INFINITY } //Vincoli sulle forze di contatto for(int i = 0; i<4; i++){ // Componente x bndl(3*i+18)=fp_neginf;//-INFINITY bndu(3*i+18)=fp_posinf;//+INFINITY //Componente y bndl(3*i+19)=fp_neginf;//-INFINITY bndu(3*i+19)=fp_posinf;//+INFINITY //Componente z bndu(3*i+20)=fp_posinf;//+INFINITY } //Vincoli sulle coppie for(int i=30; i<42; i++){ bndl(i)= -60; bndu(i)= 60; } printf("%s\n", bndl.tostring(1).c_str()); bndl(42)= 0;//-Infinity bndu(42)= fp_posinf;//+Infinity*/ /* for(int i = 6;i<18;i++){ cout<<"limite superiore sulle accelerazioni: "<<bndu(i)<<endl; cout<<"limite inferiore sulle accelerazioni: "<<bndl(i)<<endl; cout<<"q joints corrente "<<i<<": "<<q_joints_total(i)<<endl; cout<<"qmax - qcorrente: "<<qmax(i-6)-q_joints_total(i)<<endl; cout<<"qmin - qcorrente: "<<qmin(i-6)-q_joints_total(i)<<endl; } */ real_1d_array x; minqpstate state; minqpreport rep; // NOTE: for convex problems you may try using minqpsetscaleautodiag() // which automatically determines variable scales. minqpsetscale(state, s); // create solver, set quadratic/linear terms minqpcreate(42, state); minqpsetquadraticterm(state, a); minqpsetlinearterm(state, lineartermalglib); //non mi servono perchè di default sono già impostati a zero minqpsetlc(state, c, ct); //minqpsetbc(state, bndl, bndu); minqpsetalgodenseaul(state, 1.0e-9, 1.0e+4, 15); minqpoptimize(state); minqpresults(state, x, rep); printf("%d\n", int(rep.terminationtype)); cout<<"Variabili ottimizzate: "; printf("%s\n", x.tostring(1).c_str()); cout<<endl; tau = { x(30),x(40),x(41),x(31),x(38),x(39),x(33),x(34),x(35),x(32),x(36),x(37)}; cpx = com_pos(0)+com_vel(0)/w; cpy = com_pos(1)+com_vel(1)/w; cout<<"cpx: "<<cpx<<endl; cout<<"cpy: "<<cpy<<endl; } //get function vector<double> PROB_QUAD_CP::getTau(){ return tau; }
32.351097
261
0.627035
salvatore-punzo
2f97b95359ab74dfa04b9b3abed2f0d8ebab456e
220
cpp
C++
Source/KiruroboMocapPlugin/KiruroboMocapPlugin.cpp
kirurobo/KiruroboMocapPlugin
c23ece40b3630bcc1acfa41e01ae136e3872d5df
[ "MIT" ]
15
2015-09-15T03:11:55.000Z
2020-08-27T15:27:45.000Z
Source/KiruroboMocapPlugin/KiruroboMocapPlugin.cpp
kirurobo/KiruroboMocapPlugin
c23ece40b3630bcc1acfa41e01ae136e3872d5df
[ "MIT" ]
1
2015-09-16T13:07:14.000Z
2015-10-18T10:11:50.000Z
Source/KiruroboMocapPlugin/KiruroboMocapPlugin.cpp
kirurobo/KiruroboMocapPlugin
c23ece40b3630bcc1acfa41e01ae136e3872d5df
[ "MIT" ]
5
2015-11-10T14:38:37.000Z
2021-05-26T08:00:53.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "KiruroboMocapPlugin.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, KiruroboMocapPlugin, "KiruroboMocapPlugin" );
36.666667
101
0.813636
kirurobo
2fa5d266af49fb51ae70a69e4cf1f66239db1a77
24,208
cpp
C++
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/hwsurfrtdata.cpp
nsivov/wpf
d36941860f05dd7a09008e99d1bcd635b0a69fdb
[ "MIT" ]
2
2020-05-18T17:00:43.000Z
2021-12-01T10:00:29.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/hwsurfrtdata.cpp
nsivov/wpf
d36941860f05dd7a09008e99d1bcd635b0a69fdb
[ "MIT" ]
5
2020-05-05T08:05:01.000Z
2021-12-11T21:35:37.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/hwsurfrtdata.cpp
nsivov/wpf
d36941860f05dd7a09008e99d1bcd635b0a69fdb
[ "MIT" ]
4
2020-05-04T06:43:25.000Z
2022-02-20T12:02:50.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //+----------------------------------------------------------------------------- // // // $TAG ENGR // $Module: win_mil_graphics_d3d // $Keywords: // // $Description: // CHwSurfaceRenderTargetSharedData implementation. // Contains costly data that we want to share between hw surface render targets. // // $ENDTAG // //------------------------------------------------------------------------------ #include "precomp.hpp" // Names of the Stock Shaders available in our Resource File // NOTE: This MUST be in the same order as the StockShader enum definition // in shaderutils.h or there will be a mismatch on load WCHAR const *g_rgstrStockShaderNames[] = { L"SS_RadialGradientCenteredShader2D", L"SS_RadialGradientNonCenteredShader2D", }; //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::ctor // // Synopsis: // ctor // //------------------------------------------------------------------------------ CHwSurfaceRenderTargetSharedData::CHwSurfaceRenderTargetSharedData() { m_pswFallback = NULL; m_pD3DDevice = NULL; m_pDrawBitmapScratchBrush = NULL; m_pHwDestinationTexturePoolBGR = NULL; m_pHwDestinationTexturePoolPBGRA = NULL; m_pHwShaderCache = NULL; m_pScratchHwBoxColorSource = NULL; } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::dtor // // Synopsis: // dtor // //------------------------------------------------------------------------------ CHwSurfaceRenderTargetSharedData::~CHwSurfaceRenderTargetSharedData() { delete m_pswFallback; ReleaseInterfaceNoNULL(m_pDrawBitmapScratchBrush); ReleaseInterfaceNoNULL(m_pHwShaderCache); ReleaseInterfaceNoNULL(m_pScratchHwBoxColorSource); for (UINT i = 0; i < m_dynpColorComponentSources.GetCount(); i++) { ReleaseInterfaceNoNULL(m_dynpColorComponentSources[i]); } ReleaseInterfaceNoNULL(m_pHwDestinationTexturePoolBGR); ReleaseInterfaceNoNULL(m_pHwDestinationTexturePoolPBGRA); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::InitSharedData // // Synopsis: // Init our shared data // //------------------------------------------------------------------------------ HRESULT CHwSurfaceRenderTargetSharedData::InitSharedData( __in_ecount(1) CD3DDeviceLevel1 *pD3DDevice ) { HRESULT hr = S_OK; Assert(m_pD3DDevice == NULL); // Don't addref to avoid a cycle. Since this object is // owned by the device, there are no lifetime issues. m_pD3DDevice = pD3DDevice; IFC(m_poolHwBrushes.Init(pD3DDevice)); IFC(m_solidColorTextureSourcePool.Init(pD3DDevice)); IFC(CHwDestinationTexturePool::Create( pD3DDevice, &m_pHwDestinationTexturePoolBGR ));; IFC(CHwDestinationTexturePool::Create( pD3DDevice, &m_pHwDestinationTexturePoolPBGRA ));; IFC(InitColorComponentSources()); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::InitColorComponentSources // // Synopsis: // Initializes the ColorComponent Sources that we're going to use // //------------------------------------------------------------------------------ HRESULT CHwSurfaceRenderTargetSharedData::InitColorComponentSources() { HRESULT hr = S_OK; CHwColorComponentSource *pColorComponent = NULL; DWORD dwSourceEnum = static_cast<DWORD>(CHwColorComponentSource::Diffuse); while (dwSourceEnum < static_cast<DWORD>(CHwColorComponentSource::Total)) { CHwColorComponentSource::VertexComponent eLocation = static_cast<CHwColorComponentSource::VertexComponent>(dwSourceEnum); IFC(CHwColorComponentSource::Create( eLocation, &pColorComponent )); IFC(m_dynpColorComponentSources.Add(pColorComponent)); pColorComponent = NULL; dwSourceEnum++; } Cleanup: ReleaseInterfaceNoNULL(pColorComponent); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::ResetPerPrimitiveResourceUsage // // Synopsis: // Release any per-primitive resource accumulations. // // Notes: // This should be called between rendering primitives that may realize // pooled resources. // //------------------------------------------------------------------------------ void CHwSurfaceRenderTargetSharedData::ResetPerPrimitiveResourceUsage( ) { m_solidColorTextureSourcePool.Clear(); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::DerivePipelineShader // // Synopsis: // Create a shader class from the shader fragments. // HRESULT CHwSurfaceRenderTargetSharedData::DerivePipelineShader( __in_ecount(uNumPipelineItems) HwPipelineItem const * rgShaderPipelineItems, UINT uNumPipelineItems, __deref_out_ecount(1) CHwPipelineShader ** const ppHwShader ) { HRESULT hr = S_OK; PCSTR pHLSLSource = NULL; UINT cbHLSLSource = 0; IDirect3DPixelShader9 *pPixelShader = NULL; IDirect3DVertexShader9 *pVertexShader = NULL; // // Generate the shader source // IFC(ConvertHwShaderFragmentsToHLSL( rgShaderPipelineItems, uNumPipelineItems, OUT pHLSLSource, OUT cbHLSLSource )); IFC(m_pD3DDevice->CompilePipelineVertexShader( pHLSLSource, cbHLSLSource, &pVertexShader )); IFC(m_pD3DDevice->CompilePipelinePixelShader( pHLSLSource, cbHLSLSource, &pPixelShader )); IFC(CHwPipelineShader::Create( rgShaderPipelineItems, uNumPipelineItems, m_pD3DDevice, pVertexShader, pPixelShader, ppHwShader DBG_COMMA_PARAM(pHLSLSource) )); Cleanup: ReleaseInterfaceNoNULL(pVertexShader); ReleaseInterfaceNoNULL(pPixelShader); WPFFree(ProcessHeap, const_cast<PSTR>(pHLSLSource)); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::GetHwShaderCache // // Synopsis: // Retrieve the shader cache. // HRESULT CHwSurfaceRenderTargetSharedData::GetHwShaderCache( __deref_out_ecount(1) CHwShaderCache ** const ppCache ) { HRESULT hr = S_OK; if (m_pHwShaderCache == NULL) { IFC(CHwShaderCache::Create( m_pD3DDevice, &m_pHwShaderCache )); } *ppCache = m_pHwShaderCache; m_pHwShaderCache->AddRef(); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::GetCachedBrush // // Synopsis: // Get a HW cached brush. Returns NULL if the brush is not found in the // cache. // //------------------------------------------------------------------------------ HRESULT CHwSurfaceRenderTargetSharedData::GetCachedBrush( __in_ecount(1) CMILBrush *pBrush, __in_ecount(1) CHwBrushContext const &hwBrushContext, __deref_out_ecount_opt(1) CHwBrush ** const ppHwCachedBrush ) { HRESULT hr = S_OK; *ppHwCachedBrush = NULL; // // Check cache for linear & radial gradient brushes // if ( pBrush->GetType() != BrushGradientLinear && pBrush->GetType() != BrushGradientRadial ) { goto Cleanup; } CMILBrushGradient *pBrushGradientNoRef; pBrushGradientNoRef = DYNCAST(CMILBrushGradient, pBrush); Assert(pBrushGradientNoRef); // // Check for caching // // First make sure valid cache index has been acquired // if (m_uCacheIndex == CMILResourceCache::InvalidToken) { goto Cleanup; } IMILCacheableResource *pICachedResource; pICachedResource = NULL; IFC(pBrushGradientNoRef->GetResource( m_uCacheIndex, &pICachedResource )); // GetResource can return NULL indicating that it successfully // found that nothing is stored. if (!pICachedResource) { goto Cleanup; } { // Cast to cached type and steal reference CHwCacheablePoolBrush *pCachedBrush = DYNCAST(CHwCacheablePoolBrush, pICachedResource); Assert(pCachedBrush); // // Get a realization for the current context // hr = THR(pCachedBrush->SetBrushAndContext( pBrushGradientNoRef, hwBrushContext )); // If the realization, failed then this brush needs to be // removed from the cache. if (FAILED(hr)) { IGNORE_HR(pBrushGradientNoRef->SetResource(m_uCacheIndex, NULL)); // Release reference obtained from GetResource pCachedBrush->Release(); } else { *ppHwCachedBrush = pCachedBrush; // Transfer reference } } Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::DeriveHWBrush // // Synopsis: // Get a HW brush capable of realizing the given device independent brush // in the given context. // // Note: // only one reference to a HW Brush is allowed at one time; do not try to // derive a second HW Brush before releasing the first // HRESULT CHwSurfaceRenderTargetSharedData::DeriveHWBrush( __in_ecount(1) CMILBrush *pBrush, __in_ecount(1) CHwBrushContext const &hwBrushContext, __deref_out_ecount(1) CHwBrush ** const ppHwBrush ) { HRESULT hr = S_OK; *ppHwBrush = NULL; if (SUCCEEDED(GetCachedBrush( pBrush, hwBrushContext, ppHwBrush )) && *ppHwBrush ) { goto Cleanup; } // // If unable to get a brush from the cache, try the pool. // IFC(m_poolHwBrushes.GetHwBrush( pBrush, hwBrushContext, ppHwBrush )); Cleanup: // // Check results // if (SUCCEEDED(hr)) { Assert(*ppHwBrush); } else { Assert(!*ppHwBrush); } RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::DeriveHWTexturedColorSource // // Synopsis: // Get a HW textured color source capable of realizing the given device // independent brush in the given context. // HRESULT CHwSurfaceRenderTargetSharedData::DeriveHWTexturedColorSource( __in_ecount(1) CMILBrush *pBrush, __in_ecount(1) CHwBrushContext const &hwBrushContext, __deref_out_ecount(1) CHwTexturedColorSource ** const ppHwTexturedColorSource ) { HRESULT hr = S_OK; CHwBrush *pHwLinearGradientBrush = NULL; *ppHwTexturedColorSource = NULL; switch (pBrush->GetType()) { case BrushSolid: { // // Get the color source from the solid color texture pool // MilColorF solidColor; const CMILBrushSolid *pSolidBrushNoRef = DYNCAST(CMILBrushSolid, pBrush); CHwSolidColorTextureSource *pHwSolidColorTextureSource = NULL; Assert(pSolidBrushNoRef); pSolidBrushNoRef->GetColor(&solidColor); IFC(m_solidColorTextureSourcePool.RetrieveTexture( solidColor, &pHwSolidColorTextureSource )); *ppHwTexturedColorSource = pHwSolidColorTextureSource; // steal ref break; } case BrushGradientLinear: case BrushGradientRadial: { // // Derive a primary color source for the linear or radial gradient // and grab the color source from it. // // // We derive a linear gradient hw brush for both linear // and radial gradients. Both should be realized as a 1D texture // // // It is not okay to use DeriveHWBrush for any brush types // other than linear gradient brushes. This is because all other brushes // use a scratch brush. The scratch brush, if retrieved twice, cannot be used // to do two conflicting operations. // Linear gradient brushes are retrieved from the cache or the pool--not from // a reused scratch location--so they do not suffer from this problem. // IFC(DeriveHWBrush( pBrush, hwBrushContext, &pHwLinearGradientBrush )); CHwLinearGradientBrush *pHwLinearGradientBrushNoRef = DYNCAST(CHwLinearGradientBrush, pHwLinearGradientBrush); Assert(pHwLinearGradientBrushNoRef); IFC(pHwLinearGradientBrushNoRef->GetHwTexturedColorSource( ppHwTexturedColorSource )); break; } case BrushBitmap: { CMILBrushBitmap *pBitmapBrush = DYNCAST(CMILBrushBitmap, pBrush); Assert(pBitmapBrush); IFC(CHwBitmapColorSource::DeriveFromBrushAndContext( m_pD3DDevice, pBitmapBrush, hwBrushContext, ppHwTexturedColorSource )); break; } default: IFC(E_NOTIMPL); break; } Assert(*ppHwTexturedColorSource); Cleanup: ReleaseInterfaceNoNULL(pHwLinearGradientBrush); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::GetColorComponentSource // // Synopsis: // Gets a HwColorComponentSource that satisfies the specified parameters. // //------------------------------------------------------------------------------ void CHwSurfaceRenderTargetSharedData::GetColorComponentSource( CHwColorComponentSource::VertexComponent eComponent, __deref_out_ecount(1) CHwColorComponentSource ** const ppColorComponentSource ) { Assert( eComponent == CHwColorComponentSource::Diffuse || eComponent == CHwColorComponentSource::Specular ); *ppColorComponentSource = m_dynpColorComponentSources[eComponent]; (*ppColorComponentSource)->AddRef(); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::DeriveHWShader // // Synopsis: // Get a HW shader capable of realizing it's device independent brushs in // the given context. // HRESULT CHwSurfaceRenderTargetSharedData::DeriveHWShader( __in_ecount(1) CMILShader *pShader, __in_ecount(1) CHwBrushContext const &hwBrushContext, __deref_out_ecount(1) CHwShader ** const ppHwShader ) { HRESULT hr = S_OK; CBrushRealizer *pBrushRealizer = NULL; *ppHwShader = NULL; // We're beginning a new shader which means that we don't have to hold onto // any of the texture sources. We can begin to reuse them. m_solidColorTextureSourcePool.Clear(); switch (pShader->GetType()) { case ShaderDiffuse: case ShaderSpecular: case ShaderEmissive: { CMILShaderBrush *pMILShader = DYNCAST(CMILShaderBrush, pShader); CMILBrush *pMILBrush = NULL; IMILEffectList *pEffectList = NULL; Assert(pMILShader); // Grab the CMILBrush from the Shader { IFC(pMILShader->GetSurfaceSource(&pBrushRealizer)); // // The 3D rendering pipeline doesn't have the support for NULL brushes, // so we use a solid color brush that's transparent and pass that // down. // // We have to render even if all brushes are transparent, because we // have to populate the zbuffer. // pMILBrush = pBrushRealizer->GetRealizedBrushNoRef(true /* fConvertNULLToTransparent */); Assert(pMILBrush); IFC(pBrushRealizer->GetRealizedEffectsNoRef(&pEffectList)); } CHwBrush *pHwBrush = NULL; IFC(DeriveHWBrush( pMILBrush, hwBrushContext, &pHwBrush )); switch (pShader->GetType()) { case ShaderDiffuse: { CHwDiffuseShader *pDiffuseShader = NULL; IFC(CHwDiffuseShader::Create( m_pD3DDevice, pHwBrush, pEffectList, hwBrushContext, &pDiffuseShader )); *ppHwShader = pDiffuseShader; } break; case ShaderSpecular: { CHwSpecularShader *pSpecularShader = NULL; IFC(CHwSpecularShader::Create( m_pD3DDevice, pHwBrush, pEffectList, hwBrushContext, &pSpecularShader )); *ppHwShader = pSpecularShader; } break; case ShaderEmissive: { CHwEmissiveShader *pEmissiveShader = NULL; IFC(CHwEmissiveShader::Create( m_pD3DDevice, pHwBrush, pEffectList, hwBrushContext, &pEmissiveShader )); *ppHwShader = pEmissiveShader; } break; default: NO_DEFAULT("Has pShader->GetType() changed?"); } } break; default: NO_DEFAULT("Has pShader->GetType() changed?"); } Cleanup: ReleaseInterfaceNoNULL(pBrushRealizer); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::GetHwDestinationTexture // // Synopsis: // Gets a texture containing the Destination Surface // //------------------------------------------------------------------------------ HRESULT CHwSurfaceRenderTargetSharedData::GetHwDestinationTexture( __in_ecount(1) CHwSurfaceRenderTarget *pHwSurfaceRenderTarget, __in_ecount(1) CMILSurfaceRect const &rcDestRect, __in_ecount_opt(crgSubDestCopyRects) CMILSurfaceRect const *prgSubDestCopyRects, UINT crgSubDestCopyRects, __deref_out_ecount(1) CHwDestinationTexture ** const ppHwDestinationTexture ) { HRESULT hr = S_OK; CHwDestinationTexture *pHwDestinationTexture = NULL; MilPixelFormat::Enum fmtRT; IFC(pHwSurfaceRenderTarget->GetPixelFormat(&fmtRT)); // Separate pools are kept for different render target formats. This prevents // a cache being thrashed when both RT formats are used in a single frame. if (fmtRT == MilPixelFormat::PBGRA32bpp) { IFC(m_pHwDestinationTexturePoolPBGRA->GetHwDestinationTexture( &pHwDestinationTexture )); } else { // HW texture pooling is currently used by clip/opacity only, so // the only formats expected are the two supported for back buffers/intermediates // since the HwDestinationTexture format is matched to the RT format. Assert(fmtRT == MilPixelFormat::BGR32bpp); IFC(m_pHwDestinationTexturePoolBGR->GetHwDestinationTexture( &pHwDestinationTexture )); } IFC(pHwDestinationTexture->SetContents( pHwSurfaceRenderTarget, rcDestRect, prgSubDestCopyRects, crgSubDestCopyRects )); *ppHwDestinationTexture = pHwDestinationTexture; pHwDestinationTexture = NULL; // steal ref Cleanup: ReleaseInterfaceNoNULL(pHwDestinationTexture); RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::GetCachedHwBoxColorSource // // Synopsis: // Gets a cached box color source and sets its context. // //------------------------------------------------------------------------------ HRESULT CHwSurfaceRenderTargetSharedData::GetScratchHwBoxColorSource( __in_ecount(1) MILMatrix3x2 const *pMatXSpaceToSourceClip, __deref_out_ecount(1) CHwBoxColorSource ** const ppTextureSource ) { HRESULT hr = S_OK; if (m_pScratchHwBoxColorSource) { #if DBG Assert(!DbgHasMultipleReferences(m_pScratchHwBoxColorSource)); #endif } else { IFC(CHwBoxColorSource::Create( m_pD3DDevice, &m_pScratchHwBoxColorSource )); } m_pScratchHwBoxColorSource->SetContext( pMatXSpaceToSourceClip ); *ppTextureSource = m_pScratchHwBoxColorSource; m_pScratchHwBoxColorSource->AddRef(); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::GetScratchDrawBitmapBrush // // Synopsis: // Lazily allocate and return a scratch bitmap brush for the DrawBitmap // call. // //------------------------------------------------------------------------------ HRESULT CHwSurfaceRenderTargetSharedData::GetScratchDrawBitmapBrushNoAddRef( __deref_out_ecount(1) CMILBrushBitmap ** const ppDrawBitmapScratchBrushNoAddRef ) { HRESULT hr = S_OK; if (m_pDrawBitmapScratchBrush) { #if DBG Assert(!DbgHasMultipleReferences(m_pDrawBitmapScratchBrush)); #endif } else { IFC(CMILBrushBitmap::Create(&m_pDrawBitmapScratchBrush)); } *ppDrawBitmapScratchBrushNoAddRef = m_pDrawBitmapScratchBrush; Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CHwSurfaceRenderTargetSharedData::GetSoftwareFallback // // Synopsis: // Lazily allocate and return SW fallback resource // //------------------------------------------------------------------------------ HRESULT CHwSurfaceRenderTargetSharedData::GetSoftwareFallback( __deref_out_ecount(1) CHwSoftwareFallback ** const ppSoftwareFallback, HRESULT hrReasonForFallback ) { HRESULT hr = S_OK; *ppSoftwareFallback = NULL; if (!m_pswFallback) { m_pswFallback = new CHwSoftwareFallback; IFCOOM(m_pswFallback); hr = THR(m_pswFallback->Init(m_pD3DDevice)); if (FAILED(hr)) { delete m_pswFallback; m_pswFallback = NULL; goto Cleanup; } } if (ETW_ENABLED_CHECK(TRACE_LEVEL_INFORMATION)) { if (hrReasonForFallback == D3DERR_OUTOFVIDEOMEMORY) { EventWriteUnexpectedSoftwareFallback(UnexpectedSWFallback_OutOfVideoMemory); } else if (hrReasonForFallback == E_NOTIMPL || hrReasonForFallback == WGXERR_DEVICECANNOTRENDERTEXT) { // SW Fallback reasons is likely expected- don't log it. // there are some unexpcted cases where we return E_NOTIMPL. // It would be nice to log those as well, perhaps by changing the return code. } else { EventWriteUnexpectedSoftwareFallback(UnexpectedSWFallback_UnexpectedPrimitiveFallback); } } *ppSoftwareFallback = m_pswFallback; Cleanup: RRETURN(hr); }
26.808416
104
0.57543
nsivov
2fa687b64af682cf357d4778b6c4f72ad128e329
1,051
cpp
C++
AAD/Aufgabe3.2/myClass.cpp
Solaflex/hf-ict
2ebed689087407019b540df07612525e8b8d6821
[ "MIT" ]
null
null
null
AAD/Aufgabe3.2/myClass.cpp
Solaflex/hf-ict
2ebed689087407019b540df07612525e8b8d6821
[ "MIT" ]
null
null
null
AAD/Aufgabe3.2/myClass.cpp
Solaflex/hf-ict
2ebed689087407019b540df07612525e8b8d6821
[ "MIT" ]
null
null
null
#include <C:\git\RunProject\RunProject\myHeader.h> #include <string> #include <algorithm> // std::transform using namespace std; bool StringUtil::isPalindrome(string input){ // Make the string lowercase to compare it std::transform(input.begin(), input.end(), input.begin(), ::tolower); // Store the length of the string for later use int length = input.length(); // Get the first and the last char string first = input.substr(0,1); string last = input.substr((length - 1), 1); // If we have reached the last char or the two last which are equal, return true if ((length == 1) || ((first == last) && (length == 2))) { return true; } // Else if compare if they are equal. Because they are longer then two and not an odd number, remove the first // and last char and call the function again. Return the return value of the child function. else if (first == last) { input = input.substr((0 + 1), (length - 2)); return isPalindrome(input); } // The first and last char are not equal, return false else { return false; } };
30.028571
111
0.686013
Solaflex
2fa8c77ac4a5780c2e737dde2a5c1c08f6f61e8f
1,007
hpp
C++
plugins/TaiwanSE/TaiwanSE.hpp
Vladimir-Lin/QtFIXAPI
d62f582828267d02b9f4e5d5ddc96d966c3848e1
[ "MIT" ]
null
null
null
plugins/TaiwanSE/TaiwanSE.hpp
Vladimir-Lin/QtFIXAPI
d62f582828267d02b9f4e5d5ddc96d966c3848e1
[ "MIT" ]
null
null
null
plugins/TaiwanSE/TaiwanSE.hpp
Vladimir-Lin/QtFIXAPI
d62f582828267d02b9f4e5d5ddc96d966c3848e1
[ "MIT" ]
null
null
null
#ifndef TAIWANSE_HPP #define TAIWANSE_HPP #ifdef QT_CORE_LIB #include <QtCore> #endif #ifdef QT_GUI_LIB #include <QtGui> #endif #ifdef QT_NETWORK_LIB #include <QtNetwork> #endif #ifdef QT_SQL_LIB #include <QtSql> #endif #include "nFixEngine.hpp" class TaiwanApplication : public FixApplication { public: explicit TaiwanApplication (void); virtual ~TaiwanApplication (void); protected: private: }; class TaiwanThread : public FixThread { Q_OBJECT public: explicit TaiwanThread (QObject * parent = 0); virtual ~TaiwanThread (void ); protected: private: public slots: private slots: signals: }; class TaiwanConnection : public FixConnection { Q_OBJECT public: explicit TaiwanConnection (QObject * parent = 0); virtual ~TaiwanConnection (void ); QString name (void) const; protected: private: public slots: private slots: signals: }; #endif // DUKASCOPY_HPP
12.910256
57
0.662363
Vladimir-Lin
2fa8cb9872514ddfbd2b0ac7637cad6debe4a828
330
cpp
C++
cpp/Environment/PytorchEnvironment.cpp
zigui-ps/PPO-PyTorchCpp-API
b1a8b1b3aade3ca79d4e903f3473bab3cbcac755
[ "MIT" ]
3
2020-03-29T04:50:42.000Z
2021-12-02T14:57:59.000Z
cpp/Environment/PytorchEnvironment.cpp
zigui-ps/PPO-PyTorchCpp-API
b1a8b1b3aade3ca79d4e903f3473bab3cbcac755
[ "MIT" ]
null
null
null
cpp/Environment/PytorchEnvironment.cpp
zigui-ps/PPO-PyTorchCpp-API
b1a8b1b3aade3ca79d4e903f3473bab3cbcac755
[ "MIT" ]
2
2020-03-29T05:21:17.000Z
2020-04-12T08:00:01.000Z
#include "Environment/PytorchEnvironment.h" PytorchEnvironment::PytorchEnvironment(torch::Device device):device(device){ } void PytorchEnvironment::to(torch::Device dev){ device = dev; } int PytorchEnvironment::getObservationSize(){ return observationSize; } int PytorchEnvironment::getActionSize(){ return actionSize; }
19.411765
76
0.784848
zigui-ps
2faeccf55d6271538e24bb823b2f9e6c2d24e0d2
387
hpp
C++
Headers/Recorder.hpp
adivekk94/UDT
645538937722f8a6ad3fc3dfb032a0e5add7adc3
[ "MIT" ]
null
null
null
Headers/Recorder.hpp
adivekk94/UDT
645538937722f8a6ad3fc3dfb032a0e5add7adc3
[ "MIT" ]
null
null
null
Headers/Recorder.hpp
adivekk94/UDT
645538937722f8a6ad3fc3dfb032a0e5add7adc3
[ "MIT" ]
null
null
null
/* * Recorder.hpp * * Created on: 14.04.2017 * Author: adivek */ #ifndef HEADERS_RECORDER_HPP_ #define HEADERS_RECORDER_HPP_ #include "../Definitions/glo_def.hpp" #include "../Definitions/glo_inc.hpp" #include <SFML/Config.hpp> class Recorder : public sf::SoundBufferRecorder { public: Recorder(); void recordData(const u32 delay); }; #endif /* HEADERS_RECORDER_HPP_ */
16.826087
47
0.715762
adivekk94
2faeea6f5e6e6a7c1c6cdf98958df822e15992f1
17,097
cpp
C++
src/prosecoPlanner.cpp
ProSeCo-Planning/ros_proseco_planning
484beedb01e5faafa7e03e95bc88b1e4f969285e
[ "BSD-3-Clause" ]
null
null
null
src/prosecoPlanner.cpp
ProSeCo-Planning/ros_proseco_planning
484beedb01e5faafa7e03e95bc88b1e4f969285e
[ "BSD-3-Clause" ]
null
null
null
src/prosecoPlanner.cpp
ProSeCo-Planning/ros_proseco_planning
484beedb01e5faafa7e03e95bc88b1e4f969285e
[ "BSD-3-Clause" ]
null
null
null
#include <ros/console.h> #include <ros/time.h> #include <cassert> #include <fstream> #include <map> #include <memory> #include <numeric> #include <stdexcept> #include <string> #include <utility> #include <vector> #include "nlohmann/json.hpp" #include "proseco_planning/action/action.h" #include "proseco_planning/action/actionClass.h" #include "proseco_planning/action/noiseGenerator.h" #include "proseco_planning/agent/agent.h" #include "proseco_planning/agent/vehicle.h" #include "proseco_planning/collision_checker/collisionChecker.h" #include "proseco_planning/config/computeOptions.h" #include "proseco_planning/config/configuration.h" #include "proseco_planning/config/outputOptions.h" #include "proseco_planning/config/scenarioOptions.h" #include "proseco_planning/exporters/exporter.h" #include "proseco_planning/math/mathlib.h" #include "proseco_planning/monteCarloTreeSearch.h" #include "proseco_planning/node.h" #include "proseco_planning/scenarioEvaluation.h" #include "proseco_planning/trajectory/trajectorygenerator.h" #include "proseco_planning/util/alias.h" #include "proseco_planning/util/utilities.h" #include "ros_proseco_planning/prosecoPlanner.h" namespace proseco_planning { /** * @brief Constructs a new ProSeCo Planner object. * * @param packagePath The path to the ros_proseco_planning package. * @param optionsArg The path of the options file relative to * ros_proseco_planning/config/options. * @param scenarioArg The path of the scenario file relative to * ros_proseco_planning/config/scenarios. * @param absolute_path A flag that indicates whether or not to use absolute paths instead of * relative to the ros_proseco_planning package. */ ProSeCoPlanner::ProSeCoPlanner(const std::string& packagePath, const std::string& optionsArg, const std::string& scenarioArg, const bool absolute_path) : packagePath(packagePath), optionsArg(optionsArg), scenarioArg(scenarioArg) { std::string optionsPath{"/config/options/"}; std::string scenarioPath{"/config/scenarios/"}; // Load options const auto& options = config::Options::fromJSON(load_config(optionsArg, optionsPath, packagePath, absolute_path)); ROS_INFO("Options initialized"); // Set the seed for the thread-safe random engine to generate randomness (needs to be loaded // before the scenarios, since the engine is used by them) math::Random::setRandomSeed(options.compute_options.random_seed); // Load scenario const auto& scenario = config::Scenario::fromJSON( load_config(scenarioArg, scenarioPath, packagePath, absolute_path)); ROS_INFO("Scenario initialized"); // Assign the config to the planner m_cfg = Config::create(scenario, options); // Initialize the correct exporter class depending on the data format if (oOpt().export_format != config::exportFormat::NONE) m_exporter = Exporter::createExporter(oOpt().output_path, oOpt().export_format); // Initialize the noise generator m_noiseGenerator = std::make_unique<NoiseGenerator>(); // Initialize the environment m_environment = std::make_unique<Node>(sOpt().agents); // Check that starting positions do not produce invalid states or collisions const auto& [notInvalid, notColliding] = m_environment->validateInitialization(); if (!notInvalid) { throw std::runtime_error("Initial agent positions are invalid. Aborting"); } else if (!notColliding) { throw std::runtime_error("Initial agent positions produce collisions. Aborting."); } ROS_INFO("Successfully initialized proseco planner"); } /** * @brief Loads a config from a JSON string. * @details It either loads it directly from the commandline, from an absolute path or from a path * relative to the ros_proseco_planning package. * * @param config The config to be loaded, either a .json file or a JSON string. * @param configPath The path of the config file. * @param packagePath The ros_proseco_planning package path. * @param absolute_path A flag that indicates whether or not to use absolute paths instead of * relative to the ros_proseco_planning package. * @return json The loaded JSON config. */ json ProSeCoPlanner::load_config(const std::string& config, const std::string& configPath, const std::string& packagePath, const bool absolute_path) { if (!util::hasEnding(config, ".json")) { ROS_INFO_STREAM("CONFIG IS NOT A FILE"); return json::parse(config); } else if (absolute_path) { ROS_INFO_STREAM("Config: " + config); return util::loadJSON(config); } else { ROS_INFO_STREAM("Config: " + packagePath + configPath); return util::loadJSON(packagePath + configPath + config); } } /** * @brief Determines the agents of interest (i.e. the agents that are within sensor range) for a * specific agent. * * @param ego_agent The agent for which to determine the agents of interest. * @return std::vector<Agent> The agents that are within the region of interest. */ std::vector<Agent> ProSeCoPlanner::agents_of_interest(const Agent& ego_agent) { std::vector<Agent> agents; agents.reserve(m_environment->m_agents.size()); for (auto& agent : m_environment->m_agents) { // if it is not the agent itself if (ego_agent.m_id != agent.m_id) { agent.is_ego = false; if (std::abs(agent.m_vehicle.m_positionX - ego_agent.m_vehicle.m_positionX) < cOpt().region_of_interest) { agents.emplace_back(agent); } } // the ego agent is always in the ROI else { agents.emplace_back(ego_agent); } } return agents; } /** * @brief Evaluates whether the planner has reached a terminal state. * * @return true If the environment reached a collision or invalid state, as well as when the maximum * number of steps or maximum duration has been reached. But also, when the desire is fulfilled or * the terminal condition of the scenario is met. * @return false Otherwise. */ bool ProSeCoPlanner::isTerminal() const { // terminate if a collision has occurred or an invalid state has been reached if (m_environment->m_collision || m_environment->m_invalid || max_steps_reached() || max_duration_reached()) { return true; } // terminate if desire is fulfilled else if (cOpt().end_condition == "desire") { return m_environment->m_terminal && isScenarioTerminal(m_environment.get()); // terminate if terminal conditions specfied in scenario are met } else if (cOpt().end_condition == "scenario") { return isScenarioTerminal(m_environment.get()); } else { return false; } } /** * @brief Checks whether the maximum number of planning steps for a scenario have been reached. * * @return true If the maximum has been reached. * @return false Otherwise. */ bool ProSeCoPlanner::max_steps_reached() const { return cOpt().max_scenario_steps != 0 && m_step >= cOpt().max_scenario_steps; } /** * @brief Checks whether the maximum planning duration for a scenario has been reached. * * @return true If the maximum has been reached. * @return false Otherwise */ bool ProSeCoPlanner::max_duration_reached() const { return cOpt().max_scenario_duration != 0 && m_duration.toSec() > cOpt().max_scenario_duration; } /** * @brief Saves the result and the config of the planner to the disk. * */ void ProSeCoPlanner::save() const { save_config(); if (oOpt().hasExportType("result")) save_result(); } /** * @brief Saves the options and scenario config to the disk. * @details This is needed for the analysis and to reproduce a specific run. * */ void ProSeCoPlanner::save_config() const { ROS_INFO_STREAM("Writing output to: " + oOpt().output_path); util::saveJSON(oOpt().output_path + "/options_output", m_cfg->options.toJSON()); util::saveJSON(oOpt().output_path + "/scenario_output", sOpt().toJSON()); } /** * @brief Saves the result to the disk. * */ void ProSeCoPlanner::save_result() const { json jResult; jResult["scenario"] = sOpt().name; jResult["carsCollided"] = m_environment->m_collision; jResult["carsInvalid"] = m_environment->m_invalid; jResult["desiresFulfilled"] = m_environment->m_terminal; jResult["maxSimTimeReached"] = max_duration_reached(); jResult["maxStepsReached"] = max_steps_reached(); // final step is the last step that has been executed jResult["finalstep"] = m_step - 1; // normalize over steps to get a fully comparable reward value for one run of the MCTS // m_step is incremented at the end of the plan method jResult["normalizedEgoRewardSum"] = m_normalizedEgoRewardSum / m_step; jResult["normalizedCoopRewardSum"] = m_normalizedCoopRewardSum / m_step; jResult["normalizedStepDuration"] = m_duration.toSec() / m_step; util::saveJSON(oOpt().output_path + "/result", jResult); } /** * @brief Determines the minimum size of the action set sequence of the decentralized plans. * * @param decentralizedActionSetSequences The different action set sequences for each agent. * @return size_t * @todo refactor/doc */ size_t ProSeCoPlanner::getMinimumSequenceSize( const std::vector<ActionSetSequence>& decentralizedActionSetSequences) { size_t minSequenceSize = decentralizedActionSetSequences[0].size(); for (const auto& sequences : decentralizedActionSetSequences) { if (sequences.size() < minSequenceSize) { minSequenceSize = sequences.size(); } } return minSequenceSize; } /** * @brief Selects the action set sequence of each respective agent from the decentralized planning * results. * * @param decentralizedActionSetSequences * @param agentsROI * @return ActionSetSequence * @todo refactor/doc */ ActionSetSequence ProSeCoPlanner::mergeDecentralizedActionSetSequences( const std::vector<ActionSetSequence>& decentralizedActionSetSequences, std::vector<std::vector<Agent>>& agentsROI) const { // create action set sequence vector, where every entry represents the actions that all agents // took at this node. ActionSetSequence actionSetSequence; // decentralized action set sequences may have a different depth, so we determine the minimum // value over all returned action set sequences. const auto minSequenceSize = getMinimumSequenceSize(decentralizedActionSetSequences); for (size_t sequenceIdx{}; sequenceIdx < minSequenceSize; ++sequenceIdx) { ActionSet actionSet; // for every decentralized node, only get the returned action of the "ego agent" of the node. for (size_t nodeIdx{}; nodeIdx < m_environment->m_agents.size(); ++nodeIdx) { // rootAgents are all agents in this decentralized node. auto& rootAgents = agentsROI[nodeIdx]; auto decentralizedActionSet = decentralizedActionSetSequences[nodeIdx][sequenceIdx]; // find the action set of the "ego" agent of the decentralized node for (size_t agentIdx{}; agentIdx < rootAgents.size(); ++agentIdx) { if (m_environment->m_agents[nodeIdx].m_id == rootAgents[agentIdx].m_id) { actionSet.emplace_back(decentralizedActionSet[agentIdx]); break; } } } actionSetSequence.emplace_back(actionSet); } return actionSetSequence; } /** * @brief Overrides the actions chosen by predefined agents. * @details If an agent is predefined an action will still be chosen based on the final selection * policy, so in order to make sure that it actually executes a predefined action it is overwritten * here. * * @param actionSet The action set that is to be executed. */ void ProSeCoPlanner::overrideActionsPredefined(ActionSet& actionSet) const { for (size_t agentIdx{}; agentIdx < sOpt().agents.size(); ++agentIdx) { // modify output if (sOpt().agents[agentIdx].is_predefined) { actionSet.at(agentIdx) = std::make_shared<Action>(Action(ActionClass::DO_NOTHING, 0.0f, 0.0f)); } } } /** * @brief Accumulates the ego as well as cooperative rewards over the scenario. * @details Normalizes the sum using the number of agents in the scenario to make different * scenarios comparable to each other. * */ void ProSeCoPlanner::accumulate_reward() { float egoRewardSum = std::accumulate(m_environment->m_agents.begin(), m_environment->m_agents.end(), 0.0f, [](float sum, const Agent& agent) { return (sum + agent.m_egoReward); }); float coopRewardSum = std::accumulate(m_environment->m_agents.begin(), m_environment->m_agents.end(), 0.0f, [](float sum, const Agent& agent) { return (sum + agent.m_coopReward); }); // since the coop reward is already a weighted sum over all agents, we norm the sum with the // number of agents to keep the cooperation factors // coopRewardSum /= m_environment->m_agents.size(); // norm with agents so the reward can be used to compare over scenarios with varying amounts // of agents egoRewardSum /= m_environment->m_agents.size(); coopRewardSum /= m_environment->m_agents.size(); // sum rewards over all steps; at the end we norm over the final amount of steps to be // able to compare the same scenario with different amount of steps m_normalizedEgoRewardSum += egoRewardSum; m_normalizedCoopRewardSum += coopRewardSum; } /** * @brief Starts the actual search of the Monte Carlo Tree Search. * */ void ProSeCoPlanner::plan() { // vector of actions for each agent, in each mcts ActionSetSequence actionSetSequence; std::vector<ActionSetSequence> decentralizedActionSetSequences; std::vector<std::vector<Agent>> agentsROI; // TIMERS TO TRACK PERFORMANCE ros::Time startTime; ros::Time endTime; ros::Duration stepDuration; //### START OF THE SEARCH while (!ProSeCoPlanner::isTerminal()) { // calculate the best action set using MCTS // Measure the time since the start of the scenario startTime = ros::Time::now(); auto rootNode = std::make_unique<Node>(m_environment.get()); if (cOpt().region_of_interest > 0.0f) { decentralizedActionSetSequences.clear(); agentsROI.clear(); // initialize each root node for each agent with their respective ROI for (const auto& agent : m_environment->m_agents) { auto _rootNode = std::make_unique<Node>(m_environment.get()); _rootNode->m_agents = agents_of_interest(agent); agentsROI.emplace_back(_rootNode->m_agents); decentralizedActionSetSequences.emplace_back( computeActionSetSequence(std::move(_rootNode), m_step)); } actionSetSequence = mergeDecentralizedActionSetSequences(decentralizedActionSetSequences, agentsROI); } else { actionSetSequence = computeActionSetSequence(std::move(rootNode), m_step); } endTime = ros::Time::now(); stepDuration = endTime - startTime; m_duration += stepDuration; ROS_INFO_STREAM("step " << m_step << " took\t" << stepDuration.toSec() << " seconds"); ActionSet actionSet; if (actionSetSequence.empty()) { ROS_FATAL_STREAM("TOO FEW ITERATIONS. ABORTING."); throw std::runtime_error("Planner did not produce a valid plan."); } else { actionSet.clear(); actionSet = actionSetSequence[0]; } // add noise to actions, if enabled if (cOpt().action_noise.active) { actionSet = m_noiseGenerator->createNoisyActions(actionSet); } // modify output if other vehicles are predefined (keep velocity) overrideActionsPredefined(actionSet); // Save State of rootNode for exporting the single shot plan auto singleShotNode = std::make_unique<Node>(m_environment.get()); // CREATE COLLISION CHECKER auto collisionChecker = CollisionChecker::createCollisionChecker(cOpt().collision_checker, 0.0f); // CREATE TRAJECTORY GENERATOR auto trajectoryGenerator = TrajectoryGenerator::createTrajectoryGenerator(cOpt().trajectory_type); // execute the action set m_environment->executeActions(actionSet, *collisionChecker, *trajectoryGenerator, true); // EXPORT if (oOpt().export_format != config::exportFormat::NONE) { // save the current step to the trajectory m_exporter->exportTrajectory(m_environment.get(), actionSet, m_step); // save data for inverse reinforcement learning m_exporter->exportIrlTrajectory(m_environment.get(), actionSet, m_step); // export the single shot plan if (oOpt().hasExportType("singleShot")) m_exporter->exportSingleShot(singleShotNode.get(), actionSetSequence, m_step); } // accumulate the reward metric accumulate_reward(); // increment the step ++m_step; } //### END OF THE SEARCH if (m_step == 0) { throw std::runtime_error("Planning finished before any steps have been executed."); } // write the trajectory to disk if (oOpt().export_format != config::exportFormat::NONE) { if (oOpt().hasExportType("trajectory")) m_exporter->writeData(m_step, ExportType::EXPORT_TRAJECTORY); if (oOpt().hasExportType("irlTrajectory")) m_exporter->writeData(m_step, ExportType::EXPORT_IRL_TRAJECTORY); } }; } // namespace proseco_planning
38.94533
100
0.721589
ProSeCo-Planning
2faf59608878f589a52e6e891638075fb986683f
842
cpp
C++
Engine/Source/Runtime/MessagingRpc/Private/MessagingRpcModule.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/MessagingRpc/Private/MessagingRpcModule.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/MessagingRpc/Private/MessagingRpcModule.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "IMessagingRpcModule.h" #include "Modules/ModuleManager.h" #include "MessageRpcClient.h" #include "MessageRpcServer.h" /** * Implements the MessagingRpc module. */ class FMessagingRpcModule : public IMessagingRpcModule { public: //~ IMessagingRpcModule interface virtual TSharedRef<IMessageRpcClient> CreateRpcClient() override { return MakeShareable(new FMessageRpcClient); } virtual TSharedRef<IMessageRpcServer> CreateRpcServer() override { return MakeShareable(new FMessageRpcServer); } public: //~ IModuleInterface interface virtual void StartupModule() override { } virtual void ShutdownModule() override { } virtual bool SupportsDynamicReloading() override { return false; } }; IMPLEMENT_MODULE(FMessagingRpcModule, MessagingRpc);
19.136364
65
0.774347
windystrife
2fb24df85c60674a3615a877855f55ff355146d9
551
cpp
C++
this/first_example/Hannah.cpp
Rudy02/CPP-Fundementals
dc3882f6c6e900043dc50b7c638b79fa6688ebc0
[ "MIT" ]
null
null
null
this/first_example/Hannah.cpp
Rudy02/CPP-Fundementals
dc3882f6c6e900043dc50b7c638b79fa6688ebc0
[ "MIT" ]
null
null
null
this/first_example/Hannah.cpp
Rudy02/CPP-Fundementals
dc3882f6c6e900043dc50b7c638b79fa6688ebc0
[ "MIT" ]
null
null
null
#include <iostream> #include "Hannah.h" using namespace std; Hannah::Hannah(int num) : h(num) { } void Hannah::printStuff() { //Method #1 //Private Variable: Implided cout << "h = " << h << endl; //Method #2 //Explicit: access the member variable of the current object //being pointed to cout << "this -> " << this->h << endl; //Method #3 //Explicit: Dereference the current object pointer //Access the member variable "h" using the . operator cout << "(*this).h =" << (*this).h << endl; }
20.407407
64
0.584392
Rudy02
2fb3805a1621c7e928bcbffb644918e11464a1d7
2,264
cc
C++
third_party/GsTL/include/GsTL/kriging/SK_constraints.cc
hiteshbedre/movetk
8d261f19538e28ff36cac98a89ef067f8c26f978
[ "Apache-2.0" ]
70
2015-01-21T12:24:50.000Z
2022-03-16T02:10:45.000Z
third_party/GsTL/include/GsTL/kriging/SK_constraints.cc
bacusters/movetk
acbc9c5acb69dd3eb23aa7d2156ede02ed468eae
[ "Apache-2.0" ]
44
2020-09-11T17:40:30.000Z
2021-04-08T23:56:19.000Z
third_party/GsTL/include/GsTL/kriging/SK_constraints.cc
aniketmitra001/movetk
cdf0c98121da6df4cadbd715fba02b05be724218
[ "Apache-2.0" ]
18
2015-02-15T18:04:31.000Z
2021-01-16T08:54:32.000Z
/* GsTL: the Geostatistics Template Library * * Author: Nicolas Remy * Copyright (c) 2000 The Board of Trustees of the Leland Stanford Junior University * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1.Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2.Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * 3.The name of the author may not be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. */ template < class InputIterator, class Location, class SymmetricMatrix, class Vector > unsigned int SK_constraints::operator() ( SymmetricMatrix& A, Vector& b, const Location& , InputIterator first_neigh, InputIterator last_neigh ) const { // compute the size of the system int syst_size=0; for( ; first_neigh != last_neigh ; ++first_neigh) { syst_size += first_neigh->size(); } A.resize(syst_size,syst_size); b.resize(syst_size); return syst_size; }; #ifdef __GNUC__ #pragma implementation #endif #include <GsTL/kriging/SK_constraints.h>
34.30303
88
0.720848
hiteshbedre
2fb3ba1048457f65086c738b93518098d8d65e77
1,903
cpp
C++
leoStockSdk/source/strDecode.cpp
leonard73/LeoJQuantSdk
d4ec0ba402ec6e4832b484fe94a79799e2e57ea5
[ "Apache-2.0" ]
null
null
null
leoStockSdk/source/strDecode.cpp
leonard73/LeoJQuantSdk
d4ec0ba402ec6e4832b484fe94a79799e2e57ea5
[ "Apache-2.0" ]
null
null
null
leoStockSdk/source/strDecode.cpp
leonard73/LeoJQuantSdk
d4ec0ba402ec6e4832b484fe94a79799e2e57ea5
[ "Apache-2.0" ]
null
null
null
#include <strDecode.h> #define LOG_TAG " [STR_DECODE] " #define LOGLINE_STR_INT(s,i) std::cout<<LOG_TAG<<s<<" "<<i<<std::endl #define LOGLINE_STR_INT_STR_STR(s1,i1,s2,s3) std::cout<<LOG_TAG<<s1<<" "<<i1<<s2<<" "<<s3<<std::endl void decode_str_by_lines(std::vector <std::string> & lines_str,std::string string_raw) { // LOGLINE_STR_INT("total char num:",string_raw.size()); static int line_nb=0; int comma_acumulator=0; char array_tmp[100]; int array_tmp_count=0; for(auto i=string_raw.begin();i<=string_raw.end();i++) { array_tmp[array_tmp_count++]=*i; if((*i)=='\n' || (*i)=='\0' ) { array_tmp[array_tmp_count-1]='\0'; // stock_name_array.copy(array_tmp,array_tmp_count,0); std::string stock_name_array=array_tmp; lines_str.push_back(stock_name_array); // std::cout<<array_tmp<<std::endl; comma_acumulator++; line_nb++; array_tmp_count=0; } } // for(int i=0;i<5;i++) // { // LOGLINE_STR_INT_STR_STR("lines_str[",i,"]data:",lines_str.at(i).c_str()); // } } void decode_str_by_comma_perline(std::vector <std::string> & str_elem,std::string string_oneLine) { //decode the first line char array_t[400]; int array_t_count=0; for(int i=0;i<string_oneLine.size()+1;i++) { array_t[array_t_count++] = (string_oneLine.c_str()[i]); if(string_oneLine.c_str()[i]==',' || string_oneLine.c_str()[i]=='\0') { array_t[array_t_count-1] = '\0'; std::string item = array_t; str_elem.push_back(item); array_t_count=0; } } // std::cout<<"item nb is "<<str_elem.size()<<std::endl; // for(int i=0;i<str_elem.size();i++) // { // std::cout<<"item["<<i<<"]: "<<str_elem.at(i).c_str()<<std::endl; // } }
34.6
100
0.566474
leonard73
2fb596f95db409cfbe5ad74c7561c06746ea7abf
305
cpp
C++
src/SGLibExceptions.cpp
yhhshb/yalff
6789a7bef08e633e2044ea597eeb4308a456c06a
[ "MIT" ]
2
2020-01-17T12:34:11.000Z
2020-04-16T15:47:01.000Z
src/SGLibExceptions.cpp
yhhshb/yalff
6789a7bef08e633e2044ea597eeb4308a456c06a
[ "MIT" ]
null
null
null
src/SGLibExceptions.cpp
yhhshb/yalff
6789a7bef08e633e2044ea597eeb4308a456c06a
[ "MIT" ]
1
2021-01-15T15:58:54.000Z
2021-01-15T15:58:54.000Z
#include "SGLibExceptions.hpp" namespace SGLib{ const char* invalid_fastx::what() const noexcept { return "The given input stream does not follow the supposed convention!"; } const char* fastx_end::what() const noexcept { return "The fast* file is finished, no more records in it"; } }//SGLib
19.0625
77
0.72459
yhhshb
2fb653fe9ae332412a59307f3958028f692ea22c
1,166
hpp
C++
driver/support_library/src/cascading/ConcatPart.hpp
ARM-software/npu-driver-stack
1e6b00b21ed4cf39b2df625fa242c6f67c05b19f
[ "Apache-2.0" ]
4
2019-05-31T18:48:24.000Z
2019-06-04T07:59:39.000Z
driver/support_library/src/cascading/ConcatPart.hpp
ARM-software/npu-driver-stack
1e6b00b21ed4cf39b2df625fa242c6f67c05b19f
[ "Apache-2.0" ]
null
null
null
driver/support_library/src/cascading/ConcatPart.hpp
ARM-software/npu-driver-stack
1e6b00b21ed4cf39b2df625fa242c6f67c05b19f
[ "Apache-2.0" ]
null
null
null
// // Copyright © 2021 Arm Limited. // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "Part.hpp" namespace ethosn { namespace support_library { class ConcatPart : public BasePart { public: ConcatPart(PartId id, const std::vector<TensorInfo>& inputTensorsInfo, const ConcatenationInfo& concatInfo, const CompilerDataFormat& compilerDataFormat, const std::set<uint32_t>& correspondingOperationIds, const EstimationOptions& estOpt, const CompilationOptions& compOpt, const HardwareCapabilities& capabilities); Plans GetPlans(CascadeType cascadeType, ethosn::command_stream::BlockConfig blockConfig, Buffer* sramBuffer, uint32_t numWeightStripes) const override; DotAttributes GetDotAttributes(DetailLevel detail) const override; virtual ~ConcatPart(); private: const std::vector<TensorInfo> m_InputTensorsInfo; const ConcatenationInfo m_ConcatInfo; void CreateConcatDramPlan(Plans& plans) const; }; } // namespace support_library } // namespace ethosn
27.761905
70
0.674957
ARM-software
2fb9bb7040b7525234d63aa8472a46fc5416cb87
1,454
hpp
C++
src/Screens/Gameplay/PreciseMusic.hpp
Subject38/jujube
664b995cc65fa6045433b4837d765c62fe6490b4
[ "MIT" ]
19
2020-02-28T20:34:12.000Z
2022-01-28T20:18:25.000Z
src/Screens/Gameplay/PreciseMusic.hpp
Subject38/jujube
664b995cc65fa6045433b4837d765c62fe6490b4
[ "MIT" ]
7
2019-10-22T09:43:16.000Z
2022-03-12T00:15:13.000Z
src/Screens/Gameplay/PreciseMusic.hpp
Subject38/jujube
664b995cc65fa6045433b4837d765c62fe6490b4
[ "MIT" ]
5
2019-10-22T08:14:57.000Z
2021-03-13T06:32:04.000Z
#pragma once #include <thread> #include <atomic> #include <SFML/Audio/Music.hpp> #include <SFML/System/Clock.hpp> #include <SFML/System/Time.hpp> #include "AbstractMusic.hpp" namespace Gameplay { struct _PreciseMusic : sf::Music { explicit _PreciseMusic(const std::string& path); ~_PreciseMusic(); std::thread position_update_watchdog; void position_update_watchdog_main(); std::atomic<bool> should_stop_watchdog = false; sf::Time getPrecisePlayingOffset() const; bool first_onGetData_call = true; sf::Clock lag_measurement; std::atomic<sf::Time> lag = sf::Time::Zero; std::atomic<bool> should_correct = false; std::atomic<sf::Time> last_music_position = sf::Time::Zero; sf::Clock last_position_update; protected: bool onGetData(sf::SoundStream::Chunk& data) override; }; struct PreciseMusic : AbstractMusic { explicit PreciseMusic(const std::string& path) : m_precise_music(path) {}; void play() override {m_precise_music.play();}; void pause() override {m_precise_music.pause();}; void stop() override {m_precise_music.stop();}; sf::SoundSource::Status getStatus() const override {return m_precise_music.getStatus();}; sf::Time getPlayingOffset() const override {return m_precise_music.getPrecisePlayingOffset();}; private: _PreciseMusic m_precise_music; }; }
33.045455
103
0.672627
Subject38
2fbcc6050d3aa07942a0291c020b66c5facb3b52
418
cpp
C++
week9/scene/src/circleScene.cpp
evejweinberg/algo2012
7e13c20bab94e1769f6751c4e124964ae05b7087
[ "MIT" ]
94
2015-01-12T16:07:57.000Z
2021-12-24T06:48:04.000Z
week9/scene/src/circleScene.cpp
theomission/algo2012
7e13c20bab94e1769f6751c4e124964ae05b7087
[ "MIT" ]
null
null
null
week9/scene/src/circleScene.cpp
theomission/algo2012
7e13c20bab94e1769f6751c4e124964ae05b7087
[ "MIT" ]
18
2015-03-12T23:11:08.000Z
2022-02-05T05:43:51.000Z
/* * squareScene.cpp * sceneExample * * Created by zachary lieberman on 11/30/10. * Copyright 2010 __MyCompanyName__. All rights reserved. * */ #include "circleScene.h" void circleScene::setup(){ } void circleScene::update(){ } void circleScene::draw(){ ofSetColor(0,0,0); for (int i = 0; i < 100; i++){ ofCircle(ofRandom(0,ofGetWidth()), ofRandom(0, ofGetHeight()), ofRandom(50,100)); } }
14.413793
83
0.648325
evejweinberg
2fbfb4a82ea69a9fce04e19ae0e9fb1f91262da9
699
hpp
C++
src/brook/runtime/gpu/gpuruntime.hpp
darwin/inferno
e87017763abae0cfe09d47987f5f6ac37c4f073d
[ "Zlib" ]
2
2016-05-09T11:57:28.000Z
2021-07-28T16:46:08.000Z
src/brook/runtime/gpu/gpuruntime.hpp
darwin/inferno
e87017763abae0cfe09d47987f5f6ac37c4f073d
[ "Zlib" ]
null
null
null
src/brook/runtime/gpu/gpuruntime.hpp
darwin/inferno
e87017763abae0cfe09d47987f5f6ac37c4f073d
[ "Zlib" ]
null
null
null
// gpuruntime.hpp #ifndef GPU_RUNTIME_HPP #define GPU_RUNTIME_HPP #include "gpucontext.hpp" namespace brook { class GPURuntime : public RunTime { public: virtual Kernel* CreateKernel(const void*[]); virtual Stream* CreateStream( int fieldCount, const __BRTStreamType fieldTypes[], int dims, const int extents[]); virtual Iter* CreateIter(__BRTStreamType type, int dims, int extents[], float range[]); virtual ~GPURuntime(); GPUContext* getContext() { return _context; } protected: GPURuntime(); bool initialize( GPUContext* inContext ); private: GPUContext* _context; }; } #endif
19.416667
58
0.639485
darwin
2fc218389ad2c87208d8275b8dbd79530dc73bbf
1,029
cpp
C++
Hero's Quest/Item.cpp
uaineteine/Hero-s-Quest
509504db82748911218541212f73a3f5ded13351
[ "MIT" ]
null
null
null
Hero's Quest/Item.cpp
uaineteine/Hero-s-Quest
509504db82748911218541212f73a3f5ded13351
[ "MIT" ]
null
null
null
Hero's Quest/Item.cpp
uaineteine/Hero-s-Quest
509504db82748911218541212f73a3f5ded13351
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Item.h" Item::Item() { } Item::~Item() { } void Item::SetType(int type) { Type = type; Description = ""; if (Type == 1) { Name = "Shield"; SetStats(0, 0, 0, 1, 0); Description = "Adds 1 defence"; Cost = 4; } if (Type == 2) { Name = "Breastplate"; SetStats(0, 0, 0, 3, 0); Description = "Adds 2 defence"; Cost = 6; } if (Type == 3) { Name = "Longsword"; SetStats(0, 0, 2, 0, 0); Description = "Adds 2 attack"; Cost = 6; } if (Type == 4) { Name = "Warhammer"; SetStats(0, 0, 0, 0, 3); Description = "Adds 3 special attack"; Cost = 6; } if (Type == 5) { Name = "Heart Jar"; SetStats(4, 0, 0, 0, 0); Description = "Adds 4 max hit points"; Cost = 4; } if (Type == 6) { Name = "Healing potion"; SetStats(5, 0, 0, 0, 0); Cost = 2; Description = "Heals 5 hit points"; Consumable = true; } if (Type == 7) { Name = "Poison"; SetStats(0, 0, 0, 0, 2); Cost = 3; Description = "Adds 3 to special attack"; Consumable = true; } }
15.590909
43
0.542274
uaineteine
2fc35f98171349d072f9e6587d5d1b7609255223
1,092
cc
C++
贪心/POJ-3190.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
67
2019-07-14T05:38:41.000Z
2021-12-23T11:52:51.000Z
贪心/POJ-3190.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
null
null
null
贪心/POJ-3190.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
12
2020-01-16T10:48:01.000Z
2021-06-11T16:49:04.000Z
/* * Created by OFShare on 2019-12-10 * */ #include <cstdio> #include <algorithm> #include <queue> #include <cmath> #include <cstring> const int maxn = 5e5 + 5; int n; struct node { int start, end, id; bool operator<(node &rhs) const { return start < rhs.start; } }A[maxn]; int ans[maxn]; // <右端点, stall的编号> std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int> >, std::greater<std::pair<int, int> > > que; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d %d", &A[i].start, &A[i].end); A[i].id = i; } std::sort(A + 1, A + 1 + n); int cnt = 0; for (int i = 1; i <= n; ++i) { // 新建stall if (que.empty() || que.top().first >= A[i].start) { ++cnt; ans[A[i].id] = cnt; que.push(std::make_pair(A[i].end, cnt)); } // 不用新建 else { int id = que.top().second; que.pop(); ans[A[i].id] = id; // 弹出来, 新的进队列 que.push(std::make_pair(A[i].end, id)); } } printf("%d\n", cnt); for (int i = 1; i <= n; ++i) { printf("%d\n", ans[i]); } return 0; }
19.5
117
0.505495
OFShare
2fc36abf89eee12c6b38e689365ef8faa7ce177d
4,692
cpp
C++
src/mino.cpp
KingAlone0/Tetris-Clone
0f6d4b81e51a290f03b5bbe74c5464fe1d41f2d7
[ "MIT" ]
null
null
null
src/mino.cpp
KingAlone0/Tetris-Clone
0f6d4b81e51a290f03b5bbe74c5464fe1d41f2d7
[ "MIT" ]
null
null
null
src/mino.cpp
KingAlone0/Tetris-Clone
0f6d4b81e51a290f03b5bbe74c5464fe1d41f2d7
[ "MIT" ]
null
null
null
#include "mino.hpp" #include <iostream> Mino::Mino() { sprPlace.left = 0; sprPlace.top = 0; sprPlace.width = 16; sprPlace.height = 16; texture = Defaults::Get().MinoTexture(); spr.setTexture(texture); spr.setPosition(sf::Vector2f(0.f, 0.f)); updateCollision(); Collision.addAreaPlayable(176.f, 0.f, 182.f, 384.f); } Mino::Mino(TilesType Type) : Type(Type) { sprPlace.left = 0; sprPlace.top = 0; sprPlace.width = 16; sprPlace.height = 16; texture = Defaults::Get().MinoTexture(); spr.setTexture(texture); setRect(); spr.setTextureRect(sprPlace); spr.setPosition(193, 32); updateCollision(); Collision.addAreaPlayable(176.f, 0.f, 182.f, 384.f); } Mino::Mino(TilesType Type, sf::Vector2f pos) : Type(Type) { sprPlace.left = 0; sprPlace.top = 0; sprPlace.width = 16; sprPlace.height = 16; texture = Defaults::Get().MinoTexture(); spr.setTexture(texture); setRect(); spr.setTextureRect(sprPlace); spr.setPosition(pos); updateCollision(); Collision.addAreaPlayable(176.f, 0.f, 182.f, 384.f); } void Mino::setMinoType(TilesType nType) { Type = nType; setRect(); spr.setTextureRect(sprPlace); } void Mino::setRect() { switch (Type) { case TilesType::I: sprPlace.left = 0; sprPlace.top = 0; break; case TilesType::O: sprPlace.left = 16; sprPlace.top = 0; break; case TilesType::T: sprPlace.left = 32; sprPlace.top = 0; break; case TilesType::J: sprPlace.left = 48; sprPlace.top = 0; break; case TilesType::L: sprPlace.left = 0; sprPlace.top = 16; break; case TilesType::S: sprPlace.left = 16; sprPlace.top = 16; break; case TilesType::Z: sprPlace.left = 32; sprPlace.top = 16; break; case TilesType::Grid: sprPlace.left = 48; sprPlace.top = 16; break; } } void Mino::setPosition(sf::Vector2f newPosition) { spr.setPosition(newPosition); updateCollision(); } void Mino::setPosition(float x, float y) { spr.setPosition(x, y); updateCollision(); } void Mino::updateCollision() { Collision.updateCollision((unsigned)spr.getPosition().x, (unsigned)spr.getPosition().y, (unsigned)spr.getGlobalBounds().width, (unsigned)spr.getGlobalBounds().height); } bool Mino::canMove(BoxCollision box) { if (Collision.checkBoxCollision(box)) { return false; } return true; } bool Mino::canMove(std::vector<Mino>& minos) { if (minos.size() == NULL && Collision.checkLimitCollision()) { return false; } else { for (size_t i = 0; i < minos.size(); ++i) { if (Collision.checkBoxCollision(minos[i].Collision)){ return false; } } } return true; } void Mino::handleMovement(sf::Vector2f direction) { spr.move(direction); updateCollision(); } void Mino::handleMovement(V2 direction) { sf::Vector2f m(direction.x, direction.y); spr.move(m); updateCollision(); } void Mino::moveDown() { spr.move(sf::Vector2f(0.f, 16.f)); updateCollision(); } void Mino::setIndex(unsigned short int i, unsigned short int based) { index.i = i; index.based = based; index.updateCoordinates(); // NOTE(AloneTheKing): index = Index(i, based) ? maybe? rIndex.i = i; rIndex.based = based; index.updateCoordinates(); tIndex = i; } void Mino::updateIndex(unsigned char nIndex) { int x = 0, y = 0; rotatedPosition.x = x; rotatedPosition.y = y; tIndex = nIndex; //index = position_index.y * 3 + position_index.x; } Index Mino::updateIndexPosition(short int degree) { rIndex.i = tIndex; rIndex.updateCoordinates(); unsigned short int indexs[3]; if (index.based == 4) { indexs[0] = 12; indexs[1] = 15; indexs[2] = 3; } else if (index.based == 3) { indexs[0] = 6; indexs[1] = 8; indexs[2] = 2; } if (degree == 0) { tIndex = index.y * index.based + index.x; } if (degree == 1) { tIndex = indexs[0] + index.y - (index.based * index.x); } if(degree == 2) { tIndex = indexs[1] - (index.y * index.based) - index.x; } if (degree == 3) { tIndex = indexs[2] - index.y + (index.x * index.based); } Index n_Index(tIndex); return rIndex; //updateIndex(nIndex); } void Mino::Update(RenderWindow* window) { window->draw(spr); } Mino& Mino::operator=(const Mino& mino) { this->Type = mino.Type; sf::Vector2f position = mino.spr.getPosition(); setRect(); spr.setTextureRect(sprPlace); spr.setPosition(position); updateCollision(); }
19.15102
171
0.607204
KingAlone0
2fc36edc3d77df88bedde116f5c7ee042d2b723b
4,345
cxx
C++
vtkImageDualSigmoid.cxx
aWilson41/vtkImageDualSigmoid
dd7bd47449fb462fc0ef67c188d44e05ac2ed733
[ "MIT" ]
null
null
null
vtkImageDualSigmoid.cxx
aWilson41/vtkImageDualSigmoid
dd7bd47449fb462fc0ef67c188d44e05ac2ed733
[ "MIT" ]
null
null
null
vtkImageDualSigmoid.cxx
aWilson41/vtkImageDualSigmoid
dd7bd47449fb462fc0ef67c188d44e05ac2ed733
[ "MIT" ]
null
null
null
#include "vtkImageDualSigmoid.h" #include <vtkImageData.h> #include <vtkImageProgressIterator.h> #include <vtkObjectFactory.h> vtkStandardNewMacro(vtkImageDualSigmoid); vtkImageDualSigmoid::vtkImageDualSigmoid() { this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); Alpha = 1.0; LowerBeta = 0.0; UpperBeta = 0.0; MidBeta = 0.0; BoundType = LOWER; Range = 1.0; OutputMinimum = std::numeric_limits<double>::min(); OutputMaximum = std::numeric_limits<double>::max(); } template <class T> void vtkImageDualSigmoidExecuteDual(vtkImageDualSigmoid* self, vtkImageData* inData, vtkImageData* outData, int outExt[6], int id, T*) { vtkImageIterator<T> inIt(inData, outExt); vtkImageProgressIterator<T> outIt(outData, outExt, self, id); double upperBeta = self->GetUpperBeta(); double lowerBeta = self->GetLowerBeta(); double midBeta = self->GetMidBeta(); double alpha = self->GetAlpha(); double outputMin = self->GetOutputMinimum(); double range = self->GetRange(); // Loop through output pixels while (!outIt.IsAtEnd()) { T* inSI = inIt.BeginSpan(); T* outSI = outIt.BeginSpan(); T* outSIEnd = outIt.EndSpan(); while (outSI != outSIEnd) { // Piecewise function with two sigmoids if (*inSI > midBeta) *outSI = static_cast<T>(range / (1.0 + std::exp((*inSI - upperBeta) / alpha)) + outputMin); else *outSI = static_cast<T>(range / (1.0 + std::exp((lowerBeta - *inSI) / alpha)) + outputMin); outSI++; inSI++; } inIt.NextSpan(); outIt.NextSpan(); } } template <class T> void vtkImageDualSigmoidExecuteLower(vtkImageDualSigmoid* self, vtkImageData* inData, vtkImageData* outData, int outExt[6], int id, T*) { vtkImageIterator<T> inIt(inData, outExt); vtkImageProgressIterator<T> outIt(outData, outExt, self, id); double lowerBeta = self->GetLowerBeta(); double alpha = self->GetAlpha(); double outputMin = self->GetOutputMinimum(); double range = self->GetRange(); // Loop through output pixels while (!outIt.IsAtEnd()) { T* inSI = inIt.BeginSpan(); T* outSI = outIt.BeginSpan(); T* outSIEnd = outIt.EndSpan(); while (outSI != outSIEnd) { *outSI = static_cast<T>(range / (1.0 + std::exp((lowerBeta - *inSI) / alpha)) + outputMin); outSI++; inSI++; } inIt.NextSpan(); outIt.NextSpan(); } } template <class T> void vtkImageDualSigmoidExecuteUpper(vtkImageDualSigmoid* self, vtkImageData* inData, vtkImageData* outData, int outExt[6], int id, T*) { vtkImageIterator<T> inIt(inData, outExt); vtkImageProgressIterator<T> outIt(outData, outExt, self, id); double upperBeta = self->GetUpperBeta(); double alpha = self->GetAlpha(); double outputMin = self->GetOutputMinimum(); double range = self->GetRange(); // Loop through output pixels while (!outIt.IsAtEnd()) { T* inSI = inIt.BeginSpan(); T* outSI = outIt.BeginSpan(); T* outSIEnd = outIt.EndSpan(); while (outSI != outSIEnd) { *outSI = static_cast<T>(range / (1.0 + std::exp((*inSI - upperBeta) / alpha)) + outputMin); outSI++; inSI++; } inIt.NextSpan(); outIt.NextSpan(); } } void vtkImageDualSigmoid::ThreadedExecute(vtkImageData* inData, vtkImageData* outData, int outExt[6], int id) { // this filter expects that input is the same type as output. if (inData->GetScalarType() != outData->GetScalarType()) { vtkErrorMacro(<< "Execute: input ScalarType, " << inData->GetScalarType() << ", must match out ScalarType " << outData->GetScalarType()); return; } switch (BoundType) { case DUAL: switch (inData->GetScalarType()) { vtkTemplateMacro(vtkImageDualSigmoidExecuteDual(this, inData, outData, outExt, id, static_cast<VTK_TT*>(0))); default: vtkErrorMacro(<< "Execute: Unknown input ScalarType"); return; }; break; case LOWER: switch (inData->GetScalarType()) { vtkTemplateMacro(vtkImageDualSigmoidExecuteLower(this, inData, outData, outExt, id, static_cast<VTK_TT*>(0))); default: vtkErrorMacro(<< "Execute: Unknown input ScalarType"); return; }; break; case UPPER: switch (inData->GetScalarType()) { vtkTemplateMacro(vtkImageDualSigmoidExecuteUpper(this, inData, outData, outExt, id, static_cast<VTK_TT*>(0))); default: vtkErrorMacro(<< "Execute: Unknown input ScalarType"); return; }; break; default: vtkErrorMacro(<< "Execute: Unknown input BoundType"); return; }; }
27.327044
139
0.693211
aWilson41
2fcaf243298cdf355270b98af852486dd90ab150
3,446
cc
C++
code/render/instancing/base/instancerendererbase.cc
Nechrito/nebula
6c7ef27ab1374d3f751d866500729524f72a0c87
[ "BSD-2-Clause" ]
null
null
null
code/render/instancing/base/instancerendererbase.cc
Nechrito/nebula
6c7ef27ab1374d3f751d866500729524f72a0c87
[ "BSD-2-Clause" ]
null
null
null
code/render/instancing/base/instancerendererbase.cc
Nechrito/nebula
6c7ef27ab1374d3f751d866500729524f72a0c87
[ "BSD-2-Clause" ]
null
null
null
//------------------------------------------------------------------------------ // instancerendererbase.cc // (C) 2012 Gustav Sterbrant // (C) 2013-2018 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "instancerendererbase.h" #include "coregraphics/transformdevice.h" using namespace CoreGraphics; using namespace Math; namespace Base { __ImplementClass(Base::InstanceRendererBase, 'INRB', Core::RefCounted); //------------------------------------------------------------------------------ /** */ InstanceRendererBase::InstanceRendererBase() : isOpen(false), inBeginUpdate(false), shader(0) { // empty } //------------------------------------------------------------------------------ /** */ InstanceRendererBase::~InstanceRendererBase() { this->shader = 0; this->modelTransforms.Clear(); this->modelViewTransforms.Clear(); this->modelViewProjectionTransforms.Clear(); this->objectIds.Clear(); } //------------------------------------------------------------------------------ /** */ void InstanceRendererBase::Setup() { n_assert(!this->isOpen); this->isOpen = true; } //------------------------------------------------------------------------------ /** */ void InstanceRendererBase::Close() { n_assert(this->isOpen); this->isOpen = false; } //------------------------------------------------------------------------------ /** */ void InstanceRendererBase::BeginUpdate(SizeT amount) { n_assert(!this->inBeginUpdate); this->modelTransforms.Clear(); this->modelViewTransforms.Clear(); this->modelViewProjectionTransforms.Clear(); this->objectIds.Clear(); this->modelTransforms.Reserve(amount); this->modelViewTransforms.Reserve(amount); this->modelViewProjectionTransforms.Reserve(amount); this->objectIds.Reserve(amount); this->inBeginUpdate = true; } //------------------------------------------------------------------------------ /** */ void InstanceRendererBase::AddTransform( const matrix44& matrix ) { n_assert(this->inBeginUpdate); this->modelTransforms.Append(matrix); } //------------------------------------------------------------------------------ /** */ void InstanceRendererBase::AddId( const int id ) { n_assert(this->inBeginUpdate); this->objectIds.Append(id); } //------------------------------------------------------------------------------ /** Assumes all transforms has been set. Calculate remaining transforms. */ void InstanceRendererBase::EndUpdate() { n_assert(this->inBeginUpdate); this->inBeginUpdate = false; // get view and projection transforms const Ptr<TransformDevice>& transDev = TransformDevice::Instance(); const matrix44& view = transDev->GetViewTransform(); const matrix44& viewProj = transDev->GetViewProjTransform(); // calculate remainder of transforms IndexT i; for (i = 0; i < this->modelTransforms.Size(); i++) { // get base transform const matrix44& trans = this->modelTransforms[i]; // add transforms this->modelViewTransforms.Append(matrix44::multiply(trans, view)); this->modelViewProjectionTransforms.Append(matrix44::multiply(trans, viewProj)); } } //------------------------------------------------------------------------------ /** */ void InstanceRendererBase::Render(const SizeT multiplier) { // override in subclass n_error("InstanceRendererBase::Render() called!\n"); } } // namespace Instancing
25.153285
82
0.543529
Nechrito
2fcbde70552692282e12fced2607777709b6f9b2
10,616
cpp
C++
ctrl/stdga.cpp
lmcv-ufc/BIOS
1e4d7ad67fd3b6744ae03ffb6ef650c442164ee3
[ "BSD-2-Clause" ]
null
null
null
ctrl/stdga.cpp
lmcv-ufc/BIOS
1e4d7ad67fd3b6744ae03ffb6ef650c442164ee3
[ "BSD-2-Clause" ]
null
null
null
ctrl/stdga.cpp
lmcv-ufc/BIOS
1e4d7ad67fd3b6744ae03ffb6ef650c442164ee3
[ "BSD-2-Clause" ]
null
null
null
// ------------------------------------------------------------------------- // stdga.cpp - implementation of cStandardGA class. // ------------------------------------------------------------------------- // Copyright (c) 2021 LMCV/UFC // 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ------------------------------------------------------------------------- // Created: 22-Apr-2012 Iuri Barcelos Rocha // // Modified: 15-Mar-2013 Evandro Parente Junior // Renamed from convga.cpp to stdga.cpp. The algorithm can // be used with different types of individuals. // ------------------------------------------------------------------------- #include <iostream> #include <fstream> #include <cmath> #include <string> #include <vector> using namespace std; #ifdef _OMP_ #include "omp.h" #endif #ifdef _MPI_ #include "mpi.h" #endif #include "stdga.h" #include "problem.h" #include "sel.h" #include "group.h" #include "individual.h" #include "penalty.h" #include "utl.h" #include "input.h" #include "gblvar.h" #include "gbldef.h" #include "optalg.h" // ------------------------------------------------------------------------- // Class StandardGA: // // ------------------------------------------------------------------------- // Public methods: // // ============================= ReadCrossRate ============================= void cStandardGA :: ReadCrossRate(istream &in) { if (!(in >> CrossRate)) { cout << "Error in the input of the crossover rate." << endl; exit(0); } } // ============================ ReadCrossRange ============================= void cStandardGA :: ReadCrossRange(istream &in) { if (!(in >> MaxCross) || !(in >> MinCross)) { cout << "Error in the input of the crossover range." << endl; exit(0); } } // =============================== LoadReadFunc ============================ void cStandardGA :: LoadReadFunc(cInpMap &im) { // Call parent class load functions. cOptAlgorithm :: LoadReadFunc(im); // Register read functions. im.Insert("CROSSOVER.RANGE", makeReadObj(cStandardGA,ReadCrossRange)); im.Insert("CROSSOVER.RATE", makeReadObj(cStandardGA,ReadCrossRate)); } // ============================== cStandardGA ============================== cStandardGA :: cStandardGA(void) : cOptAlgorithm( ) { Type = STANDARD_GA; CrossRate = 0.80; MutProb = 0.10; } // ============================= ~cStandardGA ============================== cStandardGA :: ~cStandardGA(void) { } // =============================== Solver ================================== void cStandardGA :: Solver(void) { // Solve the problem as many times as specified by the user. for (int opt = 0; opt < OptNum; opt++) { // Track number of individual evaluations. int EvalNum = 0; // Track the best objective function. double lastBest = 0.0; // Randomize rates. RandomRates( ); // Create the population, mating pool and parent array. int parsize = round(CrossRate*PopSize); int sonsize = parsize - parsize%2; cPopulation pop(PopSize, SolType, Prob); cPopulation son(sonsize, SolType, Prob); cPopulation matpool(PopSize, SolType, Prob); cPopulation parent(parsize, SolType, Prob); // Evaluate initial sample points. vector<cVector> sx; int sizsamp = PopSize - NumInpSol; if (sizsamp < 1) IntPopSamp = 0; if (IntPopSamp) { sx.reserve(sizsamp); int nvar = Prob->VarNumRow( ) * Prob->VarNumCol( ); cSamp InitialSample; InitialSample.InitSample(SampType,nvar,sizsamp,sx); } // Generate the initial population. for (int i = 0; i < PopSize; i++) { // Initialize genotypes. if (i < NumInpSol) pop[i]->Init(InpSolVec[i]); // Input values. else if (IntPopSamp) pop[i]->Init(sx[i]); // Sample values. else { pop[i]->Init( ); // Random values. } EvalNum++; } #pragma omp parallel for num_threads(omp_maxthread) for (int i = 0; i < PopSize; i++) { // Evaluate the objective function and constraints of the initial pop. pop[i]->Evaluate( ); #pragma omp critical EvalNum++; } if (Feedback) cout << "Optimization: " << opt + 1 << endl; // Perform the GA iterations. for (int gen = 0; gen < MaxGen; gen++) { if ((gen+1)%1 == 0 && Feedback) cout << "Generation: " << gen + 1 << endl; // Evaluate the penalized objective function of the population. if (Pen) Pen->EvalPenObjFunc(&pop, TolViol); // Evaluate fitness function. Fitness(pop); // Create the mating pool. Sel->Select(1.0, &pop, &matpool); // Select parents for crossover. Sel->Select(CrossRate, &matpool, &parent); // Crossover. Crossover(parent, son); // Mutation. Mutation(son); // Evaluate the objective function and constraints of offsprings. #pragma omp parallel for num_threads(omp_maxthread) for (int i = 0; i < sonsize; i++) { son[i]->Evaluate( ); #pragma omp critical EvalNum++; } // Evaluate the fitness function of the offspring population. if (Pen) Pen->EvalPenObjFunc(&son, TolViol); Fitness(son); // Merge the offspring population with the original one. pop.Sort( ); Merge(pop, son); // Migration. #ifdef _MPI_ if (!((gen+1)%MigrationGap) && (gen+1) != MaxGen) { pop.Sort( ); Migration(pop); if (Pen) Pen->EvalPenObjFunc(&pop, TolViol); } #endif // Update variables related to PostProcessing. UpdatePostVar(gen, opt, lastBest, &pop); // Check conditions to stop optimization if (OptStopCrit(gen, opt, lastBest, &pop)) break; } // Store the best individual. best->Insert(pop.BestSol( )); // Print data in the output file. PrintPostVar(MaxGen, opt, EvalNum, &pop); } } // ------------------------------------------------------------------------- // Protected methods: // // ============================= Fitness =================================== void cStandardGA :: Fitness(cPopulation &pop) { // Compute the fitness function from the objective function. if (!Pen) // Unconstrained problems. { double bigval = abs(pop[0]->GetObjFunc(0)); for (int i = 1; i < pop.GetSize( ); i++) bigval = MAX(bigval, pop[i]->GetObjFunc(0)); #pragma omp parallel for num_threads(omp_maxthread) for (int i = 0; i < pop.GetSize( ); i++) pop[i]->AssignFitFunc(1.10*bigval - pop[i]->GetObjFunc(0)); } else // Constrained problems. { double bigval = abs(pop[0]->GetPenObjFunc( )); for (int i = 1; i < pop.GetSize( ); i++) bigval = MAX(bigval, pop[i]->GetPenObjFunc( )); #pragma omp parallel for num_threads(omp_maxthread) for (int i = 0; i < pop.GetSize( ); i++) pop[i]->AssignFitFunc(1.10*bigval - pop[i]->GetPenObjFunc( )); } } // ============================ Crossover ================================== void cStandardGA :: Crossover(cPopulation &parent, cPopulation &son) { // Perform the crossover operation. #pragma omp parallel for num_threads(omp_maxthread) for (int i = 0; i < son.GetSize( ); i = i+2) { double r = Utl::RandDec( ); son[ i ]->Crossover(CrossType, r, parent[i],parent[i+1]); son[i+1]->Crossover(CrossType, r, parent[i+1],parent[i]); } } // ============================== Mutation ================================= void cStandardGA :: Mutation(cPopulation &son) { // Perform the mutation operation. if (MutProb) { #pragma omp parallel for num_threads(omp_maxthread) for (int i = 0; i < son.GetSize( ); i++) son[i]->Mutate(MutProb); } } // ============================= Migration ================================= void cStandardGA :: Migration(cPopulation &pop) { #ifdef _MPI_ // Get deme size. int popsize = pop.GetSize( ); // Get size and rank. int rank = MPI::COMM_WORLD.Get_rank( ); int size = MPI::COMM_WORLD.Get_size( ); // Check population size constraint. if ((size-1)*MigrationNum >= pop.GetSize( )) { cout << "Number of received individuals in one deme is greater than the original population size." << endl; exit(0); } // Send and receive individuals. for (int i = 0; i < MigrationNum; i++) for (int deme = 0; deme < size; deme++) { if (rank == deme) pop[i]->Send( ); else pop[popsize-1-i]->Receive(deme); } #endif } // ================================ Merge ================================== void cStandardGA :: Merge(cPopulation &pop, cPopulation &son) { // Get necessary data. int popsize = pop.GetSize( ); int sonsize = son.GetSize( ); int last = popsize - 1; #pragma omp parallel for num_threads(omp_maxthread) for (int i = 0; i < sonsize; i++) { pop[last-i]->Copy(son[i]); } } // ============================= RandomRates ============================== void cStandardGA :: RandomRates(void) { if (!MutProb && MaxMut) MutProb = Utl::RandDouble(MinMut, MaxMut); if (!CrossRate && MaxCross) CrossRate = Utl::RandDouble(MinCross, MaxCross); } // ======================================================= End of file =====
26.606516
114
0.553881
lmcv-ufc
2fccd780483ab7faf6af89ea9c7fbcc844c5e096
541
cxx
C++
cxx/test/utils/file.cxx
mcptr/pjxxs
b95de3d13e05cd9a68e16015a39c29edf8e5bd59
[ "MIT" ]
null
null
null
cxx/test/utils/file.cxx
mcptr/pjxxs
b95de3d13e05cd9a68e16015a39c29edf8e5bd59
[ "MIT" ]
null
null
null
cxx/test/utils/file.cxx
mcptr/pjxxs
b95de3d13e05cd9a68e16015a39c29edf8e5bd59
[ "MIT" ]
null
null
null
#include "file.hxx" #include <fstream> #include <stdexcept> namespace test { namespace utils { void read_file_contents(const std::string& filename, std::string& dest) { std::ifstream in(filename, std::ios::in | std::ios::binary); if(in) { in.seekg(0, std::ios::end); dest.resize(in.tellg()); in.seekg(0, std::ios::beg); in.read(&dest[0], dest.size()); in.close(); return; } std::string msg = "Could not read contents of: "; msg.append(filename); throw std::runtime_error(msg); } } // utils } // test
18.033333
71
0.628466
mcptr
2fd154830cc9e42a0104f87b723053a13f90c1f8
49,912
hpp
C++
include/System/String.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/String.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/String.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 <initializer_list> // Including type: System.IComparable #include "System/IComparable.hpp" // Including type: System.ICloneable #include "System/ICloneable.hpp" // Including type: System.IConvertible #include "System/IConvertible.hpp" // Including type: System.IComparable`1 #include "System/IComparable_1.hpp" // Including type: System.Collections.Generic.IEnumerable`1 #include "System/Collections/Generic/IEnumerable_1.hpp" // Including type: System.IEquatable`1 #include "System/IEquatable_1.hpp" // Including type: System.Int32 #include "System/Int32.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: System namespace System { // Forward declaring type: StringComparison struct StringComparison; // Forward declaring type: StringSplitOptions struct StringSplitOptions; // Forward declaring type: IFormatProvider class IFormatProvider; // Forward declaring type: ParamsArray struct ParamsArray; // Forward declaring type: TypeCode struct TypeCode; // Forward declaring type: Decimal struct Decimal; // Forward declaring type: DateTime struct DateTime; // Forward declaring type: Type class Type; } // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: Encoding class Encoding; // Forward declaring type: NormalizationForm struct NormalizationForm; } // Forward declaring namespace: System::Globalization namespace System::Globalization { // Forward declaring type: CultureInfo class CultureInfo; // Forward declaring type: CompareOptions struct CompareOptions; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: IEnumerator`1<T> template<typename T> class IEnumerator_1; } // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: IEnumerator class IEnumerator; } // Completed forward declares // Type namespace: System namespace System { // Size: 0x16 #pragma pack(push, 1) // Autogenerated type: System.String // [DefaultMemberAttribute] Offset: D7AD44 // [ComVisibleAttribute] Offset: D7AD44 class String : public ::Il2CppObject/*, public System::IComparable, public System::ICloneable, public System::IConvertible, public System::IComparable_1<::Il2CppString*>, public System::Collections::Generic::IEnumerable_1<::Il2CppChar>, public System::IEquatable_1<::Il2CppString*>*/ { public: // private System.Int32 m_stringLength // Size: 0x4 // Offset: 0x10 int m_stringLength; // Field size check static_assert(sizeof(int) == 0x4); // private System.Char m_firstChar // Size: 0x2 // Offset: 0x14 ::Il2CppChar m_firstChar; // Field size check static_assert(sizeof(::Il2CppChar) == 0x2); // Creating value type constructor for type: String String(int m_stringLength_ = {}, ::Il2CppChar m_firstChar_ = {}) noexcept : m_stringLength{m_stringLength_}, m_firstChar{m_firstChar_} {} // Creating interface conversion operator: operator System::IComparable operator System::IComparable() noexcept { return *reinterpret_cast<System::IComparable*>(this); } // Creating interface conversion operator: operator System::ICloneable operator System::ICloneable() noexcept { return *reinterpret_cast<System::ICloneable*>(this); } // Creating interface conversion operator: operator System::IConvertible operator System::IConvertible() noexcept { return *reinterpret_cast<System::IConvertible*>(this); } // Creating interface conversion operator: operator System::IComparable_1<::Il2CppString*> operator System::IComparable_1<::Il2CppString*>() noexcept { return *reinterpret_cast<System::IComparable_1<::Il2CppString*>*>(this); } // Creating interface conversion operator: operator System::Collections::Generic::IEnumerable_1<::Il2CppChar> operator System::Collections::Generic::IEnumerable_1<::Il2CppChar>() noexcept { return *reinterpret_cast<System::Collections::Generic::IEnumerable_1<::Il2CppChar>*>(this); } // Creating interface conversion operator: operator System::IEquatable_1<::Il2CppString*> operator System::IEquatable_1<::Il2CppString*>() noexcept { return *reinterpret_cast<System::IEquatable_1<::Il2CppString*>*>(this); } // static field const value: static private System.Int32 TrimHead static constexpr const int TrimHead = 0; // Get static field: static private System.Int32 TrimHead static int _get_TrimHead(); // Set static field: static private System.Int32 TrimHead static void _set_TrimHead(int value); // static field const value: static private System.Int32 TrimTail static constexpr const int TrimTail = 1; // Get static field: static private System.Int32 TrimTail static int _get_TrimTail(); // Set static field: static private System.Int32 TrimTail static void _set_TrimTail(int value); // static field const value: static private System.Int32 TrimBoth static constexpr const int TrimBoth = 2; // Get static field: static private System.Int32 TrimBoth static int _get_TrimBoth(); // Set static field: static private System.Int32 TrimBoth static void _set_TrimBoth(int value); // Get static field: static public readonly System.String Empty static ::Il2CppString* _get_Empty(); // Set static field: static public readonly System.String Empty static void _set_Empty(::Il2CppString* value); // static field const value: static private System.Int32 charPtrAlignConst static constexpr const int charPtrAlignConst = 1; // Get static field: static private System.Int32 charPtrAlignConst static int _get_charPtrAlignConst(); // Set static field: static private System.Int32 charPtrAlignConst static void _set_charPtrAlignConst(int value); // static field const value: static private System.Int32 alignConst static constexpr const int alignConst = 3; // Get static field: static private System.Int32 alignConst static int _get_alignConst(); // Set static field: static private System.Int32 alignConst static void _set_alignConst(int value); // static public System.String Join(System.String separator, params System.String[] value) // Offset: 0x1B35C50 static ::Il2CppString* Join(::Il2CppString* separator, ::Array<::Il2CppString*>* value); // Creating initializer_list -> params proxy for: System.String Join(System.String separator, params System.String[] value) static ::Il2CppString* Join(::Il2CppString* separator, std::initializer_list<::Il2CppString*> value); // Creating TArgs -> initializer_list proxy for: System.String Join(System.String separator, params System.String[] value) template<class ...TParams> static ::Il2CppString* Join(::Il2CppString* separator, TParams&&... value) { return Join(separator, {value...}); } // static public System.String Join(System.String separator, System.Collections.Generic.IEnumerable`1<T> values) // Offset: 0xFFFFFFFF template<class T> static ::Il2CppString* Join(::Il2CppString* separator, System::Collections::Generic::IEnumerable_1<T>* values) { static auto ___internal__logger = ::Logger::get().WithContext("System::String::Join"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System", "String", "Join", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(separator), ::il2cpp_utils::ExtractType(values)}))); static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()})); return ::il2cpp_utils::RunMethodThrow<::Il2CppString*, false>(static_cast<Il2CppClass*>(nullptr), ___generic__method, separator, values); } // static public System.String Join(System.String separator, System.Collections.Generic.IEnumerable`1<System.String> values) // Offset: 0x1B35F8C static ::Il2CppString* Join(::Il2CppString* separator, System::Collections::Generic::IEnumerable_1<::Il2CppString*>* values); // static public System.String Join(System.String separator, System.String[] value, System.Int32 startIndex, System.Int32 count) // Offset: 0x1B35CEC static ::Il2CppString* Join(::Il2CppString* separator, ::Array<::Il2CppString*>* value, int startIndex, int count); // static private System.Int32 CompareOrdinalIgnoreCaseHelper(System.String strA, System.String strB) // Offset: 0x1B36464 static int CompareOrdinalIgnoreCaseHelper(::Il2CppString* strA, ::Il2CppString* strB); // static private System.Boolean EqualsHelper(System.String strA, System.String strB) // Offset: 0x1B36550 static bool EqualsHelper(::Il2CppString* strA, ::Il2CppString* strB); // static private System.Int32 CompareOrdinalHelper(System.String strA, System.String strB) // Offset: 0x1B3669C static int CompareOrdinalHelper(::Il2CppString* strA, ::Il2CppString* strB); // public System.Boolean Equals(System.String value) // Offset: 0x1B35350 bool Equals(::Il2CppString* value); // public System.Boolean Equals(System.String value, System.StringComparison comparisonType) // Offset: 0x1B3690C bool Equals(::Il2CppString* value, System::StringComparison comparisonType); // static public System.Boolean Equals(System.String a, System.String b) // Offset: 0x1B36C00 static bool Equals(::Il2CppString* a, ::Il2CppString* b); // static public System.Boolean Equals(System.String a, System.String b, System.StringComparison comparisonType) // Offset: 0x1B36C3C static bool Equals(::Il2CppString* a, ::Il2CppString* b, System::StringComparison comparisonType); // public System.Char get_Chars(System.Int32 index) // Offset: 0x1B33BE0 ::Il2CppChar get_Chars(int index); // public System.Void CopyTo(System.Int32 sourceIndex, System.Char[] destination, System.Int32 destinationIndex, System.Int32 count) // Offset: 0x1B36F18 void CopyTo(int sourceIndex, ::Array<::Il2CppChar>* destination, int destinationIndex, int count); // public System.Char[] ToCharArray() // Offset: 0x1B37104 ::Array<::Il2CppChar>* ToCharArray(); // static public System.Boolean IsNullOrEmpty(System.String value) // Offset: 0x1B3719C static bool IsNullOrEmpty(::Il2CppString* value); // static public System.Boolean IsNullOrWhiteSpace(System.String value) // Offset: 0x1B371B8 static bool IsNullOrWhiteSpace(::Il2CppString* value); // System.Int32 GetLegacyNonRandomizedHashCode() // Offset: 0x1B372EC int GetLegacyNonRandomizedHashCode(); // public System.String[] Split(params System.Char[] separator) // Offset: 0x1B37364 ::Array<::Il2CppString*>* Split(::Array<::Il2CppChar>* separator); // Creating initializer_list -> params proxy for: System.String[] Split(params System.Char[] separator) ::Array<::Il2CppString*>* Split(std::initializer_list<::Il2CppChar> separator); // Creating TArgs -> initializer_list proxy for: System.String[] Split(params System.Char[] separator) template<class ...TParams> ::Array<::Il2CppString*>* Split(TParams&&... separator) { return Split({separator...}); } // public System.String[] Split(System.Char[] separator, System.Int32 count) // Offset: 0x1B375D0 ::Array<::Il2CppString*>* Split(::Array<::Il2CppChar>* separator, int count); // public System.String[] Split(System.Char[] separator, System.StringSplitOptions options) // Offset: 0x1B375D8 ::Array<::Il2CppString*>* Split(::Array<::Il2CppChar>* separator, System::StringSplitOptions options); // System.String[] SplitInternal(System.Char[] separator, System.Int32 count, System.StringSplitOptions options) // Offset: 0x1B37370 ::Array<::Il2CppString*>* SplitInternal(::Array<::Il2CppChar>* separator, int count, System::StringSplitOptions options); // public System.String[] Split(System.String[] separator, System.StringSplitOptions options) // Offset: 0x1B37CBC ::Array<::Il2CppString*>* Split(::Array<::Il2CppString*>* separator, System::StringSplitOptions options); // public System.String[] Split(System.String[] separator, System.Int32 count, System.StringSplitOptions options) // Offset: 0x1B37CC8 ::Array<::Il2CppString*>* Split(::Array<::Il2CppString*>* separator, int count, System::StringSplitOptions options); // private System.String[] InternalSplitKeepEmptyEntries(System.Int32[] sepList, System.Int32[] lengthList, System.Int32 numReplaces, System.Int32 count) // Offset: 0x1B37A98 ::Array<::Il2CppString*>* InternalSplitKeepEmptyEntries(::Array<int>* sepList, ::Array<int>* lengthList, int numReplaces, int count); // private System.String[] InternalSplitOmitEmptyEntries(System.Int32[] sepList, System.Int32[] lengthList, System.Int32 numReplaces, System.Int32 count) // Offset: 0x1B377B0 ::Array<::Il2CppString*>* InternalSplitOmitEmptyEntries(::Array<int>* sepList, ::Array<int>* lengthList, int numReplaces, int count); // private System.Int32 MakeSeparatorList(System.Char[] separator, ref System.Int32[] sepList) // Offset: 0x1B375E4 int MakeSeparatorList(::Array<::Il2CppChar>* separator, ::Array<int>*& sepList); // private System.Int32 MakeSeparatorList(System.String[] separators, ref System.Int32[] sepList, ref System.Int32[] lengthList) // Offset: 0x1B37F5C int MakeSeparatorList(::Array<::Il2CppString*>* separators, ::Array<int>*& sepList, ::Array<int>*& lengthList); // public System.String Substring(System.Int32 startIndex) // Offset: 0x1B38260 ::Il2CppString* Substring(int startIndex); // public System.String Substring(System.Int32 startIndex, System.Int32 length) // Offset: 0x1B38100 ::Il2CppString* Substring(int startIndex, int length); // private System.String InternalSubString(System.Int32 startIndex, System.Int32 length) // Offset: 0x1B38298 ::Il2CppString* InternalSubString(int startIndex, int length); // public System.String Trim(params System.Char[] trimChars) // Offset: 0x1B382F4 ::Il2CppString* Trim(::Array<::Il2CppChar>* trimChars); // Creating initializer_list -> params proxy for: System.String Trim(params System.Char[] trimChars) ::Il2CppString* Trim(std::initializer_list<::Il2CppChar> trimChars); // Creating TArgs -> initializer_list proxy for: System.String Trim(params System.Char[] trimChars) template<class ...TParams> ::Il2CppString* Trim(TParams&&... trimChars) { return Trim({trimChars...}); } // public System.String TrimStart(params System.Char[] trimChars) // Offset: 0x1B385C0 ::Il2CppString* TrimStart(::Array<::Il2CppChar>* trimChars); // Creating initializer_list -> params proxy for: System.String TrimStart(params System.Char[] trimChars) ::Il2CppString* TrimStart(std::initializer_list<::Il2CppChar> trimChars); // Creating TArgs -> initializer_list proxy for: System.String TrimStart(params System.Char[] trimChars) template<class ...TParams> ::Il2CppString* TrimStart(TParams&&... trimChars) { return TrimStart({trimChars...}); } // public System.String TrimEnd(params System.Char[] trimChars) // Offset: 0x1B385DC ::Il2CppString* TrimEnd(::Array<::Il2CppChar>* trimChars); // Creating initializer_list -> params proxy for: System.String TrimEnd(params System.Char[] trimChars) ::Il2CppString* TrimEnd(std::initializer_list<::Il2CppChar> trimChars); // Creating TArgs -> initializer_list proxy for: System.String TrimEnd(params System.Char[] trimChars) template<class ...TParams> ::Il2CppString* TrimEnd(TParams&&... trimChars) { return TrimEnd({trimChars...}); } // public System.Void .ctor(System.Char* value) // Offset: 0x1B385F8 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ::Il2CppString* New_ctor(::Il2CppChar* value) { static auto ___internal__logger = ::Logger::get().WithContext("System::String::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<::Il2CppString*, creationType>(value))); } // public System.Void .ctor(System.Char* value, System.Int32 startIndex, System.Int32 length) // Offset: 0x1B385FC template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ::Il2CppString* New_ctor(::Il2CppChar* value, int startIndex, int length) { static auto ___internal__logger = ::Logger::get().WithContext("System::String::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<::Il2CppString*, creationType>(value, startIndex, length))); } // public System.Void .ctor(System.SByte* value, System.Int32 startIndex, System.Int32 length, System.Text.Encoding enc) // Offset: 0x1B38600 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ::Il2CppString* New_ctor(int8_t* value, int startIndex, int length, System::Text::Encoding* enc) { static auto ___internal__logger = ::Logger::get().WithContext("System::String::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<::Il2CppString*, creationType>(value, startIndex, length, enc))); } // static System.String CreateStringFromEncoding(System.Byte* bytes, System.Int32 byteLength, System.Text.Encoding encoding) // Offset: 0x1B38604 static ::Il2CppString* CreateStringFromEncoding(uint8_t* bytes, int byteLength, System::Text::Encoding* encoding); // public System.String Normalize(System.Text.NormalizationForm normalizationForm) // Offset: 0x1B386DC ::Il2CppString* Normalize(System::Text::NormalizationForm normalizationForm); // static System.String FastAllocateString(System.Int32 length) // Offset: 0x1B36460 static ::Il2CppString* FastAllocateString(int length); // static private System.Void FillStringChecked(System.String dest, System.Int32 destPos, System.String src) // Offset: 0x1B387B4 static void FillStringChecked(::Il2CppString* dest, int destPos, ::Il2CppString* src); // public System.Void .ctor(System.Char[] value, System.Int32 startIndex, System.Int32 length) // Offset: 0x1B38868 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ::Il2CppString* New_ctor(::Array<::Il2CppChar>* value, int startIndex, int length) { static auto ___internal__logger = ::Logger::get().WithContext("System::String::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<::Il2CppString*, creationType>(value, startIndex, length))); } // public System.Void .ctor(System.Char[] value) // Offset: 0x1B3886C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ::Il2CppString* New_ctor(::Array<::Il2CppChar>* value) { static auto ___internal__logger = ::Logger::get().WithContext("System::String::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<::Il2CppString*, creationType>(value))); } // static System.Void wstrcpy(System.Char* dmem, System.Char* smem, System.Int32 charCount) // Offset: 0x1B370F8 static void wstrcpy(::Il2CppChar* dmem, ::Il2CppChar* smem, int charCount); // private System.String CtorCharArray(System.Char[] value) // Offset: 0x1B38870 ::Il2CppString* CtorCharArray(::Array<::Il2CppChar>* value); // private System.String CtorCharArrayStartLength(System.Char[] value, System.Int32 startIndex, System.Int32 length) // Offset: 0x1B38914 ::Il2CppString* CtorCharArrayStartLength(::Array<::Il2CppChar>* value, int startIndex, int length); // static private System.Int32 wcslen(System.Char* ptr) // Offset: 0x1B38AC4 static int wcslen(::Il2CppChar* ptr); // private System.String CtorCharPtr(System.Char* ptr) // Offset: 0x1B38B3C ::Il2CppString* CtorCharPtr(::Il2CppChar* ptr); // private System.String CtorCharPtrStartLength(System.Char* ptr, System.Int32 startIndex, System.Int32 length) // Offset: 0x1B38CF0 ::Il2CppString* CtorCharPtrStartLength(::Il2CppChar* ptr, int startIndex, int length); // public System.Void .ctor(System.Char c, System.Int32 count) // Offset: 0x1B38F20 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ::Il2CppString* New_ctor(::Il2CppChar c, int count) { static auto ___internal__logger = ::Logger::get().WithContext("System::String::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<::Il2CppString*, creationType>(c, count))); } // static public System.Int32 Compare(System.String strA, System.String strB) // Offset: 0x1B38F24 static int Compare(::Il2CppString* strA, ::Il2CppString* strB); // static public System.Int32 Compare(System.String strA, System.String strB, System.Boolean ignoreCase) // Offset: 0x1B38FC4 static int Compare(::Il2CppString* strA, ::Il2CppString* strB, bool ignoreCase); // static public System.Int32 Compare(System.String strA, System.String strB, System.StringComparison comparisonType) // Offset: 0x1B390AC static int Compare(::Il2CppString* strA, ::Il2CppString* strB, System::StringComparison comparisonType); // static public System.Int32 Compare(System.String strA, System.String strB, System.Boolean ignoreCase, System.Globalization.CultureInfo culture) // Offset: 0x1B393B4 static int Compare(::Il2CppString* strA, ::Il2CppString* strB, bool ignoreCase, System::Globalization::CultureInfo* culture); // static public System.Int32 Compare(System.String strA, System.Int32 indexA, System.String strB, System.Int32 indexB, System.Int32 length, System.Globalization.CultureInfo culture, System.Globalization.CompareOptions options) // Offset: 0x1B3947C static int Compare(::Il2CppString* strA, int indexA, ::Il2CppString* strB, int indexB, int length, System::Globalization::CultureInfo* culture, System::Globalization::CompareOptions options); // static public System.Int32 Compare(System.String strA, System.Int32 indexA, System.String strB, System.Int32 indexB, System.Int32 length, System.StringComparison comparisonType) // Offset: 0x1B33C74 static int Compare(::Il2CppString* strA, int indexA, ::Il2CppString* strB, int indexB, int length, System::StringComparison comparisonType); // public System.Int32 CompareTo(System.Object value) // Offset: 0x1B39718 int CompareTo(::Il2CppObject* value); // public System.Int32 CompareTo(System.String strB) // Offset: 0x1B397F0 int CompareTo(::Il2CppString* strB); // static public System.Int32 CompareOrdinal(System.String strA, System.String strB) // Offset: 0x1B398A8 static int CompareOrdinal(::Il2CppString* strA, ::Il2CppString* strB); // static public System.Int32 CompareOrdinal(System.String strA, System.Int32 indexA, System.String strB, System.Int32 indexB, System.Int32 length) // Offset: 0x1B3826C static int CompareOrdinal(::Il2CppString* strA, int indexA, ::Il2CppString* strB, int indexB, int length); // public System.Boolean Contains(System.String value) // Offset: 0x1B398F0 bool Contains(::Il2CppString* value); // public System.Boolean EndsWith(System.String value) // Offset: 0x1B39928 bool EndsWith(::Il2CppString* value); // public System.Boolean EndsWith(System.String value, System.StringComparison comparisonType) // Offset: 0x1B39930 bool EndsWith(::Il2CppString* value, System::StringComparison comparisonType); // System.Boolean EndsWith(System.Char value) // Offset: 0x1B39BC4 bool EndsWith(::Il2CppChar value); // public System.Int32 IndexOf(System.Char value) // Offset: 0x1B39C08 int IndexOf(::Il2CppChar value); // public System.Int32 IndexOf(System.Char value, System.Int32 startIndex) // Offset: 0x1B39D5C int IndexOf(::Il2CppChar value, int startIndex); // public System.Int32 IndexOfAny(System.Char[] anyOf) // Offset: 0x1B39D68 int IndexOfAny(::Array<::Il2CppChar>* anyOf); // public System.Int32 IndexOfAny(System.Char[] anyOf, System.Int32 startIndex) // Offset: 0x1B39E8C int IndexOfAny(::Array<::Il2CppChar>* anyOf, int startIndex); // public System.Int32 IndexOf(System.String value) // Offset: 0x1B39E98 int IndexOf(::Il2CppString* value); // public System.Int32 IndexOf(System.String value, System.Int32 startIndex) // Offset: 0x1B39EA8 int IndexOf(::Il2CppString* value, int startIndex); // public System.Int32 IndexOf(System.String value, System.StringComparison comparisonType) // Offset: 0x1B39918 int IndexOf(::Il2CppString* value, System::StringComparison comparisonType); // public System.Int32 IndexOf(System.String value, System.Int32 startIndex, System.StringComparison comparisonType) // Offset: 0x1B39EB8 int IndexOf(::Il2CppString* value, int startIndex, System::StringComparison comparisonType); // public System.Int32 IndexOf(System.String value, System.Int32 startIndex, System.Int32 count, System.StringComparison comparisonType) // Offset: 0x1B39EC8 int IndexOf(::Il2CppString* value, int startIndex, int count, System::StringComparison comparisonType); // public System.Int32 LastIndexOf(System.Char value) // Offset: 0x1B3A26C int LastIndexOf(::Il2CppChar value); // public System.Int32 LastIndexOf(System.Char value, System.Int32 startIndex) // Offset: 0x1B3A3C0 int LastIndexOf(::Il2CppChar value, int startIndex); // public System.Int32 LastIndexOfAny(System.Char[] anyOf) // Offset: 0x1B3A3C8 int LastIndexOfAny(::Array<::Il2CppChar>* anyOf); // public System.Int32 LastIndexOfAny(System.Char[] anyOf, System.Int32 startIndex) // Offset: 0x1B3A538 int LastIndexOfAny(::Array<::Il2CppChar>* anyOf, int startIndex); // public System.Int32 LastIndexOf(System.String value) // Offset: 0x1B3A540 int LastIndexOf(::Il2CppString* value); // public System.Int32 LastIndexOf(System.String value, System.StringComparison comparisonType) // Offset: 0x1B3A96C int LastIndexOf(::Il2CppString* value, System::StringComparison comparisonType); // public System.Int32 LastIndexOf(System.String value, System.Int32 startIndex, System.Int32 count, System.StringComparison comparisonType) // Offset: 0x1B3A550 int LastIndexOf(::Il2CppString* value, int startIndex, int count, System::StringComparison comparisonType); // public System.String PadLeft(System.Int32 totalWidth, System.Char paddingChar) // Offset: 0x1B3A97C ::Il2CppString* PadLeft(int totalWidth, ::Il2CppChar paddingChar); // public System.String PadRight(System.Int32 totalWidth, System.Char paddingChar) // Offset: 0x1B3AAD4 ::Il2CppString* PadRight(int totalWidth, ::Il2CppChar paddingChar); // public System.Boolean StartsWith(System.String value) // Offset: 0x1B3AADC bool StartsWith(::Il2CppString* value); // public System.Boolean StartsWith(System.String value, System.StringComparison comparisonType) // Offset: 0x1B3AB74 bool StartsWith(::Il2CppString* value, System::StringComparison comparisonType); // public System.String ToLower() // Offset: 0x1B3AE10 ::Il2CppString* ToLower(); // public System.String ToLower(System.Globalization.CultureInfo culture) // Offset: 0x1B3AE80 ::Il2CppString* ToLower(System::Globalization::CultureInfo* culture); // public System.String ToLowerInvariant() // Offset: 0x1B3AF30 ::Il2CppString* ToLowerInvariant(); // public System.String ToUpper() // Offset: 0x1B3AFA0 ::Il2CppString* ToUpper(); // public System.String ToUpper(System.Globalization.CultureInfo culture) // Offset: 0x1B3B010 ::Il2CppString* ToUpper(System::Globalization::CultureInfo* culture); // public System.String ToUpperInvariant() // Offset: 0x1B3B0C0 ::Il2CppString* ToUpperInvariant(); // public System.String ToString(System.IFormatProvider provider) // Offset: 0x1B3B134 ::Il2CppString* ToString(System::IFormatProvider* provider); // public System.Object Clone() // Offset: 0x1B3B138 ::Il2CppObject* Clone(); // static private System.Boolean IsBOMWhitespace(System.Char c) // Offset: 0x1B3B13C static bool IsBOMWhitespace(::Il2CppChar c); // public System.String Trim() // Offset: 0x1B35348 ::Il2CppString* Trim(); // private System.String TrimHelper(System.Int32 trimType) // Offset: 0x1B38310 ::Il2CppString* TrimHelper(int trimType); // private System.String TrimHelper(System.Char[] trimChars, System.Int32 trimType) // Offset: 0x1B38474 ::Il2CppString* TrimHelper(::Array<::Il2CppChar>* trimChars, int trimType); // private System.String CreateTrimmedString(System.Int32 start, System.Int32 end) // Offset: 0x1B3B144 ::Il2CppString* CreateTrimmedString(int start, int end); // public System.String Insert(System.Int32 startIndex, System.String value) // Offset: 0x1B3B1DC ::Il2CppString* Insert(int startIndex, ::Il2CppString* value); // public System.String Replace(System.Char oldChar, System.Char newChar) // Offset: 0x1B3B33C ::Il2CppString* Replace(::Il2CppChar oldChar, ::Il2CppChar newChar); // public System.String Replace(System.String oldValue, System.String newValue) // Offset: 0x1B3B430 ::Il2CppString* Replace(::Il2CppString* oldValue, ::Il2CppString* newValue); // public System.String Remove(System.Int32 startIndex, System.Int32 count) // Offset: 0x1B3B5D0 ::Il2CppString* Remove(int startIndex, int count); // public System.String Remove(System.Int32 startIndex) // Offset: 0x1B3B750 ::Il2CppString* Remove(int startIndex); // static public System.String Format(System.String format, System.Object arg0) // Offset: 0x1B34A90 static ::Il2CppString* Format(::Il2CppString* format, ::Il2CppObject* arg0); // static public System.String Format(System.String format, System.Object arg0, System.Object arg1) // Offset: 0x1B34B6C static ::Il2CppString* Format(::Il2CppString* format, ::Il2CppObject* arg0, ::Il2CppObject* arg1); // static public System.String Format(System.String format, System.Object arg0, System.Object arg1, System.Object arg2) // Offset: 0x1B3B908 static ::Il2CppString* Format(::Il2CppString* format, ::Il2CppObject* arg0, ::Il2CppObject* arg1, ::Il2CppObject* arg2); // static public System.String Format(System.String format, params System.Object[] args) // Offset: 0x1B3B958 static ::Il2CppString* Format(::Il2CppString* format, ::Array<::Il2CppObject*>* args); // Creating initializer_list -> params proxy for: System.String Format(System.String format, params System.Object[] args) static ::Il2CppString* Format(::Il2CppString* format, std::initializer_list<::Il2CppObject*> args); // Creating TArgs -> initializer_list proxy for: System.String Format(System.String format, params System.Object[] args) template<class ...TParams> static ::Il2CppString* Format(::Il2CppString* format, TParams&&... args) { return Format(format, {args...}); } // static public System.String Format(System.IFormatProvider provider, System.String format, System.Object arg0) // Offset: 0x1B3BA30 static ::Il2CppString* Format(System::IFormatProvider* provider, ::Il2CppString* format, ::Il2CppObject* arg0); // static public System.String Format(System.IFormatProvider provider, System.String format, System.Object arg0, System.Object arg1) // Offset: 0x1B3BA88 static ::Il2CppString* Format(System::IFormatProvider* provider, ::Il2CppString* format, ::Il2CppObject* arg0, ::Il2CppObject* arg1); // static public System.String Format(System.IFormatProvider provider, System.String format, System.Object arg0, System.Object arg1, System.Object arg2) // Offset: 0x1B3BAE4 static ::Il2CppString* Format(System::IFormatProvider* provider, ::Il2CppString* format, ::Il2CppObject* arg0, ::Il2CppObject* arg1, ::Il2CppObject* arg2); // static public System.String Format(System.IFormatProvider provider, System.String format, params System.Object[] args) // Offset: 0x1B3BB44 static ::Il2CppString* Format(System::IFormatProvider* provider, ::Il2CppString* format, ::Array<::Il2CppObject*>* args); // Creating initializer_list -> params proxy for: System.String Format(System.IFormatProvider provider, System.String format, params System.Object[] args) static ::Il2CppString* Format(System::IFormatProvider* provider, ::Il2CppString* format, std::initializer_list<::Il2CppObject*> args); // Creating TArgs -> initializer_list proxy for: System.String Format(System.IFormatProvider provider, System.String format, params System.Object[] args) template<class ...TParams> static ::Il2CppString* Format(System::IFormatProvider* provider, ::Il2CppString* format, TParams&&... args) { return Format(provider, format, {args...}); } // static private System.String FormatHelper(System.IFormatProvider provider, System.String format, System.ParamsArray args) // Offset: 0x1B3B820 static ::Il2CppString* FormatHelper(System::IFormatProvider* provider, ::Il2CppString* format, System::ParamsArray args); // static public System.String Copy(System.String str) // Offset: 0x1B3BC20 static ::Il2CppString* Copy(::Il2CppString* str); // static public System.String Concat(System.Object arg0) // Offset: 0x1B3BCD8 static ::Il2CppString* Concat(::Il2CppObject* arg0); // static public System.String Concat(System.Object arg0, System.Object arg1) // Offset: 0x1B3BD48 static ::Il2CppString* Concat(::Il2CppObject* arg0, ::Il2CppObject* arg1); // static public System.String Concat(System.Object arg0, System.Object arg1, System.Object arg2) // Offset: 0x1B3BEF8 static ::Il2CppString* Concat(::Il2CppObject* arg0, ::Il2CppObject* arg1, ::Il2CppObject* arg2); // static public System.String Concat(params System.Object[] args) // Offset: 0x1B3C108 static ::Il2CppString* Concat(::Array<::Il2CppObject*>* args); // Creating initializer_list -> params proxy for: System.String Concat(params System.Object[] args) static ::Il2CppString* Concat(std::initializer_list<::Il2CppObject*> args); // Creating TArgs -> initializer_list proxy for: System.String Concat(params System.Object[] args) template<class ...TParams> static ::Il2CppString* Concat(TParams&&... args) { return Concat({args...}); } // static public System.String Concat(System.String str0, System.String str1) // Offset: 0x1B3BE0C static ::Il2CppString* Concat(::Il2CppString* str0, ::Il2CppString* str1); // static public System.String Concat(System.String str0, System.String str1, System.String str2) // Offset: 0x1B3BFF8 static ::Il2CppString* Concat(::Il2CppString* str0, ::Il2CppString* str1, ::Il2CppString* str2); // static public System.String Concat(System.String str0, System.String str1, System.String str2, System.String str3) // Offset: 0x1B3C39C static ::Il2CppString* Concat(::Il2CppString* str0, ::Il2CppString* str1, ::Il2CppString* str2, ::Il2CppString* str3); // static private System.String ConcatArray(System.String[] values, System.Int32 totalLength) // Offset: 0x1B3C2F4 static ::Il2CppString* ConcatArray(::Array<::Il2CppString*>* values, int totalLength); // static public System.String Concat(params System.String[] values) // Offset: 0x1B3C508 static ::Il2CppString* Concat(::Array<::Il2CppString*>* values); // Creating initializer_list -> params proxy for: System.String Concat(params System.String[] values) static ::Il2CppString* Concat(std::initializer_list<::Il2CppString*> values); // static public System.String IsInterned(System.String str) // Offset: 0x1B3C69C static ::Il2CppString* IsInterned(::Il2CppString* str); // public System.TypeCode GetTypeCode() // Offset: 0x1B3C724 System::TypeCode GetTypeCode(); // private System.Boolean System.IConvertible.ToBoolean(System.IFormatProvider provider) // Offset: 0x1B3C72C bool System_IConvertible_ToBoolean(System::IFormatProvider* provider); // private System.Char System.IConvertible.ToChar(System.IFormatProvider provider) // Offset: 0x1B3C7A4 ::Il2CppChar System_IConvertible_ToChar(System::IFormatProvider* provider); // private System.SByte System.IConvertible.ToSByte(System.IFormatProvider provider) // Offset: 0x1B3C81C int8_t System_IConvertible_ToSByte(System::IFormatProvider* provider); // private System.Byte System.IConvertible.ToByte(System.IFormatProvider provider) // Offset: 0x1B3C894 uint8_t System_IConvertible_ToByte(System::IFormatProvider* provider); // private System.Int16 System.IConvertible.ToInt16(System.IFormatProvider provider) // Offset: 0x1B3C90C int16_t System_IConvertible_ToInt16(System::IFormatProvider* provider); // private System.UInt16 System.IConvertible.ToUInt16(System.IFormatProvider provider) // Offset: 0x1B3C984 uint16_t System_IConvertible_ToUInt16(System::IFormatProvider* provider); // private System.Int32 System.IConvertible.ToInt32(System.IFormatProvider provider) // Offset: 0x1B3C9FC int System_IConvertible_ToInt32(System::IFormatProvider* provider); // private System.UInt32 System.IConvertible.ToUInt32(System.IFormatProvider provider) // Offset: 0x1B3CA74 uint System_IConvertible_ToUInt32(System::IFormatProvider* provider); // private System.Int64 System.IConvertible.ToInt64(System.IFormatProvider provider) // Offset: 0x1B3CAEC int64_t System_IConvertible_ToInt64(System::IFormatProvider* provider); // private System.UInt64 System.IConvertible.ToUInt64(System.IFormatProvider provider) // Offset: 0x1B3CB64 uint64_t System_IConvertible_ToUInt64(System::IFormatProvider* provider); // private System.Single System.IConvertible.ToSingle(System.IFormatProvider provider) // Offset: 0x1B3CBDC float System_IConvertible_ToSingle(System::IFormatProvider* provider); // private System.Double System.IConvertible.ToDouble(System.IFormatProvider provider) // Offset: 0x1B3CC54 double System_IConvertible_ToDouble(System::IFormatProvider* provider); // private System.Decimal System.IConvertible.ToDecimal(System.IFormatProvider provider) // Offset: 0x1B3CCCC System::Decimal System_IConvertible_ToDecimal(System::IFormatProvider* provider); // private System.DateTime System.IConvertible.ToDateTime(System.IFormatProvider provider) // Offset: 0x1B3CD44 System::DateTime System_IConvertible_ToDateTime(System::IFormatProvider* provider); // private System.Object System.IConvertible.ToType(System.Type type, System.IFormatProvider provider) // Offset: 0x1B3CDBC ::Il2CppObject* System_IConvertible_ToType(System::Type* type, System::IFormatProvider* provider); // private System.Collections.Generic.IEnumerator`1<System.Char> System.Collections.Generic.IEnumerable<System.Char>.GetEnumerator() // Offset: 0x1B3CE3C System::Collections::Generic::IEnumerator_1<::Il2CppChar>* System_Collections_Generic_IEnumerable$System_Char$_GetEnumerator(); // private System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() // Offset: 0x1B3CEA0 System::Collections::IEnumerator* System_Collections_IEnumerable_GetEnumerator(); // public System.Int32 get_Length() // Offset: 0x1B3CF04 int get_Length(); // static System.Int32 CompareOrdinalUnchecked(System.String strA, System.Int32 indexA, System.Int32 lenA, System.String strB, System.Int32 indexB, System.Int32 lenB) // Offset: 0x1B3CF0C static int CompareOrdinalUnchecked(::Il2CppString* strA, int indexA, int lenA, ::Il2CppString* strB, int indexB, int lenB); // public System.Int32 IndexOf(System.Char value, System.Int32 startIndex, System.Int32 count) // Offset: 0x1B39C14 int IndexOf(::Il2CppChar value, int startIndex, int count); // System.Int32 IndexOfUnchecked(System.Char value, System.Int32 startIndex, System.Int32 count) // Offset: 0x1B3D090 int IndexOfUnchecked(::Il2CppChar value, int startIndex, int count); // System.Int32 IndexOfUnchecked(System.String value, System.Int32 startIndex, System.Int32 count) // Offset: 0x1B3D24C int IndexOfUnchecked(::Il2CppString* value, int startIndex, int count); // public System.Int32 IndexOfAny(System.Char[] anyOf, System.Int32 startIndex, System.Int32 count) // Offset: 0x1B39D74 int IndexOfAny(::Array<::Il2CppChar>* anyOf, int startIndex, int count); // private System.Int32 IndexOfAnyUnchecked(System.Char[] anyOf, System.Int32 startIndex, System.Int32 count) // Offset: 0x1B3D36C int IndexOfAnyUnchecked(::Array<::Il2CppChar>* anyOf, int startIndex, int count); // public System.Int32 LastIndexOf(System.Char value, System.Int32 startIndex, System.Int32 count) // Offset: 0x1B3A278 int LastIndexOf(::Il2CppChar value, int startIndex, int count); // System.Int32 LastIndexOfUnchecked(System.Char value, System.Int32 startIndex, System.Int32 count) // Offset: 0x1B3D45C int LastIndexOfUnchecked(::Il2CppChar value, int startIndex, int count); // public System.Int32 LastIndexOfAny(System.Char[] anyOf, System.Int32 startIndex, System.Int32 count) // Offset: 0x1B3A3D4 int LastIndexOfAny(::Array<::Il2CppChar>* anyOf, int startIndex, int count); // private System.Int32 LastIndexOfAnyUnchecked(System.Char[] anyOf, System.Int32 startIndex, System.Int32 count) // Offset: 0x1B3D620 int LastIndexOfAnyUnchecked(::Array<::Il2CppChar>* anyOf, int startIndex, int count); // static System.Int32 nativeCompareOrdinalEx(System.String strA, System.Int32 indexA, System.String strB, System.Int32 indexB, System.Int32 count) // Offset: 0x1B395A4 static int nativeCompareOrdinalEx(::Il2CppString* strA, int indexA, ::Il2CppString* strB, int indexB, int count); // private System.String ReplaceInternal(System.Char oldChar, System.Char newChar) // Offset: 0x1B3B340 ::Il2CppString* ReplaceInternal(::Il2CppChar oldChar, ::Il2CppChar newChar); // System.String ReplaceInternal(System.String oldValue, System.String newValue) // Offset: 0x1B3B4CC ::Il2CppString* ReplaceInternal(::Il2CppString* oldValue, ::Il2CppString* newValue); // private System.String ReplaceUnchecked(System.String oldValue, System.String newValue) // Offset: 0x1B3D70C ::Il2CppString* ReplaceUnchecked(::Il2CppString* oldValue, ::Il2CppString* newValue); // private System.String ReplaceFallback(System.String oldValue, System.String newValue, System.Int32 testedCount) // Offset: 0x1B3DA98 ::Il2CppString* ReplaceFallback(::Il2CppString* oldValue, ::Il2CppString* newValue, int testedCount); // private System.String PadHelper(System.Int32 totalWidth, System.Char paddingChar, System.Boolean isRightPadded) // Offset: 0x1B3A984 ::Il2CppString* PadHelper(int totalWidth, ::Il2CppChar paddingChar, bool isRightPadded); // System.Boolean StartsWithOrdinalUnchecked(System.String value) // Offset: 0x1B3DBEC bool StartsWithOrdinalUnchecked(::Il2CppString* value); // System.Boolean IsAscii() // Offset: 0x1B36BC0 bool IsAscii(); // static private System.String InternalIsInterned(System.String str) // Offset: 0x1B3C720 static ::Il2CppString* InternalIsInterned(::Il2CppString* str); // static System.Void CharCopy(System.Char* dest, System.Char* src, System.Int32 count) // Offset: 0x1B3D6C4 static void CharCopy(::Il2CppChar* dest, ::Il2CppChar* src, int count); // static private System.Void memset(System.Byte* dest, System.Int32 val, System.Int32 len) // Offset: 0x1B3DC38 static void memset(uint8_t* dest, int val, int len); // static private System.Void memcpy(System.Byte* dest, System.Byte* src, System.Int32 size) // Offset: 0x1B3DCF4 static void memcpy(uint8_t* dest, uint8_t* src, int size); // static System.Void bzero(System.Byte* dest, System.Int32 len) // Offset: 0x1B3DCFC static void bzero_(uint8_t* dest, int len); // static System.Void bzero_aligned_1(System.Byte* dest, System.Int32 len) // Offset: 0x1B3DD08 static void bzero_aligned_1(uint8_t* dest, int len); // static System.Void bzero_aligned_2(System.Byte* dest, System.Int32 len) // Offset: 0x1B3DD10 static void bzero_aligned_2(uint8_t* dest, int len); // static System.Void bzero_aligned_4(System.Byte* dest, System.Int32 len) // Offset: 0x1B3DD18 static void bzero_aligned_4(uint8_t* dest, int len); // static System.Void bzero_aligned_8(System.Byte* dest, System.Int32 len) // Offset: 0x1B3DD20 static void bzero_aligned_8(uint8_t* dest, int len); // static System.Void memcpy_aligned_1(System.Byte* dest, System.Byte* src, System.Int32 size) // Offset: 0x1B3DD28 static void memcpy_aligned_1(uint8_t* dest, uint8_t* src, int size); // static System.Void memcpy_aligned_2(System.Byte* dest, System.Byte* src, System.Int32 size) // Offset: 0x1B3DD34 static void memcpy_aligned_2(uint8_t* dest, uint8_t* src, int size); // static System.Void memcpy_aligned_4(System.Byte* dest, System.Byte* src, System.Int32 size) // Offset: 0x1B3DD40 static void memcpy_aligned_4(uint8_t* dest, uint8_t* src, int size); // static System.Void memcpy_aligned_8(System.Byte* dest, System.Byte* src, System.Int32 size) // Offset: 0x1B3DD4C static void memcpy_aligned_8(uint8_t* dest, uint8_t* src, int size); // private System.String CreateString(System.SByte* value) // Offset: 0x1B3DD58 ::Il2CppString* CreateString(int8_t* value); // private System.String CreateString(System.SByte* value, System.Int32 startIndex, System.Int32 length) // Offset: 0x1B3E0C0 ::Il2CppString* CreateString(int8_t* value, int startIndex, int length); // private System.String CreateString(System.Char* value) // Offset: 0x1B3E0C8 ::Il2CppString* CreateString(::Il2CppChar* value); // private System.String CreateString(System.Char* value, System.Int32 startIndex, System.Int32 length) // Offset: 0x1B3E0CC ::Il2CppString* CreateString(::Il2CppChar* value, int startIndex, int length); // private System.String CreateString(System.Char[] val, System.Int32 startIndex, System.Int32 length) // Offset: 0x1B3467C ::Il2CppString* CreateString(::Array<::Il2CppChar>* val, int startIndex, int length); // private System.String CreateString(System.Char[] val) // Offset: 0x1B3E0D0 ::Il2CppString* CreateString(::Array<::Il2CppChar>* val); // private System.String CreateString(System.Char c, System.Int32 count) // Offset: 0x1B33030 ::Il2CppString* CreateString(::Il2CppChar c, int count); // private System.String CreateString(System.SByte* value, System.Int32 startIndex, System.Int32 length, System.Text.Encoding enc) // Offset: 0x1B3DDEC ::Il2CppString* CreateString(int8_t* value, int startIndex, int length, System::Text::Encoding* enc); // public override System.Boolean Equals(System.Object obj) // Offset: 0x1B3682C // Implemented from: System.Object // Base method: System.Boolean Object::Equals(System.Object obj) bool Equals(::Il2CppObject* obj); // public override System.Int32 GetHashCode() // Offset: 0x1B37274 // Implemented from: System.Object // Base method: System.Int32 Object::GetHashCode() int GetHashCode(); // public override System.String ToString() // Offset: 0x1B3B130 // Implemented from: System.Object // Base method: System.String Object::ToString() ::Il2CppString* ToString(); }; // System.String #pragma pack(pop) static check_size<sizeof(String), 20 + sizeof(::Il2CppChar)> __System_StringSizeCheck; static_assert(sizeof(String) == 0x16); // static public System.Boolean op_Equality(System.String a, System.String b) // Offset: 0x1B36EF8 bool operator ==(::Il2CppString* a, ::Il2CppString& b); // static public System.Boolean op_Inequality(System.String a, System.String b) // Offset: 0x1B36EFC bool operator !=(::Il2CppString* a, ::Il2CppString& b); } DEFINE_IL2CPP_ARG_TYPE(System::String*, "System", "String");
61.925558
317
0.722211
darknight1050