hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
01417b6a4ebc01846c383ea9eb0e7fa8fbb47e23
396
cpp
C++
N0647-Palindromic-Substrings/solution1.cpp
loypt/leetcode
4463aa17b0fb01ec6f865ea9766ccce1ab7a690a
[ "CC0-1.0" ]
null
null
null
N0647-Palindromic-Substrings/solution1.cpp
loypt/leetcode
4463aa17b0fb01ec6f865ea9766ccce1ab7a690a
[ "CC0-1.0" ]
null
null
null
N0647-Palindromic-Substrings/solution1.cpp
loypt/leetcode
4463aa17b0fb01ec6f865ea9766ccce1ab7a690a
[ "CC0-1.0" ]
2
2022-01-25T05:31:31.000Z
2022-02-26T07:22:23.000Z
class Solution { public: int countSubstrings(string s) { int num = 0; int n = s.size(); for(int i=0;i<n;i++)//遍历回文中心点 { for(int j=0;j<=1;j++)//j=0,中心是一个点,j=1,中心是两个点 { int l = i; int r = i+j; while(l>=0 && r<n && s[l--]==s[r++])num++; } } return num; } };
22
58
0.356061
loypt
0149210ca73d9a9f64c0b3f739d097f86b5e5d1d
706
cpp
C++
Fibonacci/Fibonacci.cpp
sounishnath003/CPP-for-beginner
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
[ "MIT" ]
4
2020-05-14T04:41:04.000Z
2021-06-13T06:42:03.000Z
Fibonacci/Fibonacci.cpp
sounishnath003/CPP-for-beginner
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
[ "MIT" ]
null
null
null
Fibonacci/Fibonacci.cpp
sounishnath003/CPP-for-beginner
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> using namespace std ; template<typename T> void printVector(vector<T> n) { for (auto &&i : n) { cout << i << " "; } cout << endl ; } class Fibonacci { private: double series = 0; vector<double> store; public: void getTheFibonacciUpto(int x) { int a = 0, b = 1; for (size_t i = 1; i <= x; i++) { store.push_back(series); series = a + b; a = b; b = series; } printVector(store); } }; int main(int argc, char const *argv[]) { Fibonacci obj ; obj.getTheFibonacciUpto(20); return 0; }
17.219512
40
0.474504
sounishnath003
014c9bc06539884aed89195baa0fc6e530aafb94
1,943
cpp
C++
Graphs/KruskalMST.cpp
paras2411/Algorithms
dcb280d382fc3ee3dbaaf5f1ec2896aae2b05825
[ "MIT" ]
8
2020-09-15T17:54:12.000Z
2022-01-20T04:04:27.000Z
Graphs/KruskalMST.cpp
paras2411/Algorithms
dcb280d382fc3ee3dbaaf5f1ec2896aae2b05825
[ "MIT" ]
null
null
null
Graphs/KruskalMST.cpp
paras2411/Algorithms
dcb280d382fc3ee3dbaaf5f1ec2896aae2b05825
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; // considering maximum no. of vertices to be 100000. const int N = 1e5; int parent[N]; // find the root(ancestor) of the vertex u and returns the no. of vertices in that path int findpar(int *u){ int rank = 0; while(*u != parent[*u]){ *u = parent[*u]; rank++; } return rank; } /* Kruskal is the algrithm to find minimum spanning tree. It takes list of sorted edges wrt to weight. Then iterate that list and add that edge which do not form cycle with the added edges. For checking the cycle we are using "Disjoint set Union" method. Its time complexity is O(E log(E)). Space complexity is (V+E). vector<pair<int, pair<int, int>>> edges -> list of edges with weights w {w, {u, v}} n -> no. of vertices (V) */ void kruskal(vector<pair<int, pair<int, int>>> edges, int n){ // sorting that list of edges with weights sort(edges.begin(), edges.end()); // assigning each vertices to be its parent for(int i=0; i<n; i++){ parent[i] = i; } // cost -> sum of all the weights of the edges added to the MST int cost = 0; int edg_count = 0; // should be n-1 after iteration (Tree) for(auto it = edges.begin(); it != edges.end() && edg_count < n-1; it++){ int weight = (*it).first; pair<int, int> edge = (*it).second; int u = edge.first, v = edge.second; // find the root ancestor of the both vertex and its rank as well int rank_u = findpar(&u); int rank_v = findpar(&v); // If root different then adding this edge will not form cycle. if(u != v){ cost += weight; edg_count += 1; // making root ancestor of both vertex same. if(rank_u < rank_v){ parent[u] = v; } else{ parent[v] = u; } } } }
26.256757
87
0.568194
paras2411
0152528c23cbebd0292482028545ec0aec888717
1,346
cpp
C++
liblineside/test/signalflashtests.cpp
freesurfer-rge/linesidecabinet
8944c67fa7d340aa792e3a6e681113a4676bfbad
[ "MIT" ]
null
null
null
liblineside/test/signalflashtests.cpp
freesurfer-rge/linesidecabinet
8944c67fa7d340aa792e3a6e681113a4676bfbad
[ "MIT" ]
14
2019-11-17T14:46:25.000Z
2021-03-10T02:48:40.000Z
liblineside/test/signalflashtests.cpp
freesurfer-rge/linesidecabinet
8944c67fa7d340aa792e3a6e681113a4676bfbad
[ "MIT" ]
null
null
null
#include <boost/test/unit_test.hpp> #include <boost/test/data/test_case.hpp> #include <boost/test/data/monomorphic.hpp> #include <sstream> #include "lineside/signalflash.hpp" char const* flashNames[] = { "Steady", "Flashing" }; Lineside::SignalFlash flashes[] = { Lineside::SignalFlash::Steady, Lineside::SignalFlash::Flashing }; auto nameToFlashZip = boost::unit_test::data::make(flashNames) ^ boost::unit_test::data::make(flashes); BOOST_AUTO_TEST_SUITE( SignalFlash ) BOOST_DATA_TEST_CASE( ToString, nameToFlashZip, name, flash ) { BOOST_CHECK_EQUAL( name, Lineside::ToString(flash) ); } BOOST_DATA_TEST_CASE( StreamInsertion, nameToFlashZip, name, flash ) { std::stringstream res; res << flash; BOOST_CHECK_EQUAL( res.str(), name ); } BOOST_DATA_TEST_CASE( Parse, nameToFlashZip, name, flash ) { BOOST_CHECK_EQUAL( flash, Lineside::Parse<Lineside::SignalFlash>(name) ); } BOOST_AUTO_TEST_CASE( BadParse ) { const std::string badString = "SomeRandomString"; const std::string expected = "Could not parse 'SomeRandomString' to SignalFlash"; BOOST_CHECK_EXCEPTION( Lineside::Parse<Lineside::SignalFlash>(badString), std::invalid_argument, [=](const std::invalid_argument& ia) { BOOST_CHECK_EQUAL( expected, ia.what() ); return expected == ia.what(); }); } BOOST_AUTO_TEST_SUITE_END()
27.469388
83
0.730312
freesurfer-rge
01542c10efe6ed2d057b98d9df5f63d29a5d3781
1,366
cpp
C++
luogu/3371_2.cpp
shorn1/OI-ICPC-Problems
0c18b3297190a0e108c311c74d28351ebc70c3d1
[ "MIT" ]
1
2020-05-07T09:26:05.000Z
2020-05-07T09:26:05.000Z
luogu/3371_2.cpp
shorn1/OI-ICPC-Problems
0c18b3297190a0e108c311c74d28351ebc70c3d1
[ "MIT" ]
null
null
null
luogu/3371_2.cpp
shorn1/OI-ICPC-Problems
0c18b3297190a0e108c311c74d28351ebc70c3d1
[ "MIT" ]
null
null
null
#include<cstdio> #include<cmath> #include<algorithm> #include<cstring> #include<iostream> #include<queue> using namespace std; const int M = 1111111; struct Edge { int tow,nxt,dat; }; Edge e[2 * M]; int n,m,s,sume = 0,dis[2 * M],vis[2 * M],hea[2 * M]; queue <int>q; void add(int u, int v, int w) { sume++; e[sume].nxt = hea[u]; hea[u] = sume; e[sume].tow = v; e[sume].dat = w; } void init() { for (int i = 0; i <= 2 * m + 1; i++) { e[i].dat = dis[i] = 2147483647; } memset(vis, 0, sizeof(vis)); } void spfa(int s) { dis[s] = 0; vis[s] = 1; q.push(s); while(!q.empty()) { int x = q.front(); q.pop(); vis[x] = 0; for(int now = hea[x];now;now = e[now].nxt) { int y = e[now].tow,z = e[now].dat; if(dis[y] > dis[x] + z) { dis[y] = dis[x]+z; if(!vis[y]) { vis[y] = 1; q.push(y); } } } } } void pans() { for(int i = 1;i <= n;i++) printf("%d ", dis[i]); } int main() { scanf("%d%d%d",&n,&m,&s); init(); for(int i=1;i<=m;i++) { int a,b,c; scanf("%d%d%d",&a,&b,&c); add(a,b,c); //add(b,a,c); } spfa(s); pans(); return 0; }
16.658537
52
0.400439
shorn1
01568fe4e820b402aff4f45d2fd5d36b0ffd1d9b
1,849
hh
C++
include/introvirt/windows/libraries/ws2_32/types/WSABUF.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
23
2021-02-17T16:58:52.000Z
2022-02-12T17:01:06.000Z
include/introvirt/windows/libraries/ws2_32/types/WSABUF.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
1
2021-04-01T22:41:32.000Z
2021-09-24T14:14:17.000Z
include/introvirt/windows/libraries/ws2_32/types/WSABUF.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
4
2021-02-17T16:53:18.000Z
2021-04-13T16:51:10.000Z
/* * Copyright 2021 Assured Information Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <introvirt/core/memory/guest_ptr.hh> #include <cstdint> #include <memory> namespace introvirt { namespace windows { namespace ws2_32 { /** * @brief * * @see https://docs.microsoft.com/en-us/windows/win32/api/ws2def/ns-ws2def-wsabuf */ class WSABUF { public: /** * @brief Get the length of the buffer, in bytes */ virtual uint32_t len() const = 0; /** * @brief Set the length of the buffer, in bytes */ virtual void len(uint32_t len) = 0; /** * @brief Get the buffer */ virtual guest_ptr<const uint8_t[]> buf() const = 0; virtual guest_ptr<uint8_t[]> buf() = 0; /** * @brief Set the buffer */ virtual void buf(const guest_ptr<uint8_t[]>& buf) = 0; /** * @brief Parse a WSABUF instance from the guest * * @param ptr The address of the instance * @param x64 If the structure is 64-bit or not * @return std::shared_ptr<WSABUF> */ static std::shared_ptr<WSABUF> make_shared(const guest_ptr<void>& ptr, bool x64); /** * @brief Get the size of the structure */ static size_t size(bool x64); }; } // namespace ws2_32 } // namespace windows } // namespace introvirt
25.328767
85
0.657112
IntroVirt
01594279291cd64d232ef617f493cb70ac094f93
7,036
cpp
C++
src/ZigBeeCommandLineProcessor.cpp
Suicyc1e/Sequoia
7a31bde385673e5522373eb7a2ee33c4042c3b8d
[ "MIT" ]
null
null
null
src/ZigBeeCommandLineProcessor.cpp
Suicyc1e/Sequoia
7a31bde385673e5522373eb7a2ee33c4042c3b8d
[ "MIT" ]
null
null
null
src/ZigBeeCommandLineProcessor.cpp
Suicyc1e/Sequoia
7a31bde385673e5522373eb7a2ee33c4042c3b8d
[ "MIT" ]
null
null
null
#include <ZigBeeCommandLineProcessor.h> #include <GlobalPresets.h> int StringSplit(String sInput, char cDelim, String sParams[], int iMaxParams) { int iParamCount = 0; int iPosDelim, iPosStart = 0; do { // Searching the delimiter using indexOf() iPosDelim = sInput.indexOf(cDelim,iPosStart); if (iPosDelim > (iPosStart+1)) { // Adding a new parameter using substring() sParams[iParamCount] = sInput.substring(iPosStart,iPosDelim-1); iParamCount++; // Checking the number of parameters if (iParamCount >= iMaxParams) { return (iParamCount); } iPosStart = iPosDelim + 1; } } while (iPosDelim >= 0); if (iParamCount < iMaxParams) { // Adding the last parameter as the end of the line sParams[iParamCount] = sInput.substring(iPosStart); iParamCount++; } return (iParamCount); } void ZigBeeCommandLineProcessor::ProcessIncomingData(String esp32Data) { Serial.println("ZigBee Message Data: " + esp32Data); if (esp32Data.startsWith(_attributeMessagePrefix)) { Serial.println("Message is ATTRIBUTE_CHANGE"); int attributeID = 0; int attributeValue = 0; String splitControl = _attributeMessagePrefix + "%d" + " " + "%d"; int n = sscanf(esp32Data.c_str(), splitControl.c_str(), &attributeID, &attributeValue); if (n != 2) { Serial.println("WARNING! Sscanf didn't parse the message correctly!"); } Serial.printf(" Attribute ID && Data: %d && %d \n", attributeID, attributeValue); ZigBeeMessage_AttributeChanged message = ZigBeeMessage_AttributeChanged(attributeID, attributeValue, esp32Data); _attributeChangedCallback(message); } else if (esp32Data.startsWith(_nwkSuccessMessagePrefix)) { Serial.println("Message is NWK_SUCCESS"); int finalState = 0; String splitControl = _nwkSuccessMessagePrefix + "%d"; int n = sscanf(esp32Data.c_str(), splitControl.c_str(), &finalState); if (n != 1) { Serial.println("WARNING! Sscanf didn't parse the message correctly!"); } Serial.printf(" Final State: %d \n", finalState); ZigBeeMessage_NwkSuccess message = ZigBeeMessage_NwkSuccess(finalState, esp32Data); _nwkStatusSuccededCallback(message); } else if (esp32Data.startsWith(_nwkFailedMessagePrefix)) { Serial.println("Message is NWK_FAILED"); int finalState = 0; String splitControl = _nwkFailedMessagePrefix + "%d"; int n = sscanf(esp32Data.c_str(), splitControl.c_str(), &finalState); if (n != 1) { Serial.println("WARNING! Sscanf didn't parse the message correctly!"); } Serial.printf(" Final State: %d \n", finalState); ZigBeeMessage_NwkFailed message = ZigBeeMessage_NwkFailed(finalState, esp32Data); _nwkStatusFailedCallback(message); } else { Serial.println("Message is UNKNOWN"); } } void ZigBeeCommandLineProcessor::ZigbeeCommandsReader(void *parameter) { ZigBeeCommandLineProcessor *processor = (ZigBeeCommandLineProcessor*) parameter; while (1) { TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE; TIMERG0.wdt_feed=1; TIMERG0.wdt_wprotect=0; if (ZigBeePort.available()) { String esp32Data = ZigBeePort.readStringUntil('\n'); processor->ProcessIncomingData(esp32Data); } // unsigned long thedelay; // thedelay = micros() + 100; // while (micros() < thedelay) // { // } //Too short delay for music to play. vTaskDelay(UART_COMMAND_LINE_TASK_DELAY_MS/portTICK_PERIOD_MS); } } ZigBeeCommandLineProcessor::ZigBeeCommandLineProcessor( AttributeChangedCallback attrChangedCallback, NwkStatusFailedCallback nwkFailedCallback, NwkStatusSuccededCallback nwkOkCallback) { _attributeChangedCallback = attrChangedCallback; _nwkStatusFailedCallback = nwkFailedCallback; _nwkStatusSuccededCallback = nwkOkCallback; //ExecuteStartUpProcedures(); } void ZigBeeCommandLineProcessor::ExecuteStartUpProcedures() { //Init UART, ask ZigBee if it's ready, etc... //ZigBee Console ZigBeePort.begin(115200); //DBG Message. Delete later. ZigBeePort.println("ZigBee TEST UART Is Initialized."); Serial.println("Starting Thread."); xTaskCreate( ZigbeeCommandsReader, /* Task function. */ "zigbeeCommandsReader", /* String with name of task. */ 10000, /* Stack size in bytes. */ this, /* Parameter passed as input of the task */ 1, /* Priority of the task. */ &ZigBeeCommandsReaderTask); /* Task handle. */ } void ZigBeeCommandLineProcessor::CommandsTest() { ZigBeePort.println(ZigBeeCommand_TryToConnect(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_SoundSaving(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_SetSoundDetect(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_SetAutoAnswer(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_PhotoSaving(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_MicrophoneTriggered(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_ButtonTriggered(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_BoxVibrationAlarmTriggered(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_AdditionalSensorMapperState(19).GetCommand()); ZigBeePort.println(ZigBeeCommand_SetPlantCareDeviceEnable(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_SetPlantCareFunctionalMode(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_SetPlantCareWaterValvesMapper(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_SetPlantCareSoilHumidityMapper(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_SetPlantCareLowerPlantMapper(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_SetPlantCareMiddlePlantMapper(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_SetPlantCareUpperPlantMapper(1).GetCommand()); ZigBeePort.println(ZigBeeCommand_SetPlantCareNoWaterAlarm(1).GetCommand()); } HardwareSerial ZigBeeCommandLineProcessor::ZigBeePort = Serial2; TaskHandle_t ZigBeeCommandLineProcessor::ZigBeeCommandsReaderTask = NULL;
38.032432
124
0.622513
Suicyc1e
015b2fc1bb7a3b4abc8ca03c4369020f5e67bf05
1,428
cc
C++
src/auth.cc
thejk/stuff
67362896a37742e880025b9c85c4fe49d690ba02
[ "BSD-3-Clause" ]
null
null
null
src/auth.cc
thejk/stuff
67362896a37742e880025b9c85c4fe49d690ba02
[ "BSD-3-Clause" ]
null
null
null
src/auth.cc
thejk/stuff
67362896a37742e880025b9c85c4fe49d690ba02
[ "BSD-3-Clause" ]
null
null
null
#include "common.hh" #include "auth.hh" #include "base64.hh" #include "cgi.hh" #include "http.hh" #include "strutils.hh" namespace stuff { bool Auth::auth(CGI* cgi, const std::string& realm, const std::string& passwd, std::string* user) { auto auth = cgi->http_auth(); auto pos = auth.find(' '); if (pos != std::string::npos) { if (ascii_tolower(auth.substr(0, pos)) == "basic") { std::string tmp; if (Base64::decode(auth.substr(pos + 1), &tmp)) { pos = tmp.find(':'); if (pos != std::string::npos) { if (tmp.substr(pos + 1) == passwd) { if (user) user->assign(tmp.substr(0, pos)); return true; } } } } } std::map<std::string, std::string> headers; std::string tmp = realm; for (auto it = tmp.begin(); it != tmp.end(); ++it) { if (!((*it >= 'a' && *it <= 'z') || (*it >= 'A' && *it <= 'Z') || (*it >= '0' && *it <= '9') || *it == '-' || *it == '_' || *it == '.' || *it == ' ')) { *it = '.'; } } headers.insert(std::make_pair("WWW-Authenticate", "Basic realm=\"" + tmp + "\"")); Http::response(401, headers, "Authentication needed"); return false; } } // namespace stuff
30.382979
78
0.429272
thejk
015ea70b359981eae5d6213f851d444c511c4bf3
2,546
hpp
C++
cmdstan/stan/src/stan/lang/ast/fun/var_decl_dims_vis_def.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
1
2019-07-05T01:40:40.000Z
2019-07-05T01:40:40.000Z
cmdstan/stan/src/stan/lang/ast/fun/var_decl_dims_vis_def.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/src/stan/lang/ast/fun/var_decl_dims_vis_def.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
1
2018-08-28T12:09:08.000Z
2018-08-28T12:09:08.000Z
#ifndef STAN_LANG_AST_FUN_VAR_DECL_DIMS_VIS_DEF_HPP #define STAN_LANG_AST_FUN_VAR_DECL_DIMS_VIS_DEF_HPP #include <stan/lang/ast.hpp> #include <vector> namespace stan { namespace lang { var_decl_dims_vis::var_decl_dims_vis() { } std::vector<expression> var_decl_dims_vis::operator()(const nil& /* x */) const { return std::vector<expression>(); // should not be called } std::vector<expression> var_decl_dims_vis::operator()(const int_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const double_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const vector_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const row_vector_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const matrix_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const unit_vector_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const simplex_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const ordered_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const positive_ordered_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const cholesky_factor_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const cholesky_corr_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const cov_matrix_var_decl& x) const { return x.dims_; } std::vector<expression> var_decl_dims_vis::operator()( const corr_matrix_var_decl& x) const { return x.dims_; } } } #endif
28.931818
80
0.552239
yizhang-cae
015f284d8abe647c16ca54578d7e48d01427cd6e
3,698
cpp
C++
src/chartwork/ColorPalette.cpp
nazhor/chartwork
20cb8df257bec39153ea408305640274c9e09d4c
[ "MIT" ]
20
2018-08-29T07:33:21.000Z
2022-03-12T05:05:54.000Z
src/chartwork/ColorPalette.cpp
nazhor/chartwork
20cb8df257bec39153ea408305640274c9e09d4c
[ "MIT" ]
1
2020-10-27T15:04:46.000Z
2020-10-27T15:04:46.000Z
src/chartwork/ColorPalette.cpp
nazhor/chartwork
20cb8df257bec39153ea408305640274c9e09d4c
[ "MIT" ]
7
2015-07-09T20:38:28.000Z
2021-09-27T06:38:11.000Z
#include <chartwork/ColorPalette.h> #include <chartwork/Design.h> namespace chartwork { //////////////////////////////////////////////////////////////////////////////////////////////////// // // ColorPalette // //////////////////////////////////////////////////////////////////////////////////////////////////// ColorPalette::ColorPalette() : m_colors(std::shared_ptr<QList<QColor>>(new QList<QColor>( { design::blue, design::orange, design::green, design::purple, design::red, design::yellow, design::brown, design::gray }))) { } //////////////////////////////////////////////////////////////////////////////////////////////////// const QColor &ColorPalette::color0() const { return (*m_colors)[0]; } //////////////////////////////////////////////////////////////////////////////////////////////////// void ColorPalette::setColor0(const QColor &color0) { (*m_colors)[0] = color0; handleColorUpdate(); } //////////////////////////////////////////////////////////////////////////////////////////////////// const QColor &ColorPalette::color1() const { return (*m_colors)[1]; } //////////////////////////////////////////////////////////////////////////////////////////////////// void ColorPalette::setColor1(const QColor &color1) { (*m_colors)[1] = color1; handleColorUpdate(); } //////////////////////////////////////////////////////////////////////////////////////////////////// const QColor &ColorPalette::color2() const { return (*m_colors)[2]; } //////////////////////////////////////////////////////////////////////////////////////////////////// void ColorPalette::setColor2(const QColor &color2) { (*m_colors)[2] = color2; handleColorUpdate(); } //////////////////////////////////////////////////////////////////////////////////////////////////// const QColor &ColorPalette::color3() const { return (*m_colors)[3]; } //////////////////////////////////////////////////////////////////////////////////////////////////// void ColorPalette::setColor3(const QColor &color3) { (*m_colors)[3] = color3; handleColorUpdate(); } //////////////////////////////////////////////////////////////////////////////////////////////////// const QColor &ColorPalette::color4() const { return (*m_colors)[4]; } //////////////////////////////////////////////////////////////////////////////////////////////////// void ColorPalette::setColor4(const QColor &color4) { (*m_colors)[4] = color4; handleColorUpdate(); } //////////////////////////////////////////////////////////////////////////////////////////////////// const QColor &ColorPalette::color5() const { return (*m_colors)[5]; } //////////////////////////////////////////////////////////////////////////////////////////////////// void ColorPalette::setColor5(const QColor &color5) { (*m_colors)[5] = color5; handleColorUpdate(); } //////////////////////////////////////////////////////////////////////////////////////////////////// const QColor &ColorPalette::color6() const { return (*m_colors)[6]; } //////////////////////////////////////////////////////////////////////////////////////////////////// void ColorPalette::setColor6(const QColor &color6) { (*m_colors)[6] = color6; handleColorUpdate(); } //////////////////////////////////////////////////////////////////////////////////////////////////// const QColor &ColorPalette::color7() const { return (*m_colors)[7]; } //////////////////////////////////////////////////////////////////////////////////////////////////// void ColorPalette::setColor7(const QColor &color7) { (*m_colors)[7] = color7; handleColorUpdate(); } //////////////////////////////////////////////////////////////////////////////////////////////////// }
24.328947
100
0.330719
nazhor
015f8fbd13144338c56420d36b5dfb1cc578986c
1,827
hpp
C++
header/deps/filehelp.hpp
jonathanmarp/tfsound
18942c35f1d3f4d335670b7d381f8a75b6a7e465
[ "MIT" ]
2
2021-06-05T10:15:53.000Z
2021-06-06T09:51:19.000Z
header/deps/filehelp.hpp
jonathanmarp/tfsound
18942c35f1d3f4d335670b7d381f8a75b6a7e465
[ "MIT" ]
null
null
null
header/deps/filehelp.hpp
jonathanmarp/tfsound
18942c35f1d3f4d335670b7d381f8a75b6a7e465
[ "MIT" ]
1
2021-06-08T05:56:35.000Z
2021-06-08T05:56:35.000Z
// MIT License // Copyright (c) 2021 laferenorg // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef _FILESHELP_HPP #define _FILESHELP_HPP /* Library C++ */ #include <ios> #include <fstream> // class FILESHELP class FILESHELP { private: // variable settings in here std::string namefile; // variable namefile public: // function constructor for fill variable FILESHELP FILESHELP(const char* nameFile); public: // function open and close file // function for open file void F_openFile(); // function for close file void F_closeFile(); public: // return refrencf fstream variable std::fstream& getVarFile(); public: // function for check file its exist bool itsExist(); public: // function for get all string file std::string getFile(); }; #endif // _FILESHELP_HPP
33.218182
81
0.746579
jonathanmarp
01635e6161a725aca5e9748a3bdc8945400a2a2f
6,958
cxx
C++
3rd/fltk/src/win32/list_fonts.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
11
2017-09-30T12:21:55.000Z
2021-04-29T21:31:57.000Z
3rd/fltk/src/win32/list_fonts.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
2
2017-07-11T11:20:08.000Z
2018-03-27T12:09:02.000Z
3rd/fltk/src/win32/list_fonts.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
24
2018-03-27T11:46:16.000Z
2021-05-01T20:28:34.000Z
// // "$Id: list_fonts.cxx 5958 2007-10-17 20:21:38Z spitzak $" // // _WIN32 font utilities for the Fast Light Tool Kit (FLTK). // // Copyright 1998-2006 by Bill Spitzak and others. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems to "fltk-bugs@fltk.org". // #include <fltk/events.h> #include <fltk/utf.h> #include <fltk/x.h> #include <ctype.h> #include <wchar.h> #include <string.h> #include <stdlib.h> #include <config.h> using namespace fltk; extern int has_unicode(); int Font::encodings(const char**& arrayp) { // CET - FIXME - What about this encoding stuff? // WAS: we need some way to find out what charsets are supported // and turn these into ISO encoding names, and return this list. // This is a poor simulation: static const char* simulation[] = {"iso10646-1", 0}; arrayp = simulation; return 1; } //////////////////////////////////////////////////////////////// // List sizes: static int nbSize; //static int cyPerInch; #define MAX_SIZES 16 static int sizes[MAX_SIZES]; static int CALLBACK EnumSizeCb(CONST LOGFONTW* lpelf, CONST TEXTMETRICW* lpntm, DWORD fontType, LPARAM p) { if ((fontType & RASTER_FONTTYPE) == 0) { // Scalable font sizes[0] = 0; nbSize = 1; return 0; } int add = lpntm->tmHeight - lpntm->tmInternalLeading; //add = MulDiv(add, 72, cyPerInch); // seems to be correct before this int start = 0; while ((start < nbSize) && (sizes[start] < add)) start++; if ((start < nbSize) && (sizes[start] == add)) return (1); for (int i=nbSize; i>start; i--) sizes[i] = sizes[i - 1]; sizes[start] = add; nbSize++; // Stop enum if buffer overflow return (nbSize < MAX_SIZES); } int Font::sizes(int*& sizep) { nbSize = 0; HDC dc = getDC(); //cyPerInch = GetDeviceCaps(dc, LOGPIXELSY); //if (cyPerInch < 1) cyPerInch = 1; if (has_unicode()) { wchar_t ucs[1024]; utf8towc(name_, strlen(name_), ucs, 1024); #if defined(__BORLANDC__) || defined(__DMC__) EnumFontFamiliesW(dc, ucs, (FONTENUMPROCA)EnumSizeCb, 0); #else EnumFontFamiliesW(dc, ucs, EnumSizeCb, 0); #endif } else { EnumFontFamiliesA(dc, name_, (FONTENUMPROCA)EnumSizeCb, 0); } sizep = ::sizes; return nbSize; } //////////////////////////////////////////////////////////////// // list fonts: extern "C" { static int sort_function(const void *aa, const void *bb) { fltk::Font* a = *(fltk::Font**)aa; fltk::Font* b = *(fltk::Font**)bb; int ret = stricmp(a->name_, b->name_); if (ret) return ret; return a->attributes_ - b->attributes_; }} extern Font* fl_make_font(const char* name, int attrib); static Font** font_array = 0; static int num_fonts = 0; static int array_size = 0; static int CALLBACK enumcbW(CONST LOGFONTW* lplf, CONST TEXTMETRICW* lpntm, DWORD fontType, LPARAM p) { // we need to do something about different encodings of the same font // in order to match X! I can't tell if each different encoding is // returned sepeartely or not. This is what fltk 1.0 did: if (lplf->lfCharSet != ANSI_CHARSET) return 1; const wchar_t *name = lplf->lfFaceName; //const char *name = (const char*)(((ENUMLOGFONT *)lplf)->elfFullName); char buffer[1024]; utf8fromwc(buffer, 1024, name, wcslen(name)); // ignore mystery garbage font names: if (buffer[0] == '@') return 1; if (num_fonts >= array_size) { array_size = array_size ? 2*array_size : 128; font_array = (Font**)realloc(font_array, array_size*sizeof(Font*)); } int attrib = 0; // if (lplf->lfWeight > 400 || strstr(name, " Bold") == name+strlen(name)-5) // attrib = BOLD; font_array[num_fonts++] = fl_make_font(buffer, attrib); return 1; } static int CALLBACK enumcbA(CONST LOGFONT* lplf, CONST TEXTMETRIC* lpntm, DWORD fontType, LPARAM p) { // we need to do something about different encodings of the same font // in order to match X! I can't tell if each different encoding is // returned sepeartely or not. This is what fltk 1.0 did: //if (lplf->lfCharSet != ANSI_CHARSET) return 1; const char *name = lplf->lfFaceName; if (num_fonts >= array_size) { array_size = array_size ? 2*array_size : 128; font_array = (Font**)realloc(font_array, array_size*sizeof(Font*)); } int attrib = 0; font_array[num_fonts++] = fl_make_font(name, attrib); return 1; } int fltk::list_fonts(Font**& arrayp) { if (font_array) {arrayp = font_array; return num_fonts;} HDC dc = getDC(); if (has_unicode()) { LOGFONTW lf; memset(&lf, 0, sizeof(lf)); lf.lfCharSet = DEFAULT_CHARSET; EnumFontFamiliesExW(dc, &lf, (FONTENUMPROCW)enumcbW, 0, 0); } else { LOGFONT lf; memset(&lf, 0, sizeof(lf)); lf.lfCharSet = DEFAULT_CHARSET; EnumFontFamiliesExA(dc, &lf, (FONTENUMPROCA)enumcbA, 0, 0); } ReleaseDC(0, dc); qsort(font_array, num_fonts, sizeof(*font_array), sort_function); arrayp = font_array; return num_fonts; } //////////////////////////////////////////////////////////////// // This function apparently is needed to translate some font names // stored in setup files to the actual name of a font. Currently // font(name) calls this. #if defined(WIN32) && !defined(__CYGWIN__) static const char* GetFontSubstitutes(const char* name,int& len) { static char subst_name[1024]; //used BUFLEN from bool fltk_theme() if ( strstr(name,"MS Shell Dlg") || strstr(name,"Helv") || strstr(name,"Tms Rmn")) { DWORD type = REG_SZ; LONG err; HKEY key; char truncname[1024]; strncpy(truncname, name, len); truncname[len] = 0; err = RegOpenKey( HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes", &key ); if (err == ERROR_SUCCESS) { DWORD L=1024; err = RegQueryValueEx( key, truncname, 0L, &type, (BYTE*) subst_name, &L); RegCloseKey(key); if ( err == ERROR_SUCCESS ) { len = L; return subst_name; } } } return name; } #endif // // End of "$Id: list_fonts.cxx 5958 2007-10-17 20:21:38Z spitzak $" //
29.991379
79
0.632078
MarioHenze
016871b7df9e584799df839cda630bd6279531cd
636
hpp
C++
Plutonium/Include/pu/overlay/Toast.hpp
Falki14/Plutonium
e39894f87b57695d4288052979e23d4115932697
[ "MIT" ]
null
null
null
Plutonium/Include/pu/overlay/Toast.hpp
Falki14/Plutonium
e39894f87b57695d4288052979e23d4115932697
[ "MIT" ]
null
null
null
Plutonium/Include/pu/overlay/Toast.hpp
Falki14/Plutonium
e39894f87b57695d4288052979e23d4115932697
[ "MIT" ]
null
null
null
/* Plutonium library @file Overlay.hpp @brief TODO... @author XorTroll @copyright Plutonium project - an easy-to-use UI framework for Nintendo Switch homebrew */ #pragma once #include <pu/overlay/Overlay.hpp> namespace pu::overlay { class Toast : public Overlay { public: Toast(std::string Text, u32 FontSize, draw::Color TextColor, draw::Color BaseColor); void SetText(std::string Text); void OnPreRender(render::Renderer *Drawer); void OnPostRender(render::Renderer *Drawer); private: pu::element::TextBlock *text; }; }
21.931034
96
0.624214
Falki14
6c75aa25ebca362bf52e57a3e7660b4f89500ead
5,062
cpp
C++
src-plugins/reformat/resampleProcess.cpp
nebatmusic/medInria-public
09000bd2f129692e42314a8eb1313d238603252e
[ "BSD-1-Clause" ]
1
2020-11-16T13:55:45.000Z
2020-11-16T13:55:45.000Z
src-plugins/reformat/resampleProcess.cpp
nebatmusic/medInria-public
09000bd2f129692e42314a8eb1313d238603252e
[ "BSD-1-Clause" ]
null
null
null
src-plugins/reformat/resampleProcess.cpp
nebatmusic/medInria-public
09000bd2f129692e42314a8eb1313d238603252e
[ "BSD-1-Clause" ]
null
null
null
#include "resampleProcess.h" #include <dtkCore/dtkAbstractProcessFactory.h> #include <medAbstractDataFactory.h> #include <medAbstractProcess.h> #include <medMetaDataKeys.h> #include <medUtilitiesITK.h> #include <itkResampleImageFilter.h> #include <itkBSplineInterpolateImageFunction.h> // ///////////////////////////////////////////////////////////////// // resampleProcessPrivate // ///////////////////////////////////////////////////////////////// class resampleProcessPrivate { public: resampleProcess *parent; resampleProcessPrivate(resampleProcess *p) { parent = p; } medAbstractData* input; medAbstractData* output; int interpolator; int dimX,dimY,dimZ; double spacingX,spacingY,spacingZ; }; // ///////////////////////////////////////////////////////////////// // resampleProcess // ///////////////////////////////////////////////////////////////// resampleProcess::resampleProcess(void) : d(new resampleProcessPrivate(this)) { d->dimX=0; d->dimY=0; d->dimZ=0; d->spacingX = 0.0; d->spacingY = 0.0; d->spacingZ = 0.0; } resampleProcess::~resampleProcess(void) { delete d; d = NULL; } bool resampleProcess::registered(void) { return dtkAbstractProcessFactory::instance()->registerProcessType("resampleProcess", createResampleProcess); } QString resampleProcess::description(void) const { return "resampleProcess"; } void resampleProcess::setInput ( medAbstractData *data) { if ( !data ) return; d->input = data; } void resampleProcess::setInput ( medAbstractData *data , int channel) { setInput(data); } void resampleProcess::setParameter ( double data, int channel) { switch (channel) { case 0: d->dimX = (int)data; break; case 1: d->dimY = (int)data; break; case 2: d->dimZ = (int)data; break; case 3: d->spacingX = data; break; case 4: d->spacingY = data; break; case 5: d->spacingZ = data; break; } } int resampleProcess::update ( void ) { int result = DTK_FAILURE; if (!d->input) { qDebug() << "in update method : d->input is NULL"; } else { result = DISPATCH_ON_3D_PIXEL_TYPE(&resampleProcess::resample, this, d->input); if (result == medAbstractProcess::PIXEL_TYPE) { result = DISPATCH_ON_4D_PIXEL_TYPE(&resampleProcess::resample, this, d->input); } } return result; } template <class ImageType> int resampleProcess::resample(medAbstractData* inputData) { typename ImageType::Pointer inputImage = static_cast<ImageType*>(inputData->data()); typedef typename itk::ResampleImageFilter<ImageType, ImageType,double> ResampleFilterType; typename ResampleFilterType::Pointer resampleFilter = ResampleFilterType::New(); //// Fetch original image size. const typename ImageType::RegionType& inputRegion = inputImage->GetLargestPossibleRegion(); const typename ImageType::SizeType& vnInputSize = inputRegion.GetSize(); unsigned int nOldX = vnInputSize[0]; unsigned int nOldY = vnInputSize[1]; unsigned int nOldZ = vnInputSize[2]; //// Fetch original image spacing. const typename ImageType::SpacingType& vfInputSpacing = inputImage->GetSpacing(); double vfOutputSpacing[3]={d->spacingX,d->spacingY,d->spacingZ}; if (d->dimX || d->dimY || d->dimZ) { vfOutputSpacing[0] = vfInputSpacing[0] * (double) nOldX / (double) d->dimX; vfOutputSpacing[1] = vfInputSpacing[1] * (double) nOldY / (double) d->dimY; vfOutputSpacing[2] = vfInputSpacing[2] * (double) nOldZ / (double) d->dimZ; } else { d->dimX = floor((vfInputSpacing[0] * (double) nOldX / (double) vfOutputSpacing[0]) +0.5); d->dimY = floor((vfInputSpacing[1] * (double) nOldY / (double) vfOutputSpacing[1]) +0.5); d->dimZ = floor((vfInputSpacing[2] * (double) nOldZ / (double) vfOutputSpacing[2]) +0.5); } typename ImageType::SizeType vnOutputSize; vnOutputSize[0] = d->dimX; vnOutputSize[1] = d->dimY; vnOutputSize[2] = d->dimZ; resampleFilter->SetInput(inputImage); resampleFilter->SetSize(vnOutputSize); resampleFilter->SetOutputSpacing(vfOutputSpacing); resampleFilter->SetOutputOrigin( inputImage->GetOrigin() ); resampleFilter->SetOutputDirection(inputImage->GetDirection() ); resampleFilter->UpdateLargestPossibleRegion(); d->output = medAbstractDataFactory::instance()->create(inputData->identifier()); d->output->setData(resampleFilter->GetOutput()); medUtilities::setDerivedMetaData(d->output, inputData, "resampled"); return DTK_SUCCEED; } medAbstractData * resampleProcess::output ( void ) { return ( d->output ); } // ///////////////////////////////////////////////////////////////// // Type instantiation // ///////////////////////////////////////////////////////////////// dtkAbstractProcess *createResampleProcess(void) { return new resampleProcess; }
28.925714
112
0.614184
nebatmusic
6c767fd7fe905d57aad21b55162e1077581ede1f
6,219
hpp
C++
libraries/chain/include/deip/chain/services/dbs_expertise_allocation_proposal.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
1
2021-08-16T12:44:43.000Z
2021-08-16T12:44:43.000Z
libraries/chain/include/deip/chain/services/dbs_expertise_allocation_proposal.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
null
null
null
libraries/chain/include/deip/chain/services/dbs_expertise_allocation_proposal.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
2
2021-08-16T12:44:46.000Z
2021-12-31T17:09:45.000Z
#pragma once #include "dbs_base_impl.hpp" #include <vector> #include <set> #include <functional> #include <deip/chain/schema/expertise_allocation_proposal_object.hpp> #include <deip/chain/schema/expertise_allocation_proposal_vote_object.hpp> #include <deip/chain/schema/expert_token_object.hpp> namespace deip { namespace chain { class dbs_expertise_allocation_proposal : public dbs_base { friend class dbservice_dbs_factory; dbs_expertise_allocation_proposal() = delete; protected: explicit dbs_expertise_allocation_proposal(database &db); public: using expertise_allocation_proposal_refs_type = std::vector<std::reference_wrapper<const expertise_allocation_proposal_object>>; using expertise_allocation_proposal_optional_ref_type = fc::optional<std::reference_wrapper<const expertise_allocation_proposal_object>>; const expertise_allocation_proposal_object& create(const account_name_type& claimer, const discipline_id_type& discipline_id, const string& description); const expertise_allocation_proposal_object& get(const expertise_allocation_proposal_id_type& id) const; const expertise_allocation_proposal_optional_ref_type get_expertise_allocation_proposal_if_exists(const expertise_allocation_proposal_id_type& id) const; void remove(const expertise_allocation_proposal_id_type& id); expertise_allocation_proposal_refs_type get_by_claimer(const account_name_type& claimer) const; const expertise_allocation_proposal_object& get_by_claimer_and_discipline(const account_name_type& claimer, const discipline_id_type& discipline_id) const; const expertise_allocation_proposal_optional_ref_type get_expertise_allocation_proposal_by_claimer_and_discipline_if_exists(const account_name_type& claimer, const discipline_id_type& discipline_id) const; expertise_allocation_proposal_refs_type get_by_discipline_id(const discipline_id_type& discipline_id) const; void check_existence_by_claimer_and_discipline(const account_name_type &claimer, const discipline_id_type &discipline_id); bool exists_by_claimer_and_discipline(const account_name_type &claimer, const discipline_id_type &discipline_id); void upvote(const expertise_allocation_proposal_object &expertise_allocation_proposal, const account_name_type &voter, const share_type weight); void downvote(const expertise_allocation_proposal_object &expertise_allocation_proposal, const account_name_type &voter, const share_type weight); bool is_expired(const expertise_allocation_proposal_object& expertise_allocation_proposal); bool is_quorum(const expertise_allocation_proposal_object &expertise_allocation_proposal); void delete_by_claimer_and_discipline(const account_name_type &claimer, const discipline_id_type& discipline_id); void clear_expired_expertise_allocation_proposals(); void process_expertise_allocation_proposals(); /* Expertise allocation proposal vote */ using expertise_allocation_proposal_vote_refs_type = std::vector<std::reference_wrapper<const expertise_allocation_proposal_vote_object>>; using expertise_allocation_proposal_vote_optional_ref_type = fc::optional<std::reference_wrapper<const expertise_allocation_proposal_vote_object>>; const expertise_allocation_proposal_vote_object& create_vote(const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id, const discipline_id_type& discipline_id, const account_name_type &voter, const share_type weight); const expertise_allocation_proposal_vote_object& get_vote(const expertise_allocation_proposal_vote_id_type& id) const; const expertise_allocation_proposal_vote_optional_ref_type get_expertise_allocation_proposal_vote_if_exists(const expertise_allocation_proposal_vote_id_type& id) const; const expertise_allocation_proposal_vote_object& get_vote_by_voter_and_expertise_allocation_proposal_id(const account_name_type &voter, const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id) const; const expertise_allocation_proposal_vote_optional_ref_type get_expertise_allocation_proposal_vote_by_voter_and_expertise_allocation_proposal_id_if_exists(const account_name_type &voter, const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id) const; expertise_allocation_proposal_vote_refs_type get_votes_by_expertise_allocation_proposal_id(const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id) const; expertise_allocation_proposal_vote_refs_type get_votes_by_voter_and_discipline_id(const account_name_type& voter, const discipline_id_type& discipline_id) const; expertise_allocation_proposal_vote_refs_type get_votes_by_voter(const account_name_type& voter) const; bool vote_exists_by_voter_and_expertise_allocation_proposal_id(const account_name_type &voter, const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id); /* Adjusting */ void adjust_expert_token_vote(const expert_token_object& expert_token, share_type delta); }; } // namespace chain } // namespace deip
56.027027
243
0.705419
DEIPworld
6c7737a2a29d9a93b0374dec4932899a19dd8a36
265
cpp
C++
tests/src/test.cpp
pqrs-org/cpp-environment_variable
2b1d547603f5ce4a4455a254a4dbe514f14cd75e
[ "BSL-1.0" ]
null
null
null
tests/src/test.cpp
pqrs-org/cpp-environment_variable
2b1d547603f5ce4a4455a254a4dbe514f14cd75e
[ "BSL-1.0" ]
null
null
null
tests/src/test.cpp
pqrs-org/cpp-environment_variable
2b1d547603f5ce4a4455a254a4dbe514f14cd75e
[ "BSL-1.0" ]
null
null
null
#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include <pqrs/environment_variable.hpp> TEST_CASE("find") { REQUIRE(pqrs::environment_variable::find("PATH")); REQUIRE(pqrs::environment_variable::find("UNKNOWN_ENVIRONMENT_VARIABLE") == std::nullopt); }
26.5
92
0.766038
pqrs-org
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
2fd158e68edbe45a9c974c01319d53d3d5100685
1,430
cpp
C++
5-1_if_else_if_2.cpp
ahfa92/cpp
bddd80ea5c6aca23c91bd6693bb32da06e67cbd2
[ "MIT" ]
null
null
null
5-1_if_else_if_2.cpp
ahfa92/cpp
bddd80ea5c6aca23c91bd6693bb32da06e67cbd2
[ "MIT" ]
null
null
null
5-1_if_else_if_2.cpp
ahfa92/cpp
bddd80ea5c6aca23c91bd6693bb32da06e67cbd2
[ "MIT" ]
null
null
null
#include <stdio.h> #include <conio.h> #include <iostream.h> #include <string> main() { char kd[3],mskp[15]; int kls; long hrg=0; cout<<"Masukkan Kode Pesawat [MPT/GRD/BTV] : ";cin>>kd; cout<<"Kelas Pesawat : ";cin>>kls; if(strcmp(kd,"MPT") || strcmp(kd,"mpt") || strcmp(kd,"Mpt")) { strcpy(mskp,"Merpati"); if(kls == 1){ hrg = 1500000; } else if(kls == 2){ hrg = 900000; } else if(kls == 3){ hrg = 500000; } else { cout<<"Kode Kelas Salah"<<endl; } } else if(strcmp(kd,"GRD") || strcmp(kd,"grd") || strcmp(kd,"Grd")) { strcpy(mskp,"Garuda"); if(kls == '1'){ hrg = 1200000; } else if(kls == '2'){ hrg = 800000; } else if(kls == '3'){ hrg = 400000; } else { cout<<"Kode Kelas Salah"<<endl; } } else if(strcmp(kd,"BTV") || strcmp(kd,"btv") || strcmp(kd,"Btv")) { strcpy(mskp,"Batavia"); if(kls == '1'){ hrg = 1000000; } else if(kls == '2'){ hrg = 700000; } else if(kls == '3'){ hrg = 300000; } else { cout<<"Kode Kelas Salah"<<endl; } } else { cout<<"Kode Maskapai Salah"<<endl; } cout<<"======================"<<endl; cout<<"Nama Pesawat : "<<mskp<<endl; cout<<"Harga Tiket : "<<hrg<<endl; getch(); }
19.324324
70
0.443357
ahfa92
2fd2689eda384e86d0f9c0e3dd861e7f3487a81a
912
cpp
C++
DxEngine/GDepthStencil.cpp
psk7142/DirectX2D
1d91e8a863aab2dbf57fecd2df111261a90dd3de
[ "MIT" ]
null
null
null
DxEngine/GDepthStencil.cpp
psk7142/DirectX2D
1d91e8a863aab2dbf57fecd2df111261a90dd3de
[ "MIT" ]
null
null
null
DxEngine/GDepthStencil.cpp
psk7142/DirectX2D
1d91e8a863aab2dbf57fecd2df111261a90dd3de
[ "MIT" ]
2
2020-03-09T15:12:11.000Z
2020-03-09T16:04:04.000Z
#include "GDepthStencil.h" GDepthStencil::GDepthStencil( ) : mDSDesc(D3D11_DEPTH_STENCIL_DESC( )) , mState(nullptr) { EMPTY_STATEMENT; } GDepthStencil::~GDepthStencil( ) { if ( nullptr != mState ) { mState->Release( ); mState = nullptr; } } bool GDepthStencil::Create( ) { mDSDesc.DepthEnable = true; mDSDesc.DepthFunc = D3D11_COMPARISON_FUNC::D3D11_COMPARISON_LESS; mDSDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK::D3D11_DEPTH_WRITE_MASK_ALL; mDSDesc.StencilEnable = false; return Create(mDSDesc); } bool GDepthStencil::Create(const D3D11_DEPTH_STENCIL_DESC& _desc) { if ( &mDSDesc != &_desc ) { mDSDesc = _desc; } if ( FAILED(GEngineDevice::MainDevice( ).GetIDevice( ).CreateDepthStencilState(&mDSDesc, &mState)) ) { CRASH_PROG; return false; } return true; } void GDepthStencil::Update( ) { GEngineDevice::MainDevice( ).GetIContext( ).OMSetDepthStencilState(mState, 0); }
18.612245
101
0.730263
psk7142
2fd425d15c738d0423fd34bc77ada9b61274025e
7,803
hpp
C++
sdl/Hypergraph/ArcParserFct.hpp
sdl-research/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
29
2015-01-26T21:49:51.000Z
2021-06-18T18:09:42.000Z
sdl/Hypergraph/ArcParserFct.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
1
2015-12-08T15:03:15.000Z
2016-01-26T14:31:06.000Z
sdl/Hypergraph/ArcParserFct.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
4
2015-11-21T14:25:38.000Z
2017-10-30T22:22:00.000Z
// Copyright 2014-2015 SDL plc // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** \file parse text format hypergraph arcs. */ #ifndef HYP__HYPERGRAPH_ARCPARSERFCT_HPP #define HYP__HYPERGRAPH_ARCPARSERFCT_HPP #pragma once #include <sdl/Hypergraph/ArcParser.hpp> #include <sdl/Hypergraph/Exception.hpp> #include <sdl/Hypergraph/IHypergraph.hpp> #include <sdl/Hypergraph/IMutableHypergraph.hpp> #include <sdl/Hypergraph/LabelPair.hpp> #include <sdl/Hypergraph/ParsedArcsToHg.hpp> #include <sdl/Hypergraph/SymbolPrint.hpp> #include <sdl/Util/Contains.hpp> #include <sdl/Util/Flag.hpp> #include <sdl/Util/Input.hpp> #include <sdl/Util/LogHelper.hpp> #include <sdl/Util/NormalizeUtf8.hpp> #include <sdl/IVocabulary.hpp> #include <sdl/SharedPtr.hpp> #include <cassert> #include <map> #include <string> #include <utility> #include <vector> namespace sdl { namespace Hypergraph { namespace ArcParserFctUtil { /** Determines if string starts and end with angle brackets and has some chars in between, e.g., <eps>. */ inline bool isInAngleBrackets(std::string const& str) { std::string::size_type len = str.length(); return len > 2 && str[0] == '<' && str[len - 1] == '>'; } // /** \return symbol from string unless output, if <xmt-blockN>, then increment numBlockStartSymsSeen Special syms like <eps> are not enclosed in quotes but in < >. If the parsed text contains other syms like "the" or "<html>", they will be in quotes. */ inline Sym add(IVocabulary& voc, std::string const& word, bool lex, std::size_t* numBlockStartSymsSeen, Sym defaultSym = NoSymbol, bool increaseNumBlocks = true) { if (word.empty()) return defaultSym; // we don't allow quoted "<special>" if (lex) return voc.add(word, kTerminal); else { if (isInAngleBrackets(word)) { Sym id = Vocabulary::specialSymbols().sym(word); if (id) { if (id == BLOCK_START::ID) { assert(numBlockStartSymsSeen); id += (SymInt)*numBlockStartSymsSeen; if (increaseNumBlocks) ++*numBlockStartSymsSeen; } return id; } else { SDL_WARN(Hypergraph.ArcParser, "unknown special symbol " << word << " - treating as nonterminal"); } } return voc.add(word, kNonterminal); } } } LabelPair const NoSymbols(NoSymbol, NoSymbol); template <class Arc> void addState(ParserUtil::State& s, SymsToState* symsToState, StateId& highestStateId, IVocabulary& voc, IMutableHypergraph<Arc>* result, std::string const& src, std::size_t linenum, std::size_t* numBlockStartSymsSeen) { // need to call input before output symbol so block-start is incremented (true) Sym const input = ArcParserFctUtil::add(voc, s.inputSymbol, s.isInputSymbolLexical, numBlockStartSymsSeen, NoSymbol, true); Sym const output = ArcParserFctUtil::add(voc, s.outputSymbol, s.isOutputSymbolLexical, numBlockStartSymsSeen, NoSymbol, false); LabelPair newLabels(input, output); if (s.id == kNoState) { if (newLabels == NoSymbols) SDL_THROW_LOG(Hypergraph.ArcParserFct, FileFormatException, "syntax error: addState for no labels and no state"); StateId* pState; if (Util::update(*symsToState, newLabels, pState)) { result->addStateId(s.id = *pState = ++highestStateId, newLabels); } else { s.id = *pState; assert(s.id < result->size()); } } else if (s.id == ParserUtil::State::kStart || s.id == ParserUtil::State::kFinal) { if (newLabels != NoSymbols) SDL_THROW_LOG(Hypergraph.ArcParserFct, FileFormatException, "syntax error: " << src << ":" << linenum << ":syntax error (START and FINAL cannot have symbols)" << ": " << s); } else { // state was specified already (*symsToState)[newLabels] = s.id; // this may be updated several times if user keeps using diff stateids w/ same label LabelPair existingLabels = result->labelPairOptionalOutput(s.id); if (newLabels == NoSymbols) { result->addStateId(s.id); } else if (existingLabels == NoSymbols || existingLabels == newLabels) { result->addStateId(s.id, newLabels); } else if (compatible(existingLabels, newLabels)) { if (!newLabels.second) { newLabels.second = newLabels.first; (*symsToState)[newLabels] = s.id; } result->addStateId(s.id, newLabels); } else { SDL_THROW_LOG(Hypergraph.ArcParserFct, FileFormatException, src << ":" << linenum << ": syntax error (incompatible symbols for state " << s.id << ")" << ": " << s << "; previous labels=" << printer(existingLabels, &voc) << " vs. new labels=" << printer(newLabels, &voc)); } } } namespace impl { /** used as parseText(ParsedArcs ...) which takes ownership of new arcs. TODO: smart ptr */ struct ParsedArcsConsumer { ParsedArcs& arcs; ParsedArcsConsumer(ParsedArcs& arcs) : arcs(arcs) {} ArcParser arcParser; mutable Util::Counter linenum; /// line is chomped (no trailing '\n') per StringConsumer void operator()(std::string const& line) const { ++linenum; if (!(line.empty() || line[0] == '#')) { ParserUtil::Arc* pArc = arcParser.parse(line); if (!pArc) SDL_THROW_LOG(Hypergraph.ParsedLines, FileFormatException, ":" << linenum << ":syntax error" << line); arcs.push_back(pArc); } } }; } template <class Arc> void parseText(std::istream& in, std::string const& inFilename, IMutableHypergraph<Arc>* result, bool requireNfc = true) { ParsedArcs arcs; impl::ParsedArcsConsumer accept(arcs); Util::visitChompedLines(in, accept, requireNfc); parsedArcsToHg(arcs, result, inFilename); } template <class Arc> MutableHypergraph<Arc>* readHypergraphNew(std::istream& in, IVocabularyPtr pVoc, Properties props = kFsmOutProperties, std::string const& inName = "input") { MutableHypergraph<Arc>* r = new MutableHypergraph<Arc>(props); r->setVocabulary(pVoc); parseText(in, inName, r); return r; } template <class Arc> shared_ptr<IHypergraph<Arc>> readHypergraph(std::istream& in, IVocabularyPtr pVoc, Properties props = kFsmOutProperties, std::string const& inName = "input") { return readHypergraphNew<Arc>(in, pVoc, props, inName); } template <class Arc> IHypergraph<Arc>& readHypergraph(std::istream& in, IMutableHypergraph<Arc>& hg, std::string const& inName = "input") { hg.clear(); hg.forceStoreArcs(); parseText(in, inName, &hg); return hg; } template <class Arc> shared_ptr<IHypergraph<Arc>> readHypergraph(Util::InputStream const& in, IVocabularyPtr pVoc, Properties props = kFsmOutProperties) { return readHypergraph<Arc>(*in, pVoc, props, in.name); } template <class Arc> IHypergraph<Arc>& readHypergraph(Util::InputStream const& in, IMutableHypergraph<Arc>& hg) { return readHypergraph(*in, hg, in.name); } }} #endif
36.125
110
0.647059
sdl-research
7c7d02ef078a9afa4d8469b8b6ed6e06f9f2d757
2,327
cpp
C++
Photon/photon/gfx/Shader.cpp
tatjam/Photon
a0c1584d10e1422cc2e468a6f94351a8310b7599
[ "MIT" ]
1
2017-05-28T12:10:30.000Z
2017-05-28T12:10:30.000Z
Photon/photon/gfx/Shader.cpp
tatjam/Photon
a0c1584d10e1422cc2e468a6f94351a8310b7599
[ "MIT" ]
null
null
null
Photon/photon/gfx/Shader.cpp
tatjam/Photon
a0c1584d10e1422cc2e468a6f94351a8310b7599
[ "MIT" ]
null
null
null
#include "Shader.h" namespace ph { void Shader::use() { glUseProgram(pr); } void Shader::load(std::string vpath, std::string fpath) { en->log(INF) << "Loading shaders: (" << vpath << ", " << fpath << ")" << endlog; std::string vertexCode; std::string fragmentCode; std::ifstream vShaderFile; std::ifstream fShaderFile; try { vShaderFile.open(vpath); fShaderFile.open(fpath); if (vShaderFile.bad() || fShaderFile.bad()) { throw(std::exception("!")); } std::stringstream vShaderStream, fShaderStream; vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); vShaderFile.close(); fShaderFile.close(); vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); } catch (std::exception e) { en->log(ERR) << "Could not load shader files" << endlog; } const GLchar* vShaderCode = vertexCode.c_str(); const GLchar * fShaderCode = fragmentCode.c_str(); GLuint vertex, fragment; GLint success; GLchar infoLog[512]; vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); glGetShaderiv(vertex, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertex, 512, NULL, infoLog); en->log(ERR) << "Could not compile vertex shader: " << infoLog << endlog; } fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); glGetShaderiv(fragment, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragment, 512, NULL, infoLog); en->log(ERR) << "Could not compile fragment shader: " << infoLog << endlog; } this->pr = glCreateProgram(); glAttachShader(this->pr, vertex); glAttachShader(this->pr, fragment); glLinkProgram(this->pr); glGetProgramiv(this->pr, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(this->pr, 512, NULL, infoLog); en->log(ERR) << "Could not link program: " << infoLog << endlog; } glDeleteShader(vertex); glDeleteShader(fragment); if (success) { en->log(WIN) << "Loaded shader successfully!" << endlog; } } Shader::Shader(std::string v, std::string f, Engine* e) { en = e; load(v, f); } Shader::Shader(Engine* e) { en = e; } Shader::~Shader() { } }
23.27
82
0.661796
tatjam
7c88af4a689a965a5621c9c1050e8228c0189ed9
8,154
cpp
C++
Examples/DocsExamples/source/Programming with Documents/Split Documents/Split into html pages.cpp
btolfa/Aspose.Words-for-C
f75c77380b75546907ee63b96590f5250d2ffa90
[ "MIT" ]
32
2018-08-23T07:48:20.000Z
2021-12-24T07:27:02.000Z
Examples/DocsExamples/source/Programming with Documents/Split Documents/Split into html pages.cpp
btolfa/Aspose.Words-for-C
f75c77380b75546907ee63b96590f5250d2ffa90
[ "MIT" ]
1
2021-11-23T03:35:31.000Z
2022-01-26T09:19:44.000Z
Examples/DocsExamples/source/Programming with Documents/Split Documents/Split into html pages.cpp
btolfa/Aspose.Words-for-C
f75c77380b75546907ee63b96590f5250d2ffa90
[ "MIT" ]
13
2018-07-31T05:02:33.000Z
2022-03-06T22:12:36.000Z
#include "Split into html pages.h" #include <Aspose.Words.Cpp/Body.h> #include <Aspose.Words.Cpp/BreakType.h> #include <Aspose.Words.Cpp/Fields/Field.h> #include <Aspose.Words.Cpp/ImportFormatMode.h> #include <Aspose.Words.Cpp/MailMerging/MailMerge.h> #include <Aspose.Words.Cpp/Node.h> #include <Aspose.Words.Cpp/NodeCollection.h> #include <Aspose.Words.Cpp/NodeType.h> #include <Aspose.Words.Cpp/ParagraphFormat.h> #include <Aspose.Words.Cpp/Properties/BuiltInDocumentProperties.h> #include <Aspose.Words.Cpp/Saving/ExportHeadersFootersMode.h> #include <Aspose.Words.Cpp/Saving/HtmlSaveOptions.h> #include <Aspose.Words.Cpp/Saving/SaveOutputParameters.h> #include <Aspose.Words.Cpp/SectionCollection.h> #include <Aspose.Words.Cpp/StyleIdentifier.h> #include <system/char.h> #include <system/enumerator_adapter.h> #include <system/exceptions.h> #include <system/text/string_builder.h> #include "Programming with Documents/Split Documents/Split into html pages.h" using namespace Aspose::Words; using namespace Aspose::Words::MailMerging; using namespace Aspose::Words::Saving; namespace DocsExamples { namespace Programming_with_Documents { namespace Split_Documents { void WordToHtmlConverter::HandleTocMergeField::FieldMerging(System::SharedPtr<FieldMergingArgs> e) { if (mBuilder == nullptr) { mBuilder = System::MakeObject<DocumentBuilder>(e->get_Document()); } // Our custom data source returns topic objects. auto topic = System::StaticCast<Topic>(e->get_FieldValue()); mBuilder->MoveToMergeField(e->get_FieldName()); mBuilder->InsertHyperlink(topic->get_Title(), topic->get_FileName(), false); // Signal to the mail merge engine that it does not need to insert text into the field. e->set_Text(u""); } void WordToHtmlConverter::HandleTocMergeField::ImageFieldMerging(System::SharedPtr<ImageFieldMergingArgs> args) { // Do nothing. } void WordToHtmlConverter::Execute(System::String srcFileName, System::String tocTemplate, System::String dstDir) { mDoc = System::MakeObject<Document>(srcFileName); mTocTemplate = tocTemplate; mDstDir = dstDir; System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Paragraph>>> topicStartParas = SelectTopicStarts(); InsertSectionBreaks(topicStartParas); System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Topic>>> topics = SaveHtmlTopics(); SaveTableOfContents(topics); } System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Paragraph>>> WordToHtmlConverter::SelectTopicStarts() { System::SharedPtr<NodeCollection> paras = mDoc->GetChildNodes(NodeType::Paragraph, true); System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Paragraph>>> topicStartParas = System::MakeObject<System::Collections::Generic::List<System::SharedPtr<Paragraph>>>(); for (const auto& para : System::IterateOver<Paragraph>(paras)) { StyleIdentifier style = para->get_ParagraphFormat()->get_StyleIdentifier(); if (style == StyleIdentifier::Heading1) { topicStartParas->Add(para); } } return topicStartParas; } void WordToHtmlConverter::InsertSectionBreaks(System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Paragraph>>> topicStartParas) { auto builder = System::MakeObject<DocumentBuilder>(mDoc); for (const auto& para : topicStartParas) { System::SharedPtr<Section> section = para->get_ParentSection(); // Insert section break if the paragraph is not at the beginning of a section already. if (para != section->get_Body()->get_FirstParagraph()) { builder->MoveTo(para->get_FirstChild()); builder->InsertBreak(BreakType::SectionBreakNewPage); // This is the paragraph that was inserted at the end of the now old section. // We don't really need the extra paragraph, we just needed the section. section->get_Body()->get_LastParagraph()->Remove(); } } } System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Topic>>> WordToHtmlConverter::SaveHtmlTopics() { System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Topic>>> topics = System::MakeObject<System::Collections::Generic::List<System::SharedPtr<Topic>>>(); for (int32_t sectionIdx = 0; sectionIdx < mDoc->get_Sections()->get_Count(); sectionIdx++) { System::SharedPtr<Section> section = mDoc->get_Sections()->idx_get(sectionIdx); System::String paraText = section->get_Body()->get_FirstParagraph()->GetText(); // Use the text of the heading paragraph to generate the HTML file name. System::String fileName = MakeTopicFileName(paraText); if (fileName == u"") { fileName = System::String(u"UNTITLED SECTION ") + sectionIdx; } fileName = System::IO::Path::Combine(mDstDir, fileName + u".html"); // Use the text of the heading paragraph to generate the title for the TOC. System::String title = MakeTopicTitle(paraText); if (title == u"") { title = System::String(u"UNTITLED SECTION ") + sectionIdx; } auto topic = System::MakeObject<Topic>(title, fileName); topics->Add(topic); SaveHtmlTopic(section, topic); } return topics; } System::String WordToHtmlConverter::MakeTopicFileName(System::String paraText) { auto b = System::MakeObject<System::Text::StringBuilder>(); for (char16_t c : paraText) { if (System::Char::IsLetterOrDigit(c)) { b->Append(c); } else if (c == u' ') { b->Append(u'_'); } } return b->ToString(); } System::String WordToHtmlConverter::MakeTopicTitle(System::String paraText) { return paraText.Substring(0, paraText.get_Length() - 1); } void WordToHtmlConverter::SaveHtmlTopic(System::SharedPtr<Section> section, System::SharedPtr<Topic> topic) { auto dummyDoc = System::MakeObject<Document>(); dummyDoc->RemoveAllChildren(); dummyDoc->AppendChild(dummyDoc->ImportNode(section, true, ImportFormatMode::KeepSourceFormatting)); dummyDoc->get_BuiltInDocumentProperties()->set_Title(topic->get_Title()); auto saveOptions = System::MakeObject<HtmlSaveOptions>(); saveOptions->set_PrettyFormat(true); saveOptions->set_AllowNegativeIndent(true); saveOptions->set_ExportHeadersFootersMode(ExportHeadersFootersMode::None); dummyDoc->Save(topic->get_FileName(), saveOptions); } void WordToHtmlConverter::SaveTableOfContents(System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Topic>>> topics) { auto tocDoc = System::MakeObject<Document>(mTocTemplate); // We use a custom mail merge event handler defined below, // and a custom mail merge data source based on collecting the topics we created. tocDoc->get_MailMerge()->set_FieldMergingCallback(System::MakeObject<WordToHtmlConverter::HandleTocMergeField>()); tocDoc->get_MailMerge()->ExecuteWithRegions(System::MakeObject<TocMailMergeDataSource>(topics)); tocDoc->Save(System::IO::Path::Combine(mDstDir, u"contents.html")); } namespace gtest_test { class SplitIntoHtmlPages : public ::testing::Test { protected: static System::SharedPtr<::DocsExamples::Programming_with_Documents::Split_Documents::SplitIntoHtmlPages> s_instance; void SetUp() override { s_instance->SetUp(); }; static void SetUpTestCase() { s_instance = System::MakeObject<::DocsExamples::Programming_with_Documents::Split_Documents::SplitIntoHtmlPages>(); s_instance->OneTimeSetUp(); }; static void TearDownTestCase() { s_instance->OneTimeTearDown(); s_instance = nullptr; }; }; System::SharedPtr<::DocsExamples::Programming_with_Documents::Split_Documents::SplitIntoHtmlPages> SplitIntoHtmlPages::s_instance; TEST_F(SplitIntoHtmlPages, HtmlPages) { s_instance->HtmlPages(); } } // namespace gtest_test }}} // namespace DocsExamples::Programming_with_Documents::Split_Documents
36.565022
146
0.712288
btolfa
7c8bd80dcf97df51bd3ba2e6dea94e5878938ebb
1,301
hpp
C++
Firmware/graphics/gs_event_dispatcher.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
39
2019-10-23T12:06:16.000Z
2022-01-26T04:28:29.000Z
Firmware/graphics/gs_event_dispatcher.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
20
2020-03-21T20:21:46.000Z
2021-11-19T14:34:03.000Z
Firmware/graphics/gs_event_dispatcher.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
7
2019-10-18T09:44:10.000Z
2021-06-11T13:05:16.000Z
#pragma once #include "ih/gs_events.hpp" #include "utils/Noncopyable.hpp" #include <any> #include <atomic> #include <functional> #include <memory> #include <vector> #include <etl/queue_spsc_atomic.h> #include <etl/vector.h> namespace Graphics::Events { class EventDispatcher : private Utils::noncopyable { public: using TEventHandler = std::function<void(const TEvent&)>; static constexpr inline int MaxSubscriberLimit = 3; using SubscriberStorage = etl::vector<TEventHandler, MaxSubscriberLimit>; void subscribe(EventGroup _eventGroup, const TEventHandler& _handler) noexcept; void postEvent(TEvent&& _eventToProcess) noexcept; void processEventQueue() noexcept; private: static constexpr inline int EventsCount = Events::enumConvert<EventGroup>(EventGroup::EventGroupEnd); static constexpr inline int EventPoolSize = 16; using TEventsMap = etl::vector<std::pair<EventGroup, SubscriberStorage>, EventsCount>; TEventsMap m_eventsMap; using TEventsQueue = etl::queue_spsc_atomic<TEvent, EventPoolSize, etl::memory_model::MEMORY_MODEL_SMALL>; TEventsQueue m_eventsQueue; }; using TEventDispatcherPtr = std::unique_ptr<EventDispatcher>; TEventDispatcherPtr createEventDispatcher() noexcept; } // namespace Graphics::Events
25.019231
93
0.757879
ValentiWorkLearning
7c99511af0b6cd91d4403e9bf55b979be3005c6c
1,997
cpp
C++
libmetartc2/src/yangcapture/YangScreenShare.cpp
guoai2015/metaRTC
70e9a09c9a703a547e791cd246c4054d87881f08
[ "MIT" ]
147
2021-09-12T07:23:45.000Z
2021-11-11T11:31:26.000Z
libmetartc2/src/yangcapture/YangScreenShare.cpp
guoai2015/metaRTC
70e9a09c9a703a547e791cd246c4054d87881f08
[ "MIT" ]
6
2021-11-30T07:53:09.000Z
2022-02-25T01:36:38.000Z
libmetartc2/src/yangcapture/YangScreenShare.cpp
guoai2015/metaRTC
70e9a09c9a703a547e791cd246c4054d87881f08
[ "MIT" ]
36
2021-11-16T03:32:41.000Z
2022-03-31T07:21:32.000Z
/* * YangScreenShareLinux.cpp * * Created on: 2020年8月30日 * Author: yang */ #include "YangScreenShare.h" #include "yangutil/yang_unistd.h" #include "yangavutil/video/YangYuvConvert.h" YangScreenCapture::YangScreenCapture(){ m_isStart=0; } YangScreenCapture::~YangScreenCapture(){ } void YangScreenCapture::run() { m_isStart = 1; startLoop(); m_isStart = 0; } void YangScreenCapture::stop() { stopLoop(); } YangScreenShare::YangScreenShare() { //m_capture=new YangScreenShareImpl(); //m_vhandle=new YangVideoCaptureHandle(); m_isloop=0; m_out_videoBuffer=NULL; m_capture=NULL; m_isCapture=0; m_interval=0; } YangScreenShare::~YangScreenShare() { m_capture=NULL; m_out_videoBuffer=NULL; } void YangScreenShare::setOutVideoBuffer(YangVideoBuffer *pbuf){ m_out_videoBuffer=pbuf; } void YangScreenShare::setScreenHandle(YangScreenCaptureHandleI *handle){ m_capture=handle; } void YangScreenShare::setInterval(int32_t pinterval){ m_interval=1000*pinterval; } void YangScreenShare::setVideoCaptureStart() { m_isCapture = 1; } void YangScreenShare::setVideoCaptureStop() { m_isCapture = 0; } int32_t YangScreenShare::getVideoCaptureState() { return m_isCapture; } void YangScreenShare::initstamp() { //m_vhandle->initstamp(); } void YangScreenShare::stopLoop() { m_isloop = 0; } int32_t YangScreenShare::init() { return m_capture->init(); } void YangScreenShare::startLoop() { m_isloop = 1; /** //m_vhandle->m_start_time = 0; int32_t width=m_capture->m_width; int32_t height=m_capture->m_height; uint8_t buf[width*height*4]; uint8_t yuv[width*height*3/2]; int32_t yuvLen=width*height*3/2; YangYuvConvert con; int64_t timestamp=0; YangFrame videoFrame; memset(&m_audioFrame,0,sizeof(YangFrame)); while (m_isloop) { m_capture->captureFrame(buf); con.rgb24toI420(buf,yuv,width,height); videoFrame.payload=yuv; videoFrame.nb=yuvLen; videoFrame.timestamp=timestamp; m_out_videoBuffer->putVideo(&videoFrame); yang_usleep(3000); }**/ }
21.244681
72
0.750125
guoai2015
7ca1f03d0d13e5ab1b0e383a1d885f68dca4a426
388
cpp
C++
src/server/main.cpp
Ooggle/MUSIC-exclamation-mark
55f4dd750d57227fac29d887d90e0c8ec2ad7397
[ "MIT" ]
7
2020-08-28T21:47:54.000Z
2021-01-01T17:54:27.000Z
src/server/main.cpp
Ooggle/MUSIC-exclamation-mark
55f4dd750d57227fac29d887d90e0c8ec2ad7397
[ "MIT" ]
null
null
null
src/server/main.cpp
Ooggle/MUSIC-exclamation-mark
55f4dd750d57227fac29d887d90e0c8ec2ad7397
[ "MIT" ]
1
2020-12-26T17:08:54.000Z
2020-12-26T17:08:54.000Z
/* Compilation : g++ main.cpp -std=c++17 `sdl2-config --libs` -lSDL2_mixer `taglib-config --libs` `pkg-config --cflags --libs taglib` -lz Some flags are useless for now. */ #include "DatabaseHandler.h" #include "WebHandler.h" #include <stdio.h> #define SERVER_VERSION "0.1" int main() { printf("Welcome to MUSIC! server %s.\n", SERVER_VERSION); return EXIT_SUCCESS; }
21.555556
138
0.67268
Ooggle
7ca26cc859aae12a80ec9397f9da9a51ce1475d5
323
cpp
C++
project/OFEC_sc2/core/global.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/core/global.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/core/global.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
#include "global.h" namespace OFEC { factory<Problem> g_reg_problem; factory<Algorithm> g_reg_algorithm; std::map<std::string, std::set<std::string>> g_alg_for_pro; std::set<std::string> g_param_omit; std::map<std::string, std::string> g_param_abbr; std::string g_working_dir = OFEC_DIR; std::mutex g_cout_mutex; }
26.916667
60
0.74613
BaiChunhui-9803
7ca48e1c9feca936e90619635dbdb1a2fba604ab
1,624
hpp
C++
ch10/stack_by_list.hpp
klong13579/cppL
7aa8afaf2d2e17578c7fd91654bedcccf0a6baab
[ "MIT" ]
261
2015-01-11T20:42:33.000Z
2022-02-17T01:33:39.000Z
ch10/stack_by_list.hpp
LeungGeorge/CLRS
7aa8afaf2d2e17578c7fd91654bedcccf0a6baab
[ "MIT" ]
4
2015-04-05T11:49:45.000Z
2017-02-19T08:29:52.000Z
ch10/stack_by_list.hpp
LeungGeorge/CLRS
7aa8afaf2d2e17578c7fd91654bedcccf0a6baab
[ "MIT" ]
98
2015-01-03T12:58:50.000Z
2021-07-16T07:29:31.000Z
/*************************************************************************** * @file stack_by_list.hpp * @author Alan.W * @date 30 May 2014 * @remark Chapter 10, Introduction to Algorithms * @note code style : STL ***************************************************************************/ //! //! ex10.2-2 //! Implement a stack using a singly linked list L. The operations PUSH and POP //! should still take O(1) time. //! #ifndef STACK_BY_LIST_H #define STACK_BY_LIST_H #include "single_list.hpp" namespace ch10{ namespace list{ template<typename T> class stack_by_list { public: using ValueType = T; using Node = node<ValueType>; using sPointer = std::shared_ptr<Node>; using SizeType = std::size_t; using List = single_list_ring<ValueType>; /** * @brief default ctor */ stack_by_list() = default; SizeType size() const { return data.size(); } bool empty() const { return data.empty(); } void print() const { std::cout << data; } /** * @brief enqueue * * @complexity O(1) * * as required in ex10.2-2 */ void enqueue(const ValueType& val) { data.insert(val); } /** * @brief dequeue * * @complexity O(1) * * as required in ex10.2-2 */ ValueType dequeue() { ValueType top = data.begin()->key; data.remove(data.begin()); return top; } private: List data; }; }//namespace list }//namespace ch10 #endif // STACK_BY_LIST_H
18.247191
79
0.501847
klong13579
7ca82ca251546cfb09a8f149676c8ede2ce19251
3,948
cpp
C++
Libraries/RobsJuceModules/rosic/sequencing/rosic_AcidPattern.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/rosic/sequencing/rosic_AcidPattern.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/rosic/sequencing/rosic_AcidPattern.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
//#include "rosic_AcidPattern.h" //using namespace rosic; AcidPattern::AcidPattern() { numSteps = 16; stepLength = 0.5; } //------------------------------------------------------------------------------------------------- // setup: void AcidPattern::clear() { for(int i=0; i<maxNumSteps; i++) { notes[i].key = 0; notes[i].octave = 0; notes[i].accent = false; notes[i].slide = false; notes[i].gate = false; } } void AcidPattern::randomize() { for(int i=0; i<maxNumSteps; i++) { notes[i].key = roundToInt(RAPT::rsRandomUniform( 0, 11)); notes[i].octave = roundToInt(RAPT::rsRandomUniform(-2, 2)); notes[i].accent = roundToInt(RAPT::rsRandomUniform( 0, 1)) == 1; notes[i].slide = roundToInt(RAPT::rsRandomUniform( 0, 1)) == 1; notes[i].gate = roundToInt(RAPT::rsRandomUniform( 0, 1)) == 1; } // todo: use PRNG member, provide the options to randomize only accents, slides, etc. } void AcidPattern::setNumSteps(int newNumber) { RAPT::rsAssert(newNumber <= maxNumSteps); numSteps = maxNumSteps; } void AcidPattern::circularShiftAll(int numStepsToShift) { RAPT::rsArrayTools::circularShift(notes, maxNumSteps, numStepsToShift); } int rsMod(int val, int modulus) { while(val >= modulus) val -= modulus; while(val < 0 ) val += modulus; return val; } // move somewhere else void AcidPattern::circularShiftAccents(int shift) { AcidPattern tmp = *this; for(int i = 0; i < numSteps; i++) notes[i].accent = tmp.notes[rsMod(i-shift, numSteps)].accent; } // seems not to work - maybe the mod operation doe not work for negative numbers void AcidPattern::circularShiftSlides(int shift) { AcidPattern tmp = *this; for(int i = 0; i < numSteps; i++) notes[i].slide = tmp.notes[rsMod(i-shift, numSteps)].slide; } void AcidPattern::circularShiftOctaves(int shift) { AcidPattern tmp = *this; for(int i = 0; i < numSteps; i++) notes[i].octave = tmp.notes[rsMod(i-shift, numSteps)].octave; } void AcidPattern::circularShiftNotes(int shift) { AcidPattern tmp = *this; for(int i = 0; i < numSteps; i++) { notes[i].key = tmp.notes[rsMod(i-shift, numSteps)].key; notes[i].gate = tmp.notes[rsMod(i-shift, numSteps)].gate; } } void AcidPattern::reverseAll() { for(int i = 0; i < numSteps/2; i++) RAPT::rsSwap(notes[i], notes[numSteps-1-i]); } void AcidPattern::reverseAccents() { for(int i = 0; i < numSteps/2; i++) RAPT::rsSwap(notes[i].accent, notes[numSteps-1-i].accent); } void AcidPattern::reverseSlides() { for(int i = 0; i < numSteps/2; i++) RAPT::rsSwap(notes[i].slide, notes[numSteps-1-i].slide); } void AcidPattern::reverseOctaves() { for(int i = 0; i < numSteps/2; i++) RAPT::rsSwap(notes[i].octave, notes[numSteps-1-i].octave); } void AcidPattern::reverseNotes() { for(int i = 0; i < numSteps/2; i++) RAPT::rsSwap(notes[i].key, notes[numSteps-1-i].key); } void AcidPattern::invertAccents() { for(int i = 0; i < numSteps; i++) notes[i].accent = !notes[i].accent; } void AcidPattern::invertSlides() { for(int i = 0; i < numSteps; i++) notes[i].slide = !notes[i].slide; } void AcidPattern::invertOctaves() { for(int i = 0; i < numSteps; i++) notes[i].octave = -notes[i].octave; } void AcidPattern::swapAccentsWithSlides() { for(int i = 0; i < numSteps; i++) RAPT::rsSwap(notes[i].accent, notes[i].slide); } void AcidPattern::xorAccentsWithSlides() { for(int i = 0; i < numSteps; i++) notes[i].accent = rsXor(notes[i].accent, notes[i].slide); } void AcidPattern::xorSlidesWithAccents() { for(int i = 0; i < numSteps; i++) notes[i].accent = rsXor(notes[i].accent, notes[i].slide); } //------------------------------------------------------------------------------------------------- // inquiry: bool AcidPattern::isEmpty() const { for(int i=0; i<maxNumSteps; i++) { if( notes[i].gate == true ) return false; } return true; }
23.783133
102
0.609929
RobinSchmidt
7cb574e9ac5f67235a3ff3c89c8c918f75508ed3
1,546
cpp
C++
internalconnector/internalrastercoverageconnector.cpp
ridoo/IlwisCore
9d9837507d804a4643545a03fd40d9b4d0eaee45
[ "Apache-2.0" ]
null
null
null
internalconnector/internalrastercoverageconnector.cpp
ridoo/IlwisCore
9d9837507d804a4643545a03fd40d9b4d0eaee45
[ "Apache-2.0" ]
null
null
null
internalconnector/internalrastercoverageconnector.cpp
ridoo/IlwisCore
9d9837507d804a4643545a03fd40d9b4d0eaee45
[ "Apache-2.0" ]
null
null
null
#include "kernel.h" #include "raster.h" #include "numericrange.h" #include "numericdomain.h" #include "columndefinition.h" #include "table.h" #include "connectorinterface.h" #include "mastercatalog.h" #include "ilwisobjectconnector.h" #include "catalogexplorer.h" #include "catalogconnector.h" #include "internalrastercoverageconnector.h" using namespace Ilwis; using namespace Internal; ConnectorInterface *Ilwis::Internal::InternalRasterCoverageConnector::create(const Ilwis::Resource &resource,bool load,const IOOptions& options) { return new InternalRasterCoverageConnector(resource, load, options); } InternalRasterCoverageConnector::InternalRasterCoverageConnector(const Resource &resource, bool load,const IOOptions& options) : IlwisObjectConnector(resource, load, options) { } bool InternalRasterCoverageConnector::loadMetaData(IlwisObject *data, const IOOptions &options){ RasterCoverage *gcoverage = static_cast<RasterCoverage *>(data); if(_dataType == gcoverage->datadef().range().isNull()) return false; if ( !gcoverage->datadef().range().isNull()) _dataType = gcoverage->datadef().range()->valueType(); gcoverage->gridRef()->prepare(gcoverage,gcoverage->size()); return true; } bool InternalRasterCoverageConnector::loadData(IlwisObject *, const IOOptions &){ return true; } QString Ilwis::Internal::InternalRasterCoverageConnector::provider() const { return "internal"; } IlwisObject *InternalRasterCoverageConnector::create() const { return new RasterCoverage(); }
27.607143
174
0.76326
ridoo
7cbc334cb01636a1bcb59b8de0f8ff2fcf0c0a52
2,385
cpp
C++
src/D3D9Hook.cpp
muhopensores/dmc3-inputs-thing
2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719
[ "MIT" ]
5
2021-06-09T23:53:28.000Z
2022-02-21T06:09:41.000Z
src/D3D9Hook.cpp
muhopensores/dmc3-inputs-thing
2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719
[ "MIT" ]
9
2021-06-09T23:52:43.000Z
2021-09-17T14:05:47.000Z
src/D3D9Hook.cpp
muhopensores/dmc3-inputs-thing
2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719
[ "MIT" ]
null
null
null
#include <algorithm> #include <spdlog/spdlog.h> #include "D3D9Hook.hpp" using namespace std; static D3D9Hook* g_d3d9_hook = nullptr; D3D9Hook::~D3D9Hook() { unhook(); } uintptr_t end_scene_jmp_ret = 0; __declspec(naked) void end_scene_hook(void) { __asm { pushad push eax call D3D9Hook::end_scene popad pop eax push eax call dword ptr [ecx+0xA8] jmp dword ptr [end_scene_jmp_ret] } } uintptr_t reset_jmp_ret = 0; __declspec(naked) void reset_hook(void) { __asm { pushad push eax call D3D9Hook::reset popad pop eax push eax call dword ptr [ecx+0x40] mov esi, eax jmp dword ptr [reset_jmp_ret] } } bool D3D9Hook::hook() { spdlog::info("Hooking D3D9"); g_d3d9_hook = this; IDirect3DDevice9** game = (IDirect3DDevice9**)0x0252F374; IDirect3DDevice9* d3d9_device = *game; // TODO: base + offset? m_device = d3d9_device; uintptr_t reset_fn = (*(uintptr_t**)d3d9_device)[16]; uintptr_t end_scene_fn = (*(uintptr_t**)d3d9_device)[42]; m_end_scene_hook = std::make_unique<FunctionHook>(end_scene_fn, (uintptr_t)&end_scene);//std::make_unique<FunctionHook>(end_scene_fn, (uintptr_t)&end_scene_hook); m_reset_hook = std::make_unique<FunctionHook>(reset_fn, (uintptr_t)&reset); //end_scene_jmp_ret = 0x006DC48E + 0x6; //reset_jmp_ret = reset_fn + 5; m_hooked = m_end_scene_hook->create() && m_reset_hook->create(); return m_hooked; } bool D3D9Hook::unhook() { return true; } #if 1 HRESULT WINAPI D3D9Hook::end_scene(LPDIRECT3DDEVICE9 pDevice) { auto d3d9 = g_d3d9_hook; //d3d9->m_device = pDevice; if (d3d9->m_on_end_scene) { d3d9->m_on_end_scene(*d3d9); } //return S_OK; auto end_scene_fn = d3d9->m_end_scene_hook->get_original<decltype(D3D9Hook::end_scene)>(); return end_scene_fn(pDevice); } #else static void end_scene_our(LPDIRECT3DDEVICE9 pDevice) { auto d3d9 = g_d3d9_hook; d3d9->set_device(pDevice); if (d3d9->m_on_end_scene) { d3d9->m_on_end_scene(*d3d9); } } #endif HRESULT WINAPI D3D9Hook::reset(LPDIRECT3DDEVICE9 pDevice, D3DPRESENT_PARAMETERS *pPresentationParameters) { auto d3d9 = g_d3d9_hook; d3d9->m_presentation_params = pPresentationParameters; if (d3d9->m_on_reset) { d3d9->m_on_reset(*d3d9); } //return S_OK; auto reset_fn = d3d9->m_reset_hook->get_original<decltype(D3D9Hook::reset)>(); return reset_fn(pDevice, pPresentationParameters); }
21.681818
166
0.72369
muhopensores
7cbfc7ce81026348266e9ae8ec20990e911e02ea
13,300
cpp
C++
packages/utility/archive/test/tstHDF5ArchiveTupleTypes.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/utility/archive/test/tstHDF5ArchiveTupleTypes.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/utility/archive/test/tstHDF5ArchiveTupleTypes.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file tstHDF5ArchiveTupleTypes.cpp //! \author Alex Robinson //! \brief HDF5 archive tuple type unit tests //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> #include <sstream> // FRENSIE Includes #include "Utility_HDF5IArchive.hpp" #include "Utility_HDF5OArchive.hpp" #include "Utility_Tuple.hpp" #include "Utility_ArrayView.hpp" #include "Utility_UnitTestHarnessWithMain.hpp" //---------------------------------------------------------------------------// // Template Types //---------------------------------------------------------------------------// typedef std::tuple<bool, char, unsigned char, signed char, short, unsigned short, int, unsigned int, long, unsigned long, long long, unsigned long long, float, double, long double> BasicTestTypes; template<typename... Types> struct PairTypes; template<typename T, typename... Types> struct PairTypes<T,Types...> { typedef decltype(std::tuple_cat( std::tuple<std::pair<T,T> >(), typename PairTypes<Types...>::type())) type; }; template<typename T> struct PairTypes<T> { typedef std::pair<T,T> type; }; template<typename... Types> struct PairTypes<std::tuple<Types...> > : public PairTypes<Types...> { /* ... */ }; template<typename... Types> struct OneElementTupleTypes; template<typename T, typename... Types> struct OneElementTupleTypes<T,Types...> { typedef decltype(std::tuple_cat( std::tuple<std::tuple<T> >(), typename OneElementTupleTypes<Types...>::type())) type; }; template<typename T> struct OneElementTupleTypes<T> { typedef std::tuple<std::tuple<T> > type; }; template<typename... Types> struct OneElementTupleTypes<std::tuple<Types...> > : public OneElementTupleTypes<Types...> { /* ... */ }; template<typename... Types> struct TwoElementTupleTypes; template<typename T, typename... Types> struct TwoElementTupleTypes<T,Types...> { typedef decltype(std::tuple_cat( std::tuple<std::tuple<T,T> >(), typename TwoElementTupleTypes<Types...>::type())) type; }; template<typename T> struct TwoElementTupleTypes<T> { typedef std::tuple<T,T> type; }; template<typename... Types> struct TwoElementTupleTypes<std::tuple<Types...> > : public TwoElementTupleTypes<Types...> { /* ... */ }; template<typename... Types> struct ThreeElementTupleTypes; template<typename T, typename... Types> struct ThreeElementTupleTypes<T,Types...> { typedef decltype(std::tuple_cat( std::tuple<std::tuple<T,T,T> >(), typename ThreeElementTupleTypes<Types...>::type())) type; }; template<typename T> struct ThreeElementTupleTypes<T> { typedef std::tuple<std::tuple<T,T,T> > type; }; template<typename... Types> struct ThreeElementTupleTypes<std::tuple<Types...> > : public ThreeElementTupleTypes<Types...> { /* ... */ }; template<typename... Types> struct MergeTypeLists; template<typename T, typename... Types> struct MergeTypeLists<T,Types...> { typedef decltype(std::tuple_cat( T(), typename MergeTypeLists<Types...>::type())) type; }; template<typename T> struct MergeTypeLists<T> { typedef T type; }; typedef typename MergeTypeLists<typename PairTypes<BasicTestTypes>::type,typename OneElementTupleTypes<BasicTestTypes>::type,typename TwoElementTupleTypes<BasicTestTypes>::type,typename ThreeElementTupleTypes<BasicTestTypes>::type>::type BasicTupleTestTypes; //---------------------------------------------------------------------------// // Testing functions //---------------------------------------------------------------------------// template<typename T> inline T zero( T ) { return T(0); } template<typename T1, typename T2> inline std::pair<T1,T2> zero( std::pair<T1,T2> ) { return std::make_pair( zero<T1>( T1() ), zero<T2>( T2() ) ); } template<typename... Types> inline std::tuple<Types...> zero( std::tuple<Types...> ) { return std::make_tuple( zero<Types>( Types() )... ); } template<typename T> inline T one( T ) { return T(1); } template<typename T1, typename T2> inline std::pair<T1,T2> one( std::pair<T1,T2> ) { return std::make_pair( one<T1>( T1() ), one<T2>( T2() ) ); } template<typename... Types> inline std::tuple<Types...> one( std::tuple<Types...> ) { return std::make_tuple( one<Types>( Types() )... ); } //---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// //---------------------------------------------------------------------------// // Check that tuple composed of basic types can be archived FRENSIE_UNIT_TEST_TEMPLATE( HDF5Archive, archive_tuple_basic_types, BasicTupleTestTypes ) { FETCH_TEMPLATE_PARAM( 0, T ); std::string archive_name( "test_tuple_basic_types.h5a" ); const T tuple_a = zero(T()); const T tuple_b = one(T()); const T array_a[8] = {one(T()), one(T()), one(T()), one(T()), one(T()), one(T()), one(T()), one(T())}; const T array_b[2][3] = {{one(T()), one(T()), one(T())},{one(T()), one(T()), one(T())}}; std::array<T,10> array_c; array_c.fill( one(T()) ); { Utility::HDF5OArchive archive( archive_name, Utility::HDF5OArchiveFlags::OVERWRITE_EXISTING_ARCHIVE ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_a", tuple_a ) ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_b", tuple_b ) ); // Array optimization should be used with this type FRENSIE_REQUIRE( Utility::HDF5OArchive::use_array_optimization::apply<T>::type::value ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_a", array_a ) ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_b", array_b ) ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_c", array_c ) ); } { Utility::HDF5IArchive archive( archive_name ); T extracted_tuple; T extracted_array_a[8]; T extracted_array_b[2][3]; std::array<T,10> extracted_array_c; FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_a", extracted_tuple ) ); FRENSIE_CHECK_EQUAL( extracted_tuple, tuple_a ); FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_b", extracted_tuple ) ); FRENSIE_CHECK_EQUAL( extracted_tuple, tuple_b ); // Array optimization should be used with this type FRENSIE_REQUIRE( Utility::HDF5IArchive::use_array_optimization::apply<T>::type::value ); FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_a", extracted_array_a ) ); FRENSIE_CHECK_EQUAL( Utility::ArrayView<const T>( array_a, array_a+8 ), Utility::ArrayView<const T>( extracted_array_a, extracted_array_a+8 ) ); FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_b", extracted_array_b ) ); FRENSIE_CHECK_EQUAL( Utility::ArrayView<const T>( &array_b[0][0], &array_b[0][0]+6 ), Utility::ArrayView<const T>( &extracted_array_b[0][0], &extracted_array_b[0][0]+6 ) ); FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_c", extracted_array_c ) ); FRENSIE_CHECK_EQUAL( array_c, extracted_array_c ); } } //---------------------------------------------------------------------------// // Check that tuple composed of advanced types can be archived FRENSIE_UNIT_TEST_TEMPLATE( HDF5Archive, archive_tuple_advanced_types, BasicTestTypes ) { FETCH_TEMPLATE_PARAM( 0, T ); std::string archive_name( "test_tuple_advanced_types.h5a" ); const std::pair<T,std::string> pair_a = std::make_pair( one(T()), std::string("Test message a") ); const std::pair<std::string,T> pair_b = std::make_pair( std::string("Test message b"), one(T()) ); const std::pair<std::string,std::string> pair_c = std::make_pair( std::string("Test message c-0"), std::string("Test message c-1") ); const std::tuple<T,std::string> tuple_a = std::make_tuple( one(T()), std::string("Test message a") ); const std::tuple<std::string,T> tuple_b = std::make_tuple( std::string("Test message b"), one(T()) ); const std::tuple<std::string,std::string> tuple_c = std::make_tuple( std::string("Test message c-0"), std::string("Test message c-1") ); const std::pair<T,std::string> array_a[2][3] = {{std::make_pair(one(T()), std::string("Test message a-00")), std::make_pair(one(T()), std::string("Test message a-01")), std::make_pair(one(T()), std::string("Test message a-02"))}, {std::make_pair(zero(T()), std::string("Test message a-10")), std::make_pair(zero(T()), std::string("Test message a-11")), std::make_pair(zero(T()), std::string("Test message a-12"))}}; const std::tuple<std::string,T> array_b[6] = {std::make_tuple(std::string("Test message b-00"), zero(T())), std::make_tuple(std::string("Test message b-01"), zero(T())), std::make_tuple(std::string("Test message b-02"), zero(T())), std::make_tuple(std::string("Test message b-10"), one(T())), std::make_tuple(std::string("Test message b-11"), one(T())), std::make_tuple(std::string("Test message b-12"), one(T()))}; { Utility::HDF5OArchive archive( archive_name, Utility::HDF5OArchiveFlags::OVERWRITE_EXISTING_ARCHIVE ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "pair_a", pair_a ) ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "pair_b", pair_b ) ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "pair_c", pair_c ) ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_a", tuple_a ) ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_b", tuple_b ) ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_c", tuple_c ) ); // Array optimization should be used with these types FRENSIE_REQUIRE( (Utility::HDF5OArchive::use_array_optimization::apply<std::pair<T,std::string> >::type::value) ); FRENSIE_REQUIRE( (Utility::HDF5OArchive::use_array_optimization::apply<std::tuple<std::string,T> >::type::value) ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_a", array_a ) ); FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_b", array_b ) ); } { Utility::HDF5IArchive archive( archive_name ); std::pair<T,std::string> extracted_pair_a; std::pair<std::string,T> extracted_pair_b; std::pair<std::string,std::string> extracted_pair_c; std::tuple<T,std::string> extracted_tuple_a; std::tuple<std::string,T> extracted_tuple_b; std::tuple<std::string,std::string> extracted_tuple_c; std::pair<T,std::string> extracted_array_a[2][3]; std::tuple<std::string,T> extracted_array_b[6]; FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "pair_a", extracted_pair_a ) ); FRENSIE_CHECK_EQUAL( extracted_pair_a, pair_a ); FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "pair_b", extracted_pair_b ) ); FRENSIE_CHECK_EQUAL( extracted_pair_b, pair_b ); FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "pair_c", extracted_pair_c ) ); FRENSIE_CHECK_EQUAL( extracted_pair_c, pair_c ); FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_a", extracted_tuple_a ) ); FRENSIE_CHECK_EQUAL( extracted_tuple_a, tuple_a ); FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_b", extracted_tuple_b ) ); FRENSIE_CHECK_EQUAL( extracted_tuple_b, tuple_b ); FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_c", extracted_tuple_c ) ); FRENSIE_CHECK_EQUAL( extracted_tuple_c, tuple_c ); // Array optimization should not be used with these types FRENSIE_REQUIRE( (Utility::HDF5IArchive::use_array_optimization::apply<std::pair<T,std::string> >::type::value) ); FRENSIE_REQUIRE( (Utility::HDF5IArchive::use_array_optimization::apply<std::tuple<std::string,T> >::type::value) ); FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_a", extracted_array_a ) ); FRENSIE_CHECK_EQUAL( (Utility::ArrayView<const std::pair<T,std::string> >( &array_a[0][0], &array_a[0][0]+6 )), (Utility::ArrayView<const std::pair<T,std::string> >( &extracted_array_a[0][0], &extracted_array_a[0][0]+6 )) ); FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_b", extracted_array_b ) ); FRENSIE_CHECK_EQUAL( (Utility::ArrayView<const std::tuple<std::string,T> >( array_b, array_b+6 )), (Utility::ArrayView<const std::tuple<std::string,T> >( extracted_array_b, extracted_array_b+6 )) ); } } //---------------------------------------------------------------------------// // end tstHDF5ArchiveTupleTypes.cpp //---------------------------------------------------------------------------//
40.060241
258
0.635338
bam241
7cc25b5cc7f475ba8cd715a85093f9e839f362d0
15,286
cpp
C++
src/src/tests/suites/mutation_test_bad.cpp
geneial/geneial
5e525c32b7c1e1e88788644e448e9234c93b55e2
[ "MIT" ]
5
2015-08-25T15:40:09.000Z
2020-03-15T19:33:22.000Z
src/src/tests/suites/mutation_test_bad.cpp
geneial/geneial
5e525c32b7c1e1e88788644e448e9234c93b55e2
[ "MIT" ]
null
null
null
src/src/tests/suites/mutation_test_bad.cpp
geneial/geneial
5e525c32b7c1e1e88788644e448e9234c93b55e2
[ "MIT" ]
3
2019-01-24T13:14:51.000Z
2022-01-03T07:30:20.000Z
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE operations/mutation #include <boost/test/unit_test.hpp> #include <geneial/algorithm/BaseGeneticAlgorithm.h> #include <geneial/core/fitness/Fitness.h> #include <geneial/core/fitness/FitnessEvaluator.h> #include <geneial/core/population/PopulationSettings.h> #include <geneial/core/population/builder/ContinousMultiValueBuilderSettings.h> #include <geneial/core/population/builder/ContinousMultiValueChromosomeFactory.h> #include <geneial/core/operations/mutation/MutationSettings.h> #include <geneial/core/operations/mutation/NonUniformMutationOperation.h> #include <geneial/core/operations/mutation/UniformMutationOperation.h> #include <geneial/core/operations/choosing/ChooseRandom.h> #include "mocks/MockFitnessEvaluator.h" #include <memory> using namespace geneial; using namespace geneial::population::management; using namespace geneial::operation::choosing; using namespace geneial::operation::mutation; using namespace test_mock; BOOST_AUTO_TEST_SUITE( TESTSUITE_UniformMutationOperation ) //TODO (bewo): Separate Uniform and Nonuniform into separate testcases //TODO (bewo): Use more mock objects / helper here to avoid tedious duplicate gluecode? BOOST_AUTO_TEST_CASE( UNIFORM_TEST__basicMutation ) { /* * 100% Chance of mutation * Tests if Chromosomes are actually mutated * * Test for Uniform and NonUniform Mutation */ MockFitnessEvaluator<double>::ptr evaluator(new MockFitnessEvaluator<double>()); ContinousMultiValueBuilderSettings<int, double> builderSettings (evaluator, 10, 130, 0, true, 20, 5); ContinousMultiValueChromosomeFactory<int, double> chromosomeFactory(builderSettings); BaseManager<double> manager(std::make_shared<ContinousMultiValueChromosomeFactory<int, double>>(chromosomeFactory)); BOOST_TEST_MESSAGE("Checking Mutation at 100% probability"); for (double i = 0; i <= 1; i = i + 0.1) { MutationSettings mutationSettings(1, i, 0); ChooseRandom<int, double> mutationChoosingOperation(mutationSettings); NonUniformMutationOperation<int, double> mutationOperation_NonUniform(1000, 0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory); UniformMutationOperation<int, double> mutationOperation_Uniform (mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory); BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome( BaseChromosomeFactory<double>::CREATE_VALUES); geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet; geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform; geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform; inputSet.push_back(_newChromosome); resultSet_NonUniform.push_back(_newChromosome); resultSet_Uniform.push_back(_newChromosome); resultSet_NonUniform = mutationOperation_NonUniform.doMutate(inputSet, manager); resultSet_Uniform = mutationOperation_Uniform.doMutate(inputSet, manager); BOOST_TEST_MESSAGE("Checking at amount of Mutation = "<< i); BOOST_CHECK(inputSet != resultSet_NonUniform); BOOST_CHECK(inputSet != resultSet_Uniform); } // BOOST_TEST_MESSAGE (""); // BOOST_TEST_MESSAGE ("Checking Mutation at 0% probability"); for (double i = 0; i <= 1; i = i + 0.1) { MutationSettings mutationSettings(0, i, 0); ChooseRandom<int, double> mutationChoosingOperation(mutationSettings); NonUniformMutationOperation<int, double> mutationOperation_NonUniform (1000, 0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory); UniformMutationOperation<int, double> mutationOperation_Uniform (mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory); BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome( BaseChromosomeFactory<double>::CREATE_VALUES); geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet; geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform; geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform; inputSet.push_back(_newChromosome); resultSet_NonUniform.push_back(_newChromosome); resultSet_Uniform.push_back(_newChromosome); resultSet_NonUniform = mutationOperation_NonUniform.doMutate(inputSet, manager); resultSet_Uniform = mutationOperation_Uniform.doMutate(inputSet, manager); BOOST_TEST_MESSAGE("Checking at amount of Mutation = "<< i); BOOST_CHECK(inputSet == resultSet_NonUniform); BOOST_CHECK(inputSet == resultSet_Uniform); } } BOOST_AUTO_TEST_CASE( UNIFORM_TEST__Mutation_probability ) { /* * Testing Mutation probability for 10000 Testcases * Checking UNIFOM and NONUNIFORM mutation * */ MockFitnessEvaluator<double>::ptr evaluator(new MockFitnessEvaluator<double>()); ContinousMultiValueBuilderSettings<int, double> builderSettings(evaluator, 10, 130, 0, true, 20, 5); ContinousMultiValueChromosomeFactory<int, double> chromosomeFactory(builderSettings); BaseManager<double> manager(std::make_shared<ContinousMultiValueChromosomeFactory<int, double>>(chromosomeFactory)); //TODO (bewo): Constantify magic numbers... for (double probability = 0.0; probability <= 1.0; probability = probability + 0.1) { // BaseChromosome<double>::ptr _newChromosome = chromosomeFactory->createChromosome(true); // BaseMutationOperation<double>::mutation_result_set inputSet; // BaseMutationOperation<double>::mutation_result_set resultSet[10000]; MutationSettings mutationSettings(probability, 1, 5); ChooseRandom<int, double> mutationChoosingOperation(mutationSettings); NonUniformMutationOperation<int, double> mutationOperation_NonUniform(1000, 0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory); UniformMutationOperation<int, double> mutationOperation_Uniform(mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory); BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome(BaseChromosomeFactory<double>::CREATE_VALUES); geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet; geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform[10000]; geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform[10000]; inputSet.push_back(_newChromosome); int mutationCounter_NonUniform = 0; int mutationCounter_Uniform = 0; for (int i = 0; i < 10000; i++) { resultSet_NonUniform[i].push_back(_newChromosome); resultSet_NonUniform[i] = mutationOperation_NonUniform.doMutate(inputSet, manager); if (inputSet != resultSet_NonUniform[i]) { mutationCounter_NonUniform++; } resultSet_Uniform[i].push_back(_newChromosome); resultSet_Uniform[i] = mutationOperation_Uniform.doMutate(inputSet, manager); if (inputSet != resultSet_Uniform[i]) { mutationCounter_Uniform++; } } if (probability < 0) { //Checking for NON-UNIFORM Mutation BOOST_TEST_MESSAGE("Non-Uniform-Mutation porpability: "<< probability); BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_NonUniform); BOOST_CHECK(mutationCounter_NonUniform == 0); //Checking for UNIFORM Mutation BOOST_TEST_MESSAGE("Uniform-Mutation porpability: "<< probability); BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_Uniform); BOOST_CHECK(mutationCounter_Uniform == 0); } else if (probability > 1) { //Checking for NON-UNIFORM Mutation BOOST_CHECK(mutationCounter_NonUniform = 10000); BOOST_TEST_MESSAGE("Non-Uniform-Mutation porpability: "<< probability); BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_NonUniform); //Checking for UNIFORM Mutation BOOST_CHECK(mutationCounter_Uniform = 10000); BOOST_TEST_MESSAGE("Uniform-Mutation porpability: "<< probability); BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_Uniform); } else { //Checking for NON-UNIFORM Mutation BOOST_CHECK(mutationCounter_NonUniform > (10000 * probability - 200)); BOOST_CHECK(mutationCounter_NonUniform < (10000 * probability + 200)); BOOST_TEST_MESSAGE("Non-Uniform-Mutation porpability: "<< probability); BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_NonUniform); //Checking for UNIFORM Mutation BOOST_CHECK(mutationCounter_Uniform > (10000 * probability - 200)); BOOST_CHECK(mutationCounter_Uniform < (10000 * probability + 200)); BOOST_TEST_MESSAGE("Uniform-Mutation porpability: "<< probability); BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_Uniform); } } } BOOST_AUTO_TEST_CASE ( UNIFORM_TEST__points_of_mutation ) { /* * Checking if as many points are mutated as set in Mutation settings */ MockFitnessEvaluator<double>::ptr evaluator(new MockFitnessEvaluator<double>()); ContinousMultiValueBuilderSettings<int, double> builderSettings (evaluator, 100, 130, 0, true, 20, 5); ContinousMultiValueChromosomeFactory<int, double> chromosomeFactory (builderSettings); BaseManager<double> manager(std::make_shared<ContinousMultiValueChromosomeFactory<int, double>>(chromosomeFactory)); for (unsigned int pointsOfMutation = 0; pointsOfMutation <= 102; pointsOfMutation++) { MutationSettings mutationSettings(1, 1, pointsOfMutation); ChooseRandom<int, double> mutationChoosingOperation(mutationSettings); NonUniformMutationOperation<int, double> mutationOperation_NonUniform (1000, 0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory); UniformMutationOperation<int, double> mutationOperation_Uniform(mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory); BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome( BaseChromosomeFactory<double>::CREATE_VALUES); geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet; geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform; geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform; inputSet.push_back(_newChromosome); resultSet_NonUniform.push_back(_newChromosome); resultSet_Uniform.push_back(_newChromosome); resultSet_NonUniform = mutationOperation_NonUniform.doMutate(inputSet, manager); resultSet_Uniform = mutationOperation_Uniform.doMutate(inputSet, manager); //getting Chromosome from resultSet: MultiValueChromosome<int, double>::ptr mvcMutant_NonUniform = std::dynamic_pointer_cast< MultiValueChromosome<int, double> >(*resultSet_NonUniform.begin()); MultiValueChromosome<int, double>::ptr mvcMutant_Uniform = std::dynamic_pointer_cast< MultiValueChromosome<int, double> >(*resultSet_Uniform.begin()); MultiValueChromosome<int, double>::ptr mvcOriginal = std::dynamic_pointer_cast< MultiValueChromosome<int, double> >(*inputSet.begin()); //getting ValueContainer from Chromosome: MultiValueChromosome<int, double>::value_container &mvcMutant_NonUniform_valueContainer = mvcMutant_NonUniform->getContainer(); MultiValueChromosome<int, double>::value_container &mvcMutant_Uniform_valueContainer = mvcMutant_Uniform->getContainer(); MultiValueChromosome<int, double>::value_container &mvcOriginal_valueContainer = mvcOriginal->getContainer(); //setting Iterators MultiValueChromosome<int, double>::value_container::iterator original_it = mvcOriginal_valueContainer.begin(); unsigned int nunUniformdiffCounter = 0; for (MultiValueChromosome<int, double>::value_container::iterator nonUniformMutant_it = mvcMutant_NonUniform_valueContainer.begin(); nonUniformMutant_it != mvcMutant_NonUniform_valueContainer.end(); ++nonUniformMutant_it) { //BOOST_TEST_MESSAGE(original_it); if (*original_it != *nonUniformMutant_it) { nunUniformdiffCounter++; } ++original_it; } BOOST_TEST_MESSAGE(""); BOOST_TEST_MESSAGE( "Check if as many points were Mutated as specified in MutationSettings: "<< pointsOfMutation); BOOST_TEST_MESSAGE("NON-UNIFORM: "<< nunUniformdiffCounter); if (pointsOfMutation != 0) { BOOST_CHECK( (nunUniformdiffCounter <= pointsOfMutation + 5 && pointsOfMutation <= 100) || (nunUniformdiffCounter <= 100 && pointsOfMutation > 100)); } else { BOOST_CHECK(nunUniformdiffCounter >= 90); } unsigned int uniformdiffCounter = 0; original_it = mvcOriginal_valueContainer.begin(); for (MultiValueChromosome<int, double>::value_container::iterator uniformMutant_it = mvcMutant_Uniform_valueContainer.begin(); uniformMutant_it != mvcMutant_Uniform_valueContainer.end(); ++uniformMutant_it) { if (*original_it != *uniformMutant_it) uniformdiffCounter++; ++original_it; } BOOST_TEST_MESSAGE("UNIFORM: "<< uniformdiffCounter); if (pointsOfMutation != 0) { BOOST_CHECK( (uniformdiffCounter <= pointsOfMutation + 5 && pointsOfMutation <= 100) || (uniformdiffCounter <= 100 && pointsOfMutation > 100)); } else { BOOST_CHECK(uniformdiffCounter >= 90); } } } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE( TESTSUITE_SmoothingMutation ) //Checks whether the smoothing mutation destroys chromosome's smoothness BOOST_AUTO_TEST_CASE ( SMOOTHING_TEST__ensure_nonviolated_smoothness ) { } //Test whether mutation generates values above/below minmax BOOST_AUTO_TEST_CASE ( SMOOTHING_TEST__ensure_adherence_min_max ) { } //Test Peak at chromosome borders. BOOST_AUTO_TEST_SUITE_END()
45.766467
171
0.715753
geneial
7cc4d6366a91a8a61ad3decd9b770103ff9db9c1
172
cpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Regular_13_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Regular_13_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Regular_13_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
#include <touchgfx/hal/Types.hpp> FONT_LOCATION_FLASH_PRAGMA KEEP extern const uint8_t unicodes_Asap_Regular_13_4bpp[] FONT_LOCATION_FLASH_ATTRIBUTE = { 0 // No glyphs };
24.571429
91
0.819767
ramkumarkoppu
7cc6263b91af91347ca89106b29f0e127c9f61b6
2,524
cpp
C++
windows/cpp/samples/CameraToDVD/MuxedStream.cpp
dvdbuilder/dvdbuilder-samples
8d2b472bd0af899fa342437bb41b33ef8603e0aa
[ "MIT" ]
null
null
null
windows/cpp/samples/CameraToDVD/MuxedStream.cpp
dvdbuilder/dvdbuilder-samples
8d2b472bd0af899fa342437bb41b33ef8603e0aa
[ "MIT" ]
null
null
null
windows/cpp/samples/CameraToDVD/MuxedStream.cpp
dvdbuilder/dvdbuilder-samples
8d2b472bd0af899fa342437bb41b33ef8603e0aa
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "MuxedStream.h" using namespace primo::dvdbuilder::VR; MuxedStreamCB::MuxedStreamCB() { filename[0] = L'\0'; file = NULL; MainWindow = NULL; Reset(); } MuxedStreamCB::~MuxedStreamCB() { Reset(); } void MuxedStreamCB::Reset() { if (file) { fclose(file); file = NULL; } writeCounter = 0; pVideoRecorder = NULL; bProcess = true; } bool MuxedStreamCB::WriteData(uint8_t *pBuf, uint32_t bufSize) { if (!bProcess) return false; ++writeCounter; bool fileResult = true; if (file) { size_t size = fwrite(pBuf,1,bufSize,file); fileResult = (size == bufSize); } bool dvdResult = true; int stopReason = -1; if (pVideoRecorder && !pVideoRecorder->write(pBuf, bufSize)) { ATLTRACE(L"VideoRecorder::Write() failed"); DumpErrorState(pVideoRecorder); int activeCount, failedCount, noSpaceCount; CheckRecorderDevices(pVideoRecorder, &activeCount, &failedCount, &noSpaceCount); ATLASSERT((activeCount + failedCount + noSpaceCount) == pVideoRecorder->devices()->count()); if (0 == activeCount) { dvdResult = false; if (0 == failedCount && noSpaceCount > 0) stopReason = -2; } } if (fileResult && dvdResult) return true; //STOP_CAPTURE PostMessage(MainWindow, WM_STOP_CAPTURE, stopReason, 0); bProcess = false; return false; } bool MuxedStreamCB::SetOutputFile(PCWSTR filename) { if (file) { fclose(file); file = NULL; } if (!filename) { this->filename[0] = L'\0'; return true; } wcscpy_s(this->filename,256, filename); file = _wfopen(this->filename, L"wb"); return file != NULL; } // primo::Stream bool_t MuxedStreamCB::open() { return TRUE; } void MuxedStreamCB::close() { } bool_t MuxedStreamCB::isOpen() const { return TRUE; } bool_t MuxedStreamCB::canRead() const { return FALSE; } bool_t MuxedStreamCB::canWrite() const { return TRUE; } bool_t MuxedStreamCB::canSeek() const { return FALSE; } bool_t MuxedStreamCB::read(void* buffer, int32_t bufferSize, int32_t* totalRead) { return FALSE; } bool_t MuxedStreamCB::write(const void* buffer, int32_t dataSize) { return WriteData((uint8_t*)buffer, dataSize); } int64_t MuxedStreamCB::size() const { return -1; } int64_t MuxedStreamCB::position() const { return -1; } bool_t MuxedStreamCB::seek(int64_t position) { return FALSE; }
16.496732
95
0.633914
dvdbuilder
7ccab8672dba2e6cc86748ba2213e2e6c7a12468
2,115
hpp
C++
src/mbgl/renderer/bucket.hpp
zxlee618/mapbox-gl-native
04c70f55a534ca7cb4bb5358da3217329643a0f0
[ "BSL-1.0", "Apache-2.0" ]
6
2019-06-17T05:41:03.000Z
2022-01-20T13:16:14.000Z
src/mbgl/renderer/bucket.hpp
zxlee618/mapbox-gl-native
04c70f55a534ca7cb4bb5358da3217329643a0f0
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/renderer/bucket.hpp
zxlee618/mapbox-gl-native
04c70f55a534ca7cb4bb5358da3217329643a0f0
[ "BSL-1.0", "Apache-2.0" ]
4
2019-08-30T07:40:17.000Z
2022-01-13T09:36:55.000Z
#pragma once #include <mbgl/util/noncopyable.hpp> #include <mbgl/tile/geometry_tile_data.hpp> #include <mbgl/style/layer_type.hpp> #include <mbgl/style/image_impl.hpp> #include <mbgl/renderer/image_atlas.hpp> #include <atomic> namespace mbgl { namespace gl { class Context; } // namespace gl class RenderLayer; class PatternDependency; using PatternLayerMap = std::unordered_map<std::string, PatternDependency>; class Bucket : private util::noncopyable { public: Bucket(style::LayerType layerType_) : layerType(layerType_) { } virtual ~Bucket() = default; // Check whether this bucket is of the given subtype. template <class T> bool is() const; // Dynamically cast this bucket to the given subtype. template <class T> T* as() { return is<T>() ? reinterpret_cast<T*>(this) : nullptr; } template <class T> const T* as() const { return is<T>() ? reinterpret_cast<const T*>(this) : nullptr; } // Feature geometries are also used to populate the feature index. // Obtaining these is a costly operation, so we do it only once, and // pass-by-const-ref the geometries as a second parameter. virtual void addFeature(const GeometryTileFeature&, const GeometryCollection&, const ImagePositions&, const PatternLayerMap&) {}; virtual void populateFeatureBuffers(const ImagePositions&) {}; virtual void addPatternDependencies(const std::vector<const RenderLayer*>&, ImageDependencies&) {}; // As long as this bucket has a Prepare render pass, this function is getting called. Typically, // this only happens once when the bucket is being rendered for the first time. virtual void upload(gl::Context&) = 0; virtual bool hasData() const = 0; virtual float getQueryRadius(const RenderLayer&) const { return 0; }; bool needsUpload() const { return hasData() && !uploaded; } protected: style::LayerType layerType; std::atomic<bool> uploaded { false }; }; } // namespace mbgl
28.581081
103
0.665248
zxlee618
7ccf6d8cd7e5457a4ff6c7e03c2a5a56cf69237e
809
cpp
C++
q206-Reverse-Linked-List-recursive-optimized.cpp
risyomei/leetcode
bd0eba2d31eca48c182fc328fab02aac61c15366
[ "MIT" ]
null
null
null
q206-Reverse-Linked-List-recursive-optimized.cpp
risyomei/leetcode
bd0eba2d31eca48c182fc328fab02aac61c15366
[ "MIT" ]
null
null
null
q206-Reverse-Linked-List-recursive-optimized.cpp
risyomei/leetcode
bd0eba2d31eca48c182fc328fab02aac61c15366
[ "MIT" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(head == NULL){ return NULL; } if(head -> next == NULL) { return head; } // Cache p in recursive stack ListNode* p = head; // Always return t, as that's the last node. ListNode *t = reverseList(head->next); // Reverse p -> next -> next = p; p -> next = NULL; return t; } };
22.472222
62
0.454883
risyomei
7cd2b544adf16108232c989a22345f250bc5d1f6
4,440
cpp
C++
src/Trinity.C/src/Storage/MTHash/MTHash.DiskIO.cpp
erinloy/GraphEngine
1a913c18043192c597d48e0b4e77b0a62cd6a10e
[ "MIT" ]
370
2019-05-08T07:40:52.000Z
2022-03-28T15:29:18.000Z
src/Trinity.C/src/Storage/MTHash/MTHash.DiskIO.cpp
qingzhu521/GraphEngine
56d98c09b8e9a55b4397823f20cf29263c8857b5
[ "MIT" ]
55
2019-05-20T09:01:48.000Z
2022-03-31T23:05:23.000Z
src/Trinity.C/src/Storage/MTHash/MTHash.DiskIO.cpp
qingzhu521/GraphEngine
56d98c09b8e9a55b4397823f20cf29263c8857b5
[ "MIT" ]
83
2019-05-15T14:16:23.000Z
2022-03-06T07:04:10.000Z
// Graph Engine // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // #include "Storage/MTHash/MTHash.h" #include "Storage/MemoryTrunk/MemoryTrunk.h" using namespace Trinity::IO; namespace Storage { bool MTHash::Save(const String& output_file) { BinaryWriter bw(output_file); bool success = true; success = success && bw.Write((char)VERSION); // 1B success = success && bw.Write(ExtendedInfo->NonEmptyEntryCount); // 4B success = success && bw.Write(ExtendedInfo->FreeEntryCount); // 4B success = success && bw.Write(ExtendedInfo->FreeEntryList); // 4B success = success && bw.Write(BucketCount); // 4B success = success && bw.Write(ExtendedInfo->EntryCount); // 4B int32_t mtentry_array_length = (int32_t)ExtendedInfo->EntryCount * szMTEntry(); int32_t cellentry_array_length = (int32_t)ExtendedInfo->EntryCount * szCellEntry(); int32_t bucket_array_length = (int32_t)BucketCount * szBucket(); // Write buckets array success = success && bw.Write((char*)Buckets, 0, bucket_array_length); // note here we write more // Write entry array char* buff = new char[cellentry_array_length]; memcpy(buff, CellEntries, cellentry_array_length); #pragma region Modify the offset in the entries char* p = buff; if (memory_trunk->committed_tail < memory_trunk->head.committed_head || (memory_trunk->committed_tail == memory_trunk->head.committed_head && memory_trunk->committed_tail == 0) )//one segment { CellEntry* entryPtr = (CellEntry*)p; CellEntry* entryEndPtr = entryPtr + ExtendedInfo->NonEmptyEntryCount; for (; entryPtr != entryEndPtr; ++entryPtr) { if (entryPtr->offset > 0 && entryPtr->size > 0) { entryPtr->offset -= (int32_t)memory_trunk->committed_tail; } } } else//two segments { CellEntry* entryPtr = (CellEntry*)p; CellEntry* entryEndPtr = entryPtr + ExtendedInfo->NonEmptyEntryCount; for (; entryPtr != entryEndPtr; ++entryPtr) { if (entryPtr->offset >= (int32_t)memory_trunk->head.committed_head && entryPtr->size > 0) { entryPtr->offset -= ((int32_t)memory_trunk->committed_tail - (int32_t)memory_trunk->head.append_head); } } } #pragma endregion success = success && bw.Write(buff, 0, cellentry_array_length); delete[] buff; success = success && bw.Write((char*)MTEntries, 0, mtentry_array_length); return success; } bool MTHash::Reload(const String& input_file) { BinaryReader br(input_file); if (!br.Good()) return false; DeallocateMTHash(); /*********** Read meta data ************/ int32_t version = (int32_t)br.ReadChar(); if (version != VERSION) { Trinity::Diagnostics::FatalError("The Trinity disk image version does not match."); } ExtendedInfo->NonEmptyEntryCount = br.ReadInt32(); ExtendedInfo->FreeEntryCount = br.ReadInt32(); ExtendedInfo->FreeEntryList = br.ReadInt32(); if (BucketCount != br.ReadUInt32()) { Trinity::Diagnostics::FatalError("The Trinity disk image is invalid."); } ExtendedInfo->EntryCount = br.ReadUInt32(); int32_t mtentry_array_length = (int32_t)ExtendedInfo->EntryCount * szMTEntry(); int32_t cellentry_array_length = (int32_t)ExtendedInfo->EntryCount * szCellEntry(); int32_t bucket_array_length = (int32_t)BucketCount * szBucket(); ///////////////////////////////////////////////////////// AllocateMTHash(); bool read_success = true; read_success = read_success && br.Read((char*)Buckets, 0, bucket_array_length); read_success = read_success && br.Read((char*)CellEntries, 0, cellentry_array_length); read_success = read_success && br.Read((char*)MTEntries, 0, mtentry_array_length); return read_success; } }
38.608696
116
0.592568
erinloy
7cd6712e6afe46868512b116b3c323f376e8e193
2,240
cpp
C++
code/engine.vc2008/xrGame/items/WeaponDispersion.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
7
2018-03-27T12:36:07.000Z
2020-06-26T11:31:52.000Z
code/engine.vc2008/xrGame/items/WeaponDispersion.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
2
2018-05-26T23:17:14.000Z
2019-04-14T18:33:27.000Z
code/engine.vc2008/xrGame/items/WeaponDispersion.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
3
2019-10-20T19:35:34.000Z
2022-02-28T01:42:10.000Z
// WeaponDispersion.cpp: разбос при стрельбе // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "items/Weapon.h" #include "inventoryowner.h" #include "actor.h" #include "inventory_item_impl.h" #include "actoreffector.h" #include "effectorshot.h" //возвращает 1, если оружие в отличном состоянии и >1 если повреждено float CWeapon::GetConditionDispersionFactor() const { return (1.f + fireDispersionConditionFactor*(1.f-GetCondition())); } float CWeapon::GetFireDispersion (bool with_cartridge, bool for_crosshair) { if (!with_cartridge) return GetFireDispersion(1.0f, for_crosshair); if (!m_magazine.empty()) m_fCurrentCartirdgeDisp = m_magazine.back().param_s.kDisp; return GetFireDispersion (m_fCurrentCartirdgeDisp, for_crosshair); } float CWeapon::GetBaseDispersion(float cartridge_k) { return fireDispersionBase * cur_silencer_koef.fire_dispersion * cartridge_k * GetConditionDispersionFactor(); } //текущая дисперсия (в радианах) оружия с учетом используемого патрона float CWeapon::GetFireDispersion (float cartridge_k, bool for_crosshair) { //учет базовой дисперсии, состояние оружия и влияение патрона float fire_disp = GetBaseDispersion(cartridge_k); //вычислить дисперсию, вносимую самим стрелком if(H_Parent()) { const CInventoryOwner* pOwner = smart_cast<const CInventoryOwner*>(H_Parent()); float parent_disp = pOwner->GetWeaponAccuracy(); fire_disp += parent_disp; } return fire_disp; } ////////////////////////////////////////////////////////////////////////// // Для эффекта отдачи оружия void CWeapon::AddShotEffector () { inventory_owner().on_weapon_shot_start (this); } void CWeapon::RemoveShotEffector () { CInventoryOwner* pInventoryOwner = smart_cast<CInventoryOwner*>(H_Parent()); if (pInventoryOwner) pInventoryOwner->on_weapon_shot_remove (this); } void CWeapon::ClearShotEffector () { CInventoryOwner* pInventoryOwner = smart_cast<CInventoryOwner*>(H_Parent()); if (pInventoryOwner) pInventoryOwner->on_weapon_hide (this); } void CWeapon::StopShotEffector () { CInventoryOwner* pInventoryOwner = smart_cast<CInventoryOwner*>(H_Parent()); if (pInventoryOwner) pInventoryOwner->on_weapon_shot_stop(); }
28.35443
110
0.725446
Rikoshet-234