hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
0f15f82b2da60468fbbdde03f486d9ee6527d06f
2,147
cpp
C++
src/checks/process.cpp
RichardAH/valmond
66965947fb5c7835af687ee2aa1fc00fc7f32eac
[ "MIT" ]
4
2020-01-15T22:36:01.000Z
2020-01-20T02:38:57.000Z
src/checks/process.cpp
RichardAH/valmond
66965947fb5c7835af687ee2aa1fc00fc7f32eac
[ "MIT" ]
1
2021-01-04T19:24:42.000Z
2021-07-01T20:31:01.000Z
src/checks/process.cpp
RichardAH/valmond
66965947fb5c7835af687ee2aa1fc00fc7f32eac
[ "MIT" ]
3
2020-02-10T16:52:00.000Z
2021-07-01T13:52:35.000Z
#include "process.hpp" #include <dirent.h> #include <errno.h> #include <fstream> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include <sys/types.h> #include <vector> namespace checks { namespace process { Json::Value runProcessCheck() { int pid = -1; // Open the /proc directory DIR* dp = opendir("/proc"); if (dp != NULL) { // Enumerate all entries in directory until process found struct dirent* dirp; while (pid < 0 && (dirp = readdir(dp))) { // Skip non-numeric entries int id = atoi(dirp->d_name); if (id > 0) { // Read contents of virtual /proc/{pid}/cmdline file std::string cmdPath = std::string("/proc/") + dirp->d_name + "/cmdline"; std::ifstream cmdFile(cmdPath.c_str()); std::string cmdLine; std::getline(cmdFile, cmdLine); if (!cmdLine.empty()) { // Keep first cmdline item which contains the program path size_t pos = cmdLine.find('\0'); if (pos != std::string::npos) cmdLine = cmdLine.substr(0, pos); // Keep program name only, removing the path pos = cmdLine.rfind('/'); if (pos != std::string::npos) cmdLine = cmdLine.substr(pos + 1); // Compare against requested process name if (PROCESS_NAME == cmdLine) pid = id; } } } } closedir(dp); Json::Value result; result["exit_code"] = 2; result["output"] = "Check Proccess CRITICAL: Found 0 matching validator process"; result["command"] = "CheckProcess"; // find the proccess if (pid > -1) { result["exit_code"] = 0; result["output"] = "Check Proccess OK: Found process blong to validator"; result["command"] = "CheckProcess"; } return result; } } // namespace process } // namespace checks
27.883117
88
0.510946
[ "vector" ]
0f1ae25ffad46c8582389580d2f64f990b6ee13c
1,817
cc
C++
mindspore/lite/tools/converter/adapter/dpico/checker/log_checker.cc
PowerOlive/mindspore
bda20724a94113cedd12c3ed9083141012da1f15
[ "Apache-2.0" ]
1
2022-03-05T02:59:21.000Z
2022-03-05T02:59:21.000Z
mindspore/lite/tools/converter/adapter/dpico/checker/log_checker.cc
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
null
null
null
mindspore/lite/tools/converter/adapter/dpico/checker/log_checker.cc
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "checker/log_checker.h" #include <vector> #include <string> #include <limits> #include "common/op_enum.h" namespace mindspore { namespace dpico { bool LogChecker::Check(CNodePtr op, int32_t output_num, mindspore::Format format) { if (!CheckInputW(op, kInputIndex1, format, kMaxInputWOf4Dims)) { MS_LOG(WARNING) << "input_w is not supported. " << op->fullname_with_scope(); return false; } auto primitive = GetValueNode<PrimitivePtr>(op->input(0)); if (primitive == nullptr) { MS_LOG(ERROR) << "primitive is nullptr"; return false; } auto base_ptr = primitive->GetAttr(ops::kBase); if (base_ptr != nullptr) { auto base_data = GetValue<float>(base_ptr); // support -1.0 && any positive num but 1.0 if (fabs(base_data + 1.0) <= std::numeric_limits<float>::epsilon() || (base_data > 0 && fabs(base_data - 1.0) > std::numeric_limits<float>::epsilon())) { return true; } else { MS_LOG(WARNING) << "base val only supports -1.0 or any positive num but 1.0 " << op->fullname_with_scope(); return false; } } return true; } OpCheckerRegistrar g_LogChecker("Log", new LogChecker()); } // namespace dpico } // namespace mindspore
34.942308
113
0.693451
[ "vector" ]
0f1c2dfcbc3e4bf99d6582ba5e660242e6fadeb0
5,518
cpp
C++
analysis/process_track.cpp
suerfu/veto
648996be3102f7fa6aba5e258dce8c8b0ea3eb8f
[ "Apache-2.0" ]
null
null
null
analysis/process_track.cpp
suerfu/veto
648996be3102f7fa6aba5e258dce8c8b0ea3eb8f
[ "Apache-2.0" ]
null
null
null
analysis/process_track.cpp
suerfu/veto
648996be3102f7fa6aba5e258dce8c8b0ea3eb8f
[ "Apache-2.0" ]
1
2021-11-12T04:25:18.000Z
2021-11-12T04:25:18.000Z
#include <iostream> #include <vector> #include <map> #include <fstream> #include <sstream> #include <string> #include "TTree.h" #include "TFile.h" using namespace std; // TrackInfor is used to hold information read from input ROOT file. // While reading the input, Hit objects are created and filled into a vector owned by EventInfo // EventInfo contains all informations needed for outputting reduced quantities. // At the end of an event marker, Process and Reset methods are called to fill the output tree. struct TrackInfo{ int eventID; int trackID; int parentID; char particle_name[16]; char volume_name[16]; char proc_name[16]; double Eki; double Ekf; double Edep; double time; }; struct Hit{ int parentID; string particle; string volume; string process; Double_t edep; Double_t time; }; struct EventInfo{ char file_name[128]; Int_t ID = -1; Int_t evtID = -1; Double_t edep = 0; Double_t time = -1; vector<Hit> hit_collection; }; // reset event info. void ResetEventInfo( EventInfo* wdata ){ wdata->ID = -1; wdata->evtID = -1; wdata->edep = 0; wdata->time = -1; wdata->hit_collection.clear(); } void ProcessEventInfo( EventInfo* wdata ); int GetIndex( string ); int main( int argc, char* argv[]){ bool print_usage = false; if( argc==1 ){ print_usage = true; } else{ for( int i=1; i<argc; i++){ if( strncmp( argv[i], "-h", 2) ==0 || strncmp( argv[i], "--help", 6) ==0 ){ print_usage = true; } } } if( print_usage){ cout << "usage: " << argv[0] << " File-to-process-0 [ File-to-Process-1 ...] Output-ROOT-File\n"; return 0; } string output_name = argv[argc-1]; TFile* outfile = new TFile( output_name.c_str(), "NEW"); if( !outfile ){ cout << "Error creating file " << output_name << endl; return -2; } TTree* tree = new TTree( "events", "MC simulation for Compton scattering"); EventInfo wdata; // data for writing tree->Branch( "file", &wdata.file_name, "file[128]/C"); tree->Branch( "ID", &wdata.ID, "ID/I"); tree->Branch( "evtID", &wdata.evtID, "evtID/I"); tree->Branch( "Edep", &wdata.edep, "Edep/D" ); tree->Branch( "time", &wdata.time, "time/D"); // ************************** // // * Process the input file * // // ************************** // for( int t = 1; t<argc-1; t++ ){ string filename( argv[t] ); TFile* infile = TFile::Open( filename.c_str(), "READ"); if( !infile ){ cout << "ERROR reading file " << filename << endl; } else{ cout << "Processing " << filename << endl; } strncpy( wdata.file_name, argv[t], 128); TTree* events = (TTree*)infile->Get("events"); int nentries = events->GetEntries(); TrackInfo data; // data for reading events -> SetBranchAddress("eventID", &data.eventID); events -> SetBranchAddress("trackID", &data.trackID); events -> SetBranchAddress("parentID", &data.parentID); events -> SetBranchAddress("particle", &data.particle_name); events -> SetBranchAddress("volume", &data.volume_name); events -> SetBranchAddress("Eki", &data.Eki); events -> SetBranchAddress("Ekf", &data.Ekf); events -> SetBranchAddress("Edep", &data.Edep); events -> SetBranchAddress("t", &data.time); events -> SetBranchAddress("process", &data.proc_name); // ************************** // // * Process the input file * // // ************************** // int evt_counter = -1; for( unsigned int i=0; i<nentries; i++){ events->GetEntry(i); if( ( data.parentID==0 && strncmp( data.proc_name, "initStep", 8)==0 ) || i==nentries-1 ){ if( i!=0 ){ ProcessEventInfo( &wdata ); //cout << wdata.edep_he_n << endl; tree->Fill(); evt_counter++; ResetEventInfo( &wdata ); } wdata.ID = evt_counter; wdata.evtID = data.eventID; } else{ string volume_name = data.volume_name; Hit hit; hit.parentID = data.parentID; hit.particle = data.particle_name; hit.process = data.proc_name; hit.volume = data.volume_name; hit.edep = data.Edep; hit.time = data.time; wdata.hit_collection.push_back( hit ); } } infile->Close(); } outfile->cd(); tree->Write(); outfile->Close(); return 0; } void ProcessEventInfo( EventInfo* wdata ){ vector<Hit> hc = wdata->hit_collection; for( unsigned int i=0; i<hc.size(); i++){ // compute the time that the particle hit the liquid helium if( hc[i].volume=="chamber" ){ wdata->edep += hc[i].edep; } } } int GetIndex( string fs_name){ int nchar = 0; if( fs_name.find("NaI")!=string::npos) nchar = 3; else nchar = 2; stringstream ss( fs_name ); char foo; for( unsigned int i=0; i<nchar; i++){ ss >> foo; } unsigned index = 0; ss >> index; return index; }
24.855856
105
0.528452
[ "vector" ]
0f1c9d867551b9122e39d6f3893b7e0b8d8bdbe7
2,865
cpp
C++
cpp/Graphs/network-flows-and-Bipartite-matching/edmond-karp-algorithm.cpp
fossabot/a-grim-loth
a6c8d549289a39ec981c1e0d0c754bb2708dfff9
[ "MIT" ]
4
2021-06-26T17:18:47.000Z
2022-02-02T15:02:27.000Z
cpp/Graphs/network-flows-and-Bipartite-matching/edmond-karp-algorithm.cpp
fossabot/a-grim-loth
a6c8d549289a39ec981c1e0d0c754bb2708dfff9
[ "MIT" ]
8
2021-06-29T07:00:32.000Z
2021-12-01T11:26:22.000Z
cpp/Graphs/network-flows-and-Bipartite-matching/edmond-karp-algorithm.cpp
fossabot/a-grim-loth
a6c8d549289a39ec981c1e0d0c754bb2708dfff9
[ "MIT" ]
3
2021-07-14T14:42:08.000Z
2021-12-07T19:36:53.000Z
/** * @file edmond-karp-algorithm.cpp * @author prakash (prakashsellathurai@gmail.com) * @brief edmond-karp algorithm implementation runs in O(E*V) time * @version 0.1 * @date 2021-07-23 * * @copyright Copyright (c) 2021 * */ #include <algorithm> #include <cmath> #include <iostream> #include <vector> #define INF 100000 using namespace std; class Graph { public: int V; // No. of vertices int E; // No. of edges vector<vector<int>> adj; // Adjacency Lists int *dist; // Distance from source int *parent; // parent of i int source; // source vertex int sink; // sink vertex int max_flow; // max flow int *flow; // flow values int *pred; // predecessor int *q; // queue bool *visited; // visited vertices Graph(int V) { this->V = V; } Graph(int V, int E, vector<vector<int>> adj) { this->V = V; this->E = E; this->adj = adj; this->dist = new int[V]; this->parent = new int[V]; this->flow = new int[V]; this->pred = new int[V]; this->q = new int[V]; this->visited = new bool[V]; for (int i = 0; i < V; i++) { dist[i] = INF; parent[i] = -1; flow[i] = 0; pred[i] = -1; visited[i] = false; } } ~Graph() { delete[] dist; delete[] parent; delete[] flow; delete[] pred; delete[] q; delete[] visited; } int EdmondKarp(int source, int sink) { max_flow = 0; while (BFS(source, sink)) { int path_flow = INF; for (int u = sink; u != source; u = parent[u]) { path_flow = min(path_flow, adj[u][parent[u]]); } for (int u = sink; u != source; u = parent[u]) { adj[u][parent[u]] -= path_flow; adj[parent[u]][u] += path_flow; } max_flow += path_flow; } return max_flow; } private: bool BFS(int source, int sink) { for (int i = 0; i < V; i++) { dist[i] = INF; parent[i] = -1; q[i] = 0; visited[i] = false; } dist[source] = 0; q[source] = 1; int front = 0; int rear = 1; while (front <= rear) { int u = q[front++]; visited[u] = true; for (int v = 0; v < V; v++) { if (visited[v] == false && adj[u][v] > 0 && dist[u] != INF && dist[u] + adj[u][v] < dist[v]) { dist[v] = dist[u] + adj[u][v]; parent[v] = u; q[rear++] = v; } } } return dist[sink] != INF; } }; int main(int argc, const char **argv) { int V = 5; int E = 8; vector<vector<int>> adj = { {0, 2, 0, 0, 0}, {2, 10, 4, 0, 0}, {0, 4, 0, 6, 0}, {0, 0, 6, 0, 8}, {0, 0, 0, 8, 0}, }; Graph g(V, E, adj); int sink = 4; int source = 0; int max_flow = g.EdmondKarp(source, sink); std::cout << max_flow << std::endl; return 0; }
23.104839
69
0.49459
[ "vector" ]
0f1cc03110a6b013b9ba385fe294aa912dd20657
4,039
hh
C++
include/introvirt/windows/kernel/nt/types/objects/OBJECT_HEADER.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
23
2021-02-17T16:58:52.000Z
2022-02-12T17:01:06.000Z
include/introvirt/windows/kernel/nt/types/objects/OBJECT_HEADER.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
1
2021-04-01T22:41:32.000Z
2021-09-24T14:14:17.000Z
include/introvirt/windows/kernel/nt/types/objects/OBJECT_HEADER.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/windows/kernel/nt/types/objects/OBJECT_HEADER_CREATOR_INFO.hh> #include <introvirt/windows/kernel/nt/types/objects/OBJECT_HEADER_HANDLE_INFO.hh> #include <introvirt/windows/kernel/nt/types/objects/OBJECT_HEADER_NAME_INFO.hh> #include <introvirt/windows/kernel/nt/types/objects/OBJECT_HEADER_PROCESS_INFO.hh> #include <introvirt/windows/kernel/nt/types/objects/OBJECT_HEADER_QUOTA_INFO.hh> #include <introvirt/core/memory/guest_ptr.hh> #include <introvirt/windows/kernel/nt/const/ObjectType.hh> #include <introvirt/windows/kernel/nt/fwd.hh> #include <cstdint> #include <memory> namespace introvirt { namespace windows { namespace nt { /** * @brief Wrapper for the Windows OBJECT_HEADER structure * * Windows' kernel objects are prefixed with an OBJECT_HEADER. The HANDLE_TABLE stores references to * OBJECT_HEADERs, from which we can get the actual object. */ class OBJECT_HEADER { public: /** * @brief Get the index into the Type table */ virtual uint8_t TypeIndex() const = 0; /** * @returns The guest address of the object that comes after the header */ virtual guest_ptr<void> Body() const = 0; /** * @brief Get the creator information * * @return The creator information * @throws InvalidMethodException if not available */ virtual const OBJECT_HEADER_CREATOR_INFO& CreatorInfo() const = 0; /** * @brief Get the handle information * * @return The handle information * @throws InvalidMethodException if not available */ virtual const OBJECT_HEADER_HANDLE_INFO& HandleInfo() const = 0; /** * @brief Get the name information * * @return The name information * @throws InvalidMethodException if not available */ virtual const OBJECT_HEADER_NAME_INFO& NameInfo() const = 0; /** * @brief Get the process information * * @return The process information * @throws InvalidMethodException if not available */ virtual const OBJECT_HEADER_PROCESS_INFO& ProcessInfo() const = 0; /** * @brief Get the quota information * * @return The quota information * @throws InvalidMethodException if not available */ virtual const OBJECT_HEADER_QUOTA_INFO& QuotaInfo() const = 0; /** * @returns True if creator information is available */ virtual bool has_creator_info() const = 0; /** * @returns True if handle information is available */ virtual bool has_handle_info() const = 0; /** * @returns True if name information is available */ virtual bool has_name_info() const = 0; /** * @returns True if process information is available */ virtual bool has_process_info() const = 0; /** * @returns True if quota information is available */ virtual bool has_quota_info() const = 0; /** * @returns The type of object being referred to */ virtual ObjectType type() const = 0; /** * @returns The virtual address of the OBJECT_HEADER */ virtual guest_ptr<void> ptr() const = 0; static std::unique_ptr<OBJECT_HEADER> make_unique(const NtKernel& kernel, const guest_ptr<void>& ptr); virtual ~OBJECT_HEADER() = default; }; } /* namespace nt */ } /* namespace windows */ } /* namespace introvirt */
29.268116
100
0.681109
[ "object" ]
0f22caea72ed6fea7e3055399c794954514a77b7
2,734
hpp
C++
openstudiocore/src/utilities/sql/SqlFileEnums.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/utilities/sql/SqlFileEnums.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/utilities/sql/SqlFileEnums.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2013, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef UTILITIES_SQL_SQLFILEENUMS_HPP #define UTILITIES_SQL_SQLFILEENUMS_HPP #include <utilities/UtilitiesAPI.hpp> #include <utilities/core/Enum.hpp> #include <boost/optional.hpp> namespace openstudio { /** \class ReportingFrequency * \brief Frequencies at which report variables may be specified. * \details See the OPENSTUDIO_ENUM documentation in utilities/core/Enum.hpp. The actual * macro call is: * \code OPENSTUDIO_ENUM(ReportingFrequency, ((Detailed)(HVAC System Timestep)(1)) ((Timestep)(Zone Timestep)) ((Hourly)) ((Daily)) ((Monthly)) ((RunPeriod)) ); * \endcode */ OPENSTUDIO_ENUM(ReportingFrequency, ((Detailed)(HVAC System Timestep)(1)) ((Timestep)(Zone Timestep)) ((Hourly)) ((Daily)) ((Monthly)) ((RunPeriod)) ); typedef boost::optional<ReportingFrequency> OptionalReportingFrequency; typedef std::vector<ReportingFrequency> ReportingFrequencyVector; typedef std::set<ReportingFrequency> ReportingFrequencySet; /** \class EnvironmentType * \brief Frequencies at which report variables may be specified. * \details See the OPENSTUDIO_ENUM documentation in utilities/core/Enum.hpp. The actual * macro call is: * \code OPENSTUDIO_ENUM(EnvironmentType, ((DesignDay)(DesignDay)(1)) ((DesignRunPeriod)) ((WeatherRunPeriod)) ); * \endcode */ OPENSTUDIO_ENUM(EnvironmentType, ((DesignDay)(DesignDay)(1)) ((DesignRunPeriod)) ((WeatherRunPeriod)) ); typedef boost::optional<EnvironmentType> OptionalEnvironmentType; } // openstudio #endif // UTILITIES_SQL_SQLFILEENUMS_HPP
36.453333
90
0.652158
[ "vector" ]
0f239b00d9e44e0157127d50ad53a65d23e8b355
1,366
cpp
C++
backup/2/interviewbit/c++/rotated-sorted-array-search.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/interviewbit/c++/rotated-sorted-array-search.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/interviewbit/c++/rotated-sorted-array-search.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/interviewbit/rotated-sorted-array-search.html . int getPivot(const vector<int> &nums) { int n = nums.size(), begin = 0, end = n - 1; while (end - begin > 1) { int middle = (begin + end) / 2; if (nums[middle] > nums[begin]) { begin = middle; } else { end = middle; } } return end; } int Solution::search(const vector<int> &A, int B) { int pivot = getPivot(A), begin, end, n = A.size(); if (B >= A[0]) { begin = 0, end = pivot - 1; } else { begin = pivot, end = n - 1; } while (begin <= end) { int middle = (begin + end) / 2; if (A[middle] == B) return middle; if (A[middle] < B) begin = middle + 1; else end = middle - 1; } return -1; }
36.918919
345
0.584919
[ "vector" ]
0f251261bdfdb9a204dddedc0a7f446569f986bf
5,606
hpp
C++
include/GlobalNamespace/MissionNodeSelectionManager.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MissionNodeSelectionManager.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MissionNodeSelectionManager.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.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: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: MissionNodesManager class MissionNodesManager; // Forward declaring type: MissionNodeVisualController class MissionNodeVisualController; // Forward declaring type: MissionNode class MissionNode; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x38 #pragma pack(push, 1) // Autogenerated type: MissionNodeSelectionManager class MissionNodeSelectionManager : public UnityEngine::MonoBehaviour { public: // private MissionNodesManager _missionNodesManager // Size: 0x8 // Offset: 0x18 GlobalNamespace::MissionNodesManager* missionNodesManager; // Field size check static_assert(sizeof(GlobalNamespace::MissionNodesManager*) == 0x8); // [CompilerGeneratedAttribute] Offset: 0xE23854 // private System.Action`1<MissionNodeVisualController> didSelectMissionNodeEvent // Size: 0x8 // Offset: 0x20 System::Action_1<GlobalNamespace::MissionNodeVisualController*>* didSelectMissionNodeEvent; // Field size check static_assert(sizeof(System::Action_1<GlobalNamespace::MissionNodeVisualController*>*) == 0x8); // private MissionNode[] _missionNodes // Size: 0x8 // Offset: 0x28 ::Array<GlobalNamespace::MissionNode*>* missionNodes; // Field size check static_assert(sizeof(::Array<GlobalNamespace::MissionNode*>*) == 0x8); // private MissionNodeVisualController _selectedNode // Size: 0x8 // Offset: 0x30 GlobalNamespace::MissionNodeVisualController* selectedNode; // Field size check static_assert(sizeof(GlobalNamespace::MissionNodeVisualController*) == 0x8); // Creating value type constructor for type: MissionNodeSelectionManager MissionNodeSelectionManager(GlobalNamespace::MissionNodesManager* missionNodesManager_ = {}, System::Action_1<GlobalNamespace::MissionNodeVisualController*>* didSelectMissionNodeEvent_ = {}, ::Array<GlobalNamespace::MissionNode*>* missionNodes_ = {}, GlobalNamespace::MissionNodeVisualController* selectedNode_ = {}) noexcept : missionNodesManager{missionNodesManager_}, didSelectMissionNodeEvent{didSelectMissionNodeEvent_}, missionNodes{missionNodes_}, selectedNode{selectedNode_} {} // Deleting conversion operator: operator System::IntPtr constexpr operator System::IntPtr() const noexcept = delete; // public System.Void add_didSelectMissionNodeEvent(System.Action`1<MissionNodeVisualController> value) // Offset: 0x1053C10 void add_didSelectMissionNodeEvent(System::Action_1<GlobalNamespace::MissionNodeVisualController*>* value); // public System.Void remove_didSelectMissionNodeEvent(System.Action`1<MissionNodeVisualController> value) // Offset: 0x1053CB4 void remove_didSelectMissionNodeEvent(System::Action_1<GlobalNamespace::MissionNodeVisualController*>* value); // public System.Void DeselectSelectedNode() // Offset: 0x1053D58 void DeselectSelectedNode(); // protected System.Void Start() // Offset: 0x1053E14 void Start(); // protected System.Void OnDestroy() // Offset: 0x1054094 void OnDestroy(); // private System.Void HandleNodeWasSelect(MissionNodeVisualController missionNode) // Offset: 0x1054340 void HandleNodeWasSelect(GlobalNamespace::MissionNodeVisualController* missionNode); // private System.Void HandleNodeWasDisplayed(MissionNodeVisualController missionNode) // Offset: 0x1054404 void HandleNodeWasDisplayed(GlobalNamespace::MissionNodeVisualController* missionNode); // public System.Void .ctor() // Offset: 0x1054494 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static MissionNodeSelectionManager* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MissionNodeSelectionManager::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<MissionNodeSelectionManager*, creationType>())); } }; // MissionNodeSelectionManager #pragma pack(pop) static check_size<sizeof(MissionNodeSelectionManager), 48 + sizeof(GlobalNamespace::MissionNodeVisualController*)> __GlobalNamespace_MissionNodeSelectionManagerSizeCheck; static_assert(sizeof(MissionNodeSelectionManager) == 0x38); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MissionNodeSelectionManager*, "", "MissionNodeSelectionManager");
52.392523
490
0.745451
[ "object" ]
0f278bd37ac8c39640f0d0263e71af493e41ec30
5,499
cpp
C++
libs/rigidAsPossibleMesh/src/LinearAlgebra.cpp
ofZach/ofxPuppet
95c9781e9c43c0867b0c9e916127a18efaa3851a
[ "MIT" ]
35
2015-01-19T11:38:48.000Z
2021-07-23T07:51:16.000Z
libs/rigidAsPossibleMesh/src/LinearAlgebra.cpp
n1ckfg/ofxPuppet
a634961324afe871cceb061eb0a9ce4c8f0d272d
[ "MIT" ]
null
null
null
libs/rigidAsPossibleMesh/src/LinearAlgebra.cpp
n1ckfg/ofxPuppet
a634961324afe871cceb061eb0a9ce4c8f0d272d
[ "MIT" ]
9
2015-02-03T01:57:49.000Z
2019-05-09T22:44:29.000Z
#include "LinearAlgebra.h" using namespace rmsmesh; // Matrix Types // You cannot change these types to an enum. They are used in bit operations. #define MT_NONE 0 #define MT_ROTATION 1 #define MT_TRANSLATION 1<<1 #define MT_SCALE 1<<2 #define MT_UNKNOWN 1<<10 /* * things to do * - identity type * - optimize routines based on matrix type (??) * * */ Matrix::Matrix() : m_type(MT_NONE) { identity(); } Matrix::Matrix(Matrix const & m2) { memcpy(m_elem, m2.m_elem, sizeof(float)*12); m_type = m2.m_type; } Matrix & Matrix::operator=(Matrix const & m2) { memcpy(m_elem, m2.m_elem, sizeof(float)*12); m_type = m2.m_type; return *this; } Matrix::~Matrix() { } void Matrix::identity() { memset(m_elem, 0, sizeof(float)*12); m_elem[0][0] = 1.0; m_elem[1][1] = 1.0; m_elem[2][2] = 1.0; } void Matrix::transpose() { float t; t = m_elem[0][1]; m_elem[0][1] = m_elem[1][0]; m_elem[1][0] = t; t = m_elem[0][2]; m_elem[0][2] = m_elem[2][0]; m_elem[2][0] = t; t = m_elem[1][2]; m_elem[1][2] = m_elem[2][1]; m_elem[2][1] = t; m_elem[0][3] = m_elem[1][3] = m_elem[2][3] = 0.0; } void Matrix::toScale(float sx, float sy, float sz) { m_elem[0][0] = sx; m_elem[1][1] = sy; m_elem[2][2] = sz; m_type |= MT_SCALE; } void Matrix::toTranslate(float tx, float ty, float tz) { m_elem[0][3] = tx; m_elem[1][3] = ty; m_elem[2][3] = tz; m_type |= MT_TRANSLATION; } void Matrix::toRotateX(float theta) { m_elem[1][1] = (float)cos(theta); m_elem[1][2] = -(float)sin(theta); m_elem[2][1] = -m_elem[1][2]; m_elem[2][2] = m_elem[1][1]; m_type |= MT_ROTATION; } void Matrix:: toRotate(float theta, float x, float y, float z) { float c = (float)cos(theta); float s = (float)sin(theta); float t = 1-c; m_elem[0][0] = t*x*x + c; m_elem[0][1] = t*x*y + s*z; m_elem[0][2] = t*x*z - s*y; m_elem[0][3] = 0.0; m_elem[1][0] = t*x*y - s*z; m_elem[1][1] = t*y*y + c; m_elem[1][2] = t*y*z + s*x; m_elem[1][3] = 0.0; m_elem[2][0] = t*x*z + s*y; m_elem[2][1] = t*y*z - s*x; m_elem[2][2] = t*z*z + c; m_elem[2][3] = 0.0; } void Matrix::toRotateY(float theta) { m_elem[0][0] = (float)cos(theta); m_elem[0][2] = (float)sin(theta); m_elem[2][0] = -m_elem[0][2]; m_elem[2][2] = m_elem[0][0]; m_type |= MT_ROTATION; } void Matrix::toRotateZ(float theta) { m_elem[0][0] = (float)cos(theta); m_elem[0][1] = -(float)sin(theta); m_elem[1][0] = -m_elem[0][1]; m_elem[1][1] = m_elem[0][0]; m_type |= MT_ROTATION; } int Matrix::invert() { switch(m_type){ case MT_NONE: break; case MT_SCALE: m_elem[0][0] = 1.0f / m_elem[0][0]; m_elem[1][1] = 1.0f / m_elem[1][1]; m_elem[2][2] = 1.0f / m_elem[2][2]; break; case MT_TRANSLATION: m_elem[0][3] = -m_elem[0][3]; m_elem[1][3] = -m_elem[1][3]; m_elem[2][3] = -m_elem[2][3]; break; case MT_ROTATION: transpose(); break; case MT_UNKNOWN: default: return -1; } return 0; } void Matrix::multiply(const Matrix & m2) { float t[4]; for(int i = 0; i < 3; ++i){ memcpy(t, m_elem[i], sizeof(float)*4); m_elem[i][0] = t[0]*m2.m_elem[0][0] + t[1]*m2.m_elem[1][0] + t[2]*m2.m_elem[2][0]; m_elem[i][1] = t[0]*m2.m_elem[0][1] + t[1]*m2.m_elem[1][1] + t[2]*m2.m_elem[2][1]; m_elem[i][2] = t[0]*m2.m_elem[0][2] + t[1]*m2.m_elem[1][2] + t[2]*m2.m_elem[2][2]; m_elem[i][3] = t[0]*m2.m_elem[0][3] + t[1]*m2.m_elem[1][3] + t[2]*m2.m_elem[2][3] + t[3]; } } Vector & Matrix::multiply(const Vector & v, Vector & dest) const { dest.init( v.dot4(m_elem[0]), v.dot4(m_elem[1]), v.dot4(m_elem[2]) ); return dest; } rmsmesh::Point & Matrix::multiply(const rmsmesh::Point & v, rmsmesh::Point & dest) const { dest.init( v.dot4(m_elem[0]), v.dot4(m_elem[1]), v.dot4(m_elem[2]) ); return dest; } void Matrix::multiply(float * vec) { float t[4]; memcpy(t, vec, sizeof(float)*4); vec[0] = m_elem[0][0]*t[0] + m_elem[0][1]*t[1] + m_elem[0][2]*t[2] + m_elem[0][3]*t[3]; vec[1] = m_elem[1][0]*t[0] + m_elem[1][1]*t[1] + m_elem[1][2]*t[2] + m_elem[1][3]*t[3]; vec[2] = m_elem[2][0]*t[0] + m_elem[2][1]*t[1] + m_elem[2][2]*t[2] + m_elem[2][3]*t[3]; } string Matrix::toString() const { char buf[256]; sprintf(buf, "[ %5.5f %5.5f %5.5f %5.5f]\n[ %5.5f %5.5f %5.5f %5.5f]\n[ %5.5f %5.5f %5.5f %5.5f]\n", m_elem[0][0], m_elem[0][1], m_elem[0][2], m_elem[0][3], m_elem[1][0], m_elem[1][1], m_elem[1][2], m_elem[1][3], m_elem[2][0], m_elem[2][1], m_elem[2][2], m_elem[2][3] ); return string(buf); } Transformation::Transformation() : ml_current_transform(), ml_current_inverse() { } Transformation::~Transformation() { } bool Transformation::addMatrix(const Matrix & m) { Matrix minverse(m); if(minverse.invert()) return false; ml_current_transform.multiply(m); minverse.multiply(ml_current_inverse); ml_current_inverse = minverse; return true; } bool Transformation::addMatrixPremultiply(const Matrix & m) { Matrix minverse(m); Matrix mnotinverse(m); if(minverse.invert()) return false; mnotinverse.multiply(ml_current_transform); ml_current_transform = mnotinverse; ml_current_inverse.multiply(minverse); return true; }
18.962069
106
0.557374
[ "vector" ]
0f2b1ac60f91ab5abdfee876b7d4db9832624a48
1,126
hpp
C++
lib/include/protodoc/generator.hpp
mathisloge/protocol-doc-generation
b9ec5652b83780156027cc275cc3b73ec3d75737
[ "MIT" ]
4
2021-08-18T12:20:51.000Z
2021-08-21T06:20:24.000Z
lib/include/protodoc/generator.hpp
mathisloge/protocol-doc-generation
b9ec5652b83780156027cc275cc3b73ec3d75737
[ "MIT" ]
1
2021-08-18T12:39:53.000Z
2021-08-22T20:21:11.000Z
lib/include/protodoc/generator.hpp
mathisloge/protocol-doc-generation
b9ec5652b83780156027cc275cc3b73ec3d75737
[ "MIT" ]
1
2021-10-07T00:34:17.000Z
2021-10-07T00:34:17.000Z
#pragma once #include <filesystem> #include <memory> #include <vector> #include <commsdsl/Protocol.h> #include <nlohmann/json.hpp> #include "protodoc_export.hpp" namespace protodoc { using FilesList = std::vector<std::filesystem::path>; struct GeneratorOpts { std::filesystem::path root; bool trim; bool split; bool json_output; std::filesystem::path custom_json; std::filesystem::path lang_json; std::filesystem::path output_dir; FilesList files; struct { std::filesystem::path t_root_dir; std::filesystem::path t_platforms; std::filesystem::path t_namespaces; std::filesystem::path t_namespace; } templates; }; class PROTODOC_EXPORT Generator final { public: Generator(); ~Generator(); bool generate(const GeneratorOpts &opts); private: bool parseSchemaFiles(const FilesList &files); bool write(const GeneratorOpts &opts); bool writePlatforms(nlohmann::ordered_json &json); bool writeNamespaces(nlohmann::ordered_json &json); private: class Impl; std::unique_ptr<Impl> impl_; }; } // namespace protodoc
23.458333
55
0.69627
[ "vector" ]
0f321c87484e4500bca84ec2ca50ec056f801e5b
10,490
hpp
C++
include/vierkant/Input.hpp
crocdialer/vierkan
57095a91db33cee3086b9f820520f693dd144915
[ "MIT" ]
1
2021-03-30T20:32:21.000Z
2021-03-30T20:32:21.000Z
include/vierkant/Input.hpp
crocdialer/vierkan
57095a91db33cee3086b9f820520f693dd144915
[ "MIT" ]
null
null
null
include/vierkant/Input.hpp
crocdialer/vierkan
57095a91db33cee3086b9f820520f693dd144915
[ "MIT" ]
null
null
null
#pragma once #include <unordered_map> #include <GLFW/glfw3.h> #define GLM_FORCE_CXX11 #define GLM_FORCE_SWIZZLE #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/matrix_inverse.hpp" #define GLM_ENABLE_EXPERIMENTAL #include "glm/gtx/norm.hpp" #include <glm/gtx/hash.hpp> #include "crocore/crocore.hpp" namespace vierkant { class MouseEvent; class KeyEvent; class JoystickState; struct Touch; std::vector<JoystickState> get_joystick_states(); /** * @brief MouseDelegate is a struct to group mouse-callbacks */ struct mouse_delegate_t { using enabled_cb_t = std::function<bool()>; using mouse_cb_t = std::function<void(const MouseEvent &)>; using file_drop_cb_t = std::function<void(const MouseEvent &, const std::vector<std::string> &)>; enabled_cb_t enabled; mouse_cb_t mouse_press; mouse_cb_t mouse_release; mouse_cb_t mouse_move; mouse_cb_t mouse_drag; mouse_cb_t mouse_wheel; file_drop_cb_t file_drop; }; /** * @brief TouchDelegate is a struct to group touch-callbacks */ struct touch_delegate_t { using touch_cb_t = std::function<void(const MouseEvent &, const std::set<const Touch *> &)>; touch_cb_t touch_begin; touch_cb_t touch_end; touch_cb_t touch_move; }; /** * @brief KeyDelegate is a struct to group keyboard-callbacks */ struct key_delegate_t { using enabled_cb_t = std::function<bool()>; using key_cb_t = std::function<void(const KeyEvent &)>; using char_cb_t = std::function<void(uint32_t)>; enabled_cb_t enabled; key_cb_t key_press; key_cb_t key_release; char_cb_t character_input; }; //! Base class for all Events class Event { protected: Event() {} public: virtual ~Event() {} }; //! Represents a mouse event class MouseEvent : public Event { public: MouseEvent() : Event() {} MouseEvent(int initiator, int x, int y, unsigned int modifiers, glm::ivec2 wheel_inc, int touch_idx = 0, int touch_id = 0) : Event(), m_initiator(initiator), m_x(x), m_y(y), m_modifiers(modifiers), m_wheel_inc(wheel_inc), m_touch_index(touch_idx), m_touch_id(touch_id) {} //! Returns the X coordinate of the mouse event int get_x() const { return m_x; } //! Returns the Y coordinate of the mouse event int get_y() const { return m_y; } //! Returns the coordinates of the mouse event glm::ivec2 position() const { return glm::ivec2(m_x, m_y); } //! Returns the number of detents the user has wheeled through. Positive values correspond to wheel-up and negative to wheel-down. glm::ivec2 wheel_increment() const { return m_wheel_inc; } //! Returns whether the initiator for the event was the left mouse button bool is_left() const { return m_initiator & BUTTON_LEFT; } //! Returns whether the initiator for the event was the right mouse button bool is_right() const { return m_initiator & BUTTON_RIGHT; } //! Returns whether the initiator for the event was the middle mouse button bool is_middle() const { return m_initiator & BUTTON_MIDDLE; } //! Returns whether the left mouse button was pressed during the event bool is_left_down() const { return m_modifiers & BUTTON_LEFT; } //! Returns whether the right mouse button was pressed during the event bool is_right_down() const { return m_modifiers & BUTTON_RIGHT; } //! Returns whether the middle mouse button was pressed during the event bool is_middle_down() const { return m_modifiers & BUTTON_MIDDLE; } //! Returns whether the Shift key was pressed during the event. bool is_shift_down() const { return m_modifiers & SHIFT_DOWN; } //! Returns whether the Alt (or Option) key was pressed during the event. bool is_alt_down() const { return m_modifiers & ALT_DOWN; } //! Returns whether the Control key was pressed during the event. bool is_control_down() const { return m_modifiers & CTRL_DOWN; } //! Returns whether the meta key was pressed during the event. Maps to the Windows key on Windows and the Command key on Mac OS X. bool is_meta_down() const { return m_modifiers & META_DOWN; } //! true if this MouseEvent is generated by a touch-interface bool is_touch() const { return m_modifiers & TOUCH_DOWN; } //! the current touch id int touch_id() const { return m_touch_id; } //! the current touch id int touch_index() const { return m_touch_index; } enum { BUTTON_LEFT = (1 << 0), BUTTON_RIGHT = (1 << 1), BUTTON_MIDDLE = (1 << 2), SHIFT_DOWN = (1 << 3), ALT_DOWN = (1 << 4), CTRL_DOWN = (1 << 5), META_DOWN = (1 << 6), TOUCH_DOWN = (1 << 7) }; private: uint32_t m_initiator = 0; int m_x = 0, m_y = 0; unsigned int m_modifiers = 0; glm::ivec2 m_wheel_inc{0}; int m_touch_index = 0; int m_touch_id = 0; }; //! Represents a keyboard event class KeyEvent : public Event { public: KeyEvent(int code, uint32_t character, uint32_t modifiers) : Event(), m_code(code), m_char(character), m_modifiers(modifiers) {} //! Returns the key code associated with the event (maps into Key::Type enum) int code() const { return m_code; } //! Returns the Unicode character associated with the event. uint32_t character() const { return m_char; } //! Returns whether the Shift key was pressed during the event. bool is_shift_down() const { return m_modifiers & SHIFT_DOWN; } //! Returns whether the Alt (or Option) key was pressed during the event. bool is_alt_down() const { return m_modifiers & ALT_DOWN; } //! Returns whether the Control key was pressed during the event. bool is_control_down() const { return m_modifiers & CTRL_DOWN; } //! Returns whether the meta key was pressed during the event. Maps to the Windows key on Windows and the Command key on Mac OS X. bool is_meta_down() const { return m_modifiers & META_DOWN; } enum { SHIFT_DOWN = (1 << 3), ALT_DOWN = (1 << 4), CTRL_DOWN = (1 << 5), META_DOWN = (1 << 6) }; private: int m_code = 0; uint32_t m_char = 0; uint32_t m_modifiers = 0; }; class JoystickState { public: enum class Mapping : uint32_t { ANALOG_LEFT_H, ANALOG_LEFT_V, ANALOG_RIGHT_H, ANALOG_RIGHT_V, DPAD_H, DPAD_V, TRIGGER_LEFT, TRIGGER_RIGHT, BUTTON_A, BUTTON_B, BUTTON_X, BUTTON_Y, BUTTON_MENU, BUTTON_BACK, BUTTON_BUMPER_LEFT, BUTTON_BUMPER_RIGHT, BUTTON_STICK_LEFT, BUTTON_STICK_RIGHT }; struct MapHash { inline size_t operator()(const Mapping &the_enum) const { std::hash<uint32_t> hasher; return hasher(static_cast<uint32_t>(the_enum)); } }; using ButtonMap = std::unordered_map<Mapping, uint32_t, MapHash>; JoystickState(std::string n, std::vector<uint8_t> b, std::vector<float> a); const std::string &name() const; const std::vector<uint8_t> &buttons() const; const std::vector<float> &axis() const; glm::vec2 analog_left() const; glm::vec2 analog_right() const; glm::vec2 trigger() const; glm::vec2 dpad() const; static ButtonMap &mapping() { return s_button_map; } private: float m_dead_zone = 0.03f; std::string m_name; std::vector<uint8_t> m_buttons; std::vector<float> m_axis; static ButtonMap s_button_map; }; struct Touch { int32_t m_id = -1; uint32_t m_slot_index = 0; glm::vec2 m_position; }; struct Key { enum Type { _UNKNOWN = -1, _SPACE = 32, _APOSTROPHE = 39, /* ' */ _COMMA = 44, /* , */ _MINUS = 45, /* - */ _PERIOD = 46, /* . */ _SLASH = 47, /* / */ _0 = 48, _1 = 49, _2 = 50, _3 = 51, _4 = 52, _5 = 53, _6 = 54, _7 = 55, _8 = 56, _9 = 57, _SEMICOLON = 59, /* ; */ _EQUAL = 61, /* = */ _A = 65, _B = 66, _C = 67, _D = 68, _E = 69, _F = 70, _G = 71, _H = 72, _I = 73, _J = 74, _K = 75, _L = 76, _M = 77, _N = 78, _O = 79, _P = 80, _Q = 81, _R = 82, _S = 83, _T = 84, _U = 85, _V = 86, _W = 87, _X = 88, _Y = 89, _Z = 90, _LEFT_BRACKET = 91, /* [ */ _BACKSLASH = 92, /* \ */ _RIGHT_BRACKET = 93, /* ] */ _GRAVE_ACCENT = 96, /* ` */ _WORLD_1 = 161, /* non-US #1 */ _WORLD_2 = 162, /* non-US #2 */ _ESCAPE = 256, _ENTER = 257, _TAB = 258, _BACKSPACE = 259, _INSERT = 260, _DELETE = 261, _RIGHT = 262, _LEFT = 263, _DOWN = 264, _UP = 265, _PAGE_UP = 266, _PAGE_DOWN = 267, _HOME = 268, _END = 269, _CAPS_LOCK = 280, _SCROLL_LOCK = 281, _NUM_LOCK = 282, _PRINT_SCREEN = 283, _PAUSE = 284, _F1 = 290, _F2 = 291, _F3 = 292, _F4 = 293, _F5 = 294, _F6 = 295, _F7 = 296, _F8 = 297, _F9 = 298, _F10 = 299, _F11 = 300, _F12 = 301, _F13 = 302, _F14 = 303, _F15 = 304, _F16 = 305, _F17 = 306, _F18 = 307, _F19 = 308, _F20 = 309, _F21 = 310, _F22 = 311, _F23 = 312, _F24 = 313, _F25 = 314, _KP_0 = 320, _KP_1 = 321, _KP_2 = 322, _KP_3 = 323, _KP_4 = 324, _KP_5 = 325, _KP_6 = 326, _KP_7 = 327, _KP_8 = 328, _KP_9 = 329, _KP_DECIMAL = 330, _KP_DIVIDE = 331, _KP_MULTIPLY = 332, _KP_SUBTRACT = 333, _KP_ADD = 334, _KP_ENTER = 335, _KP_EQUAL = 336, _LEFT_SHIFT = 340, _LEFT_CONTROL = 341, _LEFT_ALT = 342, _LEFT_SUPER = 343, _RIGHT_SHIFT = 344, _RIGHT_CONTROL = 345, _RIGHT_ALT = 346, _RIGHT_SUPER = 347, _MENU = 348, _LAST = _MENU }; }; }
25.837438
134
0.587321
[ "vector" ]
0f36482341c1f9ef1b43143eb0b9b6a5bd5a9f9f
78
cpp
C++
UL/CppApp/System/Attribute.cpp
xiongfang/UL
a2c7af50da0e30a34e4656b395557896781b66b1
[ "MIT" ]
23
2018-07-17T16:30:15.000Z
2022-01-03T14:02:45.000Z
UL/CppApp/System/Attribute.cpp
Halfholl/UL
76bc687a1b12ee9b69977d7e20ad007d772b2869
[ "MIT" ]
null
null
null
UL/CppApp/System/Attribute.cpp
Halfholl/UL
76bc687a1b12ee9b69977d7e20ad007d772b2869
[ "MIT" ]
9
2019-02-06T13:24:35.000Z
2022-01-03T14:02:45.000Z
#include "stdafx.h" #include "System\Attribute.h" #include "System\Object.h"
19.5
29
0.730769
[ "object" ]
0f390482e29bfc8fb65dfe8117e670635743ba8c
4,821
cpp
C++
src/PBRViewerMouseCallbacks.cpp
DanielSchmitt93/PBRViewer
bcd00288420a4406945411180a2d79477b47dd97
[ "MIT" ]
null
null
null
src/PBRViewerMouseCallbacks.cpp
DanielSchmitt93/PBRViewer
bcd00288420a4406945411180a2d79477b47dd97
[ "MIT" ]
null
null
null
src/PBRViewerMouseCallbacks.cpp
DanielSchmitt93/PBRViewer
bcd00288420a4406945411180a2d79477b47dd97
[ "MIT" ]
1
2020-11-23T08:29:22.000Z
2020-11-23T08:29:22.000Z
#include "PBRViewerMouseCallbacks.h" #include "glm/gtx/euler_angles.hpp" #include "PBRViewerInputConstants.h" // Needs to be static so we can set the GLFW callback accordingly. static std::shared_ptr<PBRViewerOverlay> myOverlay; static std::shared_ptr<PBRViewerModel> myModel; /// <summary> /// Register the callbacks. /// </summary> /// <param name="currentWindow">The current window.</param> /// <param name="overlay">The overlay.</param> /// <param name="model">The model.</param> GLvoid PBRViewerMouseCallbacks::RegisterCallbacks( GLFWwindow* currentWindow, std::shared_ptr<PBRViewerOverlay> const& overlay, std::shared_ptr<PBRViewerModel> const& model ) { myOverlay = overlay; myModel = model; glfwSetCursorPosCallback(currentWindow, []( GLFWwindow* window, const GLdouble cursorPosX, const GLdouble cursorPosY ) { if(glfwGetInputMode(window,GLFW_CURSOR) != GLFW_CURSOR_DISABLED) { // Do not interact with the UI if the cursor is disabled. // UI elements could get focus - this should be prevented. myOverlay->cursorPosCallbackEvent(cursorPosX, cursorPosY); } static GLdouble myLastCursorPosX = 0.0; static GLdouble myLastCursorPosY = 0.0; // Camera movement if (GLFW_PRESS == glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1)) { if (myModel->GetMouseProcessing()) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); const GLdouble xoffset = cursorPosX - myLastCursorPosX; const GLdouble yoffset = myLastCursorPosY - cursorPosY; // reversed since y-coordinates go from bottom to top myModel->GetCamera().lock()->ProcessLeftMouseButton(xoffset, yoffset); } } else if (GLFW_PRESS == glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_2)) { if (myModel->GetMouseProcessing()) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); const GLdouble xoffset = cursorPosX - myLastCursorPosX; const GLdouble yoffset = myLastCursorPosY - cursorPosY; // reversed since y-coordinates go from bottom to top myModel->GetCamera().lock()->ProcessRightMouseButton(xoffset, yoffset); } } // Model rotation else if (GLFW_PRESS == glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_3)) { if (myModel->GetMouseProcessing()) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); const GLdouble diffX = (cursorPosX - myLastCursorPosX) * PBRViewerInputConstants::MouseSensitivity; const GLdouble diffY = (myLastCursorPosY - cursorPosY) * PBRViewerInputConstants::MouseSensitivity; if (diffX == 0.0 && diffY == 0.0) { return; } // Use the global y-axis for the x-offset and the local y-axis to calculate the rotation axis for the y-offset. // See: https://gamedev.stackexchange.com/questions/136174/im-rotating-an-object-on-two-axes-so-why-does-it-keep-twisting-around-the-thir glm::mat4 rotationMatrix = glm::identity<glm::mat4>(); rotationMatrix = rotate(rotationMatrix, glm::radians(static_cast<GLfloat>(diffX)), glm::vec3(0.0f, 1.0f, 0.0f)); const glm::vec3 viewVector = myModel->GetCamera().lock()->GetFrontVector(); const glm::vec3 upVector = myModel->GetCamera().lock()->GetUpVector(); const glm::vec3 rotationAxis = normalize(cross(upVector, viewVector)); // Care if cross product is zero if (rotationAxis == glm::vec3(0.0f)) { rotationMatrix = rotate(rotationMatrix, glm::radians(static_cast<GLfloat>(diffY)), upVector); } else { rotationMatrix = rotate(rotationMatrix, glm::radians(static_cast<GLfloat>(diffY)), rotationAxis); } myModel->RotateModel(rotationMatrix); } } myLastCursorPosX = cursorPosX; myLastCursorPosY = cursorPosY; }); glfwSetMouseButtonCallback(currentWindow, []( GLFWwindow* window, const GLint button, const GLint action, const GLint modifiers ) { if (button == GLFW_MOUSE_BUTTON_1 || button == GLFW_MOUSE_BUTTON_2) { // Check if the user clicked on any of the UI elements if (myOverlay->mouseButtonCallbackEvent(button, action, modifiers)) { // If the user did so, disable the camera movement if (action == GLFW_PRESS) { myModel->SetMouseProcessing(GL_FALSE); return; } } if (action == GLFW_RELEASE) { // Restore cursor from camera movement if (GLFW_CURSOR_DISABLED == glfwGetInputMode(window, GLFW_CURSOR)) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } myModel->SetMouseProcessing(GL_TRUE); } } else if (button == GLFW_MOUSE_BUTTON_3) { // Restore cursor from model rotation if (action == GLFW_RELEASE && GLFW_CURSOR_DISABLED == glfwGetInputMode(window, GLFW_CURSOR)) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } } }); }
34.683453
142
0.703796
[ "object", "model" ]
0f3b7675f3a6506db299ba06ee782167a71d7911
22,796
cc
C++
chrome/browser/extensions/api/notifications/notifications_api.cc
tmpsantos/chromium
802d4aeeb33af25c01ee5994037bbf14086d4ac0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/api/notifications/notifications_api.cc
tmpsantos/chromium
802d4aeeb33af25c01ee5994037bbf14086d4ac0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/api/notifications/notifications_api.cc
tmpsantos/chromium
802d4aeeb33af25c01ee5994037bbf14086d4ac0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:23:37.000Z
2020-11-04T07:23:37.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/notifications/notifications_api.h" #include "base/callback.h" #include "base/guid.h" #include "base/rand_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/notifications/desktop_notification_service.h" #include "chrome/browser/notifications/desktop_notification_service_factory.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/notifications/notification_conversion_helper.h" #include "chrome/browser/notifications/notification_ui_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/extensions/api/notifications/notification_style.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/event_router.h" #include "extensions/common/extension.h" #include "extensions/common/features/feature.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/layout.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_rep.h" #include "ui/message_center/message_center_style.h" #include "ui/message_center/notifier_settings.h" #include "url/gurl.h" namespace extensions { namespace notifications = api::notifications; namespace { const char kMissingRequiredPropertiesForCreateNotification[] = "Some of the required properties are missing: type, iconUrl, title and " "message."; const char kUnableToDecodeIconError[] = "Unable to successfully use the provided image."; const char kUnexpectedProgressValueForNonProgressType[] = "The progress value should not be specified for non-progress notification"; const char kInvalidProgressValue[] = "The progress value should range from 0 to 100"; const char kExtraListItemsProvided[] = "List items provided for notification type != list"; const char kExtraImageProvided[] = "Image resource provided for notification type != image"; // Given an extension id and another id, returns an id that is unique // relative to other extensions. std::string CreateScopedIdentifier(const std::string& extension_id, const std::string& id) { return extension_id + "-" + id; } // Removes the unique internal identifier to send the ID as the // extension expects it. std::string StripScopeFromIdentifier(const std::string& extension_id, const std::string& id) { size_t index_of_separator = extension_id.length() + 1; DCHECK_LT(index_of_separator, id.length()); return id.substr(index_of_separator); } class NotificationsApiDelegate : public NotificationDelegate { public: NotificationsApiDelegate(ChromeAsyncExtensionFunction* api_function, Profile* profile, const std::string& extension_id, const std::string& id) : api_function_(api_function), profile_(profile), extension_id_(extension_id), id_(id), scoped_id_(CreateScopedIdentifier(extension_id, id)), process_id_(-1) { DCHECK(api_function_.get()); if (api_function_->render_view_host()) process_id_ = api_function->render_view_host()->GetProcess()->GetID(); } virtual void Display() OVERRIDE { } virtual void Error() OVERRIDE {} virtual void Close(bool by_user) OVERRIDE { EventRouter::UserGestureState gesture = by_user ? EventRouter::USER_GESTURE_ENABLED : EventRouter::USER_GESTURE_NOT_ENABLED; scoped_ptr<base::ListValue> args(CreateBaseEventArgs()); args->Append(new base::FundamentalValue(by_user)); SendEvent(notifications::OnClosed::kEventName, gesture, args.Pass()); } virtual void Click() OVERRIDE { scoped_ptr<base::ListValue> args(CreateBaseEventArgs()); SendEvent(notifications::OnClicked::kEventName, EventRouter::USER_GESTURE_ENABLED, args.Pass()); } virtual bool HasClickedListener() OVERRIDE { return EventRouter::Get(profile_)->HasEventListener( notifications::OnClicked::kEventName); } virtual void ButtonClick(int index) OVERRIDE { scoped_ptr<base::ListValue> args(CreateBaseEventArgs()); args->Append(new base::FundamentalValue(index)); SendEvent(notifications::OnButtonClicked::kEventName, EventRouter::USER_GESTURE_ENABLED, args.Pass()); } virtual std::string id() const OVERRIDE { return scoped_id_; } virtual int process_id() const OVERRIDE { return process_id_; } virtual content::WebContents* GetWebContents() const OVERRIDE { // We're holding a reference to api_function_, so we know it'll be valid // until ReleaseRVH is called, and api_function_ (as a // AsyncExtensionFunction) will zero out its copy of render_view_host // when the RVH goes away. if (!api_function_.get()) return NULL; content::RenderViewHost* rvh = api_function_->render_view_host(); if (!rvh) return NULL; return content::WebContents::FromRenderViewHost(rvh); } virtual void ReleaseRenderViewHost() OVERRIDE { api_function_ = NULL; } private: virtual ~NotificationsApiDelegate() {} void SendEvent(const std::string& name, EventRouter::UserGestureState user_gesture, scoped_ptr<base::ListValue> args) { scoped_ptr<Event> event(new Event(name, args.Pass())); event->user_gesture = user_gesture; EventRouter::Get(profile_)->DispatchEventToExtension(extension_id_, event.Pass()); } scoped_ptr<base::ListValue> CreateBaseEventArgs() { scoped_ptr<base::ListValue> args(new base::ListValue()); args->Append(new base::StringValue(id_)); return args.Pass(); } scoped_refptr<ChromeAsyncExtensionFunction> api_function_; Profile* profile_; const std::string extension_id_; const std::string id_; const std::string scoped_id_; int process_id_; DISALLOW_COPY_AND_ASSIGN(NotificationsApiDelegate); }; } // namespace bool NotificationsApiFunction::IsNotificationsApiAvailable() { // We need to check this explicitly rather than letting // _permission_features.json enforce it, because we're sharing the // chrome.notifications permissions namespace with WebKit notifications. return extension()->is_platform_app() || extension()->is_extension(); } NotificationsApiFunction::NotificationsApiFunction() { } NotificationsApiFunction::~NotificationsApiFunction() { } bool NotificationsApiFunction::CreateNotification( const std::string& id, api::notifications::NotificationOptions* options) { // First, make sure the required fields exist: type, title, message, icon. // These fields are defined as optional in IDL such that they can be used as // optional for notification updates. But for notification creations, they // should be present. if (options->type == api::notifications::TEMPLATE_TYPE_NONE || !options->icon_url || !options->title || !options->message) { SetError(kMissingRequiredPropertiesForCreateNotification); return false; } NotificationBitmapSizes bitmap_sizes = GetNotificationBitmapSizes(); float image_scale = ui::GetScaleForScaleFactor(ui::GetSupportedScaleFactors().back()); // Extract required fields: type, title, message, and icon. message_center::NotificationType type = MapApiTemplateTypeToType(options->type); const base::string16 title(base::UTF8ToUTF16(*options->title)); const base::string16 message(base::UTF8ToUTF16(*options->message)); gfx::Image icon; if (!NotificationConversionHelper::NotificationBitmapToGfxImage( image_scale, bitmap_sizes.icon_size, options->icon_bitmap.get(), &icon)) { SetError(kUnableToDecodeIconError); return false; } // Then, handle any optional data that's been provided. message_center::RichNotificationData optional_fields; if (options->app_icon_mask_url.get()) { if (!NotificationConversionHelper::NotificationBitmapToGfxImage( image_scale, bitmap_sizes.app_icon_mask_size, options->app_icon_mask_bitmap.get(), &optional_fields.small_image)) { SetError(kUnableToDecodeIconError); return false; } } if (options->priority.get()) optional_fields.priority = *options->priority; if (options->event_time.get()) optional_fields.timestamp = base::Time::FromJsTime(*options->event_time); if (options->buttons.get()) { // Currently we allow up to 2 buttons. size_t number_of_buttons = options->buttons->size(); number_of_buttons = number_of_buttons > 2 ? 2 : number_of_buttons; for (size_t i = 0; i < number_of_buttons; i++) { message_center::ButtonInfo info( base::UTF8ToUTF16((*options->buttons)[i]->title)); NotificationConversionHelper::NotificationBitmapToGfxImage( image_scale, bitmap_sizes.button_icon_size, (*options->buttons)[i]->icon_bitmap.get(), &info.icon); optional_fields.buttons.push_back(info); } } if (options->context_message) { optional_fields.context_message = base::UTF8ToUTF16(*options->context_message); } bool has_image = NotificationConversionHelper::NotificationBitmapToGfxImage( image_scale, bitmap_sizes.image_size, options->image_bitmap.get(), &optional_fields.image); // We should have an image if and only if the type is an image type. if (has_image != (type == message_center::NOTIFICATION_TYPE_IMAGE)) { SetError(kExtraImageProvided); return false; } // We should have list items if and only if the type is a multiple type. bool has_list_items = options->items.get() && options->items->size() > 0; if (has_list_items != (type == message_center::NOTIFICATION_TYPE_MULTIPLE)) { SetError(kExtraListItemsProvided); return false; } if (options->progress.get() != NULL) { // We should have progress if and only if the type is a progress type. if (type != message_center::NOTIFICATION_TYPE_PROGRESS) { SetError(kUnexpectedProgressValueForNonProgressType); return false; } optional_fields.progress = *options->progress; // Progress value should range from 0 to 100. if (optional_fields.progress < 0 || optional_fields.progress > 100) { SetError(kInvalidProgressValue); return false; } } if (has_list_items) { using api::notifications::NotificationItem; std::vector<linked_ptr<NotificationItem> >::iterator i; for (i = options->items->begin(); i != options->items->end(); ++i) { message_center::NotificationItem item( base::UTF8ToUTF16(i->get()->title), base::UTF8ToUTF16(i->get()->message)); optional_fields.items.push_back(item); } } if (options->is_clickable.get()) optional_fields.clickable = *options->is_clickable; NotificationsApiDelegate* api_delegate(new NotificationsApiDelegate( this, GetProfile(), extension_->id(), id)); // ownership is passed to // Notification Notification notification(type, extension_->url(), title, message, icon, blink::WebTextDirectionDefault, message_center::NotifierId( message_center::NotifierId::APPLICATION, extension_->id()), base::UTF8ToUTF16(extension_->name()), base::UTF8ToUTF16(api_delegate->id()), optional_fields, api_delegate); g_browser_process->notification_ui_manager()->Add(notification, GetProfile()); return true; } bool NotificationsApiFunction::UpdateNotification( const std::string& id, api::notifications::NotificationOptions* options, Notification* notification) { NotificationBitmapSizes bitmap_sizes = GetNotificationBitmapSizes(); float image_scale = ui::GetScaleForScaleFactor(ui::GetSupportedScaleFactors().back()); // Update optional fields if provided. if (options->type != api::notifications::TEMPLATE_TYPE_NONE) notification->set_type(MapApiTemplateTypeToType(options->type)); if (options->title) notification->set_title(base::UTF8ToUTF16(*options->title)); if (options->message) notification->set_message(base::UTF8ToUTF16(*options->message)); // TODO(dewittj): Return error if this fails. if (options->icon_bitmap) { gfx::Image icon; NotificationConversionHelper::NotificationBitmapToGfxImage( image_scale, bitmap_sizes.icon_size, options->icon_bitmap.get(), &icon); notification->set_icon(icon); } gfx::Image app_icon_mask; if (NotificationConversionHelper::NotificationBitmapToGfxImage( image_scale, bitmap_sizes.app_icon_mask_size, options->app_icon_mask_bitmap.get(), &app_icon_mask)) { notification->set_small_image(app_icon_mask); } if (options->priority) notification->set_priority(*options->priority); if (options->event_time) notification->set_timestamp(base::Time::FromJsTime(*options->event_time)); if (options->buttons) { // Currently we allow up to 2 buttons. size_t number_of_buttons = options->buttons->size(); number_of_buttons = number_of_buttons > 2 ? 2 : number_of_buttons; std::vector<message_center::ButtonInfo> buttons; for (size_t i = 0; i < number_of_buttons; i++) { message_center::ButtonInfo button( base::UTF8ToUTF16((*options->buttons)[i]->title)); NotificationConversionHelper::NotificationBitmapToGfxImage( image_scale, bitmap_sizes.button_icon_size, (*options->buttons)[i]->icon_bitmap.get(), &button.icon); buttons.push_back(button); } notification->set_buttons(buttons); } if (options->context_message) { notification->set_context_message( base::UTF8ToUTF16(*options->context_message)); } gfx::Image image; bool has_image = NotificationConversionHelper::NotificationBitmapToGfxImage( image_scale, bitmap_sizes.image_size, options->image_bitmap.get(), &image); if (has_image) { // We should have an image if and only if the type is an image type. if (notification->type() != message_center::NOTIFICATION_TYPE_IMAGE) { SetError(kExtraImageProvided); return false; } notification->set_image(image); } if (options->progress) { // We should have progress if and only if the type is a progress type. if (notification->type() != message_center::NOTIFICATION_TYPE_PROGRESS) { SetError(kUnexpectedProgressValueForNonProgressType); return false; } int progress = *options->progress; // Progress value should range from 0 to 100. if (progress < 0 || progress > 100) { SetError(kInvalidProgressValue); return false; } notification->set_progress(progress); } if (options->items.get() && options->items->size() > 0) { // We should have list items if and only if the type is a multiple type. if (notification->type() != message_center::NOTIFICATION_TYPE_MULTIPLE) { SetError(kExtraListItemsProvided); return false; } std::vector<message_center::NotificationItem> items; using api::notifications::NotificationItem; std::vector<linked_ptr<NotificationItem> >::iterator i; for (i = options->items->begin(); i != options->items->end(); ++i) { message_center::NotificationItem item( base::UTF8ToUTF16(i->get()->title), base::UTF8ToUTF16(i->get()->message)); items.push_back(item); } notification->set_items(items); } // Then override if it's already set. if (options->is_clickable.get()) notification->set_clickable(*options->is_clickable); g_browser_process->notification_ui_manager()->Update(*notification, GetProfile()); return true; } bool NotificationsApiFunction::AreExtensionNotificationsAllowed() const { DesktopNotificationService* service = DesktopNotificationServiceFactory::GetForProfile(GetProfile()); return service->IsNotifierEnabled(message_center::NotifierId( message_center::NotifierId::APPLICATION, extension_->id())); } bool NotificationsApiFunction::IsNotificationsApiEnabled() const { return CanRunWhileDisabled() || AreExtensionNotificationsAllowed(); } bool NotificationsApiFunction::CanRunWhileDisabled() const { return false; } bool NotificationsApiFunction::RunAsync() { if (IsNotificationsApiAvailable() && IsNotificationsApiEnabled()) { return RunNotificationsApi(); } else { SendResponse(false); return true; } } message_center::NotificationType NotificationsApiFunction::MapApiTemplateTypeToType( api::notifications::TemplateType type) { switch (type) { case api::notifications::TEMPLATE_TYPE_NONE: case api::notifications::TEMPLATE_TYPE_BASIC: return message_center::NOTIFICATION_TYPE_BASE_FORMAT; case api::notifications::TEMPLATE_TYPE_IMAGE: return message_center::NOTIFICATION_TYPE_IMAGE; case api::notifications::TEMPLATE_TYPE_LIST: return message_center::NOTIFICATION_TYPE_MULTIPLE; case api::notifications::TEMPLATE_TYPE_PROGRESS: return message_center::NOTIFICATION_TYPE_PROGRESS; default: // Gracefully handle newer application code that is running on an older // runtime that doesn't recognize the requested template. return message_center::NOTIFICATION_TYPE_BASE_FORMAT; } } NotificationsCreateFunction::NotificationsCreateFunction() { } NotificationsCreateFunction::~NotificationsCreateFunction() { } bool NotificationsCreateFunction::RunNotificationsApi() { params_ = api::notifications::Create::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params_.get()); const std::string extension_id(extension_->id()); std::string notification_id; if (!params_->notification_id.empty()) { // If the caller provided a notificationId, use that. notification_id = params_->notification_id; } else { // Otherwise, use a randomly created GUID. In case that GenerateGUID returns // the empty string, simply generate a random string. notification_id = base::GenerateGUID(); if (notification_id.empty()) notification_id = base::RandBytesAsString(16); } SetResult(new base::StringValue(notification_id)); // TODO(dewittj): Add more human-readable error strings if this fails. if (!CreateNotification(notification_id, &params_->options)) return false; SendResponse(true); return true; } NotificationsUpdateFunction::NotificationsUpdateFunction() { } NotificationsUpdateFunction::~NotificationsUpdateFunction() { } bool NotificationsUpdateFunction::RunNotificationsApi() { params_ = api::notifications::Update::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params_.get()); // We are in update. If the ID doesn't exist, succeed but call the callback // with "false". const Notification* matched_notification = g_browser_process->notification_ui_manager()->FindById( CreateScopedIdentifier(extension_->id(), params_->notification_id)); if (!matched_notification) { SetResult(new base::FundamentalValue(false)); SendResponse(true); return true; } // Copy the existing notification to get a writable version of it. Notification notification = *matched_notification; // If we have trouble updating the notification (could be improper use of API // or some other reason), mark the function as failed, calling the callback // with false. // TODO(dewittj): Add more human-readable error strings if this fails. bool could_update_notification = UpdateNotification( params_->notification_id, &params_->options, &notification); SetResult(new base::FundamentalValue(could_update_notification)); if (!could_update_notification) return false; // No trouble, created the notification, send true to the callback and // succeed. SendResponse(true); return true; } NotificationsClearFunction::NotificationsClearFunction() { } NotificationsClearFunction::~NotificationsClearFunction() { } bool NotificationsClearFunction::RunNotificationsApi() { params_ = api::notifications::Clear::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params_.get()); bool cancel_result = g_browser_process->notification_ui_manager()->CancelById( CreateScopedIdentifier(extension_->id(), params_->notification_id)); SetResult(new base::FundamentalValue(cancel_result)); SendResponse(true); return true; } NotificationsGetAllFunction::NotificationsGetAllFunction() {} NotificationsGetAllFunction::~NotificationsGetAllFunction() {} bool NotificationsGetAllFunction::RunNotificationsApi() { NotificationUIManager* notification_ui_manager = g_browser_process->notification_ui_manager(); std::set<std::string> notification_ids = notification_ui_manager->GetAllIdsByProfileAndSourceOrigin( GetProfile(), extension_->url()); scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue()); for (std::set<std::string>::iterator iter = notification_ids.begin(); iter != notification_ids.end(); iter++) { result->SetBooleanWithoutPathExpansion( StripScopeFromIdentifier(extension_->id(), *iter), true); } SetResult(result.release()); SendResponse(true); return true; } NotificationsGetPermissionLevelFunction:: NotificationsGetPermissionLevelFunction() {} NotificationsGetPermissionLevelFunction:: ~NotificationsGetPermissionLevelFunction() {} bool NotificationsGetPermissionLevelFunction::CanRunWhileDisabled() const { return true; } bool NotificationsGetPermissionLevelFunction::RunNotificationsApi() { api::notifications::PermissionLevel result = AreExtensionNotificationsAllowed() ? api::notifications::PERMISSION_LEVEL_GRANTED : api::notifications::PERMISSION_LEVEL_DENIED; SetResult(new base::StringValue(api::notifications::ToString(result))); SendResponse(true); return true; } } // namespace extensions
35.61875
80
0.709379
[ "vector" ]
0f3e4b87a8a658ba89f5c362dd44b623d76b7132
777
cpp
C++
CS2370/Code/unwind.cpp
Davidjbennett/DavidBennett.github.io
09a2652b7ace8741bf23c6432abd58ee790b9f0c
[ "MIT" ]
3
2021-05-18T16:17:29.000Z
2022-01-20T15:46:59.000Z
CS2370/Code/unwind.cpp
Davidjbennett/DavidBennett
09a2652b7ace8741bf23c6432abd58ee790b9f0c
[ "MIT" ]
null
null
null
CS2370/Code/unwind.cpp
Davidjbennett/DavidBennett
09a2652b7ace8741bf23c6432abd58ee790b9f0c
[ "MIT" ]
null
null
null
// unwind.cpp: Illustrates stack unwinding #include <iostream> #include <stdexcept> using namespace std; class Foo { int* p; public: Foo(int x) { p = new int(x); // Allocate heap memory cout << *p << " allocated\n"; } ~Foo() { cout << *p << " deallocated\n"; delete p; } }; // Functions g and f each have a local Foo object, which has a destructor. void g() { Foo b(2); throw runtime_error("I give up!"); cout << "g\n"; // Won't print } void f() { Foo a(1); g(); } int main() { try { f(); cout << "This won't print\n"; } catch(runtime_error& exc) { cout << exc.what() << endl; } } /* Output: 1 allocated 2 allocated 2 deallocated 1 deallocated I give up! */
16.531915
74
0.532819
[ "object" ]
0f406793c71cd97b3db732ad2c0eee29d858fce2
2,846
cpp
C++
src/lr/lr_momentum.cpp
langqiu/LogisticRegressionwithAdamAdadeltaAdagradRmspropNagMomentum
ee0f0432a107aaf3ce05ae30c6ce99894723fc72
[ "Apache-2.0" ]
7
2018-09-03T12:27:49.000Z
2022-03-12T16:45:27.000Z
src/lr/lr_momentum.cpp
langqiu/LogisticRegressionwithAdamAdadeltaAdagradRmspropNagMomentum
ee0f0432a107aaf3ce05ae30c6ce99894723fc72
[ "Apache-2.0" ]
null
null
null
src/lr/lr_momentum.cpp
langqiu/LogisticRegressionwithAdamAdadeltaAdagradRmspropNagMomentum
ee0f0432a107aaf3ce05ae30c6ce99894723fc72
[ "Apache-2.0" ]
3
2018-06-12T12:05:45.000Z
2021-10-10T12:46:44.000Z
#include "lr_momentum.h" using namespace util; namespace model { LRMomentumModel::LRMomentumModel(DataSet* p_train_dataset, DataSet* p_test_dataset, const hash2index_type& f_hash2index, const index2hash_type& f_index2hash, const f_index_type& f_size, const std::string& model_type) : LRModel(p_train_dataset, p_test_dataset, f_hash2index, f_index2hash, f_size, model_type) {} void LRMomentumModel::_backward(const size_t& l, const size_t& r) { /* * attention! element-wise operation * g(t) = -1 * [g(logloss) + g(L2)] * v(t) = beta_1 * v(t-1) + alpha * g(t) * theta(t) = theta(t-1) + v(t) */ if (_curr_batch == 1) _print_step("backward"); auto& data = _p_train_dataset->get_data(); // get train dataset std::unordered_set<f_index_type> theta_updated; // record theta in BGD _theta_updated_vector.clear(); // clear before backward // calculate -1 * gradient param_type factor = -1 * _lambda / (r - l); // L2 gradient factor for (size_t i=l; i<r; i++) { auto& curr_sample = data[i]; // current sample for (size_t k=0; k<curr_sample._sparse_f_list.size(); k++) { // loop features auto& curr_f = curr_sample._sparse_f_list[k]; // current feature _gradient[curr_f.first] += (curr_sample._label - curr_sample._score) * curr_f.second / (r - l); // gradient from logloss // gradient from L2 if (r - l == 1) { // SGD _gradient[curr_f.first] += factor * _theta[curr_f.first]; _theta_updated_vector.push_back(curr_f.first); } else if (theta_updated.find(curr_f.first) == theta_updated.end()) { // BGD _gradient[curr_f.first] += factor * _theta[curr_f.first]; theta_updated.insert(curr_f.first); // record the index of feature that has showed up _theta_updated_vector.push_back(curr_f.first); } } _gradient[_f_size-1] += (curr_sample._label - curr_sample._score) / (r - l); // gradient from logloss for bias } _theta_updated_vector.push_back(_f_size-1); _gradient[_f_size-1] += factor * _theta[_f_size-1]; // gradient from L2 for bias // accumulate gradient of history separately in each direction for (auto& index : _theta_updated_vector) { _first_moment_vector[index] = _beta_1 * _first_moment_vector[index] + _alpha * _gradient[index]; } // calculate theta_new for (auto& index : _theta_updated_vector) { _theta_new[index] += _first_moment_vector[index]; } } void LRMomentumModel::_update() { if (_curr_batch == 1) _print_step("update"); _theta = _theta_new; for (size_t i=0; i<_f_size; i++) { // do not set zero to moment vector, because features don't show up continuously between batchs _gradient[i] = 0.0; } } } // namespace model
42.477612
101
0.651089
[ "vector", "model" ]
0f42f174b26e1547a30fd8771c2a7a4058c3680e
595
cpp
C++
test/unit/math/mix/fun/crossprod_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-06-14T14:33:37.000Z
2020-06-14T14:33:37.000Z
test/unit/math/mix/fun/crossprod_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
2
2019-07-23T12:45:30.000Z
2020-05-01T20:43:03.000Z
test/unit/math/mix/fun/crossprod_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-05-10T12:55:07.000Z
2020-05-10T12:55:07.000Z
#include <test/unit/math/test_ad.hpp> #include <vector> TEST(MathMixMatFun, crossprod) { auto f = [](const auto& y) { return stan::math::crossprod(y); }; Eigen::MatrixXd t(0, 0); Eigen::MatrixXd x(1, 1); x << 3; Eigen::MatrixXd u(1, 3); u << 1, 2, 3; Eigen::MatrixXd y(2, 2); y << 3, 0, 4, -3; Eigen::MatrixXd v(2, 3); v << 1, 2, 3, -1, 4, 9; Eigen::MatrixXd w(3, 2); w << 1, 2, 3, -1, 4, 9; Eigen::MatrixXd z(3, 3); z << 1, 0, 0, 2, 3, 0, 4, 5, 6; for (const auto& a : std::vector<Eigen::MatrixXd>{t, x, u, y, v, w, z}) stan::test::expect_ad(f, a); }
19.833333
73
0.529412
[ "vector" ]
0f43e517831bbf74f94bd6ffa57f1b63df512053
779
cpp
C++
test/test_model_lstm_test.cpp
Zax37/frugally-deep
a119eea982b3622f57a75e1d58106002d9511b00
[ "MIT" ]
null
null
null
test/test_model_lstm_test.cpp
Zax37/frugally-deep
a119eea982b3622f57a75e1d58106002d9511b00
[ "MIT" ]
null
null
null
test/test_model_lstm_test.cpp
Zax37/frugally-deep
a119eea982b3622f57a75e1d58106002d9511b00
[ "MIT" ]
null
null
null
// Copyright 2016, Tobias Hermann. // https://github.com/Dobiasd/frugally-deep // Distributed under the MIT License. // (See accompanying LICENSE file or at // https://opensource.org/licenses/MIT) #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest/doctest.h" #include <fdeep/fdeep.hpp> #define FDEEP_FLOAT_TYPE double TEST_CASE("test_model_lstm_test, load_model") { const auto model = fdeep::load_model("../test_model_lstm.json", true, fdeep::cout_logger, static_cast<fdeep::float_type>(0.00001)); const auto multi_inputs = fplus::generate<std::vector<fdeep::tensors>>( [&]() -> fdeep::tensors {return model.generate_dummy_inputs();}, 10); model.predict_multi(multi_inputs, false); model.predict_multi(multi_inputs, true); }
33.869565
75
0.726573
[ "vector", "model" ]
0f4435566969d29cbddacd285c7c1d396368e383
1,707
tpp
C++
src/physics/rigid_body_assembler.tpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
71
2021-09-08T13:16:43.000Z
2022-03-27T10:23:33.000Z
src/physics/rigid_body_assembler.tpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
4
2021-09-08T00:16:20.000Z
2022-01-05T17:44:08.000Z
src/physics/rigid_body_assembler.tpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
2
2021-09-18T15:15:38.000Z
2021-09-21T15:15:38.000Z
#pragma once #include "rigid_body_assembler.hpp" namespace ipc::rigid { template <typename T> MatrixX<T> RigidBodyAssembler::world_vertices(const Poses<T>& poses) const { assert(poses.size() == num_bodies()); MatrixX<T> V(num_vertices(), dim()); for (size_t i = 0; i < num_bodies(); ++i) { const RigidBody& rb = m_rbs[i]; V.block(m_body_vertex_id[i], 0, rb.vertices.rows(), rb.dim()) = rb.world_vertices(poses[i]); } return V; } template <typename T> MatrixX<T> RigidBodyAssembler::world_vertices( const std::vector<MatrixMax3<T>>& rotations, const std::vector<VectorMax3<T>>& positions) const { assert(rotations.size() == num_bodies()); assert(positions.size() == num_bodies()); MatrixX<T> V(num_vertices(), dim()); for (size_t i = 0; i < num_bodies(); ++i) { const RigidBody& rb = m_rbs[i]; V.block(m_body_vertex_id[i], 0, rb.vertices.rows(), rb.dim()) = rb.world_vertices(rotations[i], positions[i]); } return V; } template <typename T> VectorMax3<T> RigidBodyAssembler::world_vertex( const Pose<T>& pose, const int vertex_idx) const { long body_idx, vertex_local_idx; global_to_local_vertex(vertex_idx, body_idx, vertex_local_idx); return m_rbs[body_idx].world_vertex(pose, vertex_local_idx); } template <typename T> VectorMax3<T> RigidBodyAssembler::world_vertex( const Poses<T>& poses, const int vertex_idx) const { assert(poses.size() == num_bodies()); long body_idx, vertex_local_idx; global_to_local_vertex(vertex_idx, body_idx, vertex_local_idx); return m_rbs[body_idx].world_vertex(poses[body_idx], vertex_local_idx); } } // namespace ipc::rigid
31.036364
75
0.677797
[ "vector" ]
0f460b19c1ee290090e0dbc0fcf8bfd0633a9189
1,409
hpp
C++
headers/turing_machine_reader.hpp
Daniel-del-Castillo/CC2
3c71493e335b658e09913e13bbfdc2a3f7a3f1d4
[ "Unlicense" ]
null
null
null
headers/turing_machine_reader.hpp
Daniel-del-Castillo/CC2
3c71493e335b658e09913e13bbfdc2a3f7a3f1d4
[ "Unlicense" ]
null
null
null
headers/turing_machine_reader.hpp
Daniel-del-Castillo/CC2
3c71493e335b658e09913e13bbfdc2a3f7a3f1d4
[ "Unlicense" ]
null
null
null
#pragma once #include <fstream> #include <string> #include <map> #include <vector> #include <stdexcept> #include "headers/turing_machine.hpp" #include "headers/debug_turing_machine.hpp" #include "headers/state.hpp" #include "headers/alphabet.hpp" // Allows reading a turing machine from a file. The turing machine // can be a TuringMachine or DebugTuringMachine depending on a debug flag class TuringMachineReader { Alphabet string_alphabet; Alphabet tape_alphabet; std::map<std::string, State> states; int number_of_tapes; public: static TuringMachine* read_turing_machine(std::istream& input, bool debug); TuringMachine* read_turing_machine_from_stream(std::istream& input, bool debug); private: std::string read_line(std::istream& input) const; std::map<std::string, State> read_states(const std::string& line) const; Alphabet read_alphabet(const std::string& line) const; void add_accepting_states(const std::string& line); void add_transitions(std::istream &input); void add_transition(const std::string& line, int id); Transition read_transition(const std::vector<std::string>& tokens, int id) const; std::vector<Action> read_actions(const std::vector<std::string>& tokens) const; Action read_action(char input, char move, char output) const; std::vector<std::string> split_whitespace(const std::string& line) const; };
36.128205
85
0.739532
[ "vector" ]
0f52070833936e0ccdcc79776bbfd3d701f88efb
38,238
cpp
C++
samples/sample_vpp/src/sample_vpp.cpp
yangnin/MediaSDK
5322c4a28b96f64425720e0416d2cb8285c7672a
[ "MIT" ]
1
2020-09-08T15:30:11.000Z
2020-09-08T15:30:11.000Z
samples/sample_vpp/src/sample_vpp.cpp
yangnin/MediaSDK
5322c4a28b96f64425720e0416d2cb8285c7672a
[ "MIT" ]
1
2021-01-21T12:27:39.000Z
2021-01-21T12:27:39.000Z
samples/sample_vpp/src/sample_vpp.cpp
yangnin/MediaSDK
5322c4a28b96f64425720e0416d2cb8285c7672a
[ "MIT" ]
1
2020-08-17T21:07:24.000Z
2020-08-17T21:07:24.000Z
/******************************************************************************\ Copyright (c) 2005-2019, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. This sample was distributed or derived from the Intel's Media Samples package. The original version of this sample may be obtained from https://software.intel.com/en-us/intel-media-server-studio or https://software.intel.com/en-us/media-client-solutions-support. \**********************************************************************************/ #include "sample_vpp_utils.h" #include "sample_vpp_pts.h" #include "sample_vpp_roi.h" #include "vm/atomic_defs.h" #define TIME_STATS 1 #include "time_statistics.h" #define MFX_CHECK(sts) {if (sts != MFX_ERR_NONE) return sts;} #ifndef MFX_VERSION #error MFX_VERSION not defined #endif using namespace std; void IncreaseReference(mfxFrameData *ptr) { msdk_atomic_inc16((volatile mfxU16*)&ptr->Locked); } void DecreaseReference(mfxFrameData *ptr) { msdk_atomic_dec16((volatile mfxU16*)&ptr->Locked); } void PutPerformanceToFile(sInputParams& Params, mfxF64 FPS) { FILE *fPRF; MSDK_FOPEN(fPRF,Params.strPerfFile, MSDK_STRING("ab")); if (!fPRF) return; msdk_char *iopattern = const_cast<msdk_char*>(IOpattern2Str(Params.IOPattern)); msdk_char iopattern_ascii[32] = {0}; msdk_char *pIOP = iopattern_ascii; while (*iopattern) *pIOP++ = (msdk_char)*iopattern++; msdk_char *srcFileName = Params.strSrcFile; msdk_char srcFileName_ascii[1024] = {0}; msdk_char *pFileName = srcFileName_ascii; while (*srcFileName) *pFileName++ = (msdk_char)*srcFileName++; msdk_tstring filters; if (Params.frameInfoIn[0].PicStruct != Params.frameInfoOut[0].PicStruct) { filters+=MSDK_STRING("DI "); } if (VPP_FILTER_DISABLED != Params.denoiseParam[0].mode) { filters+=MSDK_STRING("DN "); } if (filters.empty()) { filters=MSDK_STRING("NoFilters "); } msdk_fprintf(fPRF, MSDK_STRING("%s, %dx%d, %dx%d, %s, %s, %f\r\n"), srcFileName_ascii, Params.frameInfoIn[0].nWidth, Params.frameInfoIn[0].nHeight, Params.frameInfoOut[0].nWidth, Params.frameInfoOut[0].nHeight, iopattern_ascii, filters.c_str(), FPS); fclose(fPRF); } // void PutPerformanceToFile(sInputVppParams& Params, mfxF64 FPS) static void vppDefaultInitParams( sInputParams* pParams, sFiltersParam* pDefaultFiltersParam ) { pParams->frameInfoIn.clear(); pParams->frameInfoIn.push_back ( *pDefaultFiltersParam->pOwnFrameInfo ); pParams->frameInfoOut.clear(); pParams->frameInfoOut.push_back( *pDefaultFiltersParam->pOwnFrameInfo ); pParams->IOPattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY|MFX_IOPATTERN_OUT_SYSTEM_MEMORY; pParams->ImpLib = MFX_IMPL_HARDWARE | #ifdef LIBVA_SUPPORT MFX_IMPL_VIA_VAAPI; #else MFX_IMPL_VIA_D3D9; #endif pParams->asyncNum = 1; pParams->bPerf = false; pParams->isOutput = false; pParams->ptsCheck = false; pParams->ptsAdvanced = false; pParams->ptsFR = 0; pParams->vaType = ALLOC_IMPL_VIA_SYS; pParams->rotate.clear(); pParams->rotate.push_back(0); pParams->bScaling = false; pParams->scalingMode = MFX_SCALING_MODE_DEFAULT; pParams->bChromaSiting = false; pParams->uChromaSiting = 0; pParams->numFrames = 0; pParams->fccSource = MFX_FOURCC_NV12; // Optional video processing features pParams->mirroringParam.clear(); pParams->mirroringParam.push_back( *pDefaultFiltersParam->pMirroringParam ); pParams->videoSignalInfoParam.clear(); pParams->videoSignalInfoParam.push_back(*pDefaultFiltersParam->pVideoSignalInfo ); pParams->deinterlaceParam.clear(); pParams->deinterlaceParam.push_back( *pDefaultFiltersParam->pDIParam ); pParams->denoiseParam.clear(); pParams->denoiseParam.push_back( *pDefaultFiltersParam->pDenoiseParam ); #ifdef ENABLE_MCTF pParams->mctfParam.clear(); pParams->mctfParam.push_back( *pDefaultFiltersParam->pMctfParam ); #endif pParams->detailParam.clear(); pParams->detailParam.push_back( *pDefaultFiltersParam->pDetailParam ); pParams->procampParam.clear(); pParams->procampParam.push_back( *pDefaultFiltersParam->pProcAmpParam ); // analytics pParams->frcParam.clear(); pParams->frcParam.push_back( *pDefaultFiltersParam->pFRCParam ); // MSDK 3.0 pParams->multiViewParam.clear(); pParams->multiViewParam.push_back( *pDefaultFiltersParam->pMultiViewParam ); // MSDK API 1.5 pParams->gamutParam.clear(); pParams->gamutParam.push_back( *pDefaultFiltersParam->pGamutParam ); pParams->tccParam.clear(); pParams->tccParam.push_back( *pDefaultFiltersParam->pClrSaturationParam ); pParams->aceParam.clear(); pParams->aceParam.push_back( *pDefaultFiltersParam->pContrastParam ); pParams->steParam.clear(); pParams->steParam.push_back( *pDefaultFiltersParam->pSkinParam ); pParams->istabParam.clear(); pParams->istabParam.push_back( *pDefaultFiltersParam->pImgStabParam ); pParams->colorfillParam.clear(); pParams->colorfillParam.push_back( *pDefaultFiltersParam->pColorfillParam ); // ROI check pParams->roiCheckParam.mode = ROI_FIX_TO_FIX; // ROI check is disabled pParams->roiCheckParam.srcSeed = 0; pParams->roiCheckParam.dstSeed = 0; pParams->forcedOutputFourcc = 0; // plug-in GUID pParams->need_plugin = false; // Use RunFrameVPPAsyncEx pParams->use_extapi = false; // Do not call MFXVideoVPP_Reset pParams->resetFrmNums.clear(); pParams->bInitEx = false; pParams->GPUCopyValue = MFX_GPUCOPY_DEFAULT; return; } // void vppDefaultInitParams( sInputParams* pParams ) void SaveRealInfoForSvcOut(sSVCLayerDescr in[8], mfxFrameInfo out[8], mfxU32 fourcc) { for(mfxU32 did = 0; did < 8; did++) { out[did].Width = in[did].width; out[did].Height = in[did].height; //temp solution for crop out[did].CropX = 0; out[did].CropY = 0; out[did].CropW = out[did].Width; out[did].CropH = out[did].Height; // additional out[did].FourCC = fourcc; } } // void SaveRealInfoForSvcOut(sSVCLayerDescr in[8], mfxFrameInfo out[8]) mfxStatus OutputProcessFrame( sAppResources Resources, mfxFrameInfo* pOutFrameInfo, mfxU32 &nFrames, mfxU32 paramID) { mfxStatus sts; mfxFrameSurfaceWrap* pProcessedSurface; for(;!Resources.pSurfStore->m_SyncPoints.empty();Resources.pSurfStore->m_SyncPoints.pop_front()) { sts = Resources.pProcessor->mfxSession.SyncOperation( Resources.pSurfStore->m_SyncPoints.front().first, MSDK_VPP_WAIT_INTERVAL); if(sts==MFX_WRN_IN_EXECUTION) { msdk_printf(MSDK_STRING("SyncOperation wait interval exceeded\n")); } MSDK_CHECK_NOT_EQUAL(sts, MFX_ERR_NONE, sts); pProcessedSurface = Resources.pSurfStore->m_SyncPoints.front().second.pSurface; GeneralWriter* writer = (1 == Resources.dstFileWritersN) ? &Resources.pDstFileWriters[0] : &Resources.pDstFileWriters[paramID]; sts = writer->PutNextFrame( Resources.pAllocator, pOutFrameInfo, pProcessedSurface); DecreaseReference(&pProcessedSurface->Data); if(sts) msdk_printf(MSDK_STRING("Failed to write frame to disk\n")); MSDK_CHECK_NOT_EQUAL(sts, MFX_ERR_NONE, MFX_ERR_ABORTED); nFrames++; //VPP progress if (!Resources.pParams->bPerf) { msdk_printf(MSDK_STRING("Frame number: %d\r"), nFrames); } else { if (!(nFrames % 100)) msdk_printf(MSDK_STRING(".")); } } return MFX_ERR_NONE; } // mfxStatus OutputProcessFrame( void ownToMfxFrameInfo( sOwnFrameInfo* in, mfxFrameInfo* out, bool copyCropParams=false) { out->Width = in->nWidth; out->Height = in->nHeight; if(copyCropParams) { out->CropX = in->CropX; out->CropY = in->CropY; out->CropW = (in->CropW == NOT_INIT_VALUE) ? in->nWidth : in->CropW; out->CropH = (in->CropH == NOT_INIT_VALUE) ? in->nHeight : in->CropH; } else { out->CropX = 0; out->CropY = 0; out->CropW = in->nWidth; out->CropH = in->nHeight; } out->FourCC = in->FourCC; out->PicStruct = in->PicStruct; out->BitDepthLuma = in->BitDepthLuma; out->BitDepthChroma = in->BitDepthChroma; ConvertFrameRate(in->dFrameRate, &out->FrameRateExtN, &out->FrameRateExtD); return; } #if defined(_WIN32) || defined(_WIN64) int _tmain(int argc, TCHAR *argv[]) #else int main(int argc, msdk_char *argv[]) #endif { mfxStatus sts = MFX_ERR_NONE; mfxU32 nFrames = 0; mfxU16 nInStreamInd = 0; CRawVideoReader yuvReaders[MAX_INPUT_STREAMS]; CTimeStatistics statTimer; sFrameProcessor frameProcessor; sMemoryAllocator allocator{}; sInputParams Params; MfxVideoParamsWrapper mfxParamsVideo; // to prevent incorrect read/write of image in case of CropW/H != width/height mfxFrameInfo realFrameInfoIn[MAX_INPUT_STREAMS]; // Inputs+output mfxFrameInfo realFrameInfoOut; sAppResources Resources; mfxFrameSurfaceWrap* pInSurf[MAX_INPUT_STREAMS]={}; mfxFrameSurfaceWrap* pOutSurf = nullptr; mfxFrameSurfaceWrap* pWorkSurf = nullptr; mfxSyncPoint syncPoint; bool bFrameNumLimit = false; mfxU32 numGetFrames = 0; SurfaceVPPStore surfStore; unique_ptr<PTSMaker> ptsMaker; /* generators for ROI testing */ ROIGenerator inROIGenerator; ROIGenerator outROIGenerator; bool bROITest[2] = {false, false}; #ifdef ENABLE_VPP_RUNTIME_HSBC /* a counter of output frames*/ mfxU32 nOutFrames = 0; #endif //mfxU16 argbSurfaceIndex = 0xffff; /* default parameters */ sOwnFrameInfo defaultOwnFrameInfo = { 0, 0, 0, 0, 0, 0, 0, 0, 0, MFX_FOURCC_NV12, MFX_PICSTRUCT_PROGRESSIVE, 30.0 }; sDIParam defaultDIParam = { 0, 0, 0, VPP_FILTER_DISABLED }; sProcAmpParam defaultProcAmpParam = { 0.0, 1.0, 1.0, 0.0, VPP_FILTER_DISABLED }; sDetailParam defaultDetailParam = { 1, VPP_FILTER_DISABLED }; sDenoiseParam defaultDenoiseParam = { 1, VPP_FILTER_DISABLED }; #ifdef ENABLE_MCTF sMCTFParam defaultMctfParam; defaultMctfParam.mode = VPP_FILTER_DISABLED; defaultMctfParam.params.FilterStrength = 0; #ifdef ENABLE_MCTF_EXT defaultMctfParam.params.BitsPerPixelx100k = 0; defaultMctfParam.params.Deblocking = MFX_CODINGOPTION_OFF; defaultMctfParam.params.Overlap = MFX_CODINGOPTION_OFF; defaultMctfParam.params.TemporalMode = MFX_MCTF_TEMPORAL_MODE_2REF; defaultMctfParam.params.MVPrecision = MFX_MVPRECISION_INTEGER; #endif #endif sVideoAnalysisParam defaultVAParam = { VPP_FILTER_DISABLED }; sIDetectParam defaultIDetectParam = { VPP_FILTER_DISABLED }; sFrameRateConversionParam defaultFRCParam = { MFX_FRCALGM_PRESERVE_TIMESTAMP, VPP_FILTER_DISABLED }; //MSDK 3.0 sMultiViewParam defaultMultiViewParam = { 1, VPP_FILTER_DISABLED }; //MSDK API 1.5 sGamutMappingParam defaultGamutParam = { false, VPP_FILTER_DISABLED }; sTccParam defaultClrSaturationParam = { 160, 160, 160, 160, VPP_FILTER_DISABLED }; sAceParam defaultContrastParam = { VPP_FILTER_DISABLED }; sSteParam defaultSkinParam = { 4, VPP_FILTER_DISABLED }; sIStabParam defaultImgStabParam = { MFX_IMAGESTAB_MODE_BOXING, VPP_FILTER_DISABLED }; sSVCParam defaultSVCParam = { {}, VPP_FILTER_DISABLED }; sVideoSignalInfoParam defaultVideoSignalInfoParam; sMirroringParam defaultMirroringParam; sColorFillParam defaultColorfillParam; sFiltersParam defaultFiltersParam = { &defaultOwnFrameInfo, &defaultDIParam, &defaultProcAmpParam, &defaultDetailParam, &defaultDenoiseParam, #ifdef ENABLE_MCTF &defaultMctfParam, #endif &defaultVAParam, &defaultIDetectParam, &defaultFRCParam, &defaultMultiViewParam, &defaultGamutParam, &defaultClrSaturationParam, &defaultContrastParam, &defaultSkinParam, &defaultImgStabParam, &defaultSVCParam, &defaultVideoSignalInfoParam, &defaultMirroringParam, &defaultColorfillParam}; //reset pointers to the all internal resources MSDK_ZERO_MEMORY(Resources); MSDK_ZERO_MEMORY(realFrameInfoIn); MSDK_ZERO_MEMORY(realFrameInfoOut); for (int i = 0; i < Resources.numSrcFiles; i++) { Resources.pSrcFileReaders[i] = &yuvReaders[i]; } Resources.pProcessor = &frameProcessor; Resources.pAllocator = &allocator; Resources.pVppParams = &mfxParamsVideo; Resources.pParams = &Params; Resources.pSurfStore = &surfStore; vppDefaultInitParams( &Params, &defaultFiltersParam ); //parse input string sts = vppParseInputString(argv, (mfxU8)argc, &Params, &defaultFiltersParam); if (MFX_ERR_NONE != sts) { vppPrintHelp(argv[0], MSDK_STRING("Parameters parsing error")); return 1; } MSDK_CHECK_STATUS(sts, "vppParseInputString failed"); // to check time stamp settings if (Params.ptsFR) { Params.frameInfoIn[0].dFrameRate = Params.ptsFR; } if (!CheckInputParams(argv, &Params)) { return 1; } if (Params.ptsCheck) { ptsMaker.reset(new PTSMaker); } //prepare file reader (YUV/RGB file) Resources.numSrcFiles = 1; if (Params.compositionParam.mode == VPP_FILTER_ENABLED_CONFIGURED) { Resources.numSrcFiles = Params.numStreams > MAX_INPUT_STREAMS ? MAX_INPUT_STREAMS : Params.numStreams; for (int i = 0; i < Resources.numSrcFiles; i++) { ownToMfxFrameInfo(&(Params.inFrameInfo[i]), &(realFrameInfoIn[i]), true); // Set ptsMaker for the first stream only - it will store PTSes sts = yuvReaders[i].Init(Params.compositionParam.streamInfo[i].streamName, i == 0 ? ptsMaker.get() : NULL, realFrameInfoIn[i].FourCC); // In-place conversion check - I420 and YV12+D3D11 should be converted in reader and processed as NV12 bool shouldConvert = false; if (realFrameInfoIn[i].FourCC == MFX_FOURCC_I420 || ((Params.ImpLib & 0x0f00) == MFX_IMPL_VIA_D3D11 && realFrameInfoIn[i].FourCC == MFX_FOURCC_YV12)) { realFrameInfoIn[i].FourCC = MFX_FOURCC_YV12; shouldConvert = true; } if (shouldConvert) { msdk_printf(MSDK_STRING("[WARNING] D3D11 does not support YV12 and I420 surfaces. Input will be converted to NV12 by file reader.\n")); } MSDK_CHECK_STATUS(sts, "yuvReaders[i].Init failed"); } } else { // D3D11 does not support I420 and YV12 surfaces. So file reader will convert them into nv12. // It may be slower than using vpp if (Params.fccSource == MFX_FOURCC_I420 || ((Params.ImpLib & 0x0f00) == MFX_IMPL_VIA_D3D11 && Params.fccSource == MFX_FOURCC_YV12)) { msdk_printf(MSDK_STRING("[WARNING] D3D11 does not support YV12 and I420 surfaces. Input will be converted to NV12 by file reader.\n")); Params.inFrameInfo[0].FourCC = MFX_FOURCC_NV12; Params.frameInfoIn[0].FourCC = MFX_FOURCC_NV12; } ownToMfxFrameInfo( &(Params.frameInfoIn[0]), &realFrameInfoIn[0]); sts = yuvReaders[VPP_IN].Init(Params.strSrcFile,ptsMaker.get(), Params.fccSource); MSDK_CHECK_STATUS(sts, "yuvReaders[VPP_IN].Init failed"); } ownToMfxFrameInfo( &(Params.frameInfoOut[0]), &realFrameInfoOut); //prepare file writers (YUV file) Resources.dstFileWritersN = (mfxU32)Params.strDstFiles.size(); Resources.pDstFileWriters = new GeneralWriter[Resources.dstFileWritersN]; const msdk_char* istream; for (mfxU32 i = 0; i < Resources.dstFileWritersN; i++) { istream = Params.isOutput ? Params.strDstFiles[i].c_str() : NULL; sts = Resources.pDstFileWriters[i].Init( istream, ptsMaker.get(), NULL, Params.forcedOutputFourcc); MSDK_CHECK_STATUS_SAFE(sts, "Resources.pDstFileWriters[i].Init failed", {WipeResources(&Resources); WipeParams(&Params);}); } //#ifdef LIBVA_SUPPORT // if(!(Params.ImpLib & MFX_IMPL_SOFTWARE)) // allocator.libvaKeeper.reset(CreateLibVA()); //#endif //prepare mfxParams sts = InitParamsVPP(&mfxParamsVideo, &Params, 0); MSDK_CHECK_STATUS_SAFE(sts, "InitParamsVPP failed", {WipeResources(&Resources); WipeParams(&Params);}); // prepare pts Checker if (ptsMaker.get()) { sts = ptsMaker.get()->Init(&mfxParamsVideo, Params.asyncNum - 1, Params.ptsAdvanced); MSDK_CHECK_STATUS_SAFE(sts, "ptsMaker.get()->Init failed", {WipeResources(&Resources); WipeParams(&Params);}); } // prepare ROI generator if( ROI_VAR_TO_FIX == Params.roiCheckParam.mode || ROI_VAR_TO_VAR == Params.roiCheckParam.mode ) { inROIGenerator.Init(realFrameInfoIn[0].Width, realFrameInfoIn[0].Height, Params.roiCheckParam.srcSeed); Params.roiCheckParam.srcSeed = inROIGenerator.GetSeed(); bROITest[VPP_IN] = true; } if( ROI_FIX_TO_VAR == Params.roiCheckParam.mode || ROI_VAR_TO_VAR == Params.roiCheckParam.mode ) { outROIGenerator.Init(realFrameInfoIn[0].Width, realFrameInfoIn[0].Height, Params.roiCheckParam.dstSeed); Params.roiCheckParam.dstSeed = outROIGenerator.GetSeed(); bROITest[VPP_OUT] = true; } sts = ConfigVideoEnhancementFilters(&Params, &Resources, 0); MSDK_CHECK_STATUS_SAFE(sts, "ConfigVideoEnhancementFilters failed", {WipeResources(&Resources); WipeParams(&Params);}); sts = InitResources(&Resources, &mfxParamsVideo, &Params); if(MFX_WRN_FILTER_SKIPPED == sts) { msdk_printf(MSDK_STRING("\nVPP_WRN: some filter(s) skipped\n")); MSDK_IGNORE_MFX_STS(sts, MFX_WRN_FILTER_SKIPPED); } MSDK_CHECK_STATUS_SAFE(sts, "InitResources failed", {WipeResources(&Resources); WipeParams(&Params);}); if (MFX_WRN_PARTIAL_ACCELERATION == sts) { Params.bPartialAccel = true; } else { Params.bPartialAccel = false; } if (Params.bPerf) { for (int i = 0; i < Resources.numSrcFiles; i++) { sts = yuvReaders[i].PreAllocateFrameChunk(&mfxParamsVideo, &Params, allocator.pMfxAllocator); } MSDK_CHECK_STATUS_SAFE(sts, "yuvReaders[i].PreAllocateFrameChunk failed", {WipeResources(&Resources); WipeParams(&Params);}); } else if (Params.numFrames) { bFrameNumLimit = true; } // print parameters to console PrintInfo(&Params, &mfxParamsVideo, &Resources.pProcessor->mfxSession); PrintDllInfo(); sts = MFX_ERR_NONE; nFrames = 0; msdk_printf(MSDK_STRING("VPP started\n")); statTimer.StartTimeMeasurement(); mfxU32 StartJumpFrame = 13; // need to correct jumping parameters due to async mode if (ptsMaker.get() && Params.ptsJump && (Params.asyncNum > 1)) { if (Params.asyncNum > StartJumpFrame) { StartJumpFrame = Params.asyncNum; } else { StartJumpFrame = StartJumpFrame/Params.asyncNum*Params.asyncNum; } } bool bDoNotUpdateIn = false; if(Params.use_extapi) bDoNotUpdateIn = true; // pre-multi-view preparation bool bMultiView = (VPP_FILTER_ENABLED_CONFIGURED == Params.multiViewParam[0].mode) ? true : false; vector<bool> bMultipleOutStore(Params.multiViewParam[0].viewCount, false); mfxFrameSurfaceWrap* viewSurfaceStore[MULTI_VIEW_COUNT_MAX]; ViewGenerator viewGenerator( Params.multiViewParam[0].viewCount ); if( bMultiView ) { if( bFrameNumLimit ) { Params.numFrames *= Params.multiViewParam[0].viewCount; } } bool bNeedReset = false; mfxU16 paramID = 0; mfxU32 nextResetFrmNum = (Params.resetFrmNums.size() > 0) ? Params.resetFrmNums[0] : NOT_INIT_VALUE; //--------------------------------------------------------- do { if (bNeedReset) { paramID++; bNeedReset = false; nextResetFrmNum = (Params.resetFrmNums.size() > paramID) ? Params.resetFrmNums[paramID] : NOT_INIT_VALUE; //prepare mfxParams sts = InitParamsVPP(&mfxParamsVideo, &Params, paramID); MSDK_CHECK_STATUS_SAFE(sts, "InitParamsVPP failed", {WipeResources(&Resources); WipeParams(&Params);}); sts = ConfigVideoEnhancementFilters(&Params, &Resources, paramID); MSDK_CHECK_STATUS_SAFE(sts, "ConfigVideoEnchancementFilters failed", {WipeResources(&Resources); WipeParams(&Params);}); sts = Resources.pProcessor->pmfxVPP->Reset(Resources.pVppParams); MSDK_CHECK_STATUS_SAFE(sts, "Resources.pProcessor->pmfxVPP->Reset failed", {WipeResources(&Resources); WipeParams(&Params);}); ownToMfxFrameInfo( &(Params.frameInfoIn[paramID]), &realFrameInfoIn[0]); ownToMfxFrameInfo( &(Params.frameInfoOut[paramID]), &realFrameInfoOut); UpdateSurfacePool(mfxParamsVideo.vpp.Out, allocator.responseOut.NumFrameActual, allocator.pSurfacesOut); if(Params.numStreams==1) { UpdateSurfacePool(mfxParamsVideo.vpp.In, allocator.responseIn[0].NumFrameActual, allocator.pSurfacesIn[0]); } else { for(int i=0;i<Params.numStreams;i++) { ownToMfxFrameInfo(&(Params.inFrameInfo[i]), &realFrameInfoIn[i]); UpdateSurfacePool(mfxParamsVideo.vpp.In, allocator.responseIn[i].NumFrameActual, allocator.pSurfacesIn[i]); } } msdk_printf(MSDK_STRING("VPP reseted at frame number %d\n"), numGetFrames); } while (MFX_ERR_NONE <= sts || MFX_ERR_MORE_DATA == sts || bDoNotUpdateIn ) { mfxU16 viewID = 0; mfxU16 viewIndx = 0; if (nInStreamInd >= MAX_INPUT_STREAMS) { sts = MFX_ERR_UNKNOWN; break; } // update for multiple output of multi-view if( bMultiView ) { viewID = viewGenerator.GetNextViewID(); viewIndx = viewGenerator.GetViewIndx( viewID ); if( bMultipleOutStore[viewIndx] ) { pInSurf[nInStreamInd] = viewSurfaceStore[viewIndx]; bDoNotUpdateIn = true; bMultipleOutStore[viewIndx] = false; } else { bDoNotUpdateIn = false; } } if( !bDoNotUpdateIn ) { if (nextResetFrmNum == numGetFrames) { bNeedReset = true; sts = MFX_ERR_MORE_DATA; break; } // if we share allocator with mediasdk we need to call Lock to access surface data and after we're done call Unlock sts = yuvReaders[nInStreamInd].GetNextInputFrame(&allocator,&realFrameInfoIn[nInStreamInd],&pInSurf[nInStreamInd],nInStreamInd); MSDK_BREAK_ON_ERROR(sts); // Set input timestamps according to input framerate mfxU64 expectedPTS = (((mfxU64)(numGetFrames) * mfxParamsVideo.vpp.In.FrameRateExtD * 90000) / mfxParamsVideo.vpp.In.FrameRateExtN); pInSurf[nInStreamInd]->Data.TimeStamp = expectedPTS; if( bMultiView ) { pInSurf[nInStreamInd]->Info.FrameId.ViewId = viewID; } if (numGetFrames++ == Params.numFrames && bFrameNumLimit) { sts = MFX_ERR_MORE_DATA; break; } } // VPP processing bDoNotUpdateIn = false; sts = GetFreeSurface( allocator.pSurfacesOut, allocator.responseOut.NumFrameActual , (Params.use_extapi ? &pWorkSurf : &pOutSurf)); MSDK_BREAK_ON_ERROR(sts); if( bROITest[VPP_IN] ) { inROIGenerator.SetROI( &(pInSurf[nInStreamInd]->Info) ); } if( bROITest[VPP_OUT] ) { outROIGenerator.SetROI((Params.use_extapi ? &pWorkSurf->Info : &pOutSurf->Info)); } if ( Params.use_extapi ) { mfxFrameSurface1 * out_surface = nullptr; do { sts = frameProcessor.pmfxVPP->RunFrameVPPAsyncEx( pInSurf[nInStreamInd], pWorkSurf, //pExtData, &out_surface, &syncPoint); } while (MFX_WRN_DEVICE_BUSY == sts); pOutSurf = static_cast<mfxFrameSurfaceWrap*>(out_surface); if(MFX_ERR_MORE_DATA != sts) bDoNotUpdateIn = true; } else { #ifdef ENABLE_VPP_RUNTIME_HSBC auto procAmp = pOutSurf->AddExtBuffer<mfxExtVPPProcAmp>(); // set default values for ProcAmp filters procAmp->Brightness = 0.0F; procAmp->Contrast = 1.0F; procAmp->Hue = 0.0F; procAmp->Saturation = 1.0F; if (Params.rtHue.isEnabled) { if((nOutFrames / Params.rtHue.interval & 0x1) == 0) { procAmp->Hue = Params.rtHue.value1; } else { procAmp->Hue = Params.rtHue.value2; } } if (Params.rtSaturation.isEnabled) { if((nOutFrames / Params.rtSaturation.interval & 0x1) == 0) { procAmp->Saturation = Params.rtSaturation.value1; } else { procAmp->Saturation = Params.rtSaturation.value2; } } if (Params.rtBrightness.isEnabled) { if((nOutFrames / Params.rtBrightness.interval & 0x1) == 0) { procAmp->Brightness = Params.rtBrightness.value1; } else { procAmp->Brightness = Params.rtBrightness.value2; } } if (Params.rtContrast.isEnabled) { if((nOutFrames / Params.rtContrast.interval & 0x1) == 0) { procAmp->Contrast = Params.rtContrast.value1; } else { procAmp->Contrast = Params.rtContrast.value2; } } nOutFrames++; #endif sts = frameProcessor.pmfxVPP->RunFrameVPPAsync( pInSurf[nInStreamInd], pOutSurf, NULL, &syncPoint); } nInStreamInd++; if (nInStreamInd == Resources.numSrcFiles) nInStreamInd = 0; if (MFX_ERR_MORE_DATA == sts) { continue; } //MFX_ERR_MORE_SURFACE (&& !use_extapi) means output is ready but need more surface //because VPP produce multiple out. example: Frame Rate Conversion 30->60 //MFX_ERR_MORE_SURFACE && use_extapi means that component need more work surfaces if (MFX_ERR_MORE_SURFACE == sts) { sts = MFX_ERR_NONE; if( bMultiView ) { if( viewSurfaceStore[viewIndx] ) { DecreaseReference( &(viewSurfaceStore[viewIndx]->Data) ); } viewSurfaceStore[viewIndx] = pInSurf[nInStreamInd]; IncreaseReference( &(viewSurfaceStore[viewIndx]->Data) ); bMultipleOutStore[viewIndx] = true; } else { bDoNotUpdateIn = true; } if ( Params.use_extapi ) { // RunFrameAsyncEx is used continue; } } else if (MFX_ERR_NONE == sts && !((nFrames+1)% StartJumpFrame) && ptsMaker.get() && Params.ptsJump) // pts jump { ptsMaker.get()->JumpPTS(); } else if ( MFX_ERR_NONE == sts && bMultiView ) { if( viewSurfaceStore[viewIndx] ) { DecreaseReference( &(viewSurfaceStore[viewIndx]->Data) ); viewSurfaceStore[viewIndx] = NULL; } } MSDK_CHECK_STATUS_NO_RET(sts, "RunFrameVPPAsync(Ex) failed") MSDK_BREAK_ON_ERROR(sts); surfStore.m_SyncPoints.push_back(SurfaceVPPStore::SyncPair(syncPoint,pOutSurf)); IncreaseReference(&pOutSurf->Data); if (surfStore.m_SyncPoints.size() != (size_t)(Params.asyncNum * Params.multiViewParam[paramID].viewCount)) { continue; } sts = OutputProcessFrame(Resources, &realFrameInfoOut, nFrames, paramID); MSDK_BREAK_ON_ERROR(sts); } // main while loop //--------------------------------------------------------- //process remain sync points if (MFX_ERR_MORE_DATA == sts) { sts = OutputProcessFrame(Resources, &realFrameInfoOut, nFrames, paramID); MSDK_CHECK_STATUS_SAFE(sts, "OutputProcessFrame failed", {WipeResources(&Resources); WipeParams(&Params);}); } // means that file has ended, need to go to buffering loop MSDK_IGNORE_MFX_STS(sts, MFX_ERR_MORE_DATA); // exit in case of other errors MSDK_CHECK_STATUS_SAFE(sts, "OutputProcessFrame failed", {WipeResources(&Resources); WipeParams(&Params);}); // loop to get buffered frames from VPP while (MFX_ERR_NONE <= sts) { sts = GetFreeSurface( allocator.pSurfacesOut, allocator.responseOut.NumFrameActual , (Params.use_extapi ? &pWorkSurf : &pOutSurf)); MSDK_BREAK_ON_ERROR(sts); bDoNotUpdateIn = false; if ( Params.use_extapi ) { mfxFrameSurface1 * out_surface = nullptr; do { sts = frameProcessor.pmfxVPP->RunFrameVPPAsyncEx( NULL, pWorkSurf, &out_surface, &syncPoint ); } while (MFX_WRN_DEVICE_BUSY == sts); pOutSurf = static_cast<mfxFrameSurfaceWrap*>(out_surface); } else { #ifdef ENABLE_VPP_RUNTIME_HSBC auto procAmp = pOutSurf->AddExtBuffer<mfxExtVPPProcAmp>(); // set default values for ProcAmp filters procAmp->Brightness = 0.0F; procAmp->Contrast = 1.0F; procAmp->Hue = 0.0F; procAmp->Saturation = 1.0F; if (Params.rtHue.isEnabled) { if((nOutFrames / Params.rtHue.interval & 0x1) == 0) { procAmp->Hue = Params.rtHue.value1; } else { procAmp->Hue = Params.rtHue.value2; } } if (Params.rtSaturation.isEnabled) { if((nOutFrames / Params.rtSaturation.interval & 0x1) == 0) { procAmp->Saturation = Params.rtSaturation.value1; } else { procAmp->Saturation = Params.rtSaturation.value2; } } if (Params.rtBrightness.isEnabled) { if((nOutFrames / Params.rtBrightness.interval & 0x1) == 0) { procAmp->Brightness = Params.rtBrightness.value1; } else { procAmp->Brightness = Params.rtBrightness.value2; } } if (Params.rtContrast.isEnabled) { if((nOutFrames / Params.rtContrast.interval & 0x1) == 0) { procAmp->Contrast = Params.rtContrast.value1; } else { procAmp->Contrast = Params.rtContrast.value2; } } nOutFrames++; #endif sts = frameProcessor.pmfxVPP->RunFrameVPPAsync( NULL, pOutSurf, NULL, &syncPoint ); } MSDK_IGNORE_MFX_STS(sts, MFX_ERR_MORE_SURFACE); MSDK_BREAK_ON_ERROR(sts); sts = Resources.pProcessor->mfxSession.SyncOperation( syncPoint, MSDK_VPP_WAIT_INTERVAL); if(sts) msdk_printf(MSDK_STRING("SyncOperation wait interval exceeded\n")); MSDK_BREAK_ON_ERROR(sts); GeneralWriter* writer = (1 == Resources.dstFileWritersN) ? &Resources.pDstFileWriters[0] : &Resources.pDstFileWriters[paramID]; sts = writer->PutNextFrame( Resources.pAllocator, &realFrameInfoOut, pOutSurf); if(sts) msdk_printf(MSDK_STRING("Failed to write frame to disk\n")); MSDK_CHECK_NOT_EQUAL(sts, MFX_ERR_NONE, MFX_ERR_ABORTED); nFrames++; //VPP progress if (!Params.bPerf) msdk_printf(MSDK_STRING("Frame number: %d\r"), nFrames); else { if (!(nFrames % 100)) msdk_printf(MSDK_STRING(".")); } } } while (bNeedReset); statTimer.StopTimeMeasurement(); MSDK_IGNORE_MFX_STS(sts, MFX_ERR_MORE_DATA); // report any errors that occurred MSDK_CHECK_STATUS_SAFE(sts, "Unexpected error", {WipeResources(&Resources); WipeParams(&Params);}); msdk_printf(MSDK_STRING("\nVPP finished\n")); msdk_printf(MSDK_STRING("\n")); msdk_printf(MSDK_STRING("Total frames %d \n"), nFrames); msdk_printf(MSDK_STRING("Total time %.2f sec \n"), statTimer.GetTotalTime()); msdk_printf(MSDK_STRING("Frames per second %.3f fps \n"), nFrames / statTimer.GetTotalTime()); PutPerformanceToFile(Params, nFrames / statTimer.GetTotalTime()); WipeResources(&Resources); WipeParams(&Params); return 0; /* OK */ } // int _tmain(int argc, msdk_char *argv[]) /* EOF */
37.414873
755
0.583268
[ "vector" ]
0f52136cb85077109d5effb63f6a08b12254fde4
1,752
cpp
C++
tests/quickfutureunittests/quickfutureunittests.cpp
Dushistov/quickfuture
021dced18718483e0b98ff06c3f97657bf35afab
[ "Apache-2.0" ]
null
null
null
tests/quickfutureunittests/quickfutureunittests.cpp
Dushistov/quickfuture
021dced18718483e0b98ff06c3f97657bf35afab
[ "Apache-2.0" ]
null
null
null
tests/quickfutureunittests/quickfutureunittests.cpp
Dushistov/quickfuture
021dced18718483e0b98ff06c3f97657bf35afab
[ "Apache-2.0" ]
null
null
null
#include <QQmlApplicationEngine> #include <QTest> #include <QElapsedTimer> #include <Automator> #include <QQmlContext> #include <QtShell> #include <QuickFuture> #include <QtConcurrent> #include "actor.h" #include "quickfutureunittests.h" Q_DECLARE_METATYPE(QFuture<QString>) using namespace QuickFuture; template <typename F> static bool waitUntil(F f, int timeout = -1) { QElapsedTimer time; time.start(); while (!f()) { Automator::wait(10); if (timeout > 0 && time.elapsed() > timeout) { return false; } } return true; } QuickFutureUnitTests::QuickFutureUnitTests(QObject *parent) : QObject(parent) { auto ref = [=]() { QTest::qExec(this, 0, 0); // Autotest detect available test cases of a QObject by looking for "QTest::qExec" in source code }; Q_UNUSED(ref); } void QuickFutureUnitTests::test_QFVariantWrapper() { QFuture<QString> future; QVariant v = QVariant::fromValue<QFuture<QString> >(future); QVERIFY(future.isFinished()); VariantWrapper<QString> wrapper; QVERIFY(wrapper.isFinished(v)); } void QuickFutureUnitTests::test_QFFuture() { Future wrapper; QFuture<QString> future; QVariant v = QVariant::fromValue<QFuture<QString> >(future); QVERIFY(future.isFinished()); QVERIFY(wrapper.isFinished(v)); } void QuickFutureUnitTests::PromiseIsNotInstalled() { QQmlApplicationEngine engine; qDebug() << "Excepted error:"; engine.rootContext()->setContextProperty("Actor", new Actor()); engine.load(QString(SRCDIR) + "/qmltests/PromiseIsNotInstalled.qml"); QObject* object = engine.rootObjects().first(); QVERIFY(object); QMetaObject::invokeMethod(object, "test",Qt::DirectConnection); }
23.675676
131
0.689498
[ "object" ]
0f54e47506e83bd9282226198ecec0ebc4a8644f
12,629
cpp
C++
src/+cv/private/RTrees_.cpp
rokm/mexopencv
22d459cd28df8a5e77fd7f2c8572b16723f60a1d
[ "BSD-3-Clause" ]
1
2021-05-12T21:33:44.000Z
2021-05-12T21:33:44.000Z
src/+cv/private/RTrees_.cpp
rokm/mexopencv
22d459cd28df8a5e77fd7f2c8572b16723f60a1d
[ "BSD-3-Clause" ]
null
null
null
src/+cv/private/RTrees_.cpp
rokm/mexopencv
22d459cd28df8a5e77fd7f2c8572b16723f60a1d
[ "BSD-3-Clause" ]
1
2020-09-29T22:33:52.000Z
2020-09-29T22:33:52.000Z
/** * @file RTrees_.cpp * @brief mex interface for cv::ml::RTrees * @ingroup ml * @author Kota Yamaguchi, Amro * @date 2012, 2015 */ #include "mexopencv.hpp" #include "mexopencv_ml.hpp" using namespace std; using namespace cv; using namespace cv::ml; // Persistent objects namespace { /// Last object id to allocate int last_id = 0; /// Object container map<int,Ptr<RTrees> > obj_; } /** * Main entry called from Matlab * @param nlhs number of left-hand-side arguments * @param plhs pointers to mxArrays in the left-hand-side * @param nrhs number of right-hand-side arguments * @param prhs pointers to mxArrays in the right-hand-side */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Check the number of arguments nargchk(nrhs>=2 && nlhs<=2); // Argument vector vector<MxArray> rhs(prhs, prhs+nrhs); int id = rhs[0].toInt(); string method(rhs[1].toString()); // Constructor is called. Create a new object from argument if (method == "new") { nargchk(nrhs==2 && nlhs<=1); obj_[++last_id] = RTrees::create(); plhs[0] = MxArray(last_id); mexLock(); return; } // Big operation switch Ptr<RTrees> obj = obj_[id]; if (obj.empty()) mexErrMsgIdAndTxt("mexopencv:error", "Object not found id=%d", id); if (method == "delete") { nargchk(nrhs==2 && nlhs==0); obj_.erase(id); mexUnlock(); } else if (method == "clear") { nargchk(nrhs==2 && nlhs==0); obj->clear(); } else if (method == "load") { nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs==0); string objname; bool loadFromString = false; for (int i=3; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key == "ObjName") objname = rhs[i+1].toString(); else if (key == "FromString") loadFromString = rhs[i+1].toBool(); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option %s", key.c_str()); } //obj_[id] = RTrees::load(rhs[2].toString()); obj_[id] = (loadFromString ? Algorithm::loadFromString<RTrees>(rhs[2].toString(), objname) : Algorithm::load<RTrees>(rhs[2].toString(), objname)); } else if (method == "save") { nargchk(nrhs==3 && nlhs<=1); string fname(rhs[2].toString()); if (nlhs > 0) { // write to memory, and return string FileStorage fs(fname, FileStorage::WRITE + FileStorage::MEMORY); if (!fs.isOpened()) mexErrMsgIdAndTxt("mexopencv:error", "Failed to open file"); fs << obj->getDefaultName() << "{"; obj->write(fs); fs << "}"; plhs[0] = MxArray(fs.releaseAndGetString()); } else // write to disk obj->save(fname); } else if (method == "empty") { nargchk(nrhs==2 && nlhs<=1); plhs[0] = MxArray(obj->empty()); } else if (method == "getDefaultName") { nargchk(nrhs==2 && nlhs<=1); plhs[0] = MxArray(obj->getDefaultName()); } else if (method == "getVarCount") { nargchk(nrhs==2 && nlhs<=1); plhs[0] = MxArray(obj->getVarCount()); } else if (method == "isClassifier") { nargchk(nrhs==2 && nlhs<=1); plhs[0] = MxArray(obj->isClassifier()); } else if (method == "isTrained") { nargchk(nrhs==2 && nlhs<=1); plhs[0] = MxArray(obj->isTrained()); } else if (method == "train") { nargchk(nrhs>=4 && (nrhs%2)==0 && nlhs<=1); vector<MxArray> dataOptions; int flags = 0; for (int i=4; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key == "Data") dataOptions = rhs[i+1].toVector<MxArray>(); else if (key == "Flags") flags = rhs[i+1].toInt(); else if (key == "RawOutput") UPDATE_FLAG(flags, rhs[i+1].toBool(), StatModel::RAW_OUTPUT); else if (key == "PredictSum") UPDATE_FLAG(flags, rhs[i+1].toBool(), DTrees::PREDICT_SUM); else if (key == "PredictMaxVote") UPDATE_FLAG(flags, rhs[i+1].toBool(), DTrees::PREDICT_MAX_VOTE); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option %s", key.c_str()); } Ptr<TrainData> data; if (rhs[2].isChar()) data = loadTrainData(rhs[2].toString(), dataOptions.begin(), dataOptions.end()); else data = createTrainData( rhs[2].toMat(CV_32F), rhs[3].toMat(rhs[3].isInt32() ? CV_32S : CV_32F), dataOptions.begin(), dataOptions.end()); bool b = obj->train(data, flags); plhs[0] = MxArray(b); } else if (method == "calcError") { nargchk(nrhs>=4 && (nrhs%2)==0 && nlhs<=2); vector<MxArray> dataOptions; bool test = false; for (int i=4; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key == "Data") dataOptions = rhs[i+1].toVector<MxArray>(); else if (key == "TestError") test = rhs[i+1].toBool(); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option %s", key.c_str()); } Ptr<TrainData> data; if (rhs[2].isChar()) data = loadTrainData(rhs[2].toString(), dataOptions.begin(), dataOptions.end()); else data = createTrainData( rhs[2].toMat(CV_32F), rhs[3].toMat(rhs[3].isInt32() ? CV_32S : CV_32F), dataOptions.begin(), dataOptions.end()); Mat resp; float err = obj->calcError(data, test, (nlhs>1 ? resp : noArray())); plhs[0] = MxArray(err); if (nlhs>1) plhs[1] = MxArray(resp); } else if (method == "predict") { nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=2); int flags = 0; for (int i=3; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key == "Flags") flags = rhs[i+1].toInt(); else if (key == "RawOutput") UPDATE_FLAG(flags, rhs[i+1].toBool(), StatModel::RAW_OUTPUT); else if (key == "CompressedInput") UPDATE_FLAG(flags, rhs[i+1].toBool(), StatModel::COMPRESSED_INPUT); else if (key == "PreprocessedInput") UPDATE_FLAG(flags, rhs[i+1].toBool(), StatModel::PREPROCESSED_INPUT); else if (key == "PredictAuto") { //UPDATE_FLAG(flags, rhs[i+1].toBool(), DTrees::PREDICT_AUTO); UPDATE_FLAG(flags, !rhs[i+1].toBool(), DTrees::PREDICT_SUM); UPDATE_FLAG(flags, !rhs[i+1].toBool(), DTrees::PREDICT_MAX_VOTE); } else if (key == "PredictSum") UPDATE_FLAG(flags, rhs[i+1].toBool(), DTrees::PREDICT_SUM); else if (key == "PredictMaxVote") UPDATE_FLAG(flags, rhs[i+1].toBool(), DTrees::PREDICT_MAX_VOTE); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option %s", key.c_str()); } Mat samples(rhs[2].toMat(CV_32F)), results; float f = obj->predict(samples, results, flags); plhs[0] = MxArray(results); if (nlhs>1) plhs[1] = MxArray(f); } else if (method == "getNodes") { nargchk(nrhs==2 && nlhs<=1); plhs[0] = toStruct(obj->getNodes()); } else if (method == "getRoots") { nargchk(nrhs==2 && nlhs<=1); plhs[0] = MxArray(obj->getRoots()); } else if (method == "getSplits") { nargchk(nrhs==2 && nlhs<=1); plhs[0] = toStruct(obj->getSplits()); } else if (method == "getSubsets") { nargchk(nrhs==2 && nlhs<=1); plhs[0] = MxArray(obj->getSubsets()); } else if (method == "getVarImportance") { nargchk(nrhs==2 && nlhs<=1); plhs[0] = MxArray(obj->getVarImportance()); } else if (method == "getVotes") { nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=1); int flags = 0; for (int i=3; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key == "Flags") flags = rhs[i+1].toInt(); else if (key == "RawOutput") UPDATE_FLAG(flags, rhs[i+1].toBool(), StatModel::RAW_OUTPUT); else if (key == "CompressedInput") UPDATE_FLAG(flags, rhs[i+1].toBool(), StatModel::COMPRESSED_INPUT); else if (key == "PreprocessedInput") UPDATE_FLAG(flags, rhs[i+1].toBool(), StatModel::PREPROCESSED_INPUT); else if (key == "PredictAuto") { //UPDATE_FLAG(flags, rhs[i+1].toBool(), DTrees::PREDICT_AUTO); UPDATE_FLAG(flags, !rhs[i+1].toBool(), DTrees::PREDICT_SUM); UPDATE_FLAG(flags, !rhs[i+1].toBool(), DTrees::PREDICT_MAX_VOTE); } else if (key == "PredictSum") UPDATE_FLAG(flags, rhs[i+1].toBool(), DTrees::PREDICT_SUM); else if (key == "PredictMaxVote") UPDATE_FLAG(flags, rhs[i+1].toBool(), DTrees::PREDICT_MAX_VOTE); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option %s", key.c_str()); } Mat samples(rhs[2].toMat(CV_32F)), results; obj->getVotes(samples, results, flags); plhs[0] = MxArray(results); } else if (method == "get") { nargchk(nrhs==3 && nlhs<=1); string prop(rhs[2].toString()); if (prop == "CVFolds") plhs[0] = MxArray(obj->getCVFolds()); else if (prop == "MaxCategories") plhs[0] = MxArray(obj->getMaxCategories()); else if (prop == "MaxDepth") plhs[0] = MxArray(obj->getMaxDepth()); else if (prop == "MinSampleCount") plhs[0] = MxArray(obj->getMinSampleCount()); else if (prop == "Priors") plhs[0] = MxArray(obj->getPriors()); else if (prop == "RegressionAccuracy") plhs[0] = MxArray(obj->getRegressionAccuracy()); else if (prop == "TruncatePrunedTree") plhs[0] = MxArray(obj->getTruncatePrunedTree()); else if (prop == "Use1SERule") plhs[0] = MxArray(obj->getUse1SERule()); else if (prop == "UseSurrogates") plhs[0] = MxArray(obj->getUseSurrogates()); else if (prop == "ActiveVarCount") plhs[0] = MxArray(obj->getActiveVarCount()); else if (prop == "CalculateVarImportance") plhs[0] = MxArray(obj->getCalculateVarImportance()); else if (prop == "TermCriteria") plhs[0] = MxArray(obj->getTermCriteria()); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized property %s", prop.c_str()); } else if (method == "set") { nargchk(nrhs==4 && nlhs==0); string prop(rhs[2].toString()); if (prop == "CVFolds") obj->setCVFolds(rhs[3].toInt()); else if (prop == "MaxCategories") obj->setMaxCategories(rhs[3].toInt()); else if (prop == "MaxDepth") obj->setMaxDepth(rhs[3].toInt()); else if (prop == "MinSampleCount") obj->setMinSampleCount(rhs[3].toInt()); else if (prop == "Priors") obj->setPriors(rhs[3].toMat()); else if (prop == "RegressionAccuracy") obj->setRegressionAccuracy(rhs[3].toFloat()); else if (prop == "TruncatePrunedTree") obj->setTruncatePrunedTree(rhs[3].toBool()); else if (prop == "Use1SERule") obj->setUse1SERule(rhs[3].toBool()); else if (prop == "UseSurrogates") obj->setUseSurrogates(rhs[3].toBool()); else if (prop == "ActiveVarCount") obj->setActiveVarCount(rhs[3].toInt()); else if (prop == "CalculateVarImportance") obj->setCalculateVarImportance(rhs[3].toBool()); else if (prop == "TermCriteria") obj->setTermCriteria(rhs[3].toTermCriteria()); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized property %s", prop.c_str()); } else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized operation %s", method.c_str()); }
38.503049
85
0.522765
[ "object", "vector" ]
0f551ff1f670343bcdb49268f3647515d1872e06
31,313
cpp
C++
app/src/mainwindow.cpp
yohrudkov/Uamp
4ec479156767907b5ae4c35716c1bea0897461cc
[ "MIT" ]
null
null
null
app/src/mainwindow.cpp
yohrudkov/Uamp
4ec479156767907b5ae4c35716c1bea0897461cc
[ "MIT" ]
null
null
null
app/src/mainwindow.cpp
yohrudkov/Uamp
4ec479156767907b5ae4c35716c1bea0897461cc
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_block = false; m_resize = false; m_rep = 0; m_netaccman = new QNetworkAccessManager(this); m_shutdown = new Timer(this); ui->SongName->setWordWrap(true); createPlayer(); playerButtons(); connectButtons(); createRadio(); radioButtons(); setVolumeButton(); setSortButton(); setDataBase(); setDBButtons(); libraryButtons(); macosArea(); ui->Screens->setCurrentIndex(0); for (auto &i : m_library) i->getButton()->setIconSize(QSize(i->getButton()->width(), i->getButton()->width())); } MainWindow::~MainWindow() { delete ui; delete m_dbexec; delete m_netaccman; delete m_songlist; delete m_volume; delete m_player; delete m_radio; delete m_shutdown; for (auto &i : m_library) delete i; } QMediaPlaylist *MainWindow::getPlayList() { return m_playlist; } QMediaPlayer *MainWindow::getPlayer() { return m_player; } QToolButton *MainWindow::getVolume() { return ui->VolumeSound; } QSqlQuery *MainWindow::getQuery() { return m_dbexec; } QString &MainWindow::getUser() { return m_user; } QToolButton *MainWindow::getButton() { return ui->PlayPause; } void MainWindow::moveInPlayList(int from, int to, int current) { auto pos = m_player->position(); m_block = true; ui->Stop->click(); m_playlist->moveMedia(from, to); m_playlist->setCurrentIndex(current); m_block = false; m_player->setPosition(pos); ui->PlayPause->click(); } void MainWindow::setSelect(int index) { m_songlist->selectionModel()->select(m_songlist->currentIndex(), QItemSelectionModel::Deselect); QModelIndex itNew = m_songlist->model()->index(index, 0); m_songlist->selectionModel()->select(itNew, QItemSelectionModel::Select); m_songlist->setCurrentIndex(itNew); ui->SongName->setText(m_songlist->model()->data(itNew).toString()); } void MainWindow::deleteRow(int index) { auto i = m_playlist->currentIndex(); auto pos = m_player->position(); m_playlist->removeMedia(index); m_songlist->model()->removeRow(index); m_playlist->setCurrentIndex(index > i ? i : i - 1 < 0 ? 0 : i - 1); setSelect(index > i ? i : i - 1 < 0 ? 0 : i - 1); m_player->setPosition(pos); if (m_playlist->isEmpty()) { QLayoutItem *item = ui->VideoFr->layout()->takeAt(0); if (item != nullptr) { delete item->widget(); delete item; m_video = new QVideoWidget(this); m_player->setVideoOutput(m_video); } m_songlist->setCurrent(-1); ui->Stop->click(); buttonsEnable(false); ui->SongName->setText("Song name"); ui->SongImg->setText("Song img"); ui->SongPos->setValue(0); } } void MainWindow::changeState(QString user, bool flag) { ui->Screens->setCurrentIndex(flag); m_user = user; ui->actionChangeUser->setEnabled(flag); ui->actionUserSettings->setEnabled(flag); ui->actionDeleteUser->setEnabled(flag); buttonsEnable(false); } void MainWindow::buttonsEnable(bool flag) { ui->ChooseImg->setEnabled(flag); ui->DeleteImg->setEnabled(flag); ui->SaveInfoTag->setEnabled(flag); ui->PalayerToolBar->setEnabled(flag); ui->SongPos->setEnabled(flag); } void MainWindow::setDataBase() { QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "uamp"); db.setHostName("127.0.0.1"); db.setDatabaseName("uamp.db"); db.setUserName("root"); db.setPassword("12345"); if (!db.open()) Message("Database error"); m_dbexec = new QSqlQuery(db); m_dbexec->exec("CREATE TABLE IF NOT EXISTS Users(" "Id INTEGER PRIMARY KEY AUTOINCREMENT," "Name TEXT NOT NULL UNIQUE," "Pass TEXT NOT NULL);"); m_dbexec->exec("CREATE TABLE IF NOT EXISTS Albums(" "User TEXT NOT NULL," "Name TEXT NOT NULL UNIQUE," "Icon BLOB," "Model BLOB);"); } void MainWindow::setDBButtons() { connect(ui->SignIn, &QPushButton::clicked, [this]() { m_dbexec->prepare("SELECT Pass FROM Users WHERE Name = :name;"); m_dbexec->bindValue(":name", ui->LoginInLe->text()); m_dbexec->exec(); if (m_dbexec->first() && m_dbexec->value(0).toString() == ui->PassInLe->text()) { changeState(ui->LoginInLe->text(), true); loadAll(); setShourCut(true); ui->TreeViewSp->setSizes(QList<int>() << width() * 0.6 << width() * 0.4); ui->TagInfoSp->setSizes(QList<int>() << height() * 0.6 << height() * 0.4); ui->ImgBassSp->setSizes(QList<int>() << ui->PlayerFr->width() * 0.5 << ui->PlayerFr->width() * 0.5); } else Message("SignIn error"); }); connect(ui->SignUp, &QPushButton::clicked, [this]() { m_dbexec->prepare("INSERT INTO Users (Name, Pass) VALUES (:name, :pass);"); m_dbexec->bindValue(":name", ui->LoginUpLe->text()); m_dbexec->bindValue(":pass", ui->PassUpLe->text()); if (ui->LoginUpLe->text() == nullptr || ui->PassUpLe->text() == nullptr || !m_dbexec->exec()) Message("SignUp error"); else { changeState(ui->LoginUpLe->text(), true); loadAll(); setShourCut(true); ui->TreeViewSp->setSizes(QList<int>() << width() * 0.6 << width() * 0.4); ui->TagInfoSp->setSizes(QList<int>() << height() * 0.6 << height() * 0.4); ui->ImgBassSp->setSizes(QList<int>() << ui->PlayerFr->width() * 0.5 << ui->PlayerFr->width() * 0.5); } }); connect(ui->actionChangeUser, &QAction::triggered, [this]() { deleteAll(); saveAll(); setShourCut(false); for (auto &i : m_library) { Q_UNUSED(i); ui->LibraryScroll->layout()->takeAt(0)->widget()->deleteLater(); } for (auto &i : m_library) delete i; m_library.clear(); changeState(nullptr, false); ui->Stop->click(); ui->RadioStop->click(); m_playlist->clear(); ui->LoginInLe->clear(); ui->PassInLe->clear(); ui->LoginUpLe->clear(); ui->PassUpLe->clear(); m_volume->setSliderPosition(100); ui->SongListName->clear(); }); connect(ui->actionUserSettings, &QAction::triggered, [this]() { Preferences pref(this); }); connect(ui->actionDeleteUser, &QAction::triggered, [this]() { m_dbexec->prepare("DELETE FROM Users WHERE Name = :name;"); m_dbexec->bindValue(":name", m_user); m_dbexec->exec(); for (auto &i : m_library) { Q_UNUSED(i); ui->LibraryScroll->layout()->takeAt(0)->widget()->deleteLater(); } for (auto &i : m_library) delete i; m_library.clear(); ui->actionChangeUser->trigger(); }); connect(ui->actionAutoShutDown, &QAction::triggered, [this]() { m_shutdown->showWindow(); }); } void MainWindow::setVolumeButton() { ui->VolumeSound->setContextMenuPolicy(Qt::CustomContextMenu); m_volume = new Volume(this); m_volume->setSlider(ui->SongPos); connect(ui->VolumeSound, &QPushButton::customContextMenuRequested, [this]() { QMenu *menu = new QMenu(this); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(m_volume); menu->setLayout(layout); menu->setContentsMargins(0, 0, 0, 0); menu->setStyleSheet("QMenu {background-color: #181B2C; border-radius: 5px; border: 1px solid black;}"); menu->popup(mapToGlobal(QPoint(ui->VolumeSound->pos().x() + ui->VolumeSound->width() + 5, ui->PalayerToolBar->pos().y()))); }); connect(ui->VolumeSound, &QToolButton::clicked, [this]() { m_player->setMuted(ui->VolumeSound->isChecked() ? true : false); ui->VolumeSound->setStyleSheet(ui->VolumeSound->isChecked() ? "image: url(:/img/Volume2.svg);" : "image: url(:/img/Volume1.svg);"); m_volume->setSliderPosition(m_player->isMuted() ? 0 : m_player->volume()); }); } void MainWindow::setSortButton() { connect(ui->Sort, &QPushButton::clicked, [this]() { QMenu *menu = new QMenu(this); QAction *Name = new QAction(tr("Name"), this); QAction *Path = new QAction(tr("Path"), this); connect(Name, &QAction::triggered, [this]() { sortModel("Name"); }); connect(Path, &QAction::triggered, [this]() { sortModel("Path"); }); menu->addAction(Name); menu->addAction(Path); menu->setMinimumWidth(ui->Sort->width()); menu->setMaximumWidth(ui->Sort->width()); menu->setLayoutDirection(Qt::RightToLeft); menu->setContentsMargins(0, 5, 0, 5); menu->setStyleSheet("QMenu {background-color: #181B2C; border-radius: 5px; border: 1px solid black;}"); menu->popup(mapToGlobal(QPoint(ui->TreeViewFr->pos().x() + 5, ui->TreeViewToolBarFr->pos().y() - 25))); }); } void MainWindow::connectButtons() { connect(ui->HideIn, &QPushButton::clicked, [this]() { ui->PassInLe->setEchoMode(ui->HideIn->isChecked() ? QLineEdit::Password : QLineEdit::Normal); if (ui->HideIn->isChecked()) ui->HideIn->setIcon(QIcon(QPixmap(":/img/Eye2.png"))); else ui->HideIn->setIcon(QIcon(QPixmap(":/img/Eye1.png"))); ui->HideIn->setIconSize(QSize(ui->HideIn->width(), ui->HideIn->height())); }); connect(ui->HideUp, &QPushButton::clicked, [this]() { ui->PassUpLe->setEchoMode(ui->HideUp->isChecked() ? QLineEdit::Password : QLineEdit::Normal); if (ui->HideUp->isChecked()) ui->HideUp->setIcon(QIcon(QPixmap(":/img/Eye2.png"))); else ui->HideUp->setIcon(QIcon(QPixmap(":/img/Eye1.png"))); ui->HideUp->setIconSize(QSize(ui->HideUp->width(), ui->HideUp->height())); }); connect(ui->Rep, &QPushButton::clicked, [this]() { m_rep = m_rep == 3 ? 0 : m_rep + 1; if (m_rep == 0) { m_playlist->setPlaybackMode(QMediaPlaylist::Sequential); ui->Rep->setStyleSheet("image: url(:/img/Rep1.svg);"); } else if (m_rep == 1) { m_playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop); ui->Rep->setStyleSheet("image: url(:/img/Rep2.svg);"); } else if (m_rep == 2) { m_playlist->setPlaybackMode(QMediaPlaylist::Loop); ui->Rep->setStyleSheet("image: url(:/img/Rep3.svg);"); } else if (m_rep == 3) { m_playlist->setPlaybackMode(QMediaPlaylist::Random); ui->Rep->setStyleSheet("image: url(:/img/Rep4.svg);"); } }); connect(m_player, &QMediaPlayer::durationChanged, ui->SongPos, &QSlider::setMaximum); connect(m_player, &QMediaPlayer::positionChanged, ui->SongPos, &QSlider::setValue); connect(ui->SongPos, &QSlider::sliderMoved, m_player, &QMediaPlayer::setPosition); connect(m_playlist, &QMediaPlaylist::currentIndexChanged, [this](int pos) { if (m_block) return ; if (pos == -1 && m_rep == 0) { clearAllIfo(); if (ui->PlayPause->isChecked()) ui->PlayPause->click(); buttonsEnable(false); ui->SongName->setText("Song name"); return ; } m_path = m_songlist->model()->index(pos, 1).data().toString(); TagLib::FileRef song(m_path.toStdString().c_str()); if (!song.isNull() && song.tag()) setSongInfo(song); else { Message("TagInfo error"); clearAllIfo(); } buttonsEnable(true); if (!ui->PlayPause->isChecked()) ui->PlayPause->click(); setSelect(pos); }); connect(ui->ChooseImg, &QPushButton::clicked, [this]() { ui->ChooseImgLe->setText(""); QString path = QFileDialog::getOpenFileName(this, tr("Open file"), "~", tr("*.jpg")); ui->ChooseImgLe->setText(path); }); connect(ui->DeleteImg, &QPushButton::clicked, [this]() { ui->ChooseImgLe->setText(""); ui->SongImg->setPixmap(QPixmap(":/img/Note.svg").scaled(ui->SongImg->width(), ui->SongImg->width(), Qt::KeepAspectRatio)); TagLib::MPEG::File audioFile(m_path.toStdString().c_str()); TagLib::ID3v2::Tag *tag = audioFile.ID3v2Tag(true); if (!tag->frameListMap()["APIC"].isEmpty()) tag->removeFrames(tag->frameListMap()["APIC"].front()->frameID()); audioFile.save(); }); connect(m_netaccman, &QNetworkAccessManager::finished, [this](QNetworkReply *reply) { QPixmap img; img.loadFromData(reply->readAll()); QString fileName = QFileDialog::getSaveFileName(this, "Save File", ".", "*.jpg"); QFile file(fileName); file.open(QIODevice::WriteOnly); if (img.save(&file)) { ImageFile::getImageFile(fileName.toStdString())->setArt(m_path.toStdString()); getImg(ui->SongImg); } }); connect(ui->SaveInfoTag, &QPushButton::clicked, [this]() { if (ui->ChooseImgLe->text().size() != 0 && (m_path.right(4) == ".mp3" || m_path.right(4) == ".mp4")) { if (QFileInfo(ui->ChooseImgLe->text()).isFile() && QFileInfo(ui->ChooseImgLe->text()).isReadable()) { ui->SongImg->setPixmap(QPixmap(ui->ChooseImgLe->text())); ImageFile::getImageFile(ui->ChooseImgLe->text().toStdString())->setArt(m_path.toStdString()); } else m_netaccman->get(QNetworkRequest(QUrl(ui->ChooseImgLe->text()))); } saveInfo(); }); } void MainWindow::createPlayer() { m_songlist = new Table(this); m_player = new QMediaPlayer(this); m_video = new QVideoWidget(this); m_playlist = new QMediaPlaylist(m_player); ui->VideoFr->layout()->addWidget(m_video); ui->SongListFr->layout()->addWidget(m_songlist); m_player->setPlaylist(m_playlist); m_player->setVolume(100); m_player->setVideoOutput(m_video); m_playlist->setPlaybackMode(QMediaPlaylist::Sequential); } void MainWindow::playerButtons() { connect(ui->PrevSong, &QToolButton::clicked, [this]() { m_playlist->previous(); ui->Stop->click(); ui->PlayPause->click(); }); connect(ui->NextSong, &QToolButton::clicked, [this]() { m_playlist->next(); ui->Stop->click(); ui->PlayPause->click(); }); connect(ui->PlayPause, &QToolButton::clicked, [this]() { m_radio->stop(); ui->PlayPause->isChecked() ? m_player->play() : m_player->pause(); ui->PlayPause->setStyleSheet(ui->PlayPause->isChecked() ? "image: url(:/img/Pause.svg);" : "image: url(:/img/Play.svg);"); }); connect(ui->Stop, &QToolButton::clicked, [this]() { if (ui->PlayPause->isChecked()) ui->PlayPause->click(); m_player->stop(); ui->SongPos->setValue(0); }); connect(ui->Forward, &QToolButton::clicked, [this]() { m_player->setPosition(m_player->position() + 10000); }); connect(ui->Rewind, &QToolButton::clicked, [this]() { m_player->setPosition(m_player->position() - 10000); }); } void MainWindow::createRadio() { m_radio = new QMediaPlayer(this); m_radio->setVolume(100); ui->RadioVolume->setValue(100); } void MainWindow::radioButtons() { connect(ui->RadioPlay, &QToolButton::clicked, [this]() { m_player->stop(); m_radio->stop(); m_radio->play(); }); connect(ui->RadioStop, &QToolButton::clicked, m_radio, &QMediaPlayer::stop); connect(ui->RadioVolume, &QDial::valueChanged, m_radio, &QMediaPlayer::setVolume); connect(ui->KissFm, &QPushButton::clicked, [this]() { m_radio->setMedia(QUrl("http://online.kissfm.ua/KissFM_HD")); ui->RadioPlay->click(); ui->RadioWaveName->setText("Now Playing: Kiss FM"); }); connect(ui->XitFm, &QPushButton::clicked, [this]() { m_radio->setMedia(QUrl("http://online.hitfm.ua/HitFM_HD")); ui->RadioPlay->click(); ui->RadioWaveName->setText("Now Playing: Xit FM"); }); connect(ui->RadioRoks, &QPushButton::clicked, [this]() { m_radio->setMedia(QUrl("http://online.radioroks.ua/RadioROKS_HD")); ui->RadioPlay->click(); ui->RadioWaveName->setText("Now Playing: Radio Roks"); }); connect(ui->NasheRadio, &QPushButton::clicked, [this]() { m_radio->setMedia(QUrl("http://online.nasheradio.ua/NasheRadio_HD")); ui->RadioPlay->click(); ui->RadioWaveName->setText("Now Playing: Наше Радіо"); }); connect(ui->RadioRelax, &QPushButton::clicked, [this]() { m_radio->setMedia(QUrl("http://online.radiorelax.ua/RadioRelax_HD")); ui->RadioPlay->click(); ui->RadioWaveName->setText("Now Playing: Radio Relax"); }); connect(ui->MelodiyaFm, &QPushButton::clicked, [this]() { m_radio->setMedia(QUrl("http://online.melodiafm.ua/MelodiaFM_HD")); ui->RadioPlay->click(); ui->RadioWaveName->setText("Now Playing: Мелодія FM"); }); connect(ui->RussRadio, &QPushButton::clicked, [this]() { m_radio->setMedia(QUrl("http://online.rusradio.ua/RusRadio_HD")); ui->RadioPlay->click(); ui->RadioWaveName->setText("Now Playing: Русское Радио"); }); connect(ui->RadioGold, &QPushButton::clicked, [this]() { m_radio->setMedia(QUrl("http://online.radioplayer.ua/RadioGold_HD")); ui->RadioPlay->click(); ui->RadioWaveName->setText("Now Playing: Radio Gold"); }); connect(ui->RadioJazz, &QPushButton::clicked, [this]() { m_radio->setMedia(QUrl("http://online.radiojazz.ua/RadioJazz_HD")); ui->RadioPlay->click(); ui->RadioWaveName->setText("Now Playing: Radio Jazz"); }); } void MainWindow::libraryButtons() { connect(ui->AddNewPlayList, &QPushButton::clicked, [this]() { if (ui->SongListName->text().isEmpty() || checkAlbumName(ui->SongListName->text())) { Message("Playlist error"); return ; } newAlbum(ui->SongListName->text(), m_songlist->getModel()); }); connect(ui->BackToDefault, &QPushButton::clicked, [this]() { libraryEnabled(true); ui->Stop->click(); ui->SongListName->setText(""); ui->SongName->setText("Song name"); m_playlist->clear(); m_songlist->setModel(nullptr); Model *newModel = new Model(m_songlist); m_songlist->setModel(newModel); m_songlist->setMyModel(newModel); m_songlist->setCurrent(0); buttonsEnable(false); }); connect(ui->ImportPlayList, &QPushButton::clicked, [this]() { QString fileName = QFileDialog::getOpenFileName(this, "Choose Playlist", ".", "*.m3u"); Model *newModel = new Model; QFile f(fileName); if (f.open(QFile::ReadOnly)) { QTextStream s(&f); QString song; while (!s.atEnd()) { song = s.readLine(); song = song.right(song.size() - 8); QList<QStandardItem *> items; items.append(new QStandardItem(QDir(song).dirName())); items.append(new QStandardItem(song)); newModel->appendRow(items); } } else { Message("Import error"); return ; } newAlbum(QFileInfo(fileName).baseName(), newModel); }); } void MainWindow::libraryEnabled(bool flag) { ui->SongListName->setEnabled(flag); ui->BackToDefault->setEnabled(flag ? false : true); } void MainWindow::choseAlbum(Album *album) { ui->BackToDefault->click(); libraryEnabled(false); ui->SongListName->setText(album->getAlbumName()); for (int i = 0; i < album->getModel()->rowCount(); i++) m_playlist->addMedia(QUrl::fromLocalFile(album->getModel()->index(i, 1).data().toString())); m_songlist->setModel(album->getModel()); m_songlist->setMyModel(album->getModel()); ui->AMPTw->setCurrentIndex(0); } void MainWindow::deleteAlbum(Album *album) { int count = 0; for (auto &i : m_library) { if (i->getAlbumName() == album->getAlbumName()) { ui->LibraryScroll->layout()->takeAt(count)->widget()->deleteLater(); m_library.remove(count); break; } count++; } if (m_songlist->getModel() == album->getModel()) ui->BackToDefault->click(); } void MainWindow::newAlbum(QString name, Model *model) { Album *newALbum = new Album(this); newALbum->setAlbumName(name); newALbum->setModel(model); m_library.push_back(newALbum); libraryEnabled(false); ui->LibraryScroll->layout()->addWidget(newALbum); } bool MainWindow::changwAlbumName(QString name, Album *album) { if (checkAlbumName(name)) { album->setAlbumName(album->getAlbumName()); return false; } if (m_songlist->getModel() == album->getModel()) ui->SongListName->setText(name); return true; } bool MainWindow::checkAlbumName(QString name) { for (auto &i : m_library) if (i->getAlbumName() == name) return true; return false; } void MainWindow::loadAll() { m_dbexec->prepare("SELECT * FROM Albums WHERE User = :user"); m_dbexec->bindValue(":user", m_user); m_dbexec->exec(); while (m_dbexec->next() == true) { QString name = m_dbexec->value(1).toString(); QByteArray arrayIcon = m_dbexec->value(2).toByteArray(); QPixmap *newIcon = new QPixmap; if (arrayIcon.size() > 0) newIcon->loadFromData(arrayIcon); QByteArray arrayModel = m_dbexec->value(3).toByteArray(); QDataStream stream(&arrayModel, QIODevice::ReadWrite); Model *newModel = new Model; Album *newALbum = new Album(this); newALbum->setAlbumName(name); newALbum->setModel(newModel); newALbum->desModel(stream); if (arrayIcon.size() != 0) newALbum->setPixMap(newIcon); m_library.push_back(newALbum); ui->LibraryScroll->layout()->addWidget(newALbum); } } void MainWindow::saveAll() { for (auto &i : m_library) { m_dbexec->prepare("INSERT INTO Albums (User, Name, Icon, Model) VALUES (:user, :name, :icon, :model);"); m_dbexec->bindValue(":user", m_user); m_dbexec->bindValue(":name", i->getAlbumName()); QPixmap *inPixmap = i->getPixMap(); QByteArray arrayIcon; if (inPixmap != nullptr) { QBuffer inBuffer(&arrayIcon); inBuffer.open(QIODevice::WriteOnly); inPixmap->save(&inBuffer, "PNG"); } m_dbexec->bindValue(":icon", arrayIcon); QByteArray arrayModel; QDataStream stream(&arrayModel, QIODevice::ReadWrite); i->serModel(stream); m_dbexec->bindValue(":model", arrayModel); m_dbexec->exec(); } } void MainWindow::deleteAll() { m_dbexec->prepare("DELETE FROM Albums WHERE User = :name;"); m_dbexec->bindValue(":name", m_user); m_dbexec->exec(); ui->BackToDefault->click(); ui->AMPTw->setCurrentIndex(0); } void MainWindow::closeEvent(QCloseEvent *event) { if (m_user != nullptr) { m_player->stop(); m_radio->stop(); ui->actionChangeUser->trigger(); } event->accept(); } void MainWindow::setLyrics(QString lyrics) { TagLib::MPEG::File file(m_path.toStdString().c_str()); TagLib::ID3v2::FrameList frames = file.ID3v2Tag()->frameListMap()["USLT"]; TagLib::ID3v2::UnsynchronizedLyricsFrame *frame = new TagLib::ID3v2::UnsynchronizedLyricsFrame; if (!file.ID3v2Tag()->frameListMap()["USLT"].isEmpty()) file.ID3v2Tag()->removeFrames(file.ID3v2Tag()->frameListMap()["USLT"].front()->frameID()); frame->setText(lyrics.toStdString().c_str()); file.ID3v2Tag()->addFrame(frame); file.save(); } void MainWindow::getImg(QLabel *label) { TagLib::MPEG::File file(m_path.toStdString().c_str()); TagLib::ID3v2::Tag *m_tag = file.ID3v2Tag(true); TagLib::ID3v2::FrameList frameList = m_tag->frameList("APIC"); if(frameList.isEmpty()) { label->setPixmap(QPixmap(":/img/Note.svg").scaled(200, 200, Qt::KeepAspectRatio)); return ; } TagLib::ID3v2::AttachedPictureFrame *coverImg = static_cast<TagLib::ID3v2::AttachedPictureFrame *>(frameList.front()); QImage coverQImg; coverQImg.loadFromData((const uchar *)coverImg->picture().data(), coverImg->picture().size()); QPixmap pix = QPixmap::fromImage(coverQImg).scaled( label->width(), label->height(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation ); QBitmap map(pix.width(), pix.height()); map.fill(Qt::color0); QPainter painter(&map); painter.setBrush(Qt::color1); painter.drawRoundedRect(0, 0, pix.width(), pix.height(), 50, 50); pix.setMask(map); label->setPixmap(pix.scaled(200, 200, Qt::KeepAspectRatio)); } QString MainWindow::getLyrics() { TagLib::String lyrics; TagLib::MPEG::File file(m_path.toStdString().c_str()); TagLib::ID3v2::FrameList frames = file.ID3v2Tag()->frameListMap()["USLT"]; TagLib::ID3v2::UnsynchronizedLyricsFrame *frame = NULL; if (!frames.isEmpty()) { frame = dynamic_cast<TagLib::ID3v2::UnsynchronizedLyricsFrame *>(frames.front()); if (frame) lyrics = frame->text(); } return lyrics.toCString(true); } void MainWindow::setSongInfo(TagLib::FileRef song) { clearAllIfo(); ui->AlbumLe->setText(song.tag()->album().toCString()); ui->ArtistLe->setText(song.tag()->artist().toCString()); ui->CommentLe->setText(song.tag()->comment().toCString()); ui->GenreLe->setText(song.tag()->genre().toCString()); ui->TitleLe->setText(song.tag()->title().toCString()); ui->YearLe->setText(TagLib::String::number(song.tag()->year()).toCString()); ui->TrackLe->setText(TagLib::String::number(song.tag()->track()).toCString()); ui->LyricsTe->setText(getLyrics()); getImg(ui->SongImg); } void MainWindow::saveInfo() { TagLib::FileRef song(m_path.toStdString().c_str()); if (!song.isNull() && song.tag()) { song.tag()->setAlbum(ui->AlbumLe->text().toStdString().empty() ? "" : ui->AlbumLe->text().toStdString()); song.tag()->setArtist(ui->ArtistLe->text().toStdString().empty() ? "" : ui->ArtistLe->text().toStdString()); song.tag()->setComment(ui->CommentLe->text().toStdString().empty() ? "" : ui->CommentLe->text().toStdString()); song.tag()->setGenre(ui->GenreLe->text().toStdString().empty() ? "" : ui->GenreLe->text().toStdString()); song.tag()->setTitle(ui->TitleLe->text().toStdString().empty() ? "" : ui->TitleLe->text().toStdString()); song.tag()->setYear(ui->YearLe->text().toInt()); song.tag()->setTrack(ui->TrackLe->text().toInt()); song.save(); if (m_path.right(4) == ".mp3" || m_path.right(4) == ".mp4") { setLyrics(ui->LyricsTe->toPlainText()); getImg(ui->SongImg); } } else { Message("Save error"); clearAllIfo(); } } void MainWindow::clearAllIfo() { ui->AlbumLe->clear(); ui->ArtistLe->clear(); ui->CommentLe->clear(); ui->GenreLe->clear(); ui->TitleLe->clear(); ui->YearLe->clear(); ui->TrackLe->clear(); ui->LyricsTe->clear(); } void MainWindow::sortModel(QString type) { ui->Stop->click(); m_playlist->clear(); m_songlist->setSortingEnabled(true); if (type == "Name") m_songlist->sortByColumn(0, Qt::SortOrder::DescendingOrder); else m_songlist->sortByColumn(1, Qt::SortOrder::DescendingOrder); for (int i = 0; i < m_songlist->model()->rowCount() - 1; i++) m_playlist->addMedia(QUrl::fromLocalFile(m_songlist->model()->index(i, 1).data().toString())); m_songlist->setSortingEnabled(false); } void MainWindow::resizeEvent(QResizeEvent *event) { QMainWindow::resizeEvent(event); if (!m_resize) { m_resize = true; return ; } for (auto &i : m_library) i->getButton()->setIconSize(QSize(i->getButton()->width() / 2, i->getButton()->width() / 2)); } void MainWindow::macosArea() { ui->LoginUpLe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->PassUpLe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->LoginInLe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->PassInLe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->SongListName->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->AlbumLe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->ArtistLe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->CommentLe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->GenreLe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->TitleLe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->YearLe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->TrackLe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->LyricsTe->setAttribute(Qt::WA_MacShowFocusRect, 0); ui->HideIn->setIcon(QIcon(QPixmap(":/img/Eye1.png"))); ui->HideIn->setIconSize(QSize(ui->HideIn->width(), ui->HideIn->height())); ui->HideUp->setIcon(QIcon(QPixmap(":/img/Eye1.png"))); ui->HideUp->setIconSize(QSize(ui->HideUp->width(), ui->HideUp->height())); ui->YearLe->setValidator(new QIntValidator(0, 100000000, this)); ui->TrackLe->setValidator(new QIntValidator(0, 100000000, this)); } void MainWindow::setShourCut(bool flag) { ui->NextSong->setShortcut(flag ? QKeySequence(Qt::CTRL + Qt::Key_N) : QKeySequence::NoMatch); ui->PrevSong->setShortcut(flag ? QKeySequence(Qt::CTRL + Qt::Key_B) : QKeySequence::NoMatch); ui->Stop->setShortcut(flag ? QKeySequence(Qt::CTRL + Qt::Key_S) : QKeySequence::NoMatch); ui->PlayPause->setShortcut(flag ? QKeySequence(Qt::CTRL + Qt::Key_P) : QKeySequence::NoMatch); ui->Rewind->setShortcut(flag ? QKeySequence(Qt::CTRL + Qt::Key_R) : QKeySequence::NoMatch); ui->Forward->setShortcut(flag ? QKeySequence(Qt::CTRL + Qt::Key_F) : QKeySequence::NoMatch); ui->VolumeSound->setShortcut(flag ? QKeySequence(Qt::CTRL + Qt::Key_V) : QKeySequence::NoMatch); } void MainWindow::keyPressEvent(QKeyEvent *event) { if(event->key() == Qt::Key_Return) { if (ui->SongListName->hasFocus()) { ui->AddNewPlayList->click(); ui->AMPTw->setCurrentIndex(1); } else if (ui->LoginInLe->hasFocus()) ui->SignIn->click(); else if (ui->PassInLe->hasFocus()) ui->SignIn->click(); else if (ui->LoginUpLe->hasFocus()) ui->SignUp->click(); else if (ui->PassUpLe->hasFocus()) ui->SignUp->click(); else QMainWindow::keyPressEvent(event); } else QMainWindow::keyPressEvent(event); }
38.420859
130
0.601923
[ "model", "solid" ]
0f570fa4352e3b0f3a2d3bf6f49678234539a483
2,283
hpp
C++
glm/glm/gtx/component_wise.hpp
gregsimon/shaderharness
22e7229c490bbca1a9cce4426f64a784edf6e8cf
[ "BSD-3-Clause" ]
1,851
2017-03-24T00:08:21.000Z
2022-03-29T21:14:30.000Z
glm/glm/gtx/component_wise.hpp
gregsimon/shaderharness
22e7229c490bbca1a9cce4426f64a784edf6e8cf
[ "BSD-3-Clause" ]
964
2017-03-24T01:20:31.000Z
2022-03-28T14:18:30.000Z
glm/glm/gtx/component_wise.hpp
gregsimon/shaderharness
22e7229c490bbca1a9cce4426f64a784edf6e8cf
[ "BSD-3-Clause" ]
458
2017-05-17T09:04:01.000Z
2022-03-31T11:52:07.000Z
/// @ref gtx_component_wise /// @file glm/gtx/component_wise.hpp /// @date 2007-05-21 / 2011-06-07 /// @author Christophe Riccio /// /// @see core (dependence) /// /// @defgroup gtx_component_wise GLM_GTX_component_wise /// @ingroup gtx /// /// @brief Operations between components of a type /// /// <glm/gtx/component_wise.hpp> need to be included to use these functionalities. #pragma once // Dependencies #include "../detail/setup.hpp" #include "../detail/precision.hpp" #if GLM_MESSAGES == GLM_MESSAGES_ENABLED && !defined(GLM_EXT_INCLUDED) # pragma message("GLM: GLM_GTX_component_wise extension included") #endif namespace glm { /// @addtogroup gtx_component_wise /// @{ /// Convert an integer vector to a normalized float vector. /// If the parameter value type is already a floating precision type, the value is passed through. /// @see gtx_component_wise template <typename floatType, typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_DECL vecType<floatType, P> compNormalize(vecType<T, P> const & v); /// Convert a normalized float vector to an integer vector. /// If the parameter value type is already a floating precision type, the value is passed through. /// @see gtx_component_wise template <typename T, typename floatType, precision P, template <typename, precision> class vecType> GLM_FUNC_DECL vecType<T, P> compScale(vecType<floatType, P> const & v); /// Add all vector components together. /// @see gtx_component_wise template <typename genType> GLM_FUNC_DECL typename genType::value_type compAdd(genType const & v); /// Multiply all vector components together. /// @see gtx_component_wise template <typename genType> GLM_FUNC_DECL typename genType::value_type compMul(genType const & v); /// Find the minimum value between single vector components. /// @see gtx_component_wise template <typename genType> GLM_FUNC_DECL typename genType::value_type compMin(genType const & v); /// Find the maximum value between single vector components. /// @see gtx_component_wise template <typename genType> GLM_FUNC_DECL typename genType::value_type compMax(genType const & v); /// @} }//namespace glm #include "component_wise.inl"
34.590909
102
0.727113
[ "vector" ]
0f57d26225e8ae079fb096212537fc25a1251594
6,390
cc
C++
tensorflow/core/kernels/sparse_to_dense_op.cc
ryan-collins-forks/tensorflow
080a1f6c64976b11437d2dc4ef4178e4ca1205b7
[ "Apache-2.0" ]
null
null
null
tensorflow/core/kernels/sparse_to_dense_op.cc
ryan-collins-forks/tensorflow
080a1f6c64976b11437d2dc4ef4178e4ca1205b7
[ "Apache-2.0" ]
null
null
null
tensorflow/core/kernels/sparse_to_dense_op.cc
ryan-collins-forks/tensorflow
080a1f6c64976b11437d2dc4ef4178e4ca1205b7
[ "Apache-2.0" ]
1
2019-11-15T21:19:42.000Z
2019-11-15T21:19:42.000Z
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See core/ops/sparse_ops.cc for documentation. // // NOTE: the operations in this file only are suitable for execution // on CPUs. #define EIGEN_USE_THREADS #include <sstream> #include <string> #include <unordered_map> #include <utility> #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/public/status.h" #include "tensorflow/core/public/tensor.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" namespace tensorflow { // Operator to convert sparse representations to dense. template <typename T, typename Index> class SparseToDense : public OpKernel { public: explicit SparseToDense(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("validate_indices", &validate_indices_)); } void Compute(OpKernelContext* c) override { // sparse_indices const Tensor& indices = c->input(0); OP_REQUIRES(c, indices.dims() <= 2, errors::InvalidArgument( "sparse_indices should be a scalar, vector, or matrix, " "got shape ", indices.shape().ShortDebugString())); const int64 num_elems = indices.dims() > 0 ? indices.dim_size(0) : 1; const int64 num_dims = indices.dims() > 1 ? indices.dim_size(1) : 1; // output_shape const Tensor& output_shape = c->input(1); OP_REQUIRES( c, IsLegacyVector(output_shape.shape()), errors::InvalidArgument("output_shape should be a vector, got shape ", output_shape.shape().ShortDebugString())); OP_REQUIRES(c, output_shape.NumElements() == num_dims, errors::InvalidArgument( "output_shape has incorrect number of elements: ", output_shape.NumElements(), " should be: ", num_dims)); // sparse_values const Tensor& sparse_values = c->input(2); const int64 num_values = sparse_values.NumElements(); OP_REQUIRES( c, sparse_values.dims() == 0 || (sparse_values.dims() == 1 && num_values == num_elems), errors::InvalidArgument("sparse_values has incorrect shape ", sparse_values.shape().ShortDebugString(), ", should be [] or [", num_elems, "]")); // default_value const Tensor& default_value = c->input(3); OP_REQUIRES(c, TensorShapeUtils::IsScalar(default_value.shape()), errors::InvalidArgument("default_value should be a scalar.")); auto output_shape_vec = output_shape.flat<Index>(); TensorShape output_tensor_shape; OP_REQUIRES_OK(c, TensorShapeUtils::MakeShape(output_shape_vec.data(), output_shape_vec.size(), &output_tensor_shape)); Tensor* output = nullptr; OP_REQUIRES_OK(c, c->allocate_output(0, output_tensor_shape, &output)); TensorShape ix_shape({num_elems, num_dims}); Tensor indices_shaped(DT_INT64, ix_shape); if (indices.dtype() == DT_INT64) { CHECK(indices_shaped.CopyFrom(indices, ix_shape)); } else { indices_shaped.matrix<int64>() = indices.shaped<Index, 2>(ix_shape.dim_sizes()).template cast<int64>(); } // If we received a scalar, we'll need to create a new // tensor with copies of the values as a vec. // TODO(ebrevdo): find a way to avoid this temp allocation. Tensor sparse_values_b; if (TensorShapeUtils::IsScalar(sparse_values.shape())) { OP_REQUIRES_OK( c, c->allocate_temp(DataTypeToEnum<T>::value, TensorShape({num_elems}), &sparse_values_b)); sparse_values_b.vec<T>().setConstant(sparse_values.scalar<T>()()); } else { sparse_values_b = sparse_values; } // Assume SparseTensor is lexicographically sorted. gtl::InlinedVector<int64, 8> order(output->shape().dims()); std::iota(order.begin(), order.end(), 0); sparse::SparseTensor st(indices_shaped, sparse_values_b, output->shape(), order); if (validate_indices_) { OP_REQUIRES(c, st.IndicesValid(), errors::InvalidArgument("Indices are not valid: not " "lexicographically sorted or " "containing repeats.")); } output->flat<T>().setConstant(default_value.scalar<T>()()); OP_REQUIRES(c, st.template ToDense<T>(output, false /* initialize */), errors::InvalidArgument( "Indices are not valid (out of bounds). Shape: ", output->shape().DebugString())); } private: bool validate_indices_; }; #define REGISTER_KERNELS(type, index_type) \ REGISTER_KERNEL_BUILDER(Name("SparseToDense") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T") \ .TypeConstraint<index_type>("Tindices"), \ SparseToDense<type, index_type>); #define REGISTER_KERNELS_ALL(type) \ REGISTER_KERNELS(type, int32); \ REGISTER_KERNELS(type, int64); TF_CALL_REAL_NUMBER_TYPES(REGISTER_KERNELS_ALL); REGISTER_KERNELS_ALL(bool); REGISTER_KERNELS_ALL(string); #undef REGISTER_KERNELS_ALL #undef REGISTER_KERNELS } // namespace tensorflow
39.9375
80
0.6277
[ "shape", "vector" ]
0f57d5bb8cc63fcb0202e55b6c93c56c92af56c7
2,846
cpp
C++
src/mongo/scripting/v8_wrapper.cpp
spencerjackson/mongo
51c46e71c9f310fc91168c0945ffa6cfc00d380b
[ "Apache-2.0" ]
null
null
null
src/mongo/scripting/v8_wrapper.cpp
spencerjackson/mongo
51c46e71c9f310fc91168c0945ffa6cfc00d380b
[ "Apache-2.0" ]
null
null
null
src/mongo/scripting/v8_wrapper.cpp
spencerjackson/mongo
51c46e71c9f310fc91168c0945ffa6cfc00d380b
[ "Apache-2.0" ]
1
2021-02-28T12:03:02.000Z
2021-02-28T12:03:02.000Z
// v8_wrapper.cpp /* Copyright 2009 10gen Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "v8_wrapper.h" #include "v8_utils.h" #include "v8_db.h" #include "engine_v8.h" #include <iostream> using namespace std; using namespace v8; namespace mongo { #define DDD(x) // --- object wrapper --- class WrapperHolder { public: WrapperHolder( V8Scope* scope, const BSONObj * o , bool readOnly , bool iDelete ) : _scope(scope), _o(o), _readOnly( readOnly ), _iDelete( iDelete ) { } ~WrapperHolder() { if ( _o && _iDelete ) { delete _o; } _o = 0; } v8::Handle<v8::Value> get( v8::Local<v8::String> name ) { const string& s = toSTLString( name ); const BSONElement& e = _o->getField( s ); return _scope->mongoToV8Element(e); } V8Scope* _scope; const BSONObj * _o; bool _readOnly; bool _iDelete; }; WrapperHolder * createWrapperHolder( V8Scope* scope, const BSONObj * o , bool readOnly , bool iDelete ) { return new WrapperHolder( scope, o , readOnly , iDelete ); } WrapperHolder * getWrapper( v8::Handle<v8::Object> o ) { Handle<v8::Value> t = o->GetRealNamedProperty( v8::String::New( "_wrapper" ) ); assert( t->IsExternal() ); Local<External> c = External::Cast( *t ); WrapperHolder * w = (WrapperHolder*)(c->Value()); assert( w ); return w; } Handle<Value> wrapperCons(V8Scope* scope, const Arguments& args) { if ( ! ( args.Length() == 1 && args[0]->IsExternal() ) ) return v8::ThrowException( v8::String::New( "wrapperCons needs 1 External arg" ) ); args.This()->Set( v8::String::New( "_wrapper" ) , args[0] ); return v8::Undefined(); } v8::Handle<v8::Value> wrapperGetHandler( v8::Local<v8::String> name, const v8::AccessorInfo &info) { return getWrapper( info.This() )->get( name ); } v8::Handle<v8::FunctionTemplate> getObjectWrapperTemplate(V8Scope* scope) { v8::Handle<v8::FunctionTemplate> t = scope->createV8Function(wrapperCons); t->InstanceTemplate()->SetNamedPropertyHandler( wrapperGetHandler ); return t; } }
30.934783
109
0.607871
[ "object" ]
0f692de387f814782395b0036b8d949497586a46
7,305
cpp
C++
windows/pw6e.official/CPlusPlus/Chapter13/FingerPaint5/FingerPaint5/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
1
2016-11-23T08:18:08.000Z
2016-11-23T08:18:08.000Z
windows/pw6e.official/CPlusPlus/Chapter13/FingerPaint5/FingerPaint5/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
null
null
null
windows/pw6e.official/CPlusPlus/Chapter13/FingerPaint5/FingerPaint5/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
1
2016-11-23T08:17:34.000Z
2016-11-23T08:17:34.000Z
// // MainPage.xaml.cpp // Implementation of the MainPage class. // #include "pch.h" #include "MainPage.xaml.h" using namespace FingerPaint5; using namespace DirectX; using namespace Platform; using namespace Platform::Collections; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::System; using namespace Windows::UI; using namespace Windows::UI::Input; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::UI::Xaml::Shapes; MainPage::MainPage() { InitializeComponent(); pointerDictionary = ref new Map<unsigned int, PointerInfo^>(); srand(int(time(NULL))); } void MainPage::OnPointerPressed(PointerRoutedEventArgs^ args) { // Get information from event arguments unsigned int id = args->Pointer->PointerId; PointerPoint^ pointerPoint = args->GetCurrentPoint(this); // Create random color unsigned char r = unsigned char((rand() % 256)); unsigned char g = unsigned char((rand() % 256)); unsigned char b = unsigned char((rand() % 256)); Color color = ColorHelper::FromArgb(255, r, g, b); // Create PointerInfo PointerInfo^ pointerInfo = ref new PointerInfo(); pointerInfo->PreviousPoint = pointerPoint->Position; pointerInfo->PreviousRadius = 24 * pointerPoint->Properties->Pressure; pointerInfo->Brush = ref new SolidColorBrush(color); // Add to dictionary pointerDictionary->Insert(id, pointerInfo); // Capture the Pointer CapturePointer(args->Pointer); } void MainPage::OnPointerMoved(PointerRoutedEventArgs^ args) { // Get information from event arguments unsigned int id = args->Pointer->PointerId; // If ID is in dictionary, create a new Line element and add to Grid if (pointerDictionary->HasKey(id)) { PointerInfo^ pointerInfo = pointerDictionary->Lookup(id); IVector<PointerPoint^>^ pointerPoints = args->GetIntermediatePoints(this); for (int i = pointerPoints->Size - 1; i >= 0; i--) { PointerPoint^ pointerPoint = pointerPoints->GetAt(i); // For each point, create a Path element and add to Grid Point point = pointerPoint->Position; float pressure = pointerPoint->Properties->Pressure; float radius = 12 * pressure; Geometry^ geometry = CreateTaperedLineGeometry(pointerInfo->PreviousPoint, pointerInfo->PreviousRadius, point, radius); Path^ path = ref new Path(); path->Data = geometry; path->Fill = pointerInfo->Brush; contentGrid->Children->Append(path); // Update PointerInfo pointerInfo->PreviousPoint = point; pointerInfo->PreviousRadius = radius; } } } void MainPage::OnPointerReleased(PointerRoutedEventArgs^ args) { // Get information from event arguments unsigned int id = args->Pointer->PointerId; // If ID is in dictionary, remove it if (pointerDictionary->HasKey(id)) pointerDictionary->Remove(id); } void MainPage::OnPointerCaptureLost(PointerRoutedEventArgs^ args) { // Get information from event arguments unsigned int id = args->Pointer->PointerId; // If ID is in dictionary, remove it if (pointerDictionary->HasKey(id)) pointerDictionary->Remove(id); } Geometry^ MainPage::CreateTaperedLineGeometry(Point c0, float r0, Point c1, float r1) { // Swap the centers and radii so that c0 is // the center of the smaller circle if (r1 < r0) { Point point = c0; c0 = c1; c1 = point; float radius = r0; r0 = r1; r1 = radius; } // Get vector from C1 to c0 XMVECTOR vC0 = XMVectorSet(c0.X, c0.Y, 0, 0); XMVECTOR vC1 = XMVectorSet(c1.X, c1.Y, 0, 0); XMVECTOR vCenters = vC0 - vC1; // Get lenth and normalized versions float d = XMVectorGetX(XMVector2Length(vCenters)); vCenters = XMVector2Normalize(vCenters); // Determine if one circle is enclosed in the other bool enclosed = r0 + d < r1; // Define tangent points derived in both algorithms XMVECTOR t0R; XMVECTOR t0L; XMVECTOR t1R; XMVECTOR t1L; // Case for two circles of same size if (r0 == r1 || enclosed) { // Rotate centers vector 90 degrees XMVECTOR vLeft = XMVector2Orthogonal(vCenters); // Rotate -90 degrees XMVECTOR vRight = -vLeft; // Find tangent points t0R = vC0 + r0 * vRight; t0L = vC0 + r0 * vLeft; t1R = vC1 + r1 * vRight; t1L = vC1 + r1 * vLeft; } // A bit more difficult for two circles of unequal size else { // Create focal point F extenting from c0 float e = d * r0 / (r1 - r0); XMVECTOR F = vC0 + e * vCenters; // Find angle and length of right-triangle legs float alpha = (float)asin(r0 / e); float leg0 = (float)sqrt(e * e - r0 * r0); float leg1 = (float)sqrt((e + d) * (e + d) - r1 * r1); // Vectors of tangent lines XMVECTOR vRight = -XMVector2Transform(vCenters, XMMatrixRotationZ(alpha)); XMVECTOR vLeft = -XMVector2Transform(vCenters, XMMatrixRotationZ(-alpha)); // Find tangent vector t0R = F + leg0 * vRight; t0L = F + leg0 * vLeft; t1R = F + leg1 * vRight; t1L = F + leg1 * vLeft; } // Create PathGeometry with implied closing line PathGeometry^ pathGeometry = ref new PathGeometry(); PathFigure^ pathFigure = ref new PathFigure(); pathFigure->StartPoint = Point(XMVectorGetX(t0R), XMVectorGetY(t0R)); pathFigure->IsClosed = true; pathFigure->IsFilled = true; pathGeometry->Figures->Append(pathFigure); // Arc around smaller circle ArcSegment^ arc0Segment = ref new ArcSegment(); arc0Segment->Point = Point(XMVectorGetX(t0L), XMVectorGetY(t0L)); arc0Segment->Size = Size(r0, r0); arc0Segment->SweepDirection = SweepDirection::Clockwise; arc0Segment->IsLargeArc = false; pathFigure->Segments->Append(arc0Segment); // Line connecting smaller circle to larger circle LineSegment^ lineSegment = ref new LineSegment(); lineSegment->Point = Point(XMVectorGetX(t1L), XMVectorGetY(t1L)); pathFigure->Segments->Append(lineSegment); // Arc around larger cirlce ArcSegment^ arc1Segment = ref new ArcSegment(); arc1Segment->Point = Point(XMVectorGetX(t1R), XMVectorGetY(t1R)); arc1Segment->Size = Size(r1, r1); arc1Segment->SweepDirection = SweepDirection::Clockwise; arc1Segment->IsLargeArc = true; pathFigure->Segments->Append(arc1Segment); return pathGeometry; }
33.356164
86
0.627105
[ "geometry", "vector" ]
0f6ae1d72ecd434afc9b64841cdc23bb3bbdad4c
1,982
cpp
C++
src/main.cpp
zeffii/glucose_graph
5c8aa02cd448425a2cc2044dc025b323290d9380
[ "MIT" ]
null
null
null
src/main.cpp
zeffii/glucose_graph
5c8aa02cd448425a2cc2044dc025b323290d9380
[ "MIT" ]
2
2021-01-08T08:46:17.000Z
2021-01-09T14:55:58.000Z
src/main.cpp
zeffii/glucose_graph
5c8aa02cd448425a2cc2044dc025b323290d9380
[ "MIT" ]
null
null
null
#include <SDL2/SDL.h> #include <string> #include <sstream> #include <iostream> #include <time.h> #include <ctime> #include <vector> #include <cctype> #include <fstream> #include <iomanip> #include "Window.h" // #include "XEvent.h" #include "EpochFunctions.h" #include "GraphDrawing.h" int FPS = 20; std::vector<std::string> lines; void pollEvents(Window &window){ SDL_Event event; if (SDL_PollEvent(&event)){ window.pollEvents(event); } } void collect_data_into_xevents(struct XEvent * events){ int index = 0; for (auto s: lines){ // 0 1 2 3 // 08/05/2020 11:05, 10.2,---,l std::vector<std::string> info = split_string(s, ","); auto *xev = &events[index]; xev->epoch = epoch_from_string(info[0]); xev->timestr = strip_string(info[0]); xev->fullstr = s; xev->comment = strip_string(info[2]); xev->tod = strip_string(info[3]); xev->whole_day = get_whole_day_start(info[0]); if (xev->tod != "c"){ std::string sfloat = strip_string(info[1]); xev->glucose = std::stof(sfloat); } index++; } } int main(int argc, char* args[]) { load_csv_file(lines); int num_lines = lines.size(); XEvent events[num_lines]; collect_data_into_xevents(events); int start = 0; // get the epoch range, of ful days int start_day, end_day; get_epoch_limits(lines, num_lines, start_day, end_day); std::cout << start_day << std::endl; std::cout << end_day << std::endl; Window window("Sugars", 1800, 550); GraphDrawing graph("test"); // for (auto ev: events){ // std::cout << ev.epoch << std::endl; // } while (!window.isClosed()){ pollEvents(window); graph.draw(events, num_lines); SDL_Delay(FPS); window.clear(); start++; if (start > 4000) start = 0; } return 0; }
21.78022
61
0.570636
[ "vector" ]
0f759daae1ee0d80905ccf69dc3c557a5f3fda54
60,616
cpp
C++
groups/bsl/bslx/bslx_outstreamfunctions.t.cpp
htmldrum/bde
36764772b14d15871cd67e464b9736ce655b481f
[ "Apache-2.0" ]
1
2019-06-27T11:32:37.000Z
2019-06-27T11:32:37.000Z
groups/bsl/bslx/bslx_outstreamfunctions.t.cpp
htmldrum/bde
36764772b14d15871cd67e464b9736ce655b481f
[ "Apache-2.0" ]
null
null
null
groups/bsl/bslx/bslx_outstreamfunctions.t.cpp
htmldrum/bde
36764772b14d15871cd67e464b9736ce655b481f
[ "Apache-2.0" ]
null
null
null
// bslx_outstreamfunctions.t.cpp -*-C++-*- #include <bslx_outstreamfunctions.h> #include <bsls_assert.h> #include <bsls_asserttest.h> #include <bsls_bsltestutil.h> #include <bsl_climits.h> #include <bsl_cstdlib.h> #include <bsl_cstring.h> #include <bsl_iostream.h> #include <bsl_vector.h> using namespace BloombergLP; using namespace bsl; using namespace bslx; //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // Overview // -------- // This component provides two functions, each of which invokes a method of its // template parameter. In addition, the component provides a number of // overloads of these methods for fundamental types, 'bsl::vector', and // 'bsl::string'. A test type and a test stream are provided, each of which // responds in a simple, observable manner when its various methods are called. // The testing requirements are fairly straightforward and the provided test // type and test stream are used to verify the behavior of the two methods. //----------------------------------------------------------------------------- // [ 2] bdexStreamOut(STREAM& stream, const TYPE& value); // [ 1] bdexStreamOut(STREAM& stream, const TYPE& value, int version); //----------------------------------------------------------------------------- // [ 3] USAGE EXAMPLE //----------------------------------------------------------------------------- //============================================================================= // STANDARD BDE ASSERT TEST MACRO //----------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(int c, const char *s, int i) { if (c) { cout << "Error " << __FILE__ << "(" << i << "): " << s << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) ++testStatus; } } } // close unnamed namespace //============================================================================= // STANDARD BDE TEST DRIVER MACROS //----------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. #define P BSLS_BSLTESTUTIL_P // Print identifier and value. #define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. #define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLS_BSLTESTUTIL_L_ // current Line number //============================================================================= // GLOBAL CONSTANTS/TYPEDEFS FOR TESTING //============================================================================= typedef bsls::Types::Int64 Int64; typedef bsls::Types::Uint64 Uint64; const int SERIALIZATION_VERSION = 20131201; const int OTHER_SERIALIZATION_VERSION = 20131101; //============================================================================= // GLOBAL TEST CLASSES //----------------------------------------------------------------------------- enum MyTestEnum { e_A = INT_MIN, e_B = -1, e_C = 0, e_D = 1, e_E = INT_MAX }; enum MySpecializedTestEnum { e_F = -1, e_G = 0, e_H = 1 }; template <class STREAM> STREAM& bdexStreamOut(STREAM& stream, const MySpecializedTestEnum& value, int /* version */) { using bslx::OutStreamFunctions::bdexStreamOut; return bdexStreamOut(stream, static_cast<float>(value), 1); } namespace ThirdParty { enum MyThirdPartyTestEnum { e_I = -1, e_J = 0, e_K = 1 }; template <class STREAM> STREAM& bdexStreamOut(STREAM& stream, const MyThirdPartyTestEnum& value, int /* version */) { using bslx::OutStreamFunctions::bdexStreamOut; return bdexStreamOut(stream, static_cast<char>(value), 1); } } // close ThirdParty namespace class MyTestClass { // This test class is used for testing the streaming functionality. public: // CLASS METHODS static int maxSupportedBdexVersion(int serializationVersion); // CREATORS MyTestClass() { } ~MyTestClass() { } // ACCESSORS template <class STREAM> STREAM& bdexStreamOut(STREAM& stream, int version) const; }; int MyTestClass::maxSupportedBdexVersion(int serializationVersion) { if (serializationVersion >= SERIALIZATION_VERSION) return 2; return 1; } template <class STREAM> STREAM& MyTestClass::bdexStreamOut(STREAM& stream, int version) const { if (2 == version) { int x = 17; double y = 3.0; OutStreamFunctions::bdexStreamOut(stream, x, 1); OutStreamFunctions::bdexStreamOut(stream, y, 1); } else if (1 == version) { int x = 17; float y = 3.0; OutStreamFunctions::bdexStreamOut(stream, x, 1); OutStreamFunctions::bdexStreamOut(stream, y, 1); } return stream; } class MyTestOutStream { // Test class used to test streaming. int d_serializationVersion; bsl::vector<int> d_fun; int d_lastVersion; public: enum { k_CHAR = 10, k_INT = 20, k_FLOAT = 30, k_STRING = 40, k_LENGTH = 50, k_VERSION = 60, k_UNSIGNED = 100, k_ARRAY = 1000, k_UINT = k_UNSIGNED + k_INT }; // CREATORS MyTestOutStream(int serializationVersion) : d_serializationVersion(serializationVersion) , d_fun() , d_lastVersion(-2) { } ~MyTestOutStream() { } MyTestOutStream& putLength(int /* length */) { d_fun.push_back(k_LENGTH); return *this; } MyTestOutStream& putVersion(int version) { d_fun.push_back(k_VERSION); d_lastVersion = version; return *this; } MyTestOutStream& putInt64(Int64 /* value */) { d_fun.push_back(k_INT + 8); return *this; } MyTestOutStream& putUint64(Int64 /* value */) { d_fun.push_back(k_UNSIGNED + k_INT + 8); return *this; } MyTestOutStream& putInt56(Int64 /* value */) { d_fun.push_back(k_INT + 7); return *this; } MyTestOutStream& putUint56(Int64 /* value */) { d_fun.push_back(k_UNSIGNED + k_INT + 7); return *this; } MyTestOutStream& putInt48(Int64 /* value */) { d_fun.push_back(k_INT + 6); return *this; } MyTestOutStream& putUint48(Int64 /* value */) { d_fun.push_back(k_UNSIGNED + k_INT + 6); return *this; } MyTestOutStream& putInt40(Int64 /* value */) { d_fun.push_back(k_INT + 5); return *this; } MyTestOutStream& putUint40(Int64 /* value */) { d_fun.push_back(k_UNSIGNED + k_INT + 5); return *this; } MyTestOutStream& putInt32(int /* value */) { d_fun.push_back(k_INT + 4); return *this; } MyTestOutStream& putUint32(unsigned int /* value */) { d_fun.push_back(k_UNSIGNED + k_INT + 4); return *this; } MyTestOutStream& putInt24(int /* value */) { d_fun.push_back(k_INT + 3); return *this; } MyTestOutStream& putUint24(int /* value */) { d_fun.push_back(k_UNSIGNED + k_INT + 3); return *this; } MyTestOutStream& putInt16(int /* value */) { d_fun.push_back(k_INT + 2); return *this; } MyTestOutStream& putUint16(int /* value */) { d_fun.push_back(k_UNSIGNED + k_INT + 2); return *this; } MyTestOutStream& putInt8(int /* value */) { d_fun.push_back(k_INT + 1); return *this; } MyTestOutStream& putUint8(int /* value */) { d_fun.push_back(k_UNSIGNED + k_INT + 1); return *this; } MyTestOutStream& putFloat64(double /* value */) { d_fun.push_back(k_FLOAT + 8); return *this; } MyTestOutStream& putFloat32(float /* value */) { d_fun.push_back(k_FLOAT + 4); return *this; } typedef bsls::Types::Uint64 Uint64; MyTestOutStream& putArrayInt64(const Int64 * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_INT + 8); return *this; } MyTestOutStream& putArrayUint64(const Uint64 * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_UNSIGNED + k_INT + 8); return *this; } MyTestOutStream& putArrayInt56(const Int64 * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_INT + 7); return *this; } MyTestOutStream& putArrayUint56(const Uint64 * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_UNSIGNED + k_INT + 7); return *this; } MyTestOutStream& putArrayInt48(const Int64 * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_INT + 6); return *this; } MyTestOutStream& putArrayUint48(const Uint64 * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_UNSIGNED + k_INT + 6); return *this; } MyTestOutStream& putArrayInt40(const Int64 * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_INT + 5); return *this; } MyTestOutStream& putArrayUint40(const Uint64 * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_UNSIGNED + k_INT + 5); return *this; } MyTestOutStream& putArrayInt32(const int * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_INT + 4); return *this; } MyTestOutStream& putArrayUint32(const unsigned int * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_UNSIGNED + k_INT + 4); return *this; } MyTestOutStream& putArrayInt24(const int * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_INT + 3); return *this; } MyTestOutStream& putArrayUint24(const unsigned int * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_UNSIGNED + k_INT + 3); return *this; } MyTestOutStream& putArrayInt16(const short * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_INT + 2); return *this; } MyTestOutStream& putArrayUint16(const unsigned short * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_UNSIGNED + k_INT + 2); return *this; } MyTestOutStream& putArrayInt8(const signed char * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_INT + 1); return *this; } MyTestOutStream& putArrayUint8(const unsigned char * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_UNSIGNED + k_INT + 1); return *this; } MyTestOutStream& putArrayInt8(const char * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_INT + 1); return *this; } MyTestOutStream& putArrayUint8(const char * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_UNSIGNED + k_INT + 1); return *this; } MyTestOutStream& putArrayFloat64(const double * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_FLOAT + 8); return *this; } MyTestOutStream& putArrayFloat32(const float * /* array */, int /* count */) { d_fun.push_back(k_ARRAY + k_FLOAT + 4); return *this; } MyTestOutStream& putString(const bsl::string& /* value */) { d_fun.push_back(k_STRING); return *this; } // MANIPULATORS void invalidate() {} void removeAll() {} void reserveCapacity(int /* newCapacity */) {} void clear() { d_fun.clear(); d_lastVersion = -2; } // ACCESSORS operator const void *() const { return this; } const char *data() const { return 0; } int bdexSerializationVersion() const { return d_serializationVersion; } int length() const { return 0; } int size() const { return static_cast<int>(d_fun.size()); } int operator[](int index) const { return index < size() ? d_fun[index] : -1; } int lastVersion() const { return d_lastVersion; } }; template <typename TYPE> struct TestWithVersion { // This class is a utility for verifying the results of // 'bdexStreamOut(stream, value, version)' applied to a (template // parameter) type 'TYPE', 'bsl::vector<TYPE>', and // 'bsl::vector<bsl::vector<TYPE> >'. static void test(const int line, int version, const std::vector<int>& expectedFunctionIndicator, bool usesArrayMethod = true) { using bslx::OutStreamFunctions::bdexStreamOut; MyTestOutStream stream(SERIALIZATION_VERSION); TYPE mValue; const TYPE& value = mValue; bsl::vector<TYPE> mV; const bsl::vector<TYPE>& V = mV; bsl::vector<bsl::vector<TYPE> > mVV; const bsl::vector<bsl::vector<TYPE> >& VV = mVV; stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, value, version)); LOOP_ASSERT(line, expectedFunctionIndicator.size() == stream.size()); for (int i = 0; i < expectedFunctionIndicator.size(); ++i) { LOOP_ASSERT(line, expectedFunctionIndicator[i] == stream[i]); } stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, V, version)); LOOP_ASSERT(line, 1 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[0]); stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, VV, version)); LOOP_ASSERT(line, 1 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[0]); mVV.push_back(V); stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, VV, version)); LOOP_ASSERT(line, 2 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[0]); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[1]); mV.push_back(value); stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, V, version)); if (usesArrayMethod) { LOOP_ASSERT(line, 1 == expectedFunctionIndicator.size()); LOOP_ASSERT(line, 2 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[0]); LOOP_ASSERT(line, MyTestOutStream::k_ARRAY + expectedFunctionIndicator[0] == stream[1]); } else { LOOP_ASSERT(line, expectedFunctionIndicator.size() + 1 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[0]); for (int i = 0; i < expectedFunctionIndicator.size(); ++i) { LOOP_ASSERT(line, expectedFunctionIndicator[i] == stream[i + 1]); } } mVV.push_back(V); stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, VV, version)); if (usesArrayMethod) { LOOP_ASSERT(line, 1 == expectedFunctionIndicator.size()); LOOP_ASSERT(line, 4 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[0]); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[1]); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[2]); LOOP_ASSERT(line, MyTestOutStream::k_ARRAY + expectedFunctionIndicator[0] == stream[3]); } else { LOOP_ASSERT(line, expectedFunctionIndicator.size() + 3 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[0]); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[1]); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[2]); for (int i = 0; i < expectedFunctionIndicator.size(); ++i) { LOOP_ASSERT(line, expectedFunctionIndicator[i] == stream[i + 3]); } } } }; template <typename TYPE> struct TestWithoutVersion { // This class is a utility for verifying the results of // 'bdexStreamOut(stream, value)' applied to a (template parameter) type // 'TYPE', 'bsl::vector<TYPE>', and 'bsl::vector<bsl::vector<TYPE> >'. static void test(const int line, MyTestOutStream& stream, int expectedVersion, const std::vector<int>& expectedFunctionIndicator, bool usesArrayMethod = true, bool externalizesVersion = false) { using bslx::OutStreamFunctions::bdexStreamOut; TYPE mValue; const TYPE& value = mValue; bsl::vector<TYPE> mV; const bsl::vector<TYPE>& V = mV; bsl::vector<bsl::vector<TYPE> > mVV; const bsl::vector<bsl::vector<TYPE> >& VV = mVV; stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, value)); if (externalizesVersion) { LOOP_ASSERT(line, expectedFunctionIndicator.size() + 1 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_VERSION == stream[0]); LOOP_ASSERT(line, expectedVersion == stream.lastVersion()); for (int i = 0; i < expectedFunctionIndicator.size(); ++i) { LOOP_ASSERT(line, expectedFunctionIndicator[i] == stream[i + 1]); } } else { LOOP_ASSERT(line, expectedFunctionIndicator.size() == stream.size()); for (int i = 0; i < expectedFunctionIndicator.size(); ++i) { LOOP_ASSERT(line, expectedFunctionIndicator[i] == stream[i]); } } stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, V)); LOOP_ASSERT(line, 2 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_VERSION == stream[0]); LOOP_ASSERT(line, expectedVersion == stream.lastVersion()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[1]); stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, VV)); LOOP_ASSERT(line, 2 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_VERSION == stream[0]); LOOP_ASSERT(line, expectedVersion == stream.lastVersion()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[1]); mVV.push_back(V); stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, VV)); LOOP_ASSERT(line, 3 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_VERSION == stream[0]); LOOP_ASSERT(line, expectedVersion == stream.lastVersion()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[1]); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[2]); mV.push_back(value); stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, V)); if (usesArrayMethod) { LOOP_ASSERT(line, 1 == expectedFunctionIndicator.size()); LOOP_ASSERT(line, 3 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_VERSION == stream[0]); LOOP_ASSERT(line, expectedVersion == stream.lastVersion()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[1]); LOOP_ASSERT(line, MyTestOutStream::k_ARRAY + expectedFunctionIndicator[0] == stream[2]); } else { LOOP_ASSERT(line, expectedFunctionIndicator.size() + 2 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_VERSION == stream[0]); LOOP_ASSERT(line, expectedVersion == stream.lastVersion()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[1]); for (int i = 0; i < expectedFunctionIndicator.size(); ++i) { LOOP_ASSERT(line, expectedFunctionIndicator[i] == stream[i + 2]); } } mVV.push_back(V); stream.clear(); LOOP_ASSERT(line, &stream == &bdexStreamOut(stream, VV)); if (usesArrayMethod) { LOOP_ASSERT(line, 1 == expectedFunctionIndicator.size()); LOOP_ASSERT(line, 5 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_VERSION == stream[0]); LOOP_ASSERT(line, expectedVersion == stream.lastVersion()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[1]); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[2]); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[3]); LOOP_ASSERT(line, MyTestOutStream::k_ARRAY + expectedFunctionIndicator[0] == stream[4]); } else { LOOP_ASSERT(line, expectedFunctionIndicator.size() + 4 == stream.size()); LOOP_ASSERT(line, MyTestOutStream::k_VERSION == stream[0]); LOOP_ASSERT(line, expectedVersion == stream.lastVersion()); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[1]); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[2]); LOOP_ASSERT(line, MyTestOutStream::k_LENGTH == stream[3]); for (int i = 0; i < expectedFunctionIndicator.size(); ++i) { LOOP_ASSERT(line, expectedFunctionIndicator[i] == stream[i + 4]); } } } }; //============================================================================= // USAGE EXAMPLE //----------------------------------------------------------------------------- ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: Using 'bslx::OutStreamFunctions' to Externalize Data ///- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // In this example we illustrate the primary intended use of the templatized // methods of this component, as well as a few trivial invocations just to show // the syntax clearly. To accomplish this, we exhibit two separate example // "components": a value-semantic point object, and an 'enum'. In all cases, // the component designs are very simple, with much of the implied // functionality omitted, in order to focus attention on the key aspects of the // functionality of *this* component. // // First, consider an 'enum' 'Color' that enumerates a set of colors: //.. enum Color { RED = 0, GREEN = 1, BLUE = 2 }; //.. // Next, we consider a very special-purpose point that has as a data member its // color. Such a point provides an excellent opportunity for factoring, but // since we are interested in highlighting BDEX streaming of various types, we // will present a simple and unfactored design here. In a real-world problem, // the 'mypoint' component would be implemented differently. // // Note that the 'MyPoint' class in this example represents its coordinates as // 'short' integer values; this is done to make the BDEX stream output byte // pattern somewhat easier for the reader of this example to recognize when the // output buffer is printed. //.. // mypoint.h class MyPoint { // This class provides a geometric point having integer coordinates and // an enumerated color property. short d_x; // x coordinate short d_y; // y coordinate Color d_color; // enumerated color property public: // CLASS METHODS static int maxSupportedBdexVersion(int serializationVersion); // Return the 'version' to be used with the 'bdexStreamOut' method // corresponding to the specified 'serializationVersion'. See the // 'bslx' package-level documentation for more information on BDEX // streaming of value-semantic types and containers. // CREATORS MyPoint(); // Create a default point. MyPoint(short x, short y, Color color); // Create a point having the specified 'x' and 'y' coordinates and // the specified 'color'. ~MyPoint(); // Destroy this point. // MANIPULATORS // ... // ACCESSORS int x() const; // Return the x coordinate of this point. int y() const; // Return the y coordinate of this point. Color color() const; // Return the enumerated color of this point. template <class STREAM> STREAM& bdexStreamOut(STREAM& stream, int version) const; // Write this value to the specified output 'stream' using the // specified 'version' format, and return a reference to 'stream'. // If 'stream' is initially invalid, this operation has no effect. // If 'version' is not supported, 'stream' is invalidated but // otherwise unmodified. Note that 'version' is not written to // 'stream'. See the 'bslx' package-level documentation for more // information on BDEX streaming of value-semantic types and // containers. }; // FREE OPERATORS inline bool operator==(const MyPoint& lhs, const MyPoint& rhs); // Return 'true' if the specified 'lhs' and 'rhs' points have the same // value, and 'false' otherwise. Two points have the same value if // they have the same x and y coordinates and the same color. //.. // Representative (inline) implementations of these methods are shown below: //.. //========================================================================= // INLINE FUNCTION DEFINITIONS //========================================================================= // CLASS METHODS inline int MyPoint::maxSupportedBdexVersion(int serializationVersion) { if (serializationVersion >= 20131201) { return 2; } return 1; } // CREATORS inline MyPoint::MyPoint(short x, short y, Color color) : d_x(x) , d_y(y) , d_color(color) { } inline MyPoint::~MyPoint() { } // ... // MANIPULATORS // ... // ACCESSORS inline int MyPoint::x() const { return d_x; } // ... template <class STREAM> STREAM& MyPoint::bdexStreamOut(STREAM& stream, int version) const { switch (version) { case 1: { stream.putInt16(d_x); // output the x coordinate stream.putInt16(d_y); // output the y coordinate stream.putInt8(static_cast<char>(d_color)); // output the color enum as one byte } break; default: { stream.invalidate(); } break; } return stream; } // FREE OPERATORS inline bool operator==(const MyPoint& lhs, const MyPoint& rhs) { return lhs.x() == rhs.x() && lhs.y() == rhs.y() && lhs.color() == rhs.color(); } //.. // Then, we will implement an extremely simple output stream that supports the // BDEX documentation-only protocol. For simplicity, we will use a fixed-size // buffer (usually a bad idea in any event, and more so here since the // implementation knows the buffer size, but makes no effort to prevent // overwriting that buffer), and will only show a few methods needed for this // example. See other 'bslx' stream components for examples of // properly-designed BDEX streams. //.. // myoutstream.h // ... class MyOutStream { // This class implements a limited-size fixed-buffer output stream that // partially conforms to the BDEX protocol for output streams. This // class is suitable for demonstration purposes only. char d_buffer[1000]; // externalized values stored as contiguous bytes int d_length; // length of data in 'd_buffer' (in bytes) bool d_validFlag; // stream validity flag; 'true' if stream is in // valid state, 'false' otherwise public: // CREATORS MyOutStream(); // Create an empty output stream of limited, fixed capacity. Note // that this object is suitable for demonstration purposes only. ~MyOutStream(); // Destroy this output stream. // MANIPULATORS void invalidate(); // Put this input stream in an invalid state. This function has no // effect if this stream is already invalid. Note that this // function should be called whenever a value extracted from this // stream is determined to be invalid, inconsistent, or otherwise // incorrect. MyOutStream& putVersion(int version); // Write to this stream the one-byte, two's complement integer // comprised of the least-significant one byte of the specified // 'version', and return a reference to this stream. MyOutStream& putInt32(int value); // Write to this stream the four-byte, two's complement integer (in // network byte order) comprised of the least-significant four // bytes of the specified 'value' (in host byte order), and return // a reference to this stream. MyOutStream& putInt16(int value); // Write to this stream the two-byte, two's complement integer (in // network byte order) comprised of the least-significant two bytes // of the specified 'value' (in host byte order), and return a // reference to this stream. MyOutStream& putInt8(int value); // Write to this stream the one-byte, two's complement integer // comprised of the least-significant one byte of the specified // 'value', and return a reference to this stream. void removeAll(); // Remove all content in this stream. // ACCESSORS const char *data() const; // Return the address of the contiguous, non-modifiable internal // memory buffer of this stream. The address will remain valid as // long as this stream is not destroyed or modified. The behavior // of accessing elements outside the range // '[ data() .. data() + (length() - 1) ]' is undefined. int length() const; // Return the number of bytes in this stream. }; // FREE OPERATORS inline bsl::ostream& operator<<(bsl::ostream& stream, const MyOutStream& object); // Write the specified 'object' to the specified output 'stream' in // some reasonable (multi-line) format, and return a reference to // 'stream'. //.. // The relevant (inline) implementations are as follows. //.. //========================================================================= // INLINE FUNCTION DEFINITIONS //========================================================================= // CREATORS inline MyOutStream::MyOutStream() : d_length(0) , d_validFlag(true) { } inline MyOutStream::~MyOutStream() { } // MANIPULATORS inline void MyOutStream::invalidate() { d_validFlag = false; } inline MyOutStream& MyOutStream::putVersion(int value) { d_buffer[d_length] = static_cast<char>(value); ++d_length; return *this; } inline MyOutStream& MyOutStream::putInt32(int value) { d_buffer[d_length + 0] = static_cast<char>((value >> 24) & 0xff); d_buffer[d_length + 1] = static_cast<char>((value >> 16) & 0xff); d_buffer[d_length + 2] = static_cast<char>((value >> 8) & 0xff); d_buffer[d_length + 3] = static_cast<char>((value >> 0) & 0xff); d_length += 4; return *this; } inline MyOutStream& MyOutStream::putInt16(int value) { d_buffer[d_length + 0] = static_cast<char>((value >> 8) & 0xff); d_buffer[d_length + 1] = static_cast<char>((value >> 0) & 0xff); d_length += 2; return *this; } inline MyOutStream& MyOutStream::putInt8(int value) { d_buffer[d_length] = static_cast<char>(value); d_length += 1; return *this; } inline void MyOutStream::removeAll() { d_length = 0; } // ACCESSORS inline const char *MyOutStream::data() const { return static_cast<const char *>(d_buffer); } inline int MyOutStream::length() const { return d_length; } //.. //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; int verbose = argc > 2; cout << "TEST " << __FILE__ << " CASE " << test << endl; switch (test) { case 0: case 3: { // -------------------------------------------------------------------- // USAGE EXAMPLE // // Concerns: //: 1 The usage example provided in the component header file must //: compile, link, and run as shown. // // Plan: //: 1 Incorporate usage example from header into test driver, replace //: leading comment characters with spaces, replace 'assert' with //: 'ASSERT', and insert 'if (veryVerbose)' before all output //: operations. (C-1) // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) cout << endl << "Testing Usage Examples" << endl << "======================" << endl; // Finally, use the above 'enum', point class, and output stream to illustrate // 'bslx::OutStreamFunctions' functionality. This test code does not attempt // to do anything more useful than writing known values to a stream and // confirming that the expected byte pattern was in fact written. //.. int i = 168496141; // byte pattern 0a 0b 0c 0d Color color = BLUE; // byte pattern 02 MyPoint p(0, -1, color); // byte pattern 00 00 ff ff 02 using bslx::OutStreamFunctions::bdexStreamOut; MyOutStream out; ASSERT(0 == out.length()); bdexStreamOut(out, i, 1); ASSERT(4 == out.length()); ASSERT(0 == bsl::memcmp(out.data(), "\x0a\x0b\x0c\x0d", out.length())); out.removeAll(); ASSERT(0 == out.length()); bdexStreamOut(out, i, 0); ASSERT(4 == out.length()); ASSERT(0 == bsl::memcmp(out.data(), "\x0a\x0b\x0c\x0d", out.length())); out.removeAll(); ASSERT(0 == out.length()); bdexStreamOut(out, color, 1); ASSERT(4 == out.length()); ASSERT(0 == bsl::memcmp(out.data(), "\x00\x00\x00\x02", out.length())); out.removeAll(); ASSERT(0 == out.length()); bdexStreamOut(out, color, 0); ASSERT(4 == out.length()); ASSERT(0 == bsl::memcmp(out.data(), "\x00\x00\x00\x02", out.length())); out.removeAll(); ASSERT(0 == out.length()); bdexStreamOut(out, p, 1); ASSERT(5 == out.length()); ASSERT(0 == bsl::memcmp(out.data(), "\x00\x00\xff\xff\x02", out.length())); //.. } break; case 2: { // -------------------------------------------------------------------- // TESTING 'bdexStreamOut(stream, value)' // Ensure the 'bdexStreamOut' methods forward to the correct stream // methods and externalize the version where required. // // Concerns: //: 1 The correct methods on 'stream' are invoked. //: //: 2 Testing covers all 'stream' methods. //: //: 3 Non-directly supported vectors are externalized correctly. //: //: 4 The version is forwarded correctly. //: //: 5 The version is externalized only where appropriate. //: //: 6 Vectors correctly externalize the version. //: //: 7 The version is indirectly obtained from the stream where //: appropriate. // // Plan: //: 1 Create a test stream object that will track invoked methods. //: //: 2 Create a test object which externalizes differently for different //: versions. //: //: 3 Externalize a set of objects which cover all directly supported //: BDEX types and verify correct method forwarding. (C-1..2) //: //: 4 Externalize vectors of a test object and verify correct method //: forwarding. (C-3) //: //: 5 Externalize a test object which externalizes differently for //: different versions and vectors of this type with different //: supplied versions; verify correct method forwarding. (C-4) //: //: 6 Verify version is correctly externalized in all tests. (C-5) //: //: 7 Repeat tests with different 'serializationVersion' in the stream //: constructor and verify results. (C-7) // // Testing: // bdexStreamOut(STREAM& stream, const TYPE& value) // -------------------------------------------------------------------- if (verbose) cout << endl << "TESTING 'bdexStreamOut(stream, value)'" << endl << "======================================" << endl; { // first choice of serializationVersion MyTestOutStream stream(OTHER_SERIALIZATION_VERSION); std::vector<int> exp; exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithoutVersion<bool >::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithoutVersion<char >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithoutVersion<signed char >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 1); TestWithoutVersion<unsigned char >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 2); TestWithoutVersion<short >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 2); TestWithoutVersion<unsigned short >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); TestWithoutVersion<int >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 4); TestWithoutVersion<unsigned int >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); TestWithoutVersion<long >::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 4); TestWithoutVersion<unsigned long >::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 8); TestWithoutVersion<Int64 >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 8); TestWithoutVersion<Uint64 >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_FLOAT + 8); TestWithoutVersion<double >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_FLOAT + 4); TestWithoutVersion<float >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_STRING); TestWithoutVersion<bsl::string >::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); TestWithoutVersion<MyTestEnum >::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_FLOAT + 4); TestWithoutVersion<MySpecializedTestEnum>::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithoutVersion<ThirdParty::MyThirdPartyTestEnum>::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); exp.push_back(MyTestOutStream::k_FLOAT + 4); TestWithoutVersion<MyTestClass >::test(L_, stream, 1, exp, false, true); } { // second choice of serializationVersion using namespace OutStreamFunctions; MyTestOutStream stream(SERIALIZATION_VERSION); std::vector<int> exp; exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithoutVersion<bool >::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithoutVersion<char >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithoutVersion<signed char >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 1); TestWithoutVersion<unsigned char >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 2); TestWithoutVersion<short >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 2); TestWithoutVersion<unsigned short >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); TestWithoutVersion<int >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 4); TestWithoutVersion<unsigned int >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); TestWithoutVersion<long >::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 4); TestWithoutVersion<unsigned long >::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 8); TestWithoutVersion<Int64 >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 8); TestWithoutVersion<Uint64 >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_FLOAT + 8); TestWithoutVersion<double >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_FLOAT + 4); TestWithoutVersion<float >::test(L_, stream, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_STRING); TestWithoutVersion<bsl::string >::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); TestWithoutVersion<MyTestEnum >::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_FLOAT + 4); TestWithoutVersion<MySpecializedTestEnum>::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithoutVersion<ThirdParty::MyThirdPartyTestEnum>::test(L_, stream, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); exp.push_back(MyTestOutStream::k_FLOAT + 8); TestWithoutVersion<MyTestClass >::test(L_, stream, 2, exp, false, true); } } break; case 1: { // -------------------------------------------------------------------- // TESTING 'bdexStreamOut(stream, value, version)' // Ensure the 'bdexStreamOut' methods forward to the correct stream // methods. // // Concerns: //: 1 The correct methods on 'stream' are invoked. //: //: 2 Testing covers all 'stream' methods. //: //: 3 Non-directly supported vectors are externalized correctly. //: //: 4 The version is forwarded correctly. // // Plan: //: 1 Create a test stream object that will track invoked methods. //: //: 2 Create a test object which externalizes differently for different //: versions. //: //: 3 Externalize a set of objects which cover all directly supported //: BDEX types and verify correct method forwarding. (C-1..2) //: //: 4 Externalize vectors of a test object and verify correct method //: forwarding. (C-3) //: //: 5 Externalize a test object which externalizes differently for //: different versions and vectors of this type with different //: supplied versions; verify correct method forwarding. (C-4) // // Testing: // bdexStreamOut(STREAM& stream, const TYPE& value, int version) // -------------------------------------------------------------------- if (verbose) cout << endl << "TESTING 'bdexStreamOut(stream, value, version)'" << endl << "===============================================" << endl; { std::vector<int> exp; exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithVersion<bool >::test(L_, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithVersion<char >::test(L_, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithVersion<signed char >::test(L_, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 1); TestWithVersion<unsigned char >::test(L_, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 2); TestWithVersion<short >::test(L_, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 2); TestWithVersion<unsigned short >::test(L_, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); TestWithVersion<int >::test(L_, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 4); TestWithVersion<unsigned int >::test(L_, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); TestWithVersion<long >::test(L_, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 4); TestWithVersion<unsigned long >::test(L_, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 8); TestWithVersion<Int64 >::test(L_, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_UINT + 8); TestWithVersion<Uint64 >::test(L_, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_FLOAT + 8); TestWithVersion<double >::test(L_, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_FLOAT + 4); TestWithVersion<float >::test(L_, 1, exp); exp.clear(); exp.push_back(MyTestOutStream::k_STRING); TestWithVersion<bsl::string >::test(L_, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); TestWithVersion<MyTestEnum >::test(L_, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_FLOAT + 4); TestWithVersion<MySpecializedTestEnum>::test(L_, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 1); TestWithVersion<ThirdParty::MyThirdPartyTestEnum>::test(L_, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); exp.push_back(MyTestOutStream::k_FLOAT + 4); TestWithVersion<MyTestClass >::test(L_, 1, exp, false); exp.clear(); exp.push_back(MyTestOutStream::k_INT + 4); exp.push_back(MyTestOutStream::k_FLOAT + 8); TestWithVersion<MyTestClass >::test(L_, 2, exp, false); } } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
41.291553
79
0.464118
[ "object", "vector" ]
0f7691ab89f310fc9c70a7a963e29c38c8ca104a
1,284
hpp
C++
geometry/Plane.hpp
Draaaaaaven/generic
f72a1896058486ef865cb2a0a722d70b2398a7af
[ "BSL-1.0" ]
3
2022-01-05T02:34:04.000Z
2022-03-19T13:51:50.000Z
geometry/Plane.hpp
Draaaaaaven/generic
f72a1896058486ef865cb2a0a722d70b2398a7af
[ "BSL-1.0" ]
null
null
null
geometry/Plane.hpp
Draaaaaaven/generic
f72a1896058486ef865cb2a0a722d70b2398a7af
[ "BSL-1.0" ]
null
null
null
/** * @file Plane.hpp * @author bwu * @brief Model of plane concept * @version 0.1 * @date 2022-02-22 */ #ifndef GENERIC_GEOMETRY_PLANE_HPP #define GENERIC_GEOMETRY_PLANE_HPP #include "generic/common/Traits.hpp" #include "Point.hpp" #include "Vector.hpp" namespace generic { namespace geometry { using generic::common::float_type; template <typename num_type> class Plane { using float_t = float_type<num_type>; public: ///@brief constructs a plane with three points that not on the same straight line Plane(const Point3D<num_type> & p1, const Point3D<num_type> & p2, const Point3D<num_type> & p3); ///@brief gets plane normal, points x on the plane satisfy Dot(n, x) = d, d is the result of D() Vector3D<float_t> Normal() const { return m_normal; } ///@brief the distance of this plane from the origin float_t D() const { return m_dot; } private: Vector3D<float_t> m_normal; float_t m_dot; }; template <typename num_type> inline Plane<num_type>::Plane(const Point3D<num_type> & p1, const Point3D<num_type> & p2, const Point3D<num_type> & p3) { m_normal = Normalize((p2 - p1).CrossProduct(p3 - p1)); m_dot = m_normal.Dot(p1.template Cast<float_t>()); } }//namespace geometry }//namespace generic #endif//GENERIC_GEOMETRY_PLANE_HPP
30.571429
119
0.715732
[ "geometry", "vector", "model" ]
0f77e0bb051f63af8ec149475b0b995c280bfa36
4,490
hpp
C++
src/multipath_alignment_emitter.hpp
pierrepeterlongo/vg
718e07e4eba003741896c79777b63290e4c60cb0
[ "MIT" ]
null
null
null
src/multipath_alignment_emitter.hpp
pierrepeterlongo/vg
718e07e4eba003741896c79777b63290e4c60cb0
[ "MIT" ]
null
null
null
src/multipath_alignment_emitter.hpp
pierrepeterlongo/vg
718e07e4eba003741896c79777b63290e4c60cb0
[ "MIT" ]
null
null
null
#ifndef VG_MULTIPATH_ALIGNMENT_EMITTER_HPP_INCLUDED #define VG_MULTIPATH_ALIGNMENT_EMITTER_HPP_INCLUDED /** * \file multipath_alignment_emitter.hpp * * Defines a system for emitting multipath alignments and groups of multipath alignments in multiple formats. */ #include <mutex> #include <iostream> #include <sstream> #include <vg/vg.pb.h> #include <vg/io/protobuf_emitter.hpp> #include <vg/io/stream_multiplexer.hpp> #include "multipath_alignment.hpp" #include "hts_alignment_emitter.hpp" #include "alignment.hpp" namespace vg { using namespace std; /* * Class that handles multithreaded output for multipath alignments */ class MultipathAlignmentEmitter : public HTSWriter { public: /// Initialize with the intended output stream and the maximum number of threads that /// will be outputting. /// Allowed formats: /// - "GAMP" /// - "GAM", involves conversion to single path /// - "GAF", involves conversion to single path, requires a graph /// - "SAM", "BAM", "CRAM:" requires path length map, and all input alignments must /// already be surjected. If alignments have connections, requires a graph MultipathAlignmentEmitter(const string& filename, size_t num_threads, const string out_format = "GAMP", const PathPositionHandleGraph* graph = nullptr, const vector<pair<string, int64_t>>* path_order_and_length = nullptr); ~MultipathAlignmentEmitter(); /// Choose a read group to apply to all emitted alignments void set_read_group(const string& read_group); /// Choose a sample name to apply to all emitted alignments void set_sample_name(const string& sample_name); /// void set_min_splice_length(int64_t min_splice_length); /// Emit paired read mappings as interleaved protobuf messages void emit_pairs(const string& name_1, const string& name_2, vector<pair<multipath_alignment_t, multipath_alignment_t>>&& mp_aln_pairs, vector<pair<tuple<string, bool, int64_t>, tuple<string, bool, int64_t>>>* path_positions = nullptr, vector<int64_t>* tlen_limits = nullptr); /// Emit read mappings as protobuf messages void emit_singles(const string& name, vector<multipath_alignment_t>&& mp_alns, vector<tuple<string, bool, int64_t>>* path_positions = nullptr); private: enum output_format_t {GAMP, GAM, GAF, BAM, SAM, CRAM}; output_format_t format; void convert_to_alignment(const multipath_alignment_t& mp_aln, Alignment& aln, const string* prev_name = nullptr, const string* next_name = nullptr) const; /// store the data in an Algnment that is used in the conversion to bam1_t void create_alignment_shim(const string& name, const multipath_alignment_t& mp_aln, Alignment& shim, const string* prev_name = nullptr, const string* next_name = nullptr) const; void convert_to_hts_unpaired(const string& name, const multipath_alignment_t& mp_aln, const string& ref_name, bool ref_rev, int64_t ref_pos, bam_hdr_t* header, vector<bam1_t*>& dest) const; void convert_to_hts_paired(const string& name_1, const string& name_2, const multipath_alignment_t& mp_aln_1, const multipath_alignment_t& mp_aln_2, const string& ref_name_1, bool ref_rev_1, int64_t ref_pos_1, const string& ref_name_2, bool ref_rev_2, int64_t ref_pos_2, int64_t tlen_limit, bam_hdr_t* header, vector<bam1_t*>& dest) const; const PathPositionHandleGraph* graph; /// an Alignment emitter for each thread vector<unique_ptr<vg::io::ProtobufEmitter<Alignment>>> aln_emitters; /// a MultipathAlignment emitter for each thread vector<unique_ptr<vg::io::ProtobufEmitter<MultipathAlignment>>> mp_aln_emitters; /// read group applied to alignments string read_group; /// sample name applied to alignments string sample_name; /// the shortest deletion that we will interpret as a splice in the CIGAR string of HTS output int64_t min_splice_length = numeric_limits<int64_t>::max(); }; } #endif
40.818182
119
0.66147
[ "vector" ]
0f79708c7622eb47b4dbf54bf211e39ccea2ee19
839
cpp
C++
Problem701-800/p704_1.cpp
dingqunfei/LeetCode
c74a21ea56ee7b35308d2f387ef24ab29b031e24
[ "Apache-2.0" ]
null
null
null
Problem701-800/p704_1.cpp
dingqunfei/LeetCode
c74a21ea56ee7b35308d2f387ef24ab29b031e24
[ "Apache-2.0" ]
null
null
null
Problem701-800/p704_1.cpp
dingqunfei/LeetCode
c74a21ea56ee7b35308d2f387ef24ab29b031e24
[ "Apache-2.0" ]
null
null
null
/** * @file p704_1.cpp * @brief * @author dingqunfei (dqflying@gmail.com) * @version 1.0 * @date 2021-04-18 * * @copyright Copyright (c) 2021 DQFLYING * * @par : * * * Date : 2021-04-18 * Version : 1.0 * Author : dqflying * Lisence : * Description : * * * * */ class Solution { public: int search(vector<int>& nums, int target) { int rhs = 0; int lhs = nums.size()-1; while(rhs <= lhs) { int mid = (rhs + lhs)/2; if(nums[mid] == target) { return mid; } else if(nums[mid] < target) { rhs = mid+1; } else if(nums[mid] > target) { lhs = mid-1; } } return -1; } };
17.122449
47
0.401669
[ "vector" ]
0f797dd5ba7bfba01a3dd2908098fd1267af807a
1,235
cpp
C++
competitive programming/leetcode/1534. Count Good Triplets.cpp
sureshmangs/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
competitive programming/leetcode/1534. Count Good Triplets.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
competitive programming/leetcode/1534. Count Good Triplets.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets. A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true: 0 <= i < j < k < arr.length |arr[i] - arr[j]| <= a |arr[j] - arr[k]| <= b |arr[i] - arr[k]| <= c Where |x| denotes the absolute value of x. Return the number of good triplets. Example 1: Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3 Output: 4 Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)]. Example 2: Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1 Output: 0 Explanation: No triplet satisfies all conditions. Constraints: 3 <= arr.length <= 100 0 <= arr[i] <= 1000 0 <= a, b, c <= 1000 // O(n3) class Solution { public: int countGoodTriplets(vector<int>& arr, int a, int b, int c) { int n=arr.size(); int res=0; for(int i=0;i<n-2;i++){ for(int j=i+1;j<n-1;j++){ if(abs(arr[i]-arr[j])<=a){ for(int k=j+1;k<n;k++){ if(abs(arr[j]-arr[k])<=b && abs(arr[i]-arr[k])<=c) res++; } } } } return res; } };
19.919355
108
0.493927
[ "vector" ]
0f7a4337d3ce7723ade153846aba7ff0e75dda59
88,910
cpp
C++
src/openms/source/ANALYSIS/TARGETED/PSLPFormulation.cpp
andreott/OpenMS
718fa2e8a91280ff65e4cf834a3d825811dce1dc
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
1
2021-07-06T09:15:10.000Z
2021-07-06T09:15:10.000Z
src/openms/source/ANALYSIS/TARGETED/PSLPFormulation.cpp
andreott/OpenMS
718fa2e8a91280ff65e4cf834a3d825811dce1dc
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
7
2018-06-19T14:51:57.000Z
2022-01-12T14:34:32.000Z
src/openms/source/ANALYSIS/TARGETED/PSLPFormulation.cpp
andreott/OpenMS
718fa2e8a91280ff65e4cf834a3d825811dce1dc
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2018. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Alexandra Zerck $ // -------------------------------------------------------------------------- #include <OpenMS/ANALYSIS/TARGETED/PSLPFormulation.h> #include <OpenMS/ANALYSIS/TARGETED/PSProteinInference.h> #include <OpenMS/ANALYSIS/TARGETED/PrecursorIonSelectionPreprocessing.h> #ifdef DEBUG_OPS #include <OpenMS/SYSTEM/StopWatch.h> #endif namespace OpenMS { PSLPFormulation::PSLPFormulation() : DefaultParamHandler("PSLPFormulation"), solver_(LPWrapper::SOLVER_GLPK) { //model_ = new LPWrapper(); defaults_.setValue("rt:min_rt", 960., "Minimal rt in seconds."); defaults_.setMinFloat("rt:min_rt", 0.); defaults_.setValue("rt:max_rt", 3840., "Maximal rt in seconds."); defaults_.setMinFloat("rt:max_rt", 0.); defaults_.setValue("rt:rt_step_size", 30., "rt step size in seconds."); defaults_.setMinFloat("rt:rt_step_size", 1.); defaults_.setValue("rt:rt_window_size", 100, "rt window size in seconds."); defaults_.setMinInt("rt:rt_window_size", 1); defaults_.setValue("thresholds:min_protein_probability", 0.2, "Minimal protein probability for a protein to be considered in the ILP"); defaults_.setMinFloat("thresholds:min_protein_probability", 0.); defaults_.setMaxFloat("thresholds:min_protein_probability", 1.); defaults_.setValue("thresholds:min_protein_id_probability", 0.95, "Minimal protein probability for a protein to be considered identified."); defaults_.setMinFloat("thresholds:min_protein_id_probability", 0.); defaults_.setMaxFloat("thresholds:min_protein_id_probability", 1.); defaults_.setValue("thresholds:min_pt_weight", 0.5, "Minimal pt weight of a precursor"); defaults_.setMinFloat("thresholds:min_pt_weight", 0.); defaults_.setMaxFloat("thresholds:min_pt_weight", 1.); defaults_.setValue("thresholds:min_mz", 500., "Minimal mz to be considered in protein based LP formulation."); defaults_.setMinFloat("thresholds:min_mz", 0.); defaults_.setValue("thresholds:max_mz", 5000., "Minimal mz to be considered in protein based LP formulation."); defaults_.setMinFloat("thresholds:max_mz", 0.); defaults_.setValue("thresholds:min_pred_pep_prob", 0.5, "Minimal predicted peptide probability of a precursor"); defaults_.setMinFloat("thresholds:min_pred_pep_prob", 0.); defaults_.setMaxFloat("thresholds:min_pred_pep_prob", 1.); defaults_.setValue("thresholds:min_rt_weight", 0.5, "Minimal rt weight of a precursor"); defaults_.setMinFloat("thresholds:min_rt_weight", 0.); defaults_.setMaxFloat("thresholds:min_rt_weight", 1.); defaults_.setValue("thresholds:use_peptide_rule", "false", "Use peptide rule instead of minimal protein id probability"); defaults_.setValidStrings("thresholds:use_peptide_rule", ListUtils::create<String>("true,false")); defaults_.setValue("thresholds:min_peptide_ids", 2, "If use_peptide_rule is true, this parameter sets the minimal number of peptide ids for a protein id"); defaults_.setMinInt("thresholds:min_peptide_ids", 1); defaults_.setValue("thresholds:min_peptide_probability", 0.95, "If use_peptide_rule is true, this parameter sets the minimal probability for a peptide to be safely identified"); defaults_.setMinFloat("thresholds:min_peptide_probability", 0.); defaults_.setMaxFloat("thresholds:min_peptide_probability", 1.); defaults_.setValue("mz_tolerance", 25., "Allowed precursor mass error tolerance in ppm."); defaults_.setMinFloat("mz_tolerance", 0.); defaults_.setValue("combined_ilp:k1", 0.2, "combined ilp: weight for z_i"); defaults_.setMinFloat("combined_ilp:k1", 0.); // defaults_.setMaxFloat("combined_ilp:k1",1.); defaults_.setValue("combined_ilp:k2", 0.2, "combined ilp: weight for x_j,s*int_j,s"); defaults_.setMinFloat("combined_ilp:k2", 0.); // defaults_.setMaxFloat("combined_ilp:k1",1.); defaults_.setValue("combined_ilp:k3", 0.4, "combined ilp: weight for -x_j,s*w_j,s"); defaults_.setMinFloat("combined_ilp:k3", 0.); // defaults_.setMaxFloat("combined_ilp:k1",1.); defaults_.setValue("combined_ilp:scale_matching_probs", "true", "flag if detectability * rt_weight shall be scaled to cover all [0,1]"); defaults_.setValidStrings("combined_ilp:scale_matching_probs", ListUtils::create<String>("true,false")); defaults_.setValue("feature_based:no_intensity_normalization", "false", "Flag indicating if intensities shall be scaled to be in [0,1]. This is done for each feature separately, so that the feature's maximal intensity in a spectrum is set to 1."); defaults_.setValidStrings("feature_based:no_intensity_normalization", ListUtils::create<String>("true,false")); defaults_.setValue("feature_based:max_number_precursors_per_feature", 1, "The maximal number of precursors per feature."); defaults_.setMinInt("feature_based:max_number_precursors_per_feature", 1); defaultsToParam_(); } PSLPFormulation::~PSLPFormulation() { //delete model_; } void PSLPFormulation::createAndSolveILP_(const FeatureMap& features, std::vector<std::vector<double> >& intensity_weights, std::set<Int>& charges_set, std::vector<std::vector<std::pair<Size, Size> > >& mass_ranges, std::vector<IndexTriple>& variable_indices, std::vector<int>& solution_indices, UInt ms2_spectra_per_rt_bin, Size number_of_scans) { Int counter = 0; model_ = new LPWrapper(); //#define DEBUG_OPS #ifdef DEBUG_OPS std::cout << "Feature Based: Build model: first objective" << std::endl; #endif /////////////////////////////////////////////////////////////////////// // add objective function /////////////////////////////////////////////////////////////////////// model_->setObjectiveSense(LPWrapper::MAX); // maximize // max \sum_j x_jk * signal_jk // column_index, feature_index,scan // for (Size i = 0; i < features.size(); ++i) { // first check if charge state is allowed // charge not in "ChargeFilter" list #ifdef DEBUG_OPS std::cout << "feat: " << i << " charge " << features[i].getCharge() << std::endl; #endif if (charges_set.count(features[i].getCharge()) < 1) continue; if (mass_ranges[i].empty()) continue; #ifdef DEBUG_OPS if (mass_ranges[i].size() > 0) { std::cout << "start_scan " << mass_ranges[i][0].first << " ?= " << features[i].getQuality(0) << " stop scan " << (mass_ranges[i].end() - 1)->first << " ?= " << features[i].getQuality(1) - 1 << std::endl; } #endif Size c = 0; // go through all rts of the current feature for (Size s_idx = 0; s_idx < mass_ranges[i].size(); s_idx += 2) // walk in size two steps { Size s = mass_ranges[i][s_idx].first; //////////////////////////////////////////////////////////////////////// #ifdef DEBUG_OPS std::cout << "add column " << counter << std::endl; #endif IndexTriple triple; triple.feature = i; triple.scan = (Int)s; Int index = model_->addColumn(); triple.variable = index; variable_indices.push_back(triple); #ifdef DEBUG_OPS std::cout << index << " variable index" << std::endl; #endif model_->setColumnBounds(index, 0, 1, LPWrapper::DOUBLE_BOUNDED); model_->setColumnType(index, LPWrapper::BINARY); // binary variable model_->setColumnName(index, (String("x_") + i + "," + s)); #ifdef DEBUG_OPS std::cout << "feat " << i << " scan " << s << " intensity_weight " << intensity_weights[i][c] << std::endl; #endif model_->setObjective(index, intensity_weights[i][c]); ++counter; ++c; } } /////////////////////////////////////////////////////////////////////// // add constraints /////////////////////////////////////////////////////////////////////// #ifdef DEBUG_OPS std::cout << "and now the constraints:" << std::endl; #endif /////////////////////////////////////////////////////////////////////// // 1: ensure that each precursor is acquired maximally once /////////////////////////////////////////////////////////////////////// #ifdef DEBUG_OPS std::cout << "first the number of times a precursors is acquired" << std::endl; #endif Size j = 0; for (Size i = 0; i < features.size(); ++i) { Size start = j; while (j < variable_indices.size() && variable_indices[j].feature == i) { #ifdef DEBUG_OPS std::cout << j << " " << variable_indices[j].variable << " " << variable_indices[j].feature << " " << variable_indices[j].scan << std::endl; #endif ++j; } Size stop = j; std::vector<double> entries(stop - start); std::vector<int> indices(stop - start); #ifdef DEBUG_OPS std::cout << "feature " << i << " " << features[i].getMZ() << " " << features[i].getRT() << " "; std::cout << stop - start << "variables in equation\n"; #endif Size c = 0; for (Size k = start; k < stop; ++k) { entries[c] = 1.; indices[c] = (int) variable_indices[k].variable; #ifdef DEBUG_OPS std::cout << "indices[" << c << "]= " << indices[c] << std::endl; #endif ++c; } #ifdef DEBUG_OPS std::cout << "\nadd row " << std::endl; #endif if (!indices.empty()) { model_->addRow(indices, entries, (String("PREC_ACQU_LIMIT_") + i), 0, param_.getValue("feature_based:max_number_precursors_per_feature"), LPWrapper::UPPER_BOUND_ONLY); // only upper bounded problem -> lower bound is ignored } #ifdef DEBUG_OPS std::cout << stop - start << " PREC_ACQU_LIMIT_" << String(i) << std::endl; std::cout << "added row" << std::endl; #endif //#undef DEBUG_OPS } /////////////////////////////////////////////////////////////////////// // 2: do not exceed rt bin capacity /////////////////////////////////////////////////////////////////////// #ifdef DEBUG_OPS std::cout << "and now the rt bin capacity" << std::endl; std::cout << ms2_spectra_per_rt_bin << " rt bin capacity" << std::endl; #endif // sort variable_indices according to their scan number sort(variable_indices.begin(), variable_indices.end(), ScanLess()); j = 0; for (Size i = 0; i < number_of_scans; ++i) { // first determine number of indices: Size start = j; while (j < variable_indices.size() && (Size)variable_indices[j].scan == i) { ++j; } // no feature occurring in this scan if (start == j) continue; Size stop = j; Size c = 0; std::vector<double> entries(stop - start); std::vector<int> indices(stop - start); for (Size s = start; s < stop; ++s) { entries[c] = 1.; indices[c] = (int) variable_indices[s].variable; #ifdef DEBUG_OPS std::cout << "indices[" << c << "]= " << indices[c] << std::endl; #endif ++c; } #ifdef DEBUG_OPS std::cout << "\nadd row " << std::endl; #endif model_->addRow(indices, entries, (String("RT_CAP") + i), 0, ms2_spectra_per_rt_bin, LPWrapper::UPPER_BOUND_ONLY); // only upper bounded problem -> lower bound is ignored #ifdef DEBUG_OPS std::cout << "added row" << std::endl; #endif } // #ifdef DEBUG_OPS // model_->writeProblem("/home/zerck/data/tmp/test_pis_problem.mps", "MPS"); // #endif solveILP(solution_indices); } void PSLPFormulation::solveILP(std::vector<int>& solution_indices) { #ifdef DEBUG_OPS std::cout << "compute .." << std::endl; #endif // test if model exists if (model_->getNumberOfColumns() == 0) { std::cout << "Model is empty." << std::endl; return; } // // add rows into solver // solver.loadFromCoinModel(*cmodel_); // /* Now let MIP calculate a solution */ // // Pass to solver // CbcModel model(solver); // model.setObjSense(cmodel_->optimizationDirection()); // -1 = maximize, 1=minimize // model.solver()->setHintParam(OsiDoReducePrint,true,OsiHintTry); // // Output details // model.messageHandler()->setLogLevel(2); // model.solver()->messageHandler()->setLogLevel(1); // CglProbing generator1; // generator1.setUsingObjective(true); // CglGomory generator2; // // try larger limit // generator2.setLimit(300); // CglKnapsackCover generator3; // CglOddHole generator4; // generator4.setMinimumViolation(0.005); // generator4.setMinimumViolationPer(0.00002); // // try larger limit // generator4.setMaximumEntries(200); // CglClique generator5; // generator5.setStarCliqueReport(false); // generator5.setRowCliqueReport(false); // CglMixedIntegerRounding mixedGen; // CglFlowCover flowGen; // // Add in generators // model.addCutGenerator(&generator1,-1,"Probing"); // model.addCutGenerator(&generator2,-1,"Gomory"); // model.addCutGenerator(&generator3,-1,"Knapsack"); // model.addCutGenerator(&generator4,-1,"OddHole"); // model.addCutGenerator(&generator5,-1,"Clique"); // model.addCutGenerator(&flowGen,-1,"FlowCover"); // model.addCutGenerator(&mixedGen,-1,"MixedIntegerRounding"); // CbcRounding heuristic1(model); // model.addHeuristic(&heuristic1); // // And local search when new solution found // CbcHeuristicLocal heuristic2(model); // model.addHeuristic(&heuristic2); // Redundant definition of default branching (as Default == User) // CbcBranchUserDecision branch; // model.setBranchingMethod(&branch); // Definition of node choice // CbcCompareUser compare; // model.setNodeComparison(compare); // model.setDblParam(CbcModel::CbcMaximumSeconds,60.0*1); // // Do initial solve to continuous // model.initialSolve(); // // solve // #ifdef DEBUG_OPS // double time1 = CoinCpuTime(); // std::cout << "starting to solve..." << std::endl; // #endif // model.branchAndBound(); // #ifdef DEBUG_OPS // std::cout<<" Branch and cut took "<<CoinCpuTime()-time1<<" seconds, " // <<model.getNodeCount()<<" nodes with objective " // <<model.getObjValue() // <<(!model.status() ? " Finished" : " Not finished") // <<std::endl; // // best_solution // std::cout << model.solver()->getNumCols()<<" columns has solution"<<std::endl; // #endif LPWrapper::SolverParam param; model_->solve(param); for (Int column = 0; column < model_->getNumberOfColumns(); ++column) { double value = model_->getColumnValue(column); #ifdef DEBUG_OPS std::cout << value << " " << model_->getColumnType(column) << std::endl; #endif if ((fabs(value) > 0.5 && model_->getColumnType(column) == LPWrapper::BINARY) || (fabs(value) > 0.5 && model_->getColumnType(column) == LPWrapper::INTEGER)) { #ifdef DEBUG_OPS std::cout << model_->getColumnName(column) << " is in optimal solution" << std::endl; #endif solution_indices.push_back((int) column); } } } void PSLPFormulation::createAndSolveILPForInclusionListCreation(PrecursorIonSelectionPreprocessing& preprocessing, UInt ms2_spectra_per_rt_bin, UInt max_list_size, FeatureMap& precursors, bool solve_ILP) { const std::map<String, std::vector<double> >& pt_prot_map = preprocessing.getProteinPTMap(); std::map<String, std::vector<double> >::const_iterator map_iter = pt_prot_map.begin(); model_ = new LPWrapper(); model_->setSolver(solver_); model_->setObjectiveSense(LPWrapper::MAX); // maximize double min_rt = param_.getValue("rt:min_rt"); double max_rt = param_.getValue("rt:max_rt"); double rt_step_size = param_.getValue("rt:rt_step_size"); Size max_index = (Size)ceil((max_rt - min_rt) / rt_step_size); Size counter = 0; Size feature_counter = 0; std::vector<IndexTriple> variable_indices; std::map<String, Size> protein_penalty_index_map; Size pep_counter = 0; #ifdef DEBUG_OPS FeatureMap test_map; #endif // std::cout << "add proteins to LP"<<std::endl; for (; map_iter != pt_prot_map.end(); ++map_iter) { addProteinToILP_(preprocessing, map_iter, counter, pep_counter, feature_counter, variable_indices, protein_penalty_index_map, precursors); } // for(;map_iter!=pt_prot_map.end();++map_iter) /////////////////////////////////////////////////////////////////////// // constraint 1: ensure that the maximal total number of precursors is not exceeded /////////////////////////////////////////////////////////////////////// addMaxInclusionListSizeConstraints_(variable_indices, /*feature_counter, */ max_list_size); ////////////////////////////////////////////////////////////////////////// // constraint 2: rt_bin_capacity ////////////////////////////////////////////////////////////////////////// addRTBinCapacityConstraint_(variable_indices, max_index, ms2_spectra_per_rt_bin); /////////////////////////////////////////////////////////////////////// // constraint 3: protein coverage /////////////////////////////////////////////////////////////////////// addProteinCoverageConstraint_(variable_indices, preprocessing, protein_penalty_index_map); // model_->writeMps("/project/maldi/data/projects/data_openms/results/inclusion_lists/20110502/test_pis_problem.mps",0,0,2,true); #ifdef DEBUG_OPS //cmodel_->writeMps("/home/zerck/data/tmp/test_pis_problem.mps",0,0,2,true); //FeatureXMLFile().store("/home/zerck/data_project_maldi/results/inclusion_lists/all_feats.featureXML",test_map); #endif if (solve_ILP) { precursors.clear(true); std::vector<int> solution_indices; solveILP(solution_indices); assembleInclusionListForProteinBasedLP_(variable_indices, precursors, solution_indices, preprocessing); } else { } // std::cout <<"ILPwrapper is finished"<<std::endl; } void PSLPFormulation::addProteinToILP_(PrecursorIonSelectionPreprocessing& preprocessing, std::map<String, std::vector<double> >::const_iterator map_iter, Size& counter, Size& pep_counter, Size& feature_counter, std::vector<IndexTriple>& variable_indices, std::map<String, Size>& protein_variable_index_map, FeatureMap& precursors) { double min_rt = param_.getValue("rt:min_rt"); double max_rt = param_.getValue("rt:max_rt"); double rt_step_size = param_.getValue("rt:rt_step_size"); double min_pt = param_.getValue("thresholds:min_pt_weight"); double min_mz = param_.getValue("thresholds:min_mz"); double max_mz = param_.getValue("thresholds:max_mz"); Size rt_window_size = param_.getValue("rt:rt_window_size"); Size max_index = (Size)ceil((max_rt - min_rt) / rt_step_size); const std::vector<double>& masses = preprocessing.getMasses(map_iter->first); // insert protein variable Int index = model_->addColumn(); model_->setColumnName(index, (String("y_") + map_iter->first).c_str()); model_->setColumnBounds(index, 0., 0., LPWrapper::LOWER_BOUND_ONLY); //model_->setColumnBounds(index,0.,1.,LPWrapper::DOUBLE_BOUNDED); // cmodel_->setColumnUpper(counter,1.); // test for inclusion list protein based // TODO: German comment // cmodel_->setColumnIsInteger(counter,true); // testweise abgeschaltet, da er sonst, wenn nicht ausreichend // Peptide da waren, um das Protein auf 1 zu setzen, gar keine Variablen f?r das Protein ausw?hlt model_->setObjective(index, 1.); protein_variable_index_map.insert(make_pair(map_iter->first, counter)); ++counter; std::cout << "protein " << map_iter->first << " with " << map_iter->second.size() << " peptides." << std::endl; std::cout << min_pt << std::endl; for (Size p = 0; p < map_iter->second.size(); ++p) { // check if peptide is in desired mass range if (masses[p] < min_mz || masses[p] > max_mz) continue; if (map_iter->second[p] > min_pt) { // std::cout <<"feature_counter "<<feature_counter<<std::endl; std::cout << "peptide " << p << "\tmz " << masses[p] << "\t"; ++pep_counter; Feature test_feature; double rt = preprocessing.getRT(map_iter->first, p); std::cout << "predicted rt " << rt; // double mz_weight = preprocessing.getWeight(masses[p]); // if(mz_weight == 0.) mz_weight = 1.; // first find closest rt Size rt_index = std::min((Size) std::max(0., ceil((rt - min_rt) / rt_step_size)), max_index); double curr_rt = min_rt + rt_index * rt_step_size; std::cout << "\tnearest rt " << curr_rt << "\t"; Size curr_rt_index = rt_index; std::cout << "dt " << map_iter->second[p] << std::endl; #ifdef DEBUG_OPS test_feature.setMZ(masses[p]); test_feature.setRT(curr_rt); // std::map<String, std::vector<String> >::const_iterator prot_pep_iter = prot_pep_seq_map.find(map_iter->first); // if (prot_pep_iter != prot_pep_seq_map.end()) // { // const std::vector<String> & pep_seqs = prot_pep_iter->second; // test_feature.setMetaValue("sequence", pep_seqs[p]); // } #endif String name = map_iter->first + "_" + String(p); Int last_index = 0, current_index = 0; Int rt_center_variable_index = 0; // then go to the left as long as possible // with a fixed window this means until we are not more than rt_window_size from rt_index // std::cout << curr_rt << " >=? "<< min_rt << "\t" << rt_index << " - "<< curr_rt_index <<" <=?" << rt_window_size << std::endl; while (curr_rt >= min_rt && fabs(curr_rt - rt) <= rt_window_size) { // create variable index = model_->addColumn(); model_->setColumnName(index, (String("x_") + map_iter->first + "_" + String(p) + "," + String(curr_rt)).c_str()); //#ifdef DEBUG_OPS std::cout << "add column " << index << " " << (String("x_") + map_iter->first + "_" + String(p) + "," + String(curr_rt)) << " " << std::endl; //#endif // std::cout <<"adding "<<counter<<std::endl; IndexTriple triple; triple.prot_acc = map_iter->first; triple.feature = p; triple.scan = (Int)curr_rt_index; triple.variable = index; variable_indices.push_back(triple); model_->setColumnBounds(index, 0., 1., LPWrapper::DOUBLE_BOUNDED); model_->setColumnType(index, LPWrapper::BINARY); ConvexHull2D hull; hull.addPoint(DPosition<2>(masses[p], curr_rt)); hull.addPoint(DPosition<2>(masses[p] + 3., curr_rt)); // TODO: different charge states!!! test_feature.getConvexHulls().push_back(hull); #ifdef DEBUG_OPS std::cout << "protein " << map_iter->first << " peptide " << p << " scan " << curr_rt_index << " weight " ///<< curr_rt_weight * map_iter->second[p] * mz_weight // << " = " << curr_rt_weight << " * " << map_iter->second[p] << std::endl; // << " * "<<mz_weight<<std::endl; #endif model_->setObjective(index, 0.0); //cmodel_->setObjective(counter,-0.05); ++counter; if (rt_index == curr_rt_index) { // last_index = index; current_index = index; rt_center_variable_index = index; } else { last_index = current_index; current_index = index; } // enter constraint that ensures only consecutive scans are chosen for a feature if (rt_index != curr_rt_index) { std::vector<double> entries(2); std::vector<Int> indices(2); indices[0] = last_index; indices[1] = current_index; entries[0] = -1.; entries[1] = 1.; //#ifdef DEBUG_OPS std::cout << "\nadd row " << std::endl; std::cout << "indices: " << indices[0] << " " << indices[1] << std::endl; //#endif model_->addRow(indices, entries, String("rt_cons_") + name + String("_") + String(curr_rt_index) + String("_") + String(curr_rt_index + 1), 0, 0, LPWrapper::UPPER_BOUND_ONLY); // only upper bounded problem -> lower bound is ignored } // update curr_rt if (curr_rt_index == 0) break; --curr_rt_index; curr_rt -= rt_step_size; } #ifdef DEBUG_OPS // TODO: German comment std::cout << "links fertig----nun nach rechts" << std::endl; #endif curr_rt_index = rt_index + 1; curr_rt = min_rt + curr_rt_index * rt_step_size; std::cout << curr_rt << " <= " << max_rt << " " << curr_rt_index - rt_index << " <= " << rt_window_size << std::endl; // then to the right // here the same applies as before // if we use a fixed rt window size we continue until we are not more than rt_window_size away from our origin while (curr_rt <= max_rt && fabs(curr_rt - rt) <= rt_window_size) { // create variable index = model_->addColumn(); model_->setColumnName(index, (String("x_") + map_iter->first + "_" + String(p) + "," + String(curr_rt)).c_str()); //#ifdef DEBUG_OPS std::cout << "add column " << index << " " << (String("x_") + map_iter->first + "_" + String(p) + "," + String(curr_rt)) << " " << std::endl; //#endif //std::cout <<"adding "<<counter<<std::endl; IndexTriple triple; triple.prot_acc = map_iter->first; triple.feature = p; triple.scan = (Int)curr_rt_index; triple.variable = index; variable_indices.push_back(triple); model_->setColumnBounds(index, 0., 1., LPWrapper::DOUBLE_BOUNDED); model_->setColumnType(index, LPWrapper::BINARY); ConvexHull2D hull; hull.addPoint(DPosition<2>(masses[p], curr_rt)); hull.addPoint(DPosition<2>(masses[p] + 3., curr_rt)); // TODO: different charge states!!! test_feature.getConvexHulls().push_back(hull); #ifdef DEBUG_OPS std::cout << "protein " << map_iter->first << " peptide " << p << " scan " << curr_rt_index << " weight " // << curr_rt_weight * map_iter->second[p] * mz_weight // << " = " << curr_rt_weight << " * " << map_iter->second[p] << std::endl; // << " * "<<mz_weight <<std::endl; #endif //cmodel_->setObjective(counter,1.-curr_rt_weight*map_iter->second[p]); //cmodel_->setObjective(counter,-0.05); model_->setObjective(index, 0.0); ++counter; if (curr_rt_index == rt_index + 1) last_index = rt_center_variable_index; else last_index = current_index; current_index = index; // enter constraint that ensures only consecutive scans are chosen for a feature std::vector<double> entries(2); std::vector<Int> indices(2); indices[0] = current_index; indices[1] = last_index; entries[0] = 1.; entries[1] = -1.; #ifdef DEBUG_OPS std::cout << "\nadd row " << std::endl; #endif model_->addRow(indices, entries, String("rt_cons_") + name + String("_") + String(curr_rt_index) + String("_") + String(curr_rt_index + 1), 0, 0, LPWrapper::UPPER_BOUND_ONLY); // only upper bounded problem -> lower bound is ignored // update curr_rt if (curr_rt_index >= max_index) break; ++curr_rt_index; curr_rt += rt_step_size; } precursors.push_back(test_feature); } // if(map_iter->second[p] > min_pt) ++feature_counter; } // for(Size p = 0;p < map_iter->second.size();++p) } void PSLPFormulation::addMaxInclusionListSizeConstraints_(std::vector<IndexTriple>& variable_indices, /*Size number_of_features,*/ UInt max_list_size) { /////////////////////////////////////////////////////////////////////// // ensure that each precursor is counted maximally once, so create new variable /////////////////////////////////////////////////////////////////////// // std::cout << "now the number of times a precursors is acquired"<<std::endl; Int old_num = model_->getNumberOfColumns(); // Size j = 0; Size old_size = variable_indices.size(); for (Size i = 0; i < old_size; ++i) { // get protein accession and feature counter String acc = variable_indices[i].prot_acc; Size feature_count = variable_indices[i].feature; std::cout << "i:" << std::endl; // get start and end point of this feature in variable_indices-vector Size start = i; Size end = i; // std::cout << acc<< " "<< variable_indices[end+1].prot_acc << " "<< feature_count << " "<<variable_indices[end+1].feature << std::endl; while (end + 1 < variable_indices.size() && variable_indices[end + 1].prot_acc == acc && variable_indices[end + 1].feature == feature_count) { ++end; // std::cout << acc<< " "<< variable_indices[end+1].prot_acc << " "<< feature_count << " "<<variable_indices[end+1].feature << std::endl; } //std::cout << "start "<<start << " end "<<end <<std::endl; // enter new x_j variable, which indicates if a (hypothetical) peptide is part of the solution, independent from its RT region (which is given by the x_js-variables) Int index = model_->addColumn(); IndexTriple triple; triple.prot_acc = acc; triple.feature = feature_count; triple.scan = -1; // to show this is not a x_j,s-variable triple.variable = index; variable_indices.push_back(triple); model_->setColumnBounds(index, 0., 1., LPWrapper::DOUBLE_BOUNDED); model_->setColumnType(index, LPWrapper::BINARY); model_->setColumnName(index, String("x_") + acc + String("_") + String(feature_count)); // ensure that x_j is 1 iff at least one of the x_js-variables is 1 for (Size f = start; f <= end; ++f) { std::vector<double> entries(2); std::vector<Int> indices(2); entries[0] = 1.; entries[1] = -1.; indices[0] = (Int)variable_indices[f].variable; indices[1] = (Int)triple.variable; String name = "x_" + String(i) + String(",") + String(variable_indices[f].scan) + "_x_" + String(i); model_->addRow(indices, entries, name, 0, 0, LPWrapper::UPPER_BOUND_ONLY); } std::cout << "added variable and constraint, now set i to " << end << std::endl; i = end; } std::cout << "now add the actual max list size constraint\nmax_list_size:" << max_list_size << "\n" << model_->getNumberOfColumns() << " - " << old_num << std::endl; // now add constraints that controls the size of the inclusion list std::vector<double> entries(model_->getNumberOfColumns() - old_num); std::vector<Int> indices(model_->getNumberOfColumns() - old_num); for (Int i = old_num; i < model_->getNumberOfColumns(); ++i) { entries[i - old_num] = 1.; indices[i - old_num] = i; // std::cout << "indices["<<i - old_num<<"]="<<i<<std::endl; } model_->addRow(indices, entries, "max_list_size", 0, max_list_size, LPWrapper::UPPER_BOUND_ONLY); } void PSLPFormulation::addRTBinCapacityConstraint_(std::vector<IndexTriple>& variable_indices, Size max_rt_index, UInt ms2_spectra_per_rt_bin, bool sequential_order) { ////////////////////////////////////////////////////////////////////////// // constraint : rt_bin_capacity ////////////////////////////////////////////////////////////////////////// // sort variable_indices according to their scan number sort(variable_indices.begin(), variable_indices.end(), ScanLess()); Size j = 0; for (Size i = 0; i < max_rt_index; ++i) { // std::cout << "RT cap, scan "<< i << std::endl; // first determine number of indices: Size start = j; while (j < variable_indices.size()) { if (variable_indices[j].scan < 0) { ++j; continue; } if ((Size)variable_indices[j].scan != i) break; ++j; } // no feature occurring in this scan if (start == j) continue; Size stop = j; Size c = 0; std::vector<double> entries(stop - start); std::vector<int> indices(stop - start); for (Size s = start; s < stop; ++s) { entries[c] = 1.; indices[c] = (int) variable_indices[s].variable; #ifdef DEBUG_OPS std::cout << "indices[" << c << "]= " << indices[c] << std::endl; #endif ++c; } //#ifdef DEBUG_OPS std::cout << "add row with " << entries.size() << " indices" << std::endl; //#endif if (sequential_order && i != 0) { model_->addRow(indices, entries, (String("RT_CAP") + i), 0, 0, LPWrapper::FIXED); // fix capacities of all other spectra than the 1st to 0 } else { model_->addRow(indices, entries, (String("RT_CAP") + i), 0, ms2_spectra_per_rt_bin, LPWrapper::UPPER_BOUND_ONLY); // only upper bounded problem -> lower bound is ignored } #ifdef DEBUG_OPS std::cout << "added row" << std::endl; #endif } } void PSLPFormulation::addProteinCoverageConstraint_(std::vector<IndexTriple>& variable_indices, PrecursorIonSelectionPreprocessing& preprocessing, std::map<String, Size> protein_variable_index_map) { // double min_prot_prob = param_.getValue("thresholds:min_protein_id_probability"); std::cout << "and now the protein coverage" << std::endl; const std::map<String, std::vector<double> >& pt_prot_map = preprocessing.getProteinPTMap(); std::map<String, std::vector<double> >::const_iterator map_iter = pt_prot_map.begin(); sort(variable_indices.begin(), variable_indices.end(), VariableIndexLess()); Size feature_counter = 0; for (; map_iter != pt_prot_map.end(); ++map_iter) { std::cout << "protein: " << map_iter->first << std::endl; std::vector<Int> indices_vec; std::vector<double> entries; std::vector<double>::const_iterator f_index_iter = map_iter->second.begin(); //const std::vector<double>& masses = preprocessing.getMasses(map_iter->first); // go through all feature that have ids belonging to this protein for (; f_index_iter != map_iter->second.end(); ++f_index_iter) { // now go through all x_variable for this feature for (Size v = 0; v < variable_indices.size(); ++v) { if (variable_indices[v].prot_acc == map_iter->first && (Int)variable_indices[v].feature == distance(map_iter->second.begin(), f_index_iter)) { // if there are duplicates in the vector CoinModel will abort if (find(indices_vec.begin(), indices_vec.end(), variable_indices[v].variable) == indices_vec.end()) { indices_vec.push_back((Int)variable_indices[v].variable); double dt = map_iter->second[distance(map_iter->second.begin(), f_index_iter)]; if (fabs(1. - dt) < 0.000001) { entries.push_back(log(0.000001)); //entries.push_back(-log(0.000001) / log(1.-min_prot_prob)); } else { //entries.push_back(-log(1.-dt) / log(1.-min_prot_prob)); entries.push_back(log(1. - dt)); } } } else if (variable_indices[v].feature > feature_counter) break; // the indices are sorted, hence if the current index is larger, we are finished } ++feature_counter; } // if(indices_vec.size() == 0) continue; // if(indices_vec.size() < 2) // { // std::cout << "too few features with ids for this protein, skipping protein"<<std::endl; // continue; // } // enter protein variable indices_vec.push_back(static_cast<Int>(protein_variable_index_map[map_iter->first])); entries.push_back(1.); Int i = distance(pt_prot_map.begin(), map_iter); #ifdef DEBUG_OPS std::cout << "\nadd row " << std::endl; std::cout << (String("PROT_COV_") + map_iter->first) << "\t" << (String("PROT_COV_") + i).c_str() << std::endl; std::cout << indices_vec.size() << " " << (indices_vec[0]) << " " << (entries[0]) // << " min " << -COIN_DBL_MAX << ", max " << log(1. - min_prot_coverage) << std::endl; #endif // at the moment we want a certain coverage for each protein model_->addRow(indices_vec, entries, (String("PROT_COV_") + i), 0., 0., LPWrapper::UPPER_BOUND_ONLY); // test for inclusion list protein based // cmodel_->addRow((int)indices_vec.size(),&(indices_vec[0]),&(entries[0]), // -COIN_DBL_MAX,COIN_DBL_MAX,(String("PROT_COV_")+i).c_str()); std::cout << "\nadded row " << std::endl; #ifdef DEBUG_OPS std::cout << "added row" << std::endl; #endif } } void PSLPFormulation::assembleInclusionListForProteinBasedLP_(std::vector<IndexTriple>& variable_indices, FeatureMap& precursors, std::vector<int>& solution_indices, PrecursorIonSelectionPreprocessing& preprocessing) { double min_rt = param_.getValue("rt:min_rt"); double max_rt = param_.getValue("rt:max_rt"); double rt_step_size = param_.getValue("rt:rt_step_size"); Size max_index = (Size)ceil((max_rt - min_rt) / rt_step_size); // const std::map<String, std::vector<double> >& pt_prot_map = preprocessing.getProteinPTMap(); const std::map<String, std::vector<String> >& prot_pep_seq_map = preprocessing.getProteinPeptideSequenceMap(); std::cout << solution_indices.size() << " out of " << variable_indices.size() << " possible precursors were chosen." << std::endl; sort(variable_indices.begin(), variable_indices.end(), VariableIndexLess()); sort(solution_indices.begin(), solution_indices.end()); for (Size idx = 0; idx < solution_indices.size(); ++idx) { std::cout << idx << " " << variable_indices.size() << " " << solution_indices[idx] << std::endl; Size var_counter = 0; while (var_counter < variable_indices.size() && (Int)variable_indices[var_counter].variable != solution_indices[idx]) { ++var_counter; } std::cout << var_counter << " " << variable_indices[var_counter].feature << std::endl; if (var_counter == variable_indices.size()) { std::cout << "variable index not found..skipping" << std::endl; continue; } std::cout << variable_indices[var_counter] << std::endl; if (variable_indices[var_counter].scan == -1) continue; // we don't enter x_j variables // now get all variables belonging to the same peptide String acc = variable_indices[var_counter].prot_acc; Size feature = variable_indices[var_counter].feature; Size start = var_counter; Size end = var_counter + 1; // we start at var_counter as the solution indices are sorted in increasing order for (; end < variable_indices.size(); ++end) { if (!(variable_indices[end].prot_acc == acc && variable_indices[end].feature == feature)) { break; } } Feature tmp_feat; tmp_feat.setMZ(preprocessing.getMasses(acc)[feature]); // set RT to nearest spectrum to the predicted rt double rt = preprocessing.getRT(acc, feature); // first find closest rt Size rt_index = std::min((Size) std::max(0., ceil((rt - min_rt) / rt_step_size)), max_index); double curr_rt = min_rt + rt_index * rt_step_size; tmp_feat.setRT(curr_rt); std::cout << "now add the convex hulls" << std::endl; std::vector<DPosition<2> > points; Size max_sol_index = idx; for (Size i = start; i < end; ++i) { if (variable_indices[i].scan == -1) continue; // we don't enter x_j variables // now check if this index is in solution std::vector<Int>::iterator iter = find(solution_indices.begin(), solution_indices.end(), variable_indices[i].variable); if (iter == solution_indices.end()) continue; // we need to remember the index in the solution_indices else if (distance(solution_indices.begin(), iter) > (Int)max_sol_index) max_sol_index = distance(solution_indices.begin(), iter); points.push_back(DPosition<2>(min_rt + variable_indices[i].scan * rt_step_size, tmp_feat.getMZ() - 0.1)); points.push_back(DPosition<2>(min_rt + variable_indices[i].scan * rt_step_size, tmp_feat.getMZ() + 3.)); } ConvexHull2D hull; hull.addPoints(points); tmp_feat.getConvexHulls().push_back(hull); std::cout << "now add sequence and protein acc" << std::endl; tmp_feat.setMetaValue("protein", acc); tmp_feat.ensureUniqueId(); std::map<String, std::vector<String> >::const_iterator prot_pep_seq_map_iter = prot_pep_seq_map.find(acc); if (prot_pep_seq_map_iter != prot_pep_seq_map.end()) { tmp_feat.setMetaValue("sequence", prot_pep_seq_map_iter->second[feature]); } std::cout << "added" << std::endl; precursors.push_back(tmp_feat); idx = max_sol_index; std::cout << tmp_feat.getRT() << " " << tmp_feat.getMZ() << " " << precursors.size() << std::endl; } std::cout << "all solution indices added " << precursors.size() << std::endl; precursors.ensureUniqueId(); } void PSLPFormulation::createAndSolveCombinedLPFeatureBased_(const FeatureMap& features, std::vector<std::vector<double> >& intensity_weights, std::set<Int>& charges_set, std::vector<std::vector<std::pair<Size, Size> > >& mass_ranges, std::vector<IndexTriple>& variable_indices, std::vector<Int>& solution_indices, UInt ms2_spectra_per_rt_bin, Size number_of_scans, Size step_size, bool sequential_order) { double k2 = param_.getValue("combined_ilp:k2"); #ifdef DEBUG_OPS std::cout << "k2: " << k2 << std::endl; #endif model_ = new LPWrapper(); model_->setSolver(solver_); Int counter = 0; #ifdef DEBUG_OPS std::cout << "Feature Based: Build model: first objective" << std::endl; #endif /////////////////////////////////////////////////////////////////////// // add objective function /////////////////////////////////////////////////////////////////////// model_->setObjectiveSense(LPWrapper::MAX); // maximize // first get maximal intensity, as we use it for normalization double max_int = 0.; for (Size i = 0; i < features.size(); ++i) { // first check if charge state is allowed // charge not in "ChargeFilter" list #ifdef DEBUG_OPS std::cout << "feat: " << i << " charge " << features[i].getCharge() << std::endl; #endif if (charges_set.count(features[i].getCharge()) < 1) continue; if ((double)features[i].getMetaValue("msms_score") > max_int) max_int = features[i].getMetaValue("msms_score"); } #ifdef DEBUG_OPS std::cout << features.size() << " features.\n"; #endif for (Size i = 0; i < features.size(); ++i) { // first check if charge state is allowed // charge not in "ChargeFilter" list #ifdef DEBUG_OPS std::cout << "feat: " << i << " charge " << features[i].getCharge() << std::endl; #endif if (charges_set.count(features[i].getCharge()) < 1) continue; if (mass_ranges[i].size() == 0) { std::cout << "No mass ranges for " << features[i].getRT() << " " << features[i].getMZ() << std::endl; } #ifdef DEBUG_OPS if (mass_ranges[i].size() > 0) { std::cout << "start_scan " << mass_ranges[i][0].first << " ?= " << features[i].getQuality(0) << " stop scan " << (mass_ranges[i].end() - 1)->first << " ?= " << features[i].getQuality(1) - 1 << std::endl; } #endif double msms_score = features[i].getMetaValue("msms_score"); Size c = 0; // go through all rts of the current feature for (Size s_idx = 0; s_idx < mass_ranges[i].size(); s_idx += 2) // walk in size two steps { Size s = mass_ranges[i][s_idx].first; //////////////////////////////////////////////////////////////////////// #ifdef DEBUG_OPS std::cout << "add column " << counter << std::endl; #endif IndexTriple triple; triple.feature = i; triple.scan = static_cast<Int>(s); Size index = model_->addColumn(); triple.variable = index; variable_indices.push_back(triple); model_->setColumnBounds(static_cast<Int>(index), 0, 1, LPWrapper::DOUBLE_BOUNDED); model_->setColumnType(static_cast<Int>(index), LPWrapper::BINARY); // binary variable model_->setColumnName(static_cast<Int>(index), (String("x_") + i + "," + s).c_str()); #ifdef DEBUG_OPS std::cout << "feat " << i << " scan " << s << " " << intensity_weights[i][c] << " msms_score " << msms_score << " max_int " << max_int << " obj: " << intensity_weights[i][c] * msms_score << " other obj.: " << intensity_weights[i][c] * msms_score / max_int << std::endl; #endif model_->setObjective(static_cast<Int>(index), intensity_weights[i][c] * (double)features[i].getMetaValue("msms_score")); ++counter; if (msms_score > max_int) max_int = msms_score; ++c; } } #ifdef DEBUG_OPS std::cout << "now normalize the objective values by " << max_int << "\n"; #endif // normalize and invert objectives for (Int i = 0; i < counter; ++i) { model_->setObjective(i, k2 * model_->getObjective(i) / max_int); } /////////////////////////////////////////////////////////////////////// // add constraints /////////////////////////////////////////////////////////////////////// #ifdef DEBUG_OPS std::cout << "and now the constraints:" << std::endl; #endif /////////////////////////////////////////////////////////////////////// // 1: ensure that each precursor is acquired maximally once /////////////////////////////////////////////////////////////////////// addPrecursorAcquisitionNumberConstraint_(variable_indices, features.size(), 1); /////////////////////////////////////////////////////////////////////// // 2: do not exceed rt bin capacity /////////////////////////////////////////////////////////////////////// addRTBinCapacityConstraint_(variable_indices, number_of_scans, ms2_spectra_per_rt_bin, sequential_order); /////////////////////////////////////////////////////////////////////// // 3: add step size constraint /////////////////////////////////////////////////////////////////////// if (step_size > 0) { addStepSizeConstraint_(variable_indices, static_cast<UInt>(step_size)); } solveILP(solution_indices); } void PSLPFormulation::addPrecursorAcquisitionNumberConstraint_(std::vector<IndexTriple>& variable_indices, Size number_of_features, UInt number_of_msms_per_precursor) { /////////////////////////////////////////////////////////////////////// // ensure that each precursor is acquired maximally once /////////////////////////////////////////////////////////////////////// //std::cout << "now the number of times a precursors is acquired"<<std::endl; Size j = 0; for (Size i = 0; i < number_of_features; ++i) { Size start = j; while (j < variable_indices.size() && variable_indices[j].feature == i) { #ifdef DEBUG_OPS std::cout << j << " " << variable_indices[j].variable << " " << variable_indices[j].feature << " " << variable_indices[j].scan << std::endl; #endif ++j; } Size stop = j; std::vector<double> entries(stop - start); std::vector<Int> indices(stop - start); #ifdef DEBUG_OPS std::cout << "feature " << i << " "; ///<<features[i].getMZ() <<" "<<features[i].getRT()<<" "; std::cout << stop - start << "variables in equation\n"; #endif Size c = 0; for (Size k = start; k < stop; ++k) { entries[c] = 1.; indices[c] = (int) variable_indices[k].variable; #ifdef DEBUG_OPS std::cout << "indices[" << c << "]= " << indices[c] << std::endl; #endif ++c; } #ifdef DEBUG_OPS std::cout << "\nadd row " << std::endl; #endif String name = "PREC_ACQU_LIMIT_" + String(i); if (stop - start > 0) { model_->addRow(indices, entries, name, 0, (Int)number_of_msms_per_precursor, LPWrapper::UPPER_BOUND_ONLY); } #ifdef DEBUG_OPS std::cout << stop - start << " " << name << std::endl; std::cout << "added row" << std::endl; #endif } } void PSLPFormulation::addStepSizeConstraint_(std::vector<IndexTriple>& variable_indices, UInt step_size) { ////////////////////////////////////////////////////////////////////////// // constraint : step size ////////////////////////////////////////////////////////////////////////// #ifdef DEBUG_OPS std::cout << "and now the step size" << std::endl; std::cout << step_size << " step size" << std::endl; #endif std::vector<double> entries(variable_indices.size(), 1.); std::vector<Int> indices(variable_indices.size()); for (Size i = 0; i < variable_indices.size(); ++i) { indices[i] = static_cast<Int>(i); } #ifdef DEBUG_OPS std::cout << "\nadd row " << std::endl; #endif model_->addRow(indices, entries, "step_size", 0, step_size, LPWrapper::UPPER_BOUND_ONLY); // only upper bounded problem -> lower bound is ignored #ifdef DEBUG_OPS std::cout << "added row" << std::endl; #endif } void PSLPFormulation::updateStepSizeConstraint(Size iteration, UInt step_size) { Int row_index = model_->getRowIndex("step_size"); #ifdef DEBUG_OPS std::cout << "index " << row_index << std::endl; std::cout << "step_size:row_upper before " << model_->getRowUpperBound(row_index); #endif model_->setRowBounds(row_index, 0, (double)(step_size * iteration + step_size), LPWrapper::UPPER_BOUND_ONLY); #ifdef DEBUG_OPS std::cout << " and after " << model_->getRowUpperBound(row_index) << std::endl; #endif } void PSLPFormulation::updateFeatureILPVariables(FeatureMap& new_features, std::vector<IndexTriple>& variable_indices, std::map<Size, std::vector<String> >& feature_constraints_map) { #ifdef DEBUG_OPS std::cout << "update feature ilp variables" << std::endl; #endif double min_rt = param_.getValue("rt:min_rt"); double max_rt = param_.getValue("rt:max_rt"); double rt_step_size = param_.getValue("rt:rt_step_size"); Int max_index = (Int)ceil((max_rt - min_rt) / rt_step_size); for (Size f = 0; f < new_features.size(); ++f) { Size f_index = new_features[f].getMetaValue("feature_index"); // find corresponding variables Size f_v_idx = 0; while (f_v_idx < variable_indices.size() && f_index != variable_indices[f_v_idx].feature) { ++f_v_idx; } if (f_v_idx == variable_indices.size()) std::cout << "This should not happen!" << std::endl; else { // now set the corresponding variables in the ILP to 1 as this peptide is already acquired // find the right spectrum Int rt_index = std::min((Int) std::max(0., ceil((new_features[f].getRT() - min_rt) / rt_step_size)), max_index); #ifdef DEBUG_OPS std::cout << "rt_index " << rt_index << " " << new_features[f].getMZ() << " " << new_features[f].getRT() << std::endl; std::cout << new_features[f].getRT() << " " << min_rt << " " << max_rt << " " << rt_step_size << std::endl; #endif bool existing = false; while (f_v_idx < variable_indices.size() && variable_indices[f_v_idx].feature == f_index) { if (variable_indices[f_v_idx].scan == rt_index) { existing = true; model_->setColumnBounds(static_cast<Int>(variable_indices[f_v_idx].variable), 1., model_->getColumnUpperBound(static_cast<Int>(variable_indices[f_v_idx].variable)), LPWrapper::FIXED); #ifdef DEBUG_OPS std::cout << "set column lower from " << model_->getColumnName(variable_indices[f_v_idx].variable) << " to " << model_->getColumnLowerBound(variable_indices[f_v_idx].variable) << std::endl; #endif break; } ++f_v_idx; } if (!existing) std::cout << "ATTENTION!!" << std::endl; } std::map<Size, std::vector<String> >::iterator c_iter = feature_constraints_map.find(f); if (c_iter != feature_constraints_map.end()) { for (Size c = 0; c < c_iter->second.size(); ++c) { Int row = model_->getRowIndex(c_iter->second[c]); if (row != -1) // if constraint is still existing { model_->deleteRow(row); } } } } // for(Size f = 0; f < new_features.size();++f) #ifdef DEBUG_OPS std::cout << "update feature ilp variables --->done" << std::endl; #endif } Int PSLPFormulation::getNumberOfPrecsInSpectrum_(Int constr_idx) { std::vector<Int> indexes; model_->getMatrixRow(constr_idx, indexes); Size count = 0; for (Size i = 0; i < indexes.size(); ++i) { if (fabs(model_->getColumnValue(indexes[i]) - 1.) < 0.001) ++count; } return static_cast<Int>(count); } void PSLPFormulation::updateRTConstraintsForSequentialILP(Size& rt_index, UInt ms2_spectra_per_rt_bin, Size max_rt_index) { String constr_name = (String("RT_CAP") + rt_index); Int idx = model_->getRowIndex(constr_name); if (idx != -1) { #ifdef DEBUG_OPS std::cout << rt_index << " " << constr_name << " " << idx << " colValue: " << getNumberOfPrecsInSpectrum_(idx) << std::endl; #endif model_->setRowBounds(idx, 0., (double) getNumberOfPrecsInSpectrum_(idx), LPWrapper::UPPER_BOUND_ONLY); } ++rt_index; constr_name = (String("RT_CAP") + rt_index); idx = model_->getRowIndex(constr_name); while (idx == -1 && rt_index < max_rt_index) { ++rt_index; constr_name = (String("RT_CAP") + rt_index); idx = model_->getRowIndex(constr_name); #ifdef DEBUG_OPS std::cout << rt_index << " " << constr_name << " " << idx << std::endl; #endif } if (idx != -1) model_->setRowBounds(idx, 0., (double)ms2_spectra_per_rt_bin, LPWrapper::UPPER_BOUND_ONLY); } void PSLPFormulation::updateObjFunction_(String acc, FeatureMap& features, PrecursorIonSelectionPreprocessing& preprocessed_db, std::vector<IndexTriple>& variable_indices) { #ifdef DEBUG_OPS std::cout << "Update Obj. function of combined ILP." << std::endl; #endif double min_pt = param_.getValue("thresholds:min_pt_weight"); double min_rt_weight = param_.getValue("thresholds:min_rt_weight"); double mz_tolerance = param_.getValue("mz_tolerance"); double log_weight = param_.getValue("combined_ilp:k3"); #ifdef DEBUG_OPS std::cout << "k3: " << log_weight << std::endl; std::cout << "parsed all parameters" << std::endl; #endif std::vector<IndexTriple> variable_indices_copy = variable_indices; sort(variable_indices_copy.begin(), variable_indices_copy.end(), VariableIndexLess()); // if protein prob exceeds min threshold (TODO: is this necessary? we only use this ILP if either a protein is // identified or no more features can be found for this certain protein) std::map<String, std::vector<double> >::const_iterator map_iter = preprocessed_db.getProteinPTMap().find(acc); if (map_iter != preprocessed_db.getProteinPTMap().end()) { // then go through all (tryptic) peptides of this protein #ifdef DEBUG_OPS std::cout << "protein " << map_iter->first << " with " << map_iter->second.size() << " entries in pt_map" << std::endl; #endif const std::vector<double>& masses = preprocessed_db.getMasses(map_iter->first); for (Size p = 0; p < map_iter->second.size(); ++p) { if (map_iter->second[p] > min_pt) { // go through all features for (Size f = 0; f < features.size(); ++f) { if (features[f].getMetaValue("fragmented") == "true") continue; // and check if they match the current peptide if (fabs(masses[p] - features[f].getMZ()) / masses[p] * 1e06 < mz_tolerance) { double rt_weight = preprocessed_db.getRTProbability(map_iter->first, p, features[f]); if (rt_weight > min_rt_weight) { #ifdef DEBUG_OPS std::cout << features[f].getMZ() << " " << features[f].getRT() << " " << rt_weight << " is matching peptide " << p << "\n"; #endif // if yes: add as variable to the protein coverage constraint // find corresponding variables Size f_v_idx = 0; while (f_v_idx < variable_indices_copy.size() && f != variable_indices_copy[f_v_idx].feature) { ++f_v_idx; } if (f_v_idx == variable_indices_copy.size()) { std::cout << features[f].getMZ() << " " << features[f].getRT() << " " << /*rt_weight <<*/ " is matching peptide " << p << ", but not existing in variable indices???" << "--->This should not happen!" << std::endl; } else { // TODO: enter here really all scans for this feature? // or only the ones with rt-weight > min_rt_weight while (f_v_idx < variable_indices_copy.size() && f == variable_indices_copy[f_v_idx].feature) { if (model_->getObjective(static_cast<Int>(f_v_idx)) < 0.00000001) { ++f_v_idx; continue; } double dt = map_iter->second[p]; // weight is detectability * rt_weight double weight = dt * rt_weight; double obj = model_->getObjective(static_cast<Int>(f_v_idx)); #ifdef DEBUG_OPS std::cout << features[f].getMZ() << " " << features[f].getRT() << " " << rt_weight << " is matching peptide " << p << " with score: "; std::cout << dt << " * " << rt_weight << " = " << dt * rt_weight << " " << weight << " -> " << log(1. - weight) << "*" << log_weight << " obj: " << model_->getObjective(f_v_idx); #endif if (log_weight * weight > obj && obj > 0.) { model_->setObjective(static_cast<Int>(f_v_idx), 0.001); } else model_->setObjective(static_cast<Int>(f_v_idx), obj - weight * log_weight); #ifdef DEBUG_OPS std::cout << " -> " << model_->getObjective(f_v_idx) << " columnname: " << model_->getColumnName(f_v_idx) << std::endl; #endif ++f_v_idx; } // while(f_v_idx < variable_indices_copy.size() && f == variable_indices_copy[f_v_idx].feature) } // else if(f_v_idx == variable_indices.size()) } // if(rt_weight > min_rt_weight) } // if(fabs(masses[p] - features[f].getMZ())/masses[p] * 1e06 < mz_tolerance) } //for(Size f = 0; f < features.size();++f) } //if(map_iter->second[p] > min_pt) } //for(Size p = 0;p < map_iter->second.size();++p) } //if(map_iter != preprocessed_db.getProteinPTMap().end()) #ifdef DEBUG_OPS std::cout << "Update Obj. function of combined ILP -->done" << std::endl; #endif } void PSLPFormulation::updateCombinedILP(FeatureMap& features, PrecursorIonSelectionPreprocessing& preprocessed_db, std::vector<IndexTriple>& variable_indices, std::vector<String>& new_protein_accs, std::vector<String>& protein_accs, PSProteinInference& prot_inference, Size& variable_counter, std::map<String, std::vector<Size> >& protein_feature_map, Feature& new_feature, std::map<String, Size>& protein_variable_index_map, std::map<String, std::set<String> >& /*prot_id_counter*/) { #ifdef DEBUG_OPS std::cout << "Update Combined ILP." << std::endl; #endif // if (param_.getValue("thresholds:use_peptide_rule") == "true") // { // updateCombinedILPPeptideRule_(features, preprocessed_db, variable_indices, new_protein_accs, protein_accs, prot_inference, // variable_counter, protein_feature_map, new_feature, protein_variable_index_map, prot_id_counter); // return; // } double min_prot_coverage = param_.getValue("thresholds:min_protein_id_probability"); double min_pt = param_.getValue("thresholds:min_pt_weight"); double min_rt_weight = param_.getValue("thresholds:min_rt_weight"); double min_pred_pep_weight = param_.getValue("thresholds:min_pred_pep_prob"); double mz_tolerance = param_.getValue("mz_tolerance"); double min_protein_probability = param_.getValue("thresholds:min_protein_probability"); double k1 = param_.getValue("combined_ilp:k1"); #ifdef DEBUG_OPS std::cout << "k1 " << k1 << std::endl; std::cout << "min_protein_probability = " << min_protein_probability << " min_prot_coverage " << min_prot_coverage << std::endl; std::cout << "parsed all parameters" << std::endl; std::cout << "log(1.-min_prot_coverage) = " << log(1. - min_prot_coverage) << std::endl; #endif sort(variable_indices.begin(), variable_indices.end(), IndexLess()); #ifdef DEBUG_OPS StopWatch timer; timer.start(); #endif if (new_feature.getPeptideIdentifications().size() > 0 && new_feature.getPeptideIdentifications()[0].getHits().size() > 0) { // if a selected feature yielded a peptide id, the peptide probability needs to be considered in the protein constraint double pep_score = new_feature.getPeptideIdentifications()[0].getHits()[0].getScore(); Size index = new_feature.getMetaValue("variable_index"); std::set<String> accs = new_feature.getPeptideIdentifications()[0].getHits()[0].extractProteinAccessionsSet(); // check all proteins that were already detected (only there we need to update a constraint) for (Size pa = 0; pa < protein_accs.size(); ++pa) { if (find(accs.begin(), accs.end(), protein_accs[pa]) == accs.end()) continue; Int row = model_->getRowIndex((String("PROT_COV_") + protein_accs[pa]).c_str()); #ifdef DEBUG_OPS std::cout << protein_accs[pa] << " index " << row << " " << model_->getElement(row, index) << std::endl; #endif if (model_->getElement(row, static_cast<Int>(index)) != 0.) { const double weight = 1.; // std::cout << "getElement("<<protein_accs[pa]<<","<<index<<")=" // << cmodel_->getElement(row,index) << "\t"; if (fabs(pep_score * weight - 1.) < 0.000001) { model_->setElement(row, static_cast<Int>(index), -log(0.000001) / log(1. - min_prot_coverage)); // pseudocount to prevent entering inf #ifdef DEBUG_OPS std::cout << protein_accs[pa] << " setElement(" << row << "," << model_->getColumnName(index) << "= " << model_->getElement(row, index) << std::endl; #endif } else { model_->setElement(row, static_cast<Int>(index), -log(1. - pep_score * weight) / log(1. - min_prot_coverage)); #ifdef DEBUG_OPS std::cout << protein_accs[pa] << " setElement(" << row << "," << model_->getColumnName(index) << "= " << model_->getElement(row, index) << std::endl; #endif } // std::cout << "getElement("<<protein_accs[pa]<<","<<index<<")=" // << cmodel_->getElement(row,index) << "\n"; } // else std::cout << "getElement("<<protein_accs[pa]<<","<<index<<") =" // << cmodel_->getElement(row,index) << " ==? 0.\n"; } //for(Size pa = 0; pa < protein_accs.size();++pa) #ifdef DEBUG_OPS std::cout << "Now search for matching features for " << accs.size() << " proteins." << std::endl; #endif for (std::set<String>::const_iterator acc_it = accs.begin(); acc_it != accs.end(); ++acc_it) { // first enter the new feature to the corresponding proteins std::map<String, std::vector<Size> >::iterator prot_var_iter = protein_feature_map.find(*acc_it); #ifdef DEBUG_OPS std::cout << "now enter " << new_feature.getRT() << " " << new_feature.getMZ() << " with variable index " << index << " to prot_variable_map " << acc_it << std::endl; #endif if (prot_var_iter == protein_feature_map.end()) { std::vector<Size> vec; vec.push_back((Size)new_feature.getMetaValue("feature_index")); protein_feature_map.insert(std::make_pair(*acc_it, vec)); } else prot_var_iter->second.push_back((Size)new_feature.getMetaValue("feature_index")); // if protein prob exceeds min threshold if ((prot_inference.getProteinProbability(*acc_it) > min_protein_probability) && (prot_inference.isProteinInMinimalList(*acc_it))) { std::map<String, std::vector<double> >::const_iterator map_iter = preprocessed_db.getProteinPTMap().find(*acc_it); if (map_iter != preprocessed_db.getProteinPTMap().end()) { std::vector<String>::iterator prot_acc_iter = find(protein_accs.begin(), protein_accs.end(), *acc_it); if (prot_acc_iter == protein_accs.end()) { // enter new variable y_i if (prot_inference.getProteinProbability(*acc_it) >= min_prot_coverage) { new_protein_accs.push_back(*acc_it); if (double(param_.getValue("combined_ilp:k3")) > 0.000001) updateObjFunction_(*acc_it, features, preprocessed_db, variable_indices); } protein_accs.push_back(*acc_it); // insert protein to ILP // first add penalty // insert penalty variable Int index = model_->addColumn(); model_->setColumnName(index, (String("y_") + map_iter->first).c_str()); model_->setColumnBounds(index, 0., 1., LPWrapper::DOUBLE_BOUNDED); //cmodel_->setColumnIsInteger(variable_counter,true); //try without integer constraint model_->setObjective(index, k1); protein_variable_index_map.insert(make_pair(map_iter->first, index)); #ifdef DEBUG_OPS std::cout << "entered protein variable " << (String("y_") + map_iter->first) << "\tit consists of:" << std::endl; #endif //std::cout << variable_counter <<" penalty for "<<map_iter->first << std::endl; ++variable_counter; std::vector<Int> indices; std::vector<double> entries; // now go through protein_feature_map and enter them to std::map<String, std::vector<Size> >::iterator prot_var_iter = protein_feature_map.find(*acc_it); if (prot_var_iter != protein_feature_map.end()) { // TODO: problem: they need not all correspond to the current feature for (Size var = 0; var < prot_var_iter->second.size(); ++var) { Int variable = features[prot_var_iter->second[var]].getMetaValue("variable_index"); double score = features[prot_var_iter->second[var]].getPeptideIdentifications()[0].getHits()[0].getScore(); bool found_index = false; for (Size idx = 0; idx < indices.size(); ++idx) { // TODO: really compare here with the variable index? // isn't the feature index more interesting here? think about it! if (indices[idx] == variable) { double weight = 1.; if (fabs(score * weight - 1.) < 0.000001) // pseudocount to prevent entering -inf { entries[idx] = -log(0.000001) / log(1. - min_prot_coverage); } // if the current entry has a better peptide id, take it instead of the old one else if (entries[idx] > -log(1. - score * weight)) { entries[idx] = -log(1. - score * weight) / log(1. - min_prot_coverage); } #ifdef DEBUG_OPS std::cout << entries[idx] << " " << score * weight << "\n"; #endif found_index = true; break; } } if (!found_index) { #ifdef DEBUG_OPS std::cout << "feature that was already measured is entered into prot_cov " << prot_var_iter->first << " matches variable no. " << variable << std::endl; #endif indices.push_back(variable); double score = features[prot_var_iter->second[var]].getPeptideIdentifications()[0].getHits()[0].getScore(); double weight = 1.; #ifdef DEBUG_OPS std::cout << features[prot_var_iter->second[var]].getMZ() << " " << features[prot_var_iter->second[var]].getRT() << std::endl; #endif if (fabs(weight * score - 1.) < 0.000001) { entries.push_back(-log(0.000001) / log(1. - min_prot_coverage)); #ifdef DEBUG_OPS std::cout << "pseudocount needed: " << score << " * " << weight << " = " << weight * score << " -> " << -log(0.000001) << std::endl; #endif } else { entries.push_back(-log(1. - weight * pep_score) / log(1. - min_prot_coverage)); #ifdef DEBUG_OPS std::cout << score << " * " << weight << " = " << weight * score << " -> " << -log(1. - weight * score) << std::endl; #endif } #ifdef DEBUG_OPS std::cout << entries.back() << " " << score * weight << "\n"; #endif } } } //if(prot_var_iter != protein_feature_map.end()) // then go through all (tryptic) peptides of this protein #ifdef DEBUG_OPS std::cout << "protein " << map_iter->first << " with " << map_iter->second.size() << " entries in pt_map" << std::endl; #endif const std::vector<double>& masses = preprocessed_db.getMasses(map_iter->first); for (Size p = 0; p < map_iter->second.size(); ++p) { if (map_iter->second[p] > min_pt) { std::vector<Int> matching_features; // go through all features for (Size f = 0; f < features.size(); ++f) { if (features[f].getMetaValue("fragmented") == "true") continue; // and check if they match the current peptide if (fabs(masses[p] - features[f].getMZ()) / masses[p] * 1e06 < mz_tolerance) { // we need to compare the rt of each scan separately, not of the whole feature double rt_weight = preprocessed_db.getRTProbability(map_iter->first, p, features[f]); if (rt_weight > min_rt_weight) { #ifdef DEBUG_OPS std::cout << features[f].getMZ() << " " << features[f].getRT() << " " << rt_weight << " is matching peptide " << p << "\n"; #endif // store all matching features to this peptide matching_features.push_back((Int)f); // if yes: add as variable to the protein coverage constraint // find corresponding variables Size f_v_idx = 0; while (f_v_idx < variable_indices.size() && f != variable_indices[f_v_idx].feature) { ++f_v_idx; } if (f_v_idx == variable_indices.size()) { std::cout << features[f].getMZ() << " " << features[f].getRT() << " " << /*rt_weight <<*/ " is matching peptide " << p << ", but not existing in variable indices???" << "--->This should not happen!" << std::endl; } else { // TODO: enter here really all scans for this feature? // or only the ones with rt-weight > min_rt_weight while (f_v_idx < variable_indices.size() && f == variable_indices[f_v_idx].feature) { bool found_index = false; for (Size idx = 0; idx < indices.size(); ++idx) { if (indices[idx] == (Int)f_v_idx) { found_index = true; break; } } if (!found_index) { // weight is detectability * rt_weight double dt = map_iter->second[p]; double weight = dt * rt_weight; #ifdef DEBUG_OPS std::cout << dt << " * " << rt_weight << " = " << dt * rt_weight << " -> " << weight << " -> " << log(1. - weight) / log(1. - min_prot_coverage) << " obj: " << model_->getObjective(f_v_idx) << " columnname: " << model_->getColumnName(f_v_idx) << std::endl; std::cout << weight << " <? " << min_pred_pep_weight << "? " << (weight < min_pred_pep_weight) << "\n"; #endif if (weight < min_pred_pep_weight) { ++f_v_idx; continue; } indices.push_back((Int)f_v_idx); if (fabs(1. - weight) < 0.000001) { entries.push_back(-log(0.000001) / log(1. - min_prot_coverage)); } else entries.push_back(-log(1. - weight) / log(1. - min_prot_coverage)); #ifdef DEBUG_OPS if (features[f].metaValueExists("pred_pep_prob")) { std::cout << "old pred_pep_prob " << features[f].getMetaValue("pred_pep_prob") << " vs. new " << weight << std::endl; } #endif features[f].setMetaValue("pred_pep_prob", weight); // enter this constraint for the this feature into the feature_constraint_map } ++f_v_idx; } // while(f_v_idx < variable_indices.size() && f == variable_indices[f_v_idx].feature) } //else } //if(rt_weight > min_rt_weight) } //if(fabs(masses[p] - features[f].getMZ())/masses[p] * 1e06 < mz_tolerance) } //for(Size f = 0; f < features.size();++f) } //if(map_iter->second[p] > min_pt) } //for(Size p = 0;p < map_iter->second.size();++p) // now enter protein variable y_i indices.push_back(protein_variable_index_map[map_iter->first]); entries.push_back(1.); //Int i = distance(preprocessed_db.getProteinPTMap().begin(),map_iter); #ifdef DEBUG_OPS std::cout << "\nadd row "; // std::cout << (String("PROT_COV_") + map_iter->first) << "\t" << (String("PROT_COV_") + i).c_str(); std::cout << " " << indices.size() << " entries " << (indices[0]) << " " << (entries[0]) << std::endl; #endif // at the moment we want a certain protein coverage model_->addRow(indices, entries, String("PROT_COV_") + map_iter->first, 0, 0., LPWrapper::UPPER_BOUND_ONLY); #ifdef DEBUG_ILP // print constraint: std::cout << " the constraint: \n"; for (Size idx = 0; idx < indices.size(); ++idx) { std::cout << indices[idx] << "\t"; } std::cout << "\n"; for (Size idx = 0; idx < entries.size(); ++idx) { std::cout << entries[idx] << "\t"; } std::cout << "\n"; #endif //std::cout << "added row"<<std::endl; } //if(prot_acc_iter == protein_accs.end()) else { if (find(new_protein_accs.begin(), new_protein_accs.end(), *acc_it) == new_protein_accs.end() && prot_inference.getProteinProbability(*acc_it) >= min_prot_coverage && double(param_.getValue("combined_ilp:k3")) > 0.000001) { new_protein_accs.push_back(*acc_it); updateObjFunction_(*acc_it, features, preprocessed_db, variable_indices); } } } else { std::cout << "Protein not present in preprocessed db: " << *acc_it << std::endl; } } } } // else if(!not_solve) else { // if a selected feature didn't yield any peptide id, all concerned // protein constraints need to be updated (feature has to be deleted from this constraint) Size index = new_feature.getMetaValue("variable_index"); Size f_index = new_feature.getMetaValue("feature_index"); std::cout << "new feature had no peptide id" << std::endl; Size f_v_idx = 0; while (f_v_idx < variable_indices.size() && variable_indices[f_v_idx].feature != f_index) { ++f_v_idx; } // TODO: maybe we need to update old protein constraints, as the selected feature didn't yield any // id std::set<String> updated_constraints; for (Size pa = 0; pa < protein_accs.size(); ++pa) { Int row = model_->getRowIndex(String("PROT_COV_") + protein_accs[pa]); Size f_v_idx2 = f_v_idx; while (f_v_idx2 < variable_indices.size() && f_index == variable_indices[f_v_idx2].feature) { index = variable_indices[f_v_idx2].variable; if (model_->getElement(row, static_cast<Int>(index)) != 0.) { updated_constraints.insert(protein_accs[pa]); #ifdef DEBUG_OPS std::cout << "getElement(" << protein_accs[pa] << "," << index << ")=" << model_->getElement(row, index) << "\t"; #endif model_->setElement(row, static_cast<Int>(index), 0.); #ifdef DEBUG_OPS std::cout << "getElement(" << protein_accs[pa] << "," << index << ")=" << model_->getElement(row, index) << "\n"; #endif } ++f_v_idx2; } } } #ifdef DEBUG_OPS std::cout << "updated Combined ILP\n"; timer.stop(); std::cout << timer.getClockTime() << " seconds needed to update combined ILP.\n"; #endif } void PSLPFormulation::getXIC_(const std::vector<std::pair<Size, Size> >& end_points, std::vector<double>& weights, const PeakMap& experiment, const bool normalize) { double max_weight = 0.; weights.clear(); for (Size i = 0; i < end_points.size(); i += 2) { double weight = 0.; for (Size j = end_points[i].second; j <= end_points[i + 1].second; ++j) { weight += experiment[end_points[i].first][j].getIntensity(); // std::cout << " add "<<experiment[end_points[i].first][j].getIntensity()<<std::endl; } if (weight > max_weight) max_weight = weight; weights.push_back(weight); } if (normalize) { // normalize weights for (Size i = 0; i < weights.size(); ++i) { #ifdef DEBUG_OPS if (end_points.size() >= i) { std::cout << "scan " << end_points[i].first << " " << weights[i] << " " << max_weight << " " << weights[i] / max_weight << std::endl; } #endif weights[i] /= max_weight; } } } void PSLPFormulation::calculateXICs_(std::vector<std::vector<double> >& xics, const FeatureMap& features, const PeakMap& experiment, const std::vector<std::vector<std::pair<Size, Size> > >& mass_ranges, const bool normalize) { xics.clear(); xics.resize(features.size()); for (Size i = 0; i < features.size(); ++i) { getXIC_(mass_ranges[i], xics[i], experiment, normalize); } } void PSLPFormulation::createAndSolveILPForKnownLCMSMapFeatureBased(const FeatureMap& features, const PeakMap& experiment, std::vector<IndexTriple>& variable_indices, std::vector<std::vector<std::pair<Size, Size> > >& mass_ranges, std::set<Int>& charges_set, UInt ms2_spectra_per_rt_bin, std::vector<int>& solution_indices) { std::vector<std::vector<double> > intensity_weights; if (param_.getValue("feature_based:no_intensity_normalization") == "false") { calculateXICs_(intensity_weights, features, experiment, mass_ranges, true); } else { calculateXICs_(intensity_weights, features, experiment, mass_ranges, false); } #ifdef DEBUG_OPS std::cout << "got xics" << std::endl; #endif createAndSolveILP_(features, intensity_weights, charges_set, mass_ranges, variable_indices, solution_indices, ms2_spectra_per_rt_bin, experiment.size()); } void PSLPFormulation::createAndSolveCombinedLPForKnownLCMSMapFeatureBased(const FeatureMap& features, const PeakMap& experiment, std::vector<IndexTriple>& variable_indices, std::vector<Int>& solution_indices, std::vector<std::vector<std::pair<Size, Size> > >& mass_ranges, std::set<Int>& charges_set, UInt ms2_spectra_per_rt_bin, Size step_size, bool sequential_order) { std::vector<std::vector<double> > intensity_weights; calculateXICs_(intensity_weights, features, experiment, mass_ranges, true); #ifdef DEBUG_OPS std::cout << "got xics" << std::endl; #endif createAndSolveCombinedLPFeatureBased_(features, intensity_weights, charges_set, mass_ranges, variable_indices, solution_indices, ms2_spectra_per_rt_bin, experiment.size(), step_size, sequential_order); } } // namespace OpenMS
45.362245
251
0.55455
[ "vector", "model" ]
0f7c15a4363ec473bac11fa11d710dd8be397bf4
11,363
cpp
C++
OPHD/Common.cpp
Daedeross/OPHD
16c0c4bf44bd74fe2ef413e344d3ef5aeab6102c
[ "BSD-3-Clause" ]
30
2018-03-31T19:16:45.000Z
2019-10-15T03:12:17.000Z
OPHD/Common.cpp
Daedeross/OPHD
16c0c4bf44bd74fe2ef413e344d3ef5aeab6102c
[ "BSD-3-Clause" ]
149
2018-04-23T01:47:22.000Z
2020-02-09T04:04:34.000Z
OPHD/Common.cpp
Daedeross/OPHD
16c0c4bf44bd74fe2ef413e344d3ef5aeab6102c
[ "BSD-3-Clause" ]
10
2018-04-28T14:59:07.000Z
2020-01-26T19:54:36.000Z
#include "Common.h" #include "Constants/Numbers.h" #include "StructureManager.h" #include "XmlSerializer.h" #include "Things/Structures/Structure.h" #include "Things/Structures/Warehouse.h" #include <NAS2D/Utility.h> #include <NAS2D/Xml/XmlDocument.h> #include <NAS2D/Xml/XmlElement.h> using namespace NAS2D; std::string difficultyString(Difficulty difficulty) { for (const auto& difficultyPair : difficultyTable) { if (difficultyPair.second == difficulty) { return difficultyPair.first; } } throw std::runtime_error("Provided difficulty does not exist in the difficultyMap"); } const std::map<StructureState, Color> STRUCTURE_COLOR_TABLE { {StructureState::UnderConstruction, Color{150, 150, 150, 100}}, {StructureState::Operational, Color{0, 185, 0}}, {StructureState::Idle, Color{0, 185, 0, 100}}, {StructureState::Disabled, Color{220, 0, 0}}, {StructureState::Destroyed, Color{220, 0, 0}} }; const std::map<StructureState, Color> STRUCTURE_TEXT_COLOR_TABLE { {StructureState::UnderConstruction, Color{185, 185, 185, 100}}, {StructureState::Operational, Color{0, 185, 0}}, {StructureState::Idle, Color{0, 185, 0, 100}}, {StructureState::Disabled, Color{220, 0, 0}}, {StructureState::Destroyed, Color{220, 0, 0}} }; const std::map<TerrainType, std::string> TILE_INDEX_TRANSLATION = { {TerrainType::Dozed, constants::TileBulldozed}, {TerrainType::Clear, constants::TileClear}, {TerrainType::Rough, constants::TileRough}, {TerrainType::Difficult, constants::TileDifficult}, {TerrainType::Impassable, constants::TileImpassable}, }; const std::map<MineProductionRate, std::string> MINE_YIELD_TRANSLATION = { {MineProductionRate::High, constants::MineYieldHigh}, {MineProductionRate::Low, constants::MineYieldLow}, {MineProductionRate::Medium, constants::MineYieldMedium} }; const std::map<DisabledReason, std::string> DISABLED_REASON_TABLE = { {DisabledReason::None, constants::StructureDisabledNone}, {DisabledReason::Chap, constants::StructureDisabledChap}, {DisabledReason::Disconnected, constants::StructureDisabledDisconnected}, {DisabledReason::Energy, constants::StructureDisabledEnergy}, {DisabledReason::Population, constants::StructureDisabledPopulation}, {DisabledReason::RefinedResources, constants::StructureDisabledRefinedResources}, {DisabledReason::StructuralIntegrity, constants::StructureDisabledStructuralIntegrity} }; const std::map<IdleReason, std::string> IDLE_REASON_TABLE = { {IdleReason::None, constants::StructureIdleNone}, {IdleReason::PlayerSet, constants::StructureIdlePlayerSet}, {IdleReason::InternalStorageFull, constants::StructureIdleInternalStorageFull}, {IdleReason::FactoryProductionComplete, constants::StructureIdleFactoryProductionComplete}, {IdleReason::FactoryInsufficientResources, constants::StructureIdleFactoryInsufficientResources}, {IdleReason::FactoryInsufficientRobotCommandCapacity, constants::StructureIdleFactoryInsufficientRobotCommandCapacity}, {IdleReason::FactoryInsufficientWarehouseSpace, constants::StructureIdleFactoryInsufficnetWarehouseCapacity}, {IdleReason::MineExhausted, constants::StructureIdleMineExhausted}, {IdleReason::MineInactive, constants::StructureIdleMineInactive}, {IdleReason::InsufficientLuxuryProduct, constants::StructureIdleInsufficientLuxuryProduct} }; const std::array MoraleStringTable = { std::string("Terrible"), std::string("Poor"), std::string("Fair"), std::string("Good"), std::string("Excellent"), std::string("Morale is "), std::string("Births"), std::string("Deaths"), std::string("No active Food Production"), std::string("Parks & Arboretums"), std::string("Recreational Facilities"), std::string("Luxury Availability"), std::string("Residential Over Capacity"), std::string("Biowaste Overflowing"), std::string("Structures Disabled"), std::string("Structures Destroyed") }; const std::string& moraleString(int index) { return MoraleStringTable[index]; } const std::string& moraleString(Morale morale) { return MoraleStringTable[static_cast<int>(morale)]; } int moraleStringTableCount() { return static_cast<int>(MoraleStringTable.size()); } /** * Description table for products. */ std::array<std::string, ProductType::PRODUCT_COUNT> PRODUCT_DESCRIPTION_TABLE = { constants::Robodigger, constants::Robodozer, constants::Robominer, constants::Roboexplorer, constants::Truck, "PRODUCT_RESERVED_AG_05", "PRODUCT_RESERVED_AG_06", "PRODUCT_RESERVED_AG_07", "PRODUCT_RESERVED_AG_08", constants::MaintenanceSupplies, "PRODUCT_RESERVED_AG_10", "PRODUCT_RESERVED_AG_11", "PRODUCT_RESERVED_AG_12", "PRODUCT_RESERVED_AG_13", "PRODUCT_RESERVED_AG_14", "PRODUCT_RESERVED_AG_15", "PRODUCT_RESERVED_AG_16", "PRODUCT_RESERVED_AG_17", "PRODUCT_RESERVED_AG_18", "PRODUCT_RESERVED_AG_19", "PRODUCT_RESERVED_AG_20", "PRODUCT_RESERVED_AG_21", "PRODUCT_RESERVED_AG_22", "PRODUCT_RESERVED_AG_23", "PRODUCT_RESERVED_AG_24", "PRODUCT_RESERVED_AG_25", "PRODUCT_RESERVED_AG_26", "PRODUCT_RESERVED_AG_27", "PRODUCT_RESERVED_AG_28", "PRODUCT_RESERVED_AG_29", "PRODUCT_RESERVED_AG_30", "PRODUCT_RESERVED_AG_31", // ===================================== // = UNDERGROUND FACTORIES // ===================================== constants::Clothing, constants::Medicine, "PRODUCT_RESERVED_UG_34", "PRODUCT_RESERVED_UG_35", "PRODUCT_RESERVED_UG_36", "PRODUCT_RESERVED_UG_37", "PRODUCT_RESERVED_UG_38", "PRODUCT_RESERVED_UG_39", "PRODUCT_RESERVED_UG_40", "PRODUCT_RESERVED_UG_41", "PRODUCT_RESERVED_UG_42", "PRODUCT_RESERVED_UG_43", "PRODUCT_RESERVED_UG_44", "PRODUCT_RESERVED_UG_45", "PRODUCT_RESERVED_UG_46", "PRODUCT_RESERVED_UG_47", "PRODUCT_RESERVED_UG_48", "PRODUCT_RESERVED_UG_49", "PRODUCT_RESERVED_UG_50", "PRODUCT_RESERVED_UG_51", "PRODUCT_RESERVED_UG_52", "PRODUCT_RESERVED_UG_53", "PRODUCT_RESERVED_UG_54", "PRODUCT_RESERVED_UG_55", "PRODUCT_RESERVED_UG_56", "PRODUCT_RESERVED_UG_57", "PRODUCT_RESERVED_UG_58", "PRODUCT_RESERVED_UG_59", "PRODUCT_RESERVED_UG_60", "PRODUCT_RESERVED_UG_61", "PRODUCT_RESERVED_UG_62", "PRODUCT_RESERVED_UG_63" }; const std::array<std::string, 4> ResourceNamesRefined = { {"Common Metals", "Common Minerals", "Rare Metals", "Rare Minerals"} }; const std::array<std::string, 4> ResourceNamesOre = { {"Common Metals Ore", "Common Minerals Ore", "Rare Metals Ore", "Rare Minerals Ore"} }; const std::array<NAS2D::Rectangle<int>, 4> ResourceImageRectsRefined = { NAS2D::Rectangle{64, 16, 16, 16}, NAS2D::Rectangle{96, 16, 16, 16}, NAS2D::Rectangle{80, 16, 16, 16}, NAS2D::Rectangle{112, 16, 16, 16}, }; const std::array<NAS2D::Rectangle<int>, 4> ResourceImageRectsOre = { NAS2D::Rectangle{64, 0, 16, 16}, NAS2D::Rectangle{96, 0, 16, 16}, NAS2D::Rectangle{80, 0, 16, 16}, NAS2D::Rectangle{112, 0, 16, 16}, }; const std::map<std::array<bool, 4>, std::string> IntersectionPatternTable = { {{true, false, true, false}, "left"}, {{true, false, false, false}, "left"}, {{false, false, true, false}, "left"}, {{false, true, false, true}, "right"}, {{false, true, false, false}, "right"}, {{false, false, false, true}, "right"}, {{false, false, false, false}, "intersection"}, {{true, true, false, false}, "intersection"}, {{false, false, true, true}, "intersection"}, {{false, true, true, true}, "intersection"}, {{true, true, true, false}, "intersection"}, {{true, true, true, true}, "intersection"}, {{true, false, false, true}, "intersection"}, {{false, true, true, false}, "intersection"}, {{false, true, true, true}, "intersection"}, {{true, false, true, true}, "intersection"}, {{true, true, false, true}, "intersection"}, {{true, true, true, false}, "intersection"} }; const std::string& productDescription(ProductType type) { if (type == ProductType::PRODUCT_NONE) { return constants::None; } return PRODUCT_DESCRIPTION_TABLE[static_cast<std::size_t>(type)]; } ProductType productTypeFromDescription(const std::string& description) { for (std::size_t i = 0; i < PRODUCT_DESCRIPTION_TABLE.size(); ++i) { if (PRODUCT_DESCRIPTION_TABLE[i] == description) { // dubious (and slow) return static_cast<ProductType>(i); } } return ProductType::PRODUCT_NONE; } const std::string& disabledReason(DisabledReason disabledReason) { return DISABLED_REASON_TABLE.at(disabledReason); } const std::string& idleReason(IdleReason idleReason) { return IDLE_REASON_TABLE.at(idleReason); } Color structureColorFromIndex(StructureState structureState) { return STRUCTURE_COLOR_TABLE.at(structureState); } Color structureTextColorFromIndex(StructureState structureState) { return STRUCTURE_TEXT_COLOR_TABLE.at(structureState); } void checkSavegameVersion(const std::string& filename) { // openSavegame checks version number after opening file openSavegame(filename); } /** * Open a saved game and validate version. * * \throws Throws a std::runtime_error if there are any errors with a savegame version, formation or missing root nodes. */ NAS2D::Xml::XmlDocument openSavegame(const std::string& filename) { auto xmlDocument = openXmlFile(filename, constants::SaveGameRootNode); auto savegameVersion = xmlDocument.firstChildElement(constants::SaveGameRootNode)->attribute("version"); if (savegameVersion != constants::SaveGameVersion) { throw std::runtime_error("Savegame version mismatch: '" + filename + "'. Expected " + constants::SaveGameVersion + ", found " + savegameVersion + "."); } return xmlDocument; } std::vector<std::string> splitString(const std::string& string, char delimiter) { std::vector<std::string> result; const char* str = string.c_str(); do { const char* begin = str; while (*str != delimiter && *str) { str++; } result.push_back(std::string(begin, str)); } while (0 != *str++); return result; } void drawBasicProgressBar(int x, int y, int width, int height, float percent, int padding) { auto& renderer = Utility<Renderer>::get(); renderer.drawBox(NAS2D::Rectangle{x, y, width, height}, NAS2D::Color{0, 185, 0}); if (percent > 0.0f) { int bar_width = static_cast<int>(static_cast<float>(width - (padding + padding)) * percent); renderer.drawBoxFilled(NAS2D::Rectangle{x + padding, y + padding + 1, bar_width - 1, height - (padding + padding) - 1}, NAS2D::Color{0, 100, 0}); } } int getTruckAvailability() { int trucksAvailable = 0; auto& warehouseList = NAS2D::Utility<StructureManager>::get().getStructures<Warehouse>(); for (auto warehouse : warehouseList) { trucksAvailable += warehouse->products().count(ProductType::PRODUCT_TRUCK); } return trucksAvailable; } int pullTruckFromInventory() { int trucksAvailable = getTruckAvailability(); if (trucksAvailable == 0) { return 0; } auto& warehouseList = NAS2D::Utility<StructureManager>::get().getStructures<Warehouse>(); for (auto warehouse : warehouseList) { if (warehouse->products().pull(ProductType::PRODUCT_TRUCK, 1) > 0) { return 1; } } return 0; } int pushTruckIntoInventory() { const int storageNeededForTruck = storageRequiredPerUnit(ProductType::PRODUCT_TRUCK); auto& warehouseList = NAS2D::Utility<StructureManager>::get().getStructures<Warehouse>(); for (auto warehouse : warehouseList) { if (warehouse->products().availableStorage() >= storageNeededForTruck) { warehouse->products().store(ProductType::PRODUCT_TRUCK, 1); return 1; } } return 0; }
26.425581
153
0.739945
[ "vector" ]
0f7d602d64d83411411cc9c49529a1ff19d28238
4,087
cpp
C++
toonz/sources/toonz/histogrampopup.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/toonz/histogrampopup.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/toonz/histogrampopup.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
1
2019-10-07T17:12:30.000Z
2019-10-07T17:12:30.000Z
#include "histogrampopup.h" // Tnz6 includes #include "menubarcommandids.h" #include "tapp.h" #include "previewer.h" // TnzQt includes #include "toonzqt/menubarcommand.h" #include "toonzqt/combohistogram.h" // TnzLib includes #include "toonz/tframehandle.h" // TnzCore includes #include "trasterimage.h" #include "tvectorimage.h" #include "ttoonzimage.h" // Qt includes #include <QTimer> #include <QMainWindow> using namespace DVGui; //============================================================================= /*! \class HistogramPopup \brief The HistogramPopup class provides a dialog to show an histogram \b Histogram Inherits \b Dialog. */ //----------------------------------------------------------------------------- HistogramPopup::HistogramPopup(QString title) : QDialog(TApp::instance()->getMainWindow()) { setTitle(title); m_histogram = new ComboHistogram(this); QVBoxLayout *mainLay = new QVBoxLayout(); mainLay->setMargin(0); mainLay->setSpacing(0); { mainLay->addWidget(m_histogram); } setLayout(mainLay); setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); } //----------------------------------------------------------------------------- void HistogramPopup::setTitle(QString title) { setWindowTitle(title); } //----------------------------------------------------------------------------- void HistogramPopup::setImage(TImageP image) { TRasterImageP rimg = (TRasterImageP)image; TVectorImageP vimg = (TVectorImageP)image; TToonzImageP timg = (TToonzImageP)image; TPaletteP palette; TRasterP ras; if (rimg) ras = rimg->getRaster(); else if (timg) { ras = timg->getRaster(); palette = timg->getPalette(); } else if (vimg) ras = vimg->render(false); m_histogram->setRaster(ras, palette); } //----------------------------------------------------------------------------- /*! show the picked color */ void HistogramPopup::updateInfo(const TPixel32 &pix, const TPointD &imagePos) { m_histogram->updateInfo(pix, imagePos); } //----------------------------------------------------------------------------- /*! show the average-picked color */ void HistogramPopup::updateAverageColor(const TPixel32 &pix) { m_histogram->updateAverageColor(pix); } //============================================================================= /*! \class ViewerHistogramPopup \brief The ViewerHistogramPopup show the histogram pertain to current viewer. Inherits \b Dialog. */ //----------------------------------------------------------------------------- ViewerHistogramPopup::ViewerHistogramPopup() : HistogramPopup(tr("Viewer Histogram")) { } //----------------------------------------------------------------------------- void ViewerHistogramPopup::showEvent(QShowEvent *e) { connect(TApp::instance()->getCurrentFrame(), SIGNAL(frameSwitched()), SLOT(setCurrentRaster())); connect(Previewer::instance(), SIGNAL(activedChanged()), SLOT(setCurrentRaster())); setCurrentRaster(); } //----------------------------------------------------------------------------- void ViewerHistogramPopup::hideEvent(QHideEvent *e) { disconnect(TApp::instance()->getCurrentFrame(), SIGNAL(frameSwitched()), this, SLOT(setCurrentRaster())); disconnect(Previewer::instance(), SIGNAL(activedChanged()), this, SLOT(setCurrentRaster())); } //----------------------------------------------------------------------------- void ViewerHistogramPopup::setCurrentRaster() { TApp *app = TApp::instance(); Previewer *previewer = Previewer::instance(); TRasterP ras = 0; if (previewer->isActive()) { int currentFrame = app->getCurrentFrame()->getFrameIndex(); //Se il preview del frame non e' pronto richiamo questo metodo dopo un intervallo di 10 ms if (!previewer->isFrameReady(currentFrame)) { QTimer::singleShot(10, this, SLOT(setCurrentRaster())); return; } ras = previewer->getRaster(currentFrame); } m_histogram->setRaster(ras); update(); } //============================================================================= OpenPopupCommandHandler<ViewerHistogramPopup> openHistogramPopup(MI_Histogram);
26.712418
106
0.56643
[ "render" ]
abee3728061983915a66060ce62c6fc7aa8cc6e1
7,775
cxx
C++
Modules/Segmentation/Classifiers/test/itkBayesianClassifierImageFilterTest.cxx
ltmakela/ITK
21f48c6d98e21ecece09be16a747221d7094d8a9
[ "Apache-2.0" ]
4
2015-05-22T03:47:43.000Z
2016-06-16T20:57:21.000Z
Modules/Segmentation/Classifiers/test/itkBayesianClassifierImageFilterTest.cxx
GEHC-Surgery/ITK
f5df62749e56c9036e5888cfed904032ba5fdfb7
[ "Apache-2.0" ]
null
null
null
Modules/Segmentation/Classifiers/test/itkBayesianClassifierImageFilterTest.cxx
GEHC-Surgery/ITK
f5df62749e56c9036e5888cfed904032ba5fdfb7
[ "Apache-2.0" ]
9
2016-06-23T16:03:12.000Z
2022-03-31T09:25:08.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkImageFileReader.h" #include "itkBayesianClassifierImageFilter.h" #include "itkBayesianClassifierInitializationImageFilter.h" #include "itkImageFileWriter.h" #include "itkGradientAnisotropicDiffusionImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkPipelineMonitorImageFilter.h" int itkBayesianClassifierImageFilterTest(int argc, char* argv[] ) { if( argc < 5 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile outputImageFile numberOfClasses smoothingIterations" << std::endl; return EXIT_FAILURE; } // setup reader const unsigned int Dimension = 2; typedef unsigned char InputPixelType; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::ImageFileReader< InputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); typedef unsigned char LabelType; typedef float PriorType; typedef float PosteriorType; typedef itk::BayesianClassifierInitializationImageFilter< InputImageType > BayesianInitializerType; BayesianInitializerType::Pointer bayesianInitializer = BayesianInitializerType::New(); bayesianInitializer->SetInput( reader->GetOutput() ); bayesianInitializer->SetNumberOfClasses( atoi( argv[3] ) ); typedef BayesianInitializerType::OutputImageType InitialLabelImageType; typedef itk::BayesianClassifierImageFilter< InitialLabelImageType, LabelType, PosteriorType, PriorType > ClassifierFilterType; ClassifierFilterType::Pointer filter = ClassifierFilterType::New(); filter->SetInput( bayesianInitializer->GetOutput() ); // // Exercise Set/GetNumberOfSmoothingIterations() // filter->SetNumberOfSmoothingIterations( 1 ); if( filter->GetNumberOfSmoothingIterations() != 1 ) { std::cerr << "Error in Set/GetNumberOfSmoothingIterations()" << std::endl; return EXIT_FAILURE; } filter->SetNumberOfSmoothingIterations( 19 ); if( filter->GetNumberOfSmoothingIterations() != 19 ) { std::cerr << "Error in Set/GetNumberOfSmoothingIterations()" << std::endl; return EXIT_FAILURE; } filter->SetNumberOfSmoothingIterations( 0 ); filter->SetNumberOfSmoothingIterations( atoi( argv[4] )); typedef ClassifierFilterType::ExtractedComponentImageType ExtractedComponentImageType; typedef itk::GradientAnisotropicDiffusionImageFilter< ExtractedComponentImageType, ExtractedComponentImageType > SmoothingFilterType; SmoothingFilterType::Pointer smoother = SmoothingFilterType::New(); smoother->SetNumberOfIterations( 1 ); smoother->SetTimeStep( 0.125 ); smoother->SetConductanceParameter( 3 ); filter->SetSmoothingFilter( smoother ); // // Exercise Set/GetSmoothingFilter() // if( filter->GetSmoothingFilter().GetPointer() != smoother.GetPointer() ) { std::cerr << "Error in Set/GetSmoothingFilter()" << std::endl; return EXIT_FAILURE; } filter->SetSmoothingFilter( NULL ); if( filter->GetSmoothingFilter().GetPointer() != NULL ) { std::cerr << "Error in Set/GetSmoothingFilter()" << std::endl; return EXIT_FAILURE; } filter->SetSmoothingFilter( smoother ); typedef itk::PipelineMonitorImageFilter<InputImageType> MonitorFilterType; MonitorFilterType::Pointer monitor = MonitorFilterType::New(); monitor->SetInput(filter->GetOutput()); typedef ClassifierFilterType::OutputImageType ClassifierOutputImageType; typedef itk::Image< unsigned char, Dimension > OutputImageType; typedef itk::RescaleIntensityImageFilter< ClassifierOutputImageType, OutputImageType > RescalerType; RescalerType::Pointer rescaler = RescalerType::New(); rescaler->SetInput( monitor->GetOutput() ); rescaler->SetOutputMinimum( 0 ); rescaler->SetOutputMaximum( 255 ); typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput( rescaler->GetOutput() ); try { filter->Update(); writer->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception caught: " << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } if (!monitor->VerifyAllInputCanNotStream()) { std::cout << "pipeline did not execute as expected!" << std::endl; return EXIT_FAILURE; } filter->Print( std::cout ); std::cout << "Test passed." << std::endl; typedef ClassifierFilterType::PriorsImageType PriorsImageType; const InputImageType * inputImage = reader->GetOutput(); PriorsImageType::Pointer priorsImage = PriorsImageType::New(); priorsImage->CopyInformation( inputImage ); priorsImage->SetRegions( inputImage->GetLargestPossibleRegion() ); priorsImage->SetNumberOfComponentsPerPixel(5); priorsImage->Allocate(); filter->SetPriors( priorsImage ); ///TEST valid image type combinations. I have a hypothesis that the vector element type for //TestInitialLabelImageType must be the same as for TestPriorType { const unsigned int TestDimension = 2; typedef unsigned char TestLabelType; typedef float TestPosteriorType; typedef float TestPriorType; typedef itk::VectorImage< TestPriorType ,TestDimension > TestInitialLabelImageType; typedef itk::BayesianClassifierImageFilter< TestInitialLabelImageType, TestLabelType, TestPosteriorType, TestPriorType > TestClassifierFilterType; TestClassifierFilterType::Pointer test=TestClassifierFilterType::New(); if(test.IsNull()) { return EXIT_FAILURE; } } { const unsigned int TestDimension = 2; typedef unsigned char TestLabelType; typedef float TestPosteriorType; typedef float TestPriorType; typedef itk::VectorImage< double ,TestDimension > TestInitialLabelImageType; //The element type MUST be the PriorType typedef itk::BayesianClassifierImageFilter< TestInitialLabelImageType, TestLabelType, TestPosteriorType, TestPriorType > TestClassifierFilterType; TestClassifierFilterType::Pointer test=TestClassifierFilterType::New(); if(test.IsNull()) { return EXIT_FAILURE; } } { const unsigned int TestDimension = 2; typedef unsigned char TestLabelType; typedef float TestPosteriorType; typedef double TestPriorType; typedef itk::VectorImage< TestPriorType ,TestDimension > TestInitialLabelImageType; //The element type MUST be the PriorType typedef itk::BayesianClassifierImageFilter< TestInitialLabelImageType, TestLabelType, TestPosteriorType, TestPriorType > TestClassifierFilterType; TestClassifierFilterType::Pointer test=TestClassifierFilterType::New(); if(test.IsNull()) { return EXIT_FAILURE; } } return EXIT_SUCCESS; }
34.402655
128
0.704952
[ "vector" ]
abf273d89df4455194ec6105c450b12bf9546bf1
1,120
hpp
C++
SDEngine/include/Utility/Transform.hpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
null
null
null
SDEngine/include/Utility/Transform.hpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
4
2021-12-10T05:01:49.000Z
2022-03-19T10:16:14.000Z
SDEngine/include/Utility/Transform.hpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
null
null
null
#ifndef SD_TRANSFORM_HPP #define SD_TRANSFORM_HPP #include "Utility/Base.hpp" #include "Utility/Serialize.hpp" #include "Utility/Math.hpp" #include <set> namespace SD { class SD_UTILITY_API Transform { public: Transform(); virtual ~Transform() = default; void SetPosition(const Vector3f& position); void SetRotation(const Quaternion& rotation); void SetScale(const Vector3f& scale); void SetTransform(const Matrix4f& transform); Vector3f GetPosition() const; Quaternion GetRotation() const; Vector3f GetScale() const; Matrix4f GetMatrix() const; Vector3f GetRight() const; Vector3f GetUp() const; Vector3f GetFront() const; Vector3f WorldToLocal(const Vector3f& world) const; Vector3f LocalToWorld(const Vector3f& local) const; Vector3f WorldToLocalVector(const Vector3f& world_vec) const; Vector3f LocalToWorldVector(const Vector3f& local_vec) const; SERIALIZE(m_position, m_rotation, m_scale) private: Vector3f m_position; Quaternion m_rotation; Vector3f m_scale; }; } // namespace SD #endif /* SD_TRANSFORM_HPP */
23.829787
65
0.726786
[ "transform" ]
abfa603b5847358915ebcdff8025d188a49b4cfe
4,836
cc
C++
source/blender/nodes/geometry/nodes/node_geo_transform.cc
jinohschool/blender
2f083f7eaabd5e699a0c08673e502ea8a274ac6c
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2021-09-29T06:25:03.000Z
2021-09-29T06:25:03.000Z
source/blender/nodes/geometry/nodes/node_geo_transform.cc
mmtt1998819/blender
c9c3bf983321990a6960c422e002a372c35a6f76
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/nodes/geometry/nodes/node_geo_transform.cc
mmtt1998819/blender
c9c3bf983321990a6960c422e002a372c35a6f76
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2021-01-08T06:33:25.000Z
2021-01-08T06:33:25.000Z
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "BLI_math_matrix.h" #include "DNA_pointcloud_types.h" #include "BKE_mesh.h" #include "node_geometry_util.hh" static bNodeSocketTemplate geo_node_transform_in[] = { {SOCK_GEOMETRY, N_("Geometry")}, {SOCK_VECTOR, N_("Translation"), 0.0f, 0.0f, 0.0f, 1.0f, -FLT_MAX, FLT_MAX, PROP_TRANSLATION}, {SOCK_VECTOR, N_("Rotation"), 0.0f, 0.0f, 0.0f, 1.0f, -FLT_MAX, FLT_MAX, PROP_EULER}, {SOCK_VECTOR, N_("Scale"), 1.0f, 1.0f, 1.0f, 1.0f, -FLT_MAX, FLT_MAX, PROP_XYZ}, {-1, ""}, }; static bNodeSocketTemplate geo_node_transform_out[] = { {SOCK_GEOMETRY, N_("Geometry")}, {-1, ""}, }; namespace blender::nodes { static bool use_translate(const float3 rotation, const float3 scale) { if (compare_ff(rotation.length_squared(), 0.0f, 1e-9f) != 1) { return false; } if (compare_ff(scale.x, 1.0f, 1e-9f) != 1 || compare_ff(scale.y, 1.0f, 1e-9f) != 1 || compare_ff(scale.z, 1.0f, 1e-9f) != 1) { return false; } return true; } static void transform_mesh(Mesh *mesh, const float3 translation, const float3 rotation, const float3 scale) { /* Use only translation if rotation and scale are zero. */ if (use_translate(rotation, scale)) { BKE_mesh_translate(mesh, translation, true); } else { float mat[4][4]; loc_eul_size_to_mat4(mat, translation, rotation, scale); BKE_mesh_transform(mesh, mat, true); BKE_mesh_calc_normals(mesh); } } static void transform_pointcloud(PointCloud *pointcloud, const float3 translation, const float3 rotation, const float3 scale) { /* Use only translation if rotation and scale don't apply. */ if (use_translate(rotation, scale)) { for (int i = 0; i < pointcloud->totpoint; i++) { add_v3_v3(pointcloud->co[i], translation); } } else { float mat[4][4]; loc_eul_size_to_mat4(mat, translation, rotation, scale); for (int i = 0; i < pointcloud->totpoint; i++) { mul_m4_v3(mat, pointcloud->co[i]); } } } static void transform_instances(InstancesComponent &instances, const float3 translation, const float3 rotation, const float3 scale) { MutableSpan<float3> positions = instances.positions(); /* Use only translation if rotation and scale don't apply. */ if (use_translate(rotation, scale)) { for (float3 &position : positions) { add_v3_v3(position, translation); } } else { float mat[4][4]; loc_eul_size_to_mat4(mat, translation, rotation, scale); for (float3 &position : positions) { mul_m4_v3(mat, position); } } } static void geo_node_transform_exec(GeoNodeExecParams params) { GeometrySet geometry_set = params.extract_input<GeometrySet>("Geometry"); const float3 translation = params.extract_input<float3>("Translation"); const float3 rotation = params.extract_input<float3>("Rotation"); const float3 scale = params.extract_input<float3>("Scale"); if (geometry_set.has_mesh()) { Mesh *mesh = geometry_set.get_mesh_for_write(); transform_mesh(mesh, translation, rotation, scale); } if (geometry_set.has_pointcloud()) { PointCloud *pointcloud = geometry_set.get_pointcloud_for_write(); transform_pointcloud(pointcloud, translation, rotation, scale); } if (geometry_set.has_instances()) { InstancesComponent &instances = geometry_set.get_component_for_write<InstancesComponent>(); transform_instances(instances, translation, rotation, scale); } params.set_output("Geometry", std::move(geometry_set)); } } // namespace blender::nodes void register_node_type_geo_transform() { static bNodeType ntype; geo_node_type_base(&ntype, GEO_NODE_TRANSFORM, "Transform", NODE_CLASS_GEOMETRY, 0); node_type_socket_templates(&ntype, geo_node_transform_in, geo_node_transform_out); ntype.geometry_node_execute = blender::nodes::geo_node_transform_exec; nodeRegisterType(&ntype); }
33.123288
98
0.673284
[ "mesh", "geometry", "transform" ]
abfb16c1fd38671a22bf7a0fc05e277d51bcf989
24,402
cpp
C++
client/MarketByPriceHandler.cpp
yeeliu01/pyrfa
536c94f1bcff232415495cbe04b8897ad91e0c76
[ "MIT" ]
33
2016-11-29T08:18:28.000Z
2021-11-11T15:40:19.000Z
client/MarketByPriceHandler.cpp
yeeliu01/pyrfa
536c94f1bcff232415495cbe04b8897ad91e0c76
[ "MIT" ]
41
2016-09-20T10:15:11.000Z
2021-10-20T01:14:22.000Z
client/MarketByPriceHandler.cpp
devcartel/thomsonreuters
536c94f1bcff232415495cbe04b8897ad91e0c76
[ "MIT" ]
9
2016-10-19T00:09:22.000Z
2020-08-03T03:02:15.000Z
#include "common/RDMUtils.h" #include "common/RDMDict.h" #include "MarketByPriceHandler.h" #include <boost/algorithm/string.hpp> using namespace rfa::data; MarketByPriceHandler::MarketByPriceHandler(rfa::sessionLayer::OMMConsumer* pOMMConsumer, rfa::common::EventQueue& eventQueue, rfa::common::Client& client, const std::string& serviceName, const RDMFieldDict* dict, rfa::logger::ComponentLogger& componentLogger): _pOMMConsumer(pOMMConsumer), _componentLogger(componentLogger), _eventQueue(eventQueue), _client(client), _serviceName(serviceName), _pDict(dict), _debug(false), _refreshCount(0), _log("") { } MarketByPriceHandler::~MarketByPriceHandler(void){} void MarketByPriceHandler::sendRequest(const std::string &itemName, const rfa::common::UInt8 &interactionType){ rfa::message::ReqMsg reqMsg; rfa::message::AttribInfo attribInfo(true) ; // // request _itemName from _serviceName // attribInfo.setName(itemName.c_str()); attribInfo.setNameType(rfa::rdm::INSTRUMENT_NAME_RIC); attribInfo.setServiceName(_serviceName.c_str()); reqMsg.setAttribInfo(attribInfo); reqMsg.setMsgModelType(rfa::rdm::MMT_MARKET_BY_PRICE); reqMsg.setInteractionType( interactionType ); rfa::sessionLayer::OMMItemIntSpec intSpec; intSpec.setMsg( &reqMsg ); std::map<rfa::common::Handle*,std::string>::iterator it; std::pair<map<rfa::common::Handle*,std::string>::iterator,bool> ret; it = _watchList.find(getHandle(itemName)); // If item already exists, re-issue the request if(it == _watchList.end()) { _pHandle = _pOMMConsumer->registerClient(&_eventQueue, &intSpec, _client); if(interactionType == (rfa::message::ReqMsg::InitialImageFlag | rfa::message::ReqMsg::InterestAfterRefreshFlag)) { ret = _watchList.insert( pair<rfa::common::Handle*,std::string>(_pHandle,itemName+"."+_serviceName) ); if(ret.second) { if(_debug) { _log = "[MarketByPriceHandler::sendRequest] Add item subscription for: "; _log.append((itemName+"."+_serviceName).c_str()); } } else { _log = "[MarketByPriceHandler::sendRequest] Watchlist insertion failed."; _componentLogger.log(LM_GENERIC_ONE,rfa::common::Error,_log.c_str()); return; } if(_debug) { _log += ". Watchlist size: "; _log.append((int)_watchList.size()); _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str()); } } } else { if(_debug) { _log = "[MarketByPriceHandler::sendRequest] Item is already in the watchlist. Re-issuing for: "; _log.append((itemName+"."+_serviceName).c_str()); _log += ". Watchlist size: "; _log.append((int)_watchList.size()); _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str()); } _pOMMConsumer->reissueClient(it->first, &intSpec); } } void MarketByPriceHandler::closeRequest(const std::string &itemName){ std::map<rfa::common::Handle*,std::string>::iterator it; it = _watchList.find(getHandle(itemName)); if(it != _watchList.end()) { if(_debug) { _log = "[MarketByPriceHandler::closeRequest] Close item subscription for: "; _log.append(it->second.c_str()); } _pOMMConsumer->unregisterClient(it->first); _watchList.erase(it); if(_debug) { _log += ". Watchlist size: "; _log.append((int)_watchList.size()); _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str()); } } } void MarketByPriceHandler::closeAllRequest(){ _pOMMConsumer->unregisterClient(); _watchList.clear(); if(_debug) { _log = "[MarketByPriceHandler::closeAllRequest] Close all item subscription."; _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str()); } } void MarketByPriceHandler::processResponse(const rfa::message::RespMsg& respMsg, rfa::common::Handle* handle, boost::python::tuple& out) { std::string itemName = ""; std::string itemServiceName = ""; itemName = getItemName(handle); if (itemName.empty()) { itemName = respMsg.getAttribInfo().getName().c_str(); } itemServiceName = getItemServiceName(handle); if (itemServiceName.empty()) { itemServiceName = _serviceName; } switch (respMsg.getRespType()){ case rfa::message::RespMsg::RefreshEnum: if(_debug) cout << "[MarketByPriceHandler::processResponse] MarketByPrice Refresh: " << itemName << "." << itemServiceName << endl; // Notify that this is a refresh if(_refreshCount == 0) { dict preempt; preempt["RIC"] = itemName; preempt["SERVICE"] = itemServiceName; preempt["MTYPE"] = "REFRESH"; out += boost::python::make_tuple(preempt); } if (respMsg.getHintMask() & rfa::message::RespMsg::PayloadFlag) { decodeMarketByPrice(respMsg.getPayload(), out, itemName, itemServiceName, "IMAGE"); } else { if(_debug) { _log = "[MarketByPriceHandler::processResponse] Empty Refresh."; _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str()); } } // if refresh complete if(respMsg.getIndicationMask() & rfa::message::RespMsg::RefreshCompleteFlag) { if(_debug) { _log = "[MarketByPriceHandler::processResponse] Refresh Complete \n"; _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str()); } _refreshCount = 0; } else { _refreshCount++; } break; case rfa::message::RespMsg::UpdateEnum: if(_debug) cout << "[MarketByPriceHandler::processResponse] MarketByPrice Update: " << itemName << "." << itemServiceName << endl; if (respMsg.getHintMask() & rfa::message::RespMsg::PayloadFlag) { decodeMarketByPrice(respMsg.getPayload(), out, itemName, itemServiceName, "UPDATE"); } else { if(_debug) { _log = "[MarketByPriceHandler::processResponse] Empty Update."; _componentLogger.log(LM_GENERIC_ONE,rfa::common::Information,_log.c_str()); } } break; case rfa::message::RespMsg::StatusEnum: dict d; d["RIC"] = itemName; d["SERVICE"] = itemServiceName; d["MTYPE"] = "STATUS"; d["TEXT"] = respMsg.getRespStatus().getStatusText().c_str(); d["DATA_STATE"] = RDMUtils::dataStateToString(respMsg.getRespStatus().getDataState()).c_str(); d["STREAM_STATE"] = RDMUtils::streamStateToString(respMsg.getRespStatus().getStreamState()).c_str(); d["STATUS_CODE"] = RDMUtils::statusCodeToString(respMsg.getRespStatus().getStatusCode()).c_str(); out += boost::python::make_tuple(d); if(_debug) cout << "[MarketByPriceHandler::processResponse] MarketByPrice Status: "<< respMsg.getRespStatus().getStatusText().c_str() << endl; _log = "[MarketByPriceHandler::processResponse] MarketByPrice Status: " + respMsg.getRespStatus().getStatusText(); _componentLogger.log(LM_GENERIC_ONE,rfa::common::Warning,_log.c_str()); break; } // display subscription status if (respMsg.getHintMask() & rfa::message::RespMsg::RespStatusFlag) { const rfa::common::RespStatus& status = respMsg.getRespStatus(); // item status details _log = " \n\tStatus :"; _log += " \n\tdataState=\""; _log.append(RDMUtils::dataStateToString(status.getDataState()).c_str()); _log += "\""; _log += " \n\tstreamState=\""; _log.append(RDMUtils::streamStateToString(status.getStreamState()).c_str()); _log += "\" \n\tstatusCode=\""; _log.append(RDMUtils::statusCodeToString(status.getStatusCode()).c_str()); _log += "\" \n\tstatusText=\""; _log += status.getStatusText(); _log += "\""; // close item if streamState is closed if(status.getStreamState() == rfa::common::RespStatus::ClosedEnum) { _componentLogger.log(LM_GENERIC_ONE,rfa::common::Error,_log.c_str()); closeRequest(itemName); } // Unspecified dataState if(status.getDataState() == rfa::common::RespStatus::UnspecifiedEnum) { _componentLogger.log(LM_GENERIC_ONE,rfa::common::Error,_log.c_str()); } } if(_debug && (out != boost::python::tuple())) prettyPrint(out); } void MarketByPriceHandler::prettyPrint(boost::python::tuple& inputTuple) { string out = ""; out.append("("); for ( int i = 0 ; i < len(inputTuple) ; i++ ) { extract<dict>dictElement(inputTuple[i]); //check whether the converted data is python dictionary if (dictElement.check()) { out.append("{"); dict dictElement = extract<dict>(inputTuple[i]); boost::python::list keys = (boost::python::list)dictElement.keys(); for (int j = 0; j < len(keys); j++) { string key = extract<string>(keys[j]); string value = ""; //string extract<string>toString(dictElement[keys[j]]); if(toString.check()) { value = extract<string>(dictElement[keys[j]]); value = "'" + value + "'"; } //double extract<double>toDouble(dictElement[keys[j]]); if(toDouble.check()) { double edouble = extract<double>(dictElement[keys[j]]); value = boost::lexical_cast<string>(edouble); } //int extract<int>toInt(dictElement[keys[j]]); if(toInt.check()) { int eint = extract<int>(dictElement[keys[j]]); value = boost::lexical_cast<string>(eint); } //long extract<long>toLong(dictElement[keys[j]]); if(toLong.check()) { value = extract<string>(str(dictElement[keys[j]])); } out.append("'"+key+"'"+":"+value); if (j != len(keys) - 1) { out.append(","); } } out.append("}"); if (i != len(inputTuple) - 1) { out.append(","); } } } out.append(")"); cout << out << endl; } void MarketByPriceHandler::decodeMarketByPrice(const rfa::common::Data& data, boost::python::tuple &out, const std::string &itemName, const std::string &serviceName, const std::string &mtype) { dict d; const rfa::data::Map& mapData = static_cast<const rfa::data::Map&>(data); // data is RFA update message if(mapData.getIndicationMask() & rfa::data::Map::EntriesFlag) { rfa::data::MapReadIterator mri; mri.start(mapData); const rfa::data::MapEntry & entryInit = mri.value(); const rfa::common::Data & valueDataInit = entryInit.getData(); const rfa::data::FieldList & EntryFieldList = static_cast<const rfa::data::FieldList &>(valueDataInit); for(mri.start(mapData); !mri.off(); mri.forth()) { const rfa::data::MapEntry & entry = mri.value(); const rfa::common::Data & keyData = entry.getKeyData(); const rfa::common::Data & valueData = entry.getData(); if (keyData.getDataType() != rfa::data::DataBufferEnum) { cout << "[MarketByPriceHandler::decodeMarketByPrice] Expected key datatype of DataBuffer" << endl; return; } const rfa::data::DataBuffer & keyBuffer = static_cast<const rfa::data::DataBuffer &>(keyData); if (keyBuffer.getDataBufferType() != rfa::data::DataBuffer::BufferEnum){ cout << "[MarketByPriceHandler::decodeMarketByPrice] Expected key buffer data buffer type of Buffer" << endl; return; } rfa::data::FieldListReadIterator flri; switch (entry.getAction()) { case rfa::data::MapEntry::Add: d["SERVICE"] = serviceName.c_str(); d["RIC"] = itemName.c_str(); d["MTYPE"]= mtype.c_str(); d["ACTION"] = "ADD"; d["KEY"] = static_cast<const rfa::data::DataBuffer&> (keyData).getAsString().c_str(); for(flri.start(EntryFieldList); !flri.off(); flri.forth()) { const rfa::data::FieldEntry& field = flri.value(); const rfa::common::Int16 fieldID = field.getFieldID(); const RDMFieldDef* fieldDef = _pDict->getFieldDef(fieldID); rfa::common::RFA_String fieldValue; // if field name does not exist, use the field ID instead // if no field definition then no dict then no dataType if(!fieldDef) { const rfa::common::UInt8 dataType = (rfa::common::UInt8)rfa::data::DataBuffer::UnknownDataBufferEnum; const rfa::common::Data& fieldData = field.getData(dataType); const rfa::data::DataBuffer& dataBuffer = static_cast<const rfa::data::DataBuffer&>(fieldData); rfa::common::RFA_String fieldValue; fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str(); d[fieldID] = fieldValue.trimWhitespace().c_str(); } else { // convert to DataBuffer const rfa::common::UInt8 dataType = fieldDef->getDataType(); const rfa::common::Data& fieldData = field.getData(dataType); const rfa::data::DataBuffer& dataBuffer = static_cast<const rfa::data::DataBuffer&>(fieldData); const rfa::common::UInt8 dataBufferType = dataBuffer.getDataBufferType(); const RDMEnumDef* enumDef = 0; //Note: somehow RDNDISPLAY has dataType=2 but dataBufferType=4 //check and decode according to data buffer type switch(dataBufferType) { case rfa::data::DataBuffer::EnumerationEnum: enumDef = fieldDef->getEnumDef(); fieldValue = RDMUtils::dataBufferToString(dataBuffer,enumDef).c_str(); d[fieldDef->getName().c_str()] = fieldValue.c_str(); break; case rfa::data::DataBuffer::FloatEnum: case rfa::data::DataBuffer::DoubleEnum: case rfa::data::DataBuffer::Real32Enum: case rfa::data::DataBuffer::Real64Enum: fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str(); if(fieldValue.empty()) { //d[fieldDef->getName().c_str()] = boost::python::object(); d[fieldDef->getName().c_str()] = ""; } else { d[fieldDef->getName().c_str()] = RDMUtils::dataBufferToDouble(dataBuffer); } break; case rfa::data::DataBuffer::Int32Enum: case rfa::data::DataBuffer::UInt32Enum: fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str(); if(fieldValue.empty()) { d[fieldDef->getName().c_str()] = ""; } else { d[fieldDef->getName().c_str()] = RDMUtils::dataBufferToInt(dataBuffer); } break; case rfa::data::DataBuffer::Int64Enum: case rfa::data::DataBuffer::UInt64Enum: fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str(); if(fieldValue.empty()) { d[fieldDef->getName().c_str()] = ""; } else { d[fieldDef->getName().c_str()] = RDMUtils::dataBufferToLong(dataBuffer); } break; default: fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str(); d[fieldDef->getName().c_str()] = fieldValue.trimWhitespace().c_str(); break; } } } break; case rfa::data::MapEntry::Update: if (valueData.getDataType() != rfa::data::FieldListEnum) { cout << "[MarketByPriceHandler::decodeMarketByPrice] Expected data datatype of FieldList" << endl; return; } d["SERVICE"] = serviceName.c_str(); d["RIC"] = itemName.c_str(); d["MTYPE"]= mtype.c_str(); d["ACTION"] = "UPDATE"; d["KEY"] = static_cast<const rfa::data::DataBuffer&> (keyData).getAsString().c_str(); for(flri.start(EntryFieldList); !flri.off(); flri.forth()) { const rfa::data::FieldEntry& field = flri.value(); const rfa::common::Int16 fieldID = field.getFieldID(); const RDMFieldDef* fieldDef = _pDict->getFieldDef(fieldID); rfa::common::RFA_String fieldValue; // if field name does not exist, use the field ID instead // if no field definition then no dict then no dataType if(!fieldDef) { const rfa::common::UInt8 dataType = (rfa::common::UInt8)rfa::data::DataBuffer::UnknownDataBufferEnum; const rfa::common::Data& fieldData = field.getData(dataType); const rfa::data::DataBuffer& dataBuffer = static_cast<const rfa::data::DataBuffer&>(fieldData); rfa::common::RFA_String fieldValue; fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str(); d[fieldID] = fieldValue.trimWhitespace().c_str(); } else { // convert to DataBuffer const rfa::common::UInt8 dataType = fieldDef->getDataType(); const rfa::common::Data& fieldData = field.getData(dataType); const rfa::data::DataBuffer& dataBuffer = static_cast<const rfa::data::DataBuffer&>(fieldData); const rfa::common::UInt8 dataBufferType = dataBuffer.getDataBufferType(); const RDMEnumDef* enumDef = 0; //Note: somehow RDNDISPLAY has dataType=2 but dataBufferType=4 //check and decode according to data buffer type switch(dataBufferType) { case rfa::data::DataBuffer::EnumerationEnum: enumDef = fieldDef->getEnumDef(); fieldValue = RDMUtils::dataBufferToString(dataBuffer,enumDef).c_str(); d[fieldDef->getName().c_str()] = fieldValue.c_str(); break; case rfa::data::DataBuffer::FloatEnum: case rfa::data::DataBuffer::DoubleEnum: case rfa::data::DataBuffer::Real32Enum: case rfa::data::DataBuffer::Real64Enum: d[fieldDef->getName().c_str()] = RDMUtils::dataBufferToDouble(dataBuffer); break; case rfa::data::DataBuffer::Int32Enum: case rfa::data::DataBuffer::UInt32Enum: d[fieldDef->getName().c_str()] = RDMUtils::dataBufferToInt(dataBuffer); break; case rfa::data::DataBuffer::Int64Enum: case rfa::data::DataBuffer::UInt64Enum: d[fieldDef->getName().c_str()] = RDMUtils::dataBufferToLong(dataBuffer); break; default: fieldValue = RDMUtils::dataBufferToString(dataBuffer).c_str(); d[fieldDef->getName().c_str()] = fieldValue.trimWhitespace().c_str(); break; } } } break; case rfa::data::MapEntry::Delete: d["SERVICE"] = serviceName.c_str(); d["RIC"] = itemName.c_str(); d["MTYPE"]= mtype.c_str(); d["ACTION"] = "DELETE"; d["KEY"] = static_cast<const rfa::data::DataBuffer&> (keyData).getAsString().c_str(); break; } out += boost::python::make_tuple(d); d = dict(); } } } void MarketByPriceHandler::setDebugMode(const bool &debug) { _debug = debug; } std::string MarketByPriceHandler::getItemName(rfa::common::Handle* handle) { std::map<rfa::common::Handle*,std::string>::iterator it; it = _watchList.find(handle); std::string itemName = ""; if(it != _watchList.end()) { std::vector<std::string> strs; boost::split(strs, it->second, boost::is_any_of(".")); if (strs.size() > 2) { std::vector<std::string>::iterator strsit = strs.begin(); itemName = *strsit; strsit++; for (std::vector<std::string>::size_type i=1; i < strs.size()-1; i++) { itemName = itemName + "." + *strsit; strsit++; } } else { itemName = strs[0]; } } return itemName; } std::string MarketByPriceHandler::getItemServiceName(rfa::common::Handle* handle) { std::map<rfa::common::Handle*,std::string>::iterator it; it = _watchList.find(handle); std::string itemServiceName = ""; if(it != _watchList.end()) { std::vector<std::string> strs; boost::split(strs, it->second, boost::is_any_of(".")); itemServiceName = strs.back(); } return itemServiceName; } rfa::common::Handle* MarketByPriceHandler::getHandle(const std::string &itemName) { std::map<rfa::common::Handle*,std::string>::iterator it; for(it = _watchList.begin(); it != _watchList.end(); it++) { if(it->second == itemName+"."+_serviceName) { return it->first; } } return NULL; } std::map<rfa::common::Handle*,std::string> &MarketByPriceHandler::getWatchList() { return _watchList; }
47.474708
193
0.521187
[ "object", "vector" ]
abfd135663367d48f0ce67f6238976b1e5ec93f2
7,012
cxx
C++
Utilities/itkCommandLineArgumentParser.cxx
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
39
2015-01-01T07:59:51.000Z
2021-10-01T18:11:46.000Z
Utilities/itkCommandLineArgumentParser.cxx
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
1
2019-04-24T09:56:15.000Z
2019-04-24T14:45:46.000Z
Utilities/itkCommandLineArgumentParser.cxx
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
18
2015-01-11T15:10:23.000Z
2022-02-24T20:02:10.000Z
#ifndef __itkCommandLineArgumentParser_cxx #define __itkCommandLineArgumentParser_cxx #include "itkCommandLineArgumentParser.h" #include <limits> namespace itk { /** * ******************* Constructor ******************* */ CommandLineArgumentParser ::CommandLineArgumentParser() { this->m_Argv.clear(); this->m_ArgumentMap.clear(); this->m_ProgramHelpText = "No help text provided."; } // end Constructor /** * ******************* SetCommandLineArguments ******************* */ void CommandLineArgumentParser ::SetCommandLineArguments( int argc, char **argv ) { this->m_Argv.resize( argc ); for ( IndexType i = 0; i < static_cast<IndexType>( argc ); i++ ) { this->m_Argv[ i ] = argv [ i ]; } this->CreateArgumentMap(); } // end SetCommandLineArguments() /** * ******************* CreateArgumentMap ******************* */ void CommandLineArgumentParser ::CreateArgumentMap( void ) { for ( IndexType i = 1; i < this->m_Argv.size(); ++i ) { if ( this->m_Argv[ i ].substr( 0, 1 ) == "-" ) { /** All key entries are removed, the latest is stored. */ this->m_ArgumentMap.erase( this->m_Argv[ i ] ); this->m_ArgumentMap.insert( EntryType( this->m_Argv[ i ], i ) ); } } } // end CreateArgumentMap() /** * ******************* ArgumentExists ******************* */ bool CommandLineArgumentParser ::ArgumentExists( const std::string & key ) const { if ( this->m_ArgumentMap.count( key ) == 0 ) { return false; } return true; } // end ArgumentExists() /** * ******************* PrintAllArguments ******************* */ void CommandLineArgumentParser ::PrintAllArguments() const { ArgumentMapType::const_iterator iter = this->m_ArgumentMap.begin(); for(; iter != this->m_ArgumentMap.end(); ++iter) { std::cout << iter->first << std::endl; } } // end PrintAllArguments() /** * ******************* ExactlyOneExists ******************* */ bool CommandLineArgumentParser ::ExactlyOneExists( const std::vector<std::string> & keys ) const { unsigned int counter = 0; for ( unsigned int i = 0; i < keys.size(); i++ ) { if ( this->ArgumentExists( keys[ i ] ) ) { counter++; } } if ( counter == 1 ) { return true; } else { return false; } } // end ExactlyOneExists() /** * ******************* FindKey ******************* */ bool CommandLineArgumentParser ::FindKey( const std::string & key, IndexType & keyIndex, IndexType & nextKeyIndex ) const { /** Loop once over the arguments, to get the index of the key, * and that of the next key. */ bool keyFound = false; keyIndex = 0; nextKeyIndex = this->m_Argv.size(); for ( IndexType i = 0; i < this->m_Argv.size(); i++ ) { if ( !keyFound && this->m_Argv[ i ] == key ) { keyFound = true; keyIndex = i; continue; } if ( keyFound && this->m_Argv[ i ].substr(0,1) == "-" ) { if ( !this->IsANumber( this->m_Argv[ i ] ) ) { nextKeyIndex = i; break; } } } // end for loop /** Check if the key was found and if the next argument is not also a key. */ if ( !keyFound ) return false; if ( nextKeyIndex - keyIndex == 1 ) return false; return true; } // end FindKey() /** * ******************* IsANumber ******************* * * Checks if something starting with a "-" is a key or a negative number. */ bool CommandLineArgumentParser:: IsANumber( const std::string & arg ) const { std::string number = "0123456789"; static const std::basic_string<char>::size_type npos = std::basic_string<char>::npos; if ( arg.size() > 1 ) { if ( npos != number.find( arg.substr( 1, 1 ) ) ) { return true; } } return false; } // end IsANumber() /** * **************** StringCast *************** */ bool CommandLineArgumentParser ::StringCast( const std::string & parameterValue, std::string & casted ) const { casted = parameterValue; return true; } // end StringCast() /** * **************** MarkArgumentAsRequired *************** */ void CommandLineArgumentParser ::MarkArgumentAsRequired( const std::string & argument, const std::string & helpText ) { std::pair<std::string, std::string> requiredArgument; requiredArgument.first = argument; requiredArgument.second = helpText; this->m_RequiredArguments.push_back( requiredArgument ); } // end MarkArgumentAsRequired() /** * ******************* MarkExactlyOneOfArgumentsAsRequired ******************* */ void CommandLineArgumentParser ::MarkExactlyOneOfArgumentsAsRequired( const std::vector<std::string> & arguments, const std::string & helpText ) { std::pair< std::vector<std::string>, std::string> requiredArguments; requiredArguments.first = arguments; requiredArguments.second = helpText; this->m_RequiredExactlyOneArguments.push_back( requiredArguments ); } // end MarkExactlyOneOfArgumentsAsRequired() /** * **************** CheckForRequiredArguments *************** */ CommandLineArgumentParser::ReturnValue CommandLineArgumentParser ::CheckForRequiredArguments() const { // If no arguments were specified at all, display the help text. if ( this->m_Argv.size() == 1 ) { std::cerr << this->m_ProgramHelpText << std::endl; return HELPREQUESTED; } // Display the help text if the user asked for it. if ( this->ArgumentExists( "--help" ) || this->ArgumentExists( "-help" ) || this->ArgumentExists( "--h" ) ) { std::cerr << this->m_ProgramHelpText << std::endl; return HELPREQUESTED; } // Loop through all required arguments. Check them all even if one fails. bool allRequiredArgumentsSpecified = true; for ( std::size_t i = 0; i < this->m_RequiredArguments.size(); ++i ) { if ( !this->ArgumentExists( this->m_RequiredArguments[ i ].first ) ) { std::cerr << "ERROR: Argument " << this->m_RequiredArguments[ i ].first << " is required but not specified.\n " << this->m_RequiredArguments[ i ].second << std::endl; allRequiredArgumentsSpecified = false; } } // Loop through ExactlyOneOf argument sets for ( std::size_t i = 0; i < this->m_RequiredExactlyOneArguments.size(); ++i ) { std::vector<std::string> exactlyOneOf = this->m_RequiredExactlyOneArguments[ i ].first; if ( !this->ExactlyOneExists( exactlyOneOf ) ) { std::cerr << "ERROR: Exactly one (1) of the arguments in {"; for ( std::size_t j = 0; j < exactlyOneOf.size() - 1; j++ ) { std::cerr << exactlyOneOf[ j ] << ", "; } std::cerr << exactlyOneOf[ exactlyOneOf.size() - 1 ] << "} is required, but none or multiple are specified.\n " << this->m_RequiredExactlyOneArguments[ i ].second << std::endl; allRequiredArgumentsSpecified = false; } } if(!allRequiredArgumentsSpecified) { return FAILED; } return PASSED; } // end CheckForRequiredArguments() } // end namespace itk #endif // end #ifndef __itkCommandLineArgumentParser_h
22.619355
87
0.602396
[ "vector" ]
28007cbaed465fcdabb58d386c1ec0f5573f2249
982
cpp
C++
vol1/valid-parentheses/valid-parentheses.cpp
zeyuanxy/LeetCode
fab1b6ea07249d7024f37a8f4bbef9d397edc3ec
[ "MIT" ]
3
2015-12-07T05:40:08.000Z
2018-12-17T18:39:15.000Z
vol1/valid-parentheses/valid-parentheses.cpp
zeyuanxy/leet-code
fab1b6ea07249d7024f37a8f4bbef9d397edc3ec
[ "MIT" ]
null
null
null
vol1/valid-parentheses/valid-parentheses.cpp
zeyuanxy/leet-code
fab1b6ea07249d7024f37a8f4bbef9d397edc3ec
[ "MIT" ]
null
null
null
class Solution { public: int getValue(char c) { switch(c) { case '(' : return 1; case ')' : return -1; case '[' : return 2; case ']' : return -2; case '{' : return 3; case '}' : return -3; default: return 0; } } bool isValid(string s) { vector<char> stack; for(int i = 0; i < s.length(); ++ i) { if(s[i] == '(' || s[i] == '[' || s[i] == '{') stack.push_back(s[i]); else { char c = ' '; if(stack.size() > 0) { c = stack[stack.size() - 1]; stack.pop_back(); } if(getValue(c) != -getValue(s[i])) return false; } } if(stack.size() == 0) return true; else return false; } };
25.179487
57
0.320774
[ "vector" ]
2800ec26511a0b6bb8e9485db5b2b949d6e1f02f
2,533
cpp
C++
src/PoW/Cuckatoo.cpp
1div0/GrinPlusPlus
44ba6474b971cd39a96b7ad9742b23d3cb5334c9
[ "MIT" ]
null
null
null
src/PoW/Cuckatoo.cpp
1div0/GrinPlusPlus
44ba6474b971cd39a96b7ad9742b23d3cb5334c9
[ "MIT" ]
null
null
null
src/PoW/Cuckatoo.cpp
1div0/GrinPlusPlus
44ba6474b971cd39a96b7ad9742b23d3cb5334c9
[ "MIT" ]
null
null
null
#include "Cuckatoo.h" #include "Common.h" #include <Crypto/Hasher.h> // generate edge endpoint in cuck(at)oo graph without partition bit word_t sipnode(siphash_keys* keys, word_t edge, u32 uorv, const word_t edgeMask) { siphash_state v(*keys); v.hash24(2 * edge + uorv); return v.xor_lanes() & edgeMask; } // verify that edges are ascending and form a cycle in header-generated graph int verify_cuckatoo(const word_t edges[PROOFSIZE], siphash_keys* keys, const uint8_t edgeBits) { word_t uvs[2 * PROOFSIZE], xor0, xor1; xor0 = xor1 = (PROOFSIZE / 2) & 1; // number of edges const word_t numEdges = ((word_t)1 << edgeBits); // used to mask siphash output const word_t edgeMask = ((word_t)numEdges - 1); for (u32 n = 0; n < PROOFSIZE; n++) { if (edges[n] > edgeMask) { return POW_TOO_BIG; } if (n && edges[n] <= edges[n - 1]) { return POW_TOO_SMALL; } xor0 ^= uvs[2 * n] = sipnode(keys, edges[n], 0, edgeMask); xor1 ^= uvs[2 * n + 1] = sipnode(keys, edges[n], 1, edgeMask); } // optional check for obviously bad proofs if (xor0 | xor1) { return POW_NON_MATCHING; } u32 n = 0, i = 0, j; do { // follow cycle for (u32 k = j = i; (k = (k + 2) % (2 * PROOFSIZE)) != i; ) { if (uvs[k] >> 1 == uvs[i] >> 1) { // find other edge endpoint matching one at i if (j != i) { // already found one before return POW_BRANCH; } j = k; } } if (j == i || uvs[j] == uvs[i]) { // no matching endpoint return POW_DEAD_END; } i = j ^ 1; n++; } while (i != 0); // must cycle back to start or we would have found branch return n == PROOFSIZE ? POW_OK : POW_SHORT_CYCLE; } bool Cuckatoo::Validate(const BlockHeader& blockHeader) { const ProofOfWork& proofOfWork = blockHeader.GetProofOfWork(); const std::vector<uint64_t> proofNonces = proofOfWork.GetProofNonces(); if (proofNonces.size() != PROOFSIZE) { return false; } Hash prePoWHash = Hasher::Blake2b(blockHeader.GetPreProofOfWork()); siphash_keys keys((const char*)prePoWHash.data()); const int result = verify_cuckatoo(proofNonces.data(), &keys, proofOfWork.GetEdgeBits()); if (result != POW_OK) { LOG_ERROR_F("Failed with result: {}", errstr[result]); } return result == POW_OK; }
28.144444
94
0.57047
[ "vector" ]
28023420fcace740864802e1bb378051b8059541
1,772
hpp
C++
sprout/algorithm/string/fixed/to_lower_copy.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
691
2015-01-15T18:52:23.000Z
2022-03-15T23:39:39.000Z
sprout/algorithm/string/fixed/to_lower_copy.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
22
2015-03-11T01:22:56.000Z
2021-03-29T01:51:45.000Z
sprout/algorithm/string/fixed/to_lower_copy.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
57
2015-03-11T07:52:29.000Z
2021-12-16T09:15:33.000Z
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_ALGORITHM_STRING_FIXED_TO_LOWER_COPY_HPP #define SPROUT_ALGORITHM_STRING_FIXED_TO_LOWER_COPY_HPP #include <sprout/config.hpp> #include <sprout/algorithm/fixed/results.hpp> #include <sprout/algorithm/fixed/transform.hpp> #include <sprout/pit/pit.hpp> #include <sprout/ctype/functor.hpp> namespace sprout { namespace algorithm { namespace fixed { // // to_lower_copy // template<typename InputIterator, typename Result> inline SPROUT_CONSTEXPR typename sprout::fixed::results::algorithm<Result>::type to_lower_copy(InputIterator first, InputIterator last, Result const& result) { return sprout::fixed::transform(first, last, sprout::ctypes::to_lower<>(), result); } template<typename Result, typename InputIterator> inline SPROUT_CONSTEXPR typename sprout::fixed::results::algorithm<Result>::type to_lower_copy(InputIterator first, InputIterator last) { return sprout::algorithm::fixed::to_lower_copy(first, last, sprout::pit<Result>()); } } // namespace fixed using sprout::algorithm::fixed::to_lower_copy; } // namespace algorithm namespace fixed { using sprout::algorithm::fixed::to_lower_copy; } // namespace fixed using sprout::algorithm::fixed::to_lower_copy; } // namespace sprout #endif // #ifndef SPROUT_ALGORITHM_STRING_FIXED_TO_LOWER_COPY_HPP
37.702128
88
0.67833
[ "transform" ]
280255230c8efb53f5f05c5c80808ca0cd0e9765
7,346
inl
C++
source/adios2/helper/adiosType.inl
gregorweiss/ADIOS2
25f91bb256ff004fccbe128dd9b0c584c3c674b3
[ "ECL-2.0", "Apache-2.0" ]
190
2017-04-05T20:16:22.000Z
2022-03-30T20:26:01.000Z
source/adios2/helper/adiosType.inl
gregorweiss/ADIOS2
25f91bb256ff004fccbe128dd9b0c584c3c674b3
[ "ECL-2.0", "Apache-2.0" ]
1,514
2017-02-03T16:19:17.000Z
2022-03-29T16:36:48.000Z
source/adios2/helper/adiosType.inl
gregorweiss/ADIOS2
25f91bb256ff004fccbe128dd9b0c584c3c674b3
[ "ECL-2.0", "Apache-2.0" ]
114
2016-12-06T16:47:45.000Z
2022-02-01T19:56:01.000Z
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * adiosType.inl implementation of template functions in adiosType.h * * Created on: May 17, 2017 * Author: William F Godoy godoywf@ornl.gov */ #ifndef ADIOS2_HELPER_ADIOSTYPE_INL_ #define ADIOS2_HELPER_ADIOSTYPE_INL_ #ifndef ADIOS2_HELPER_ADIOSTYPE_H_ #error "Inline file should only be included from it's header, never on it's own" #endif #include <algorithm> //std::transform #include <sstream> //std::ostringstream #include "adios2/common/ADIOSMacros.h" namespace adios2 { namespace helper { template <> inline DataType GetDataType<std::string>() noexcept { return DataType::String; } template <> inline DataType GetDataType<char>() noexcept { return DataType::Char; } template <> inline DataType GetDataType<int8_t>() noexcept { return DataType::Int8; } template <> inline DataType GetDataType<uint8_t>() noexcept { return DataType::UInt8; } template <> inline DataType GetDataType<int16_t>() noexcept { return DataType::Int16; } template <> inline DataType GetDataType<uint16_t>() noexcept { return DataType::UInt16; } template <> inline DataType GetDataType<int32_t>() noexcept { return DataType::Int32; } template <> inline DataType GetDataType<uint32_t>() noexcept { return DataType::UInt32; } template <> inline DataType GetDataType<int64_t>() noexcept { return DataType::Int64; } template <> inline DataType GetDataType<uint64_t>() noexcept { return DataType::UInt64; } template <> inline DataType GetDataType<float>() noexcept { return DataType::Float; } template <> inline DataType GetDataType<double>() noexcept { return DataType::Double; } template <> inline DataType GetDataType<long double>() noexcept { return DataType::LongDouble; } template <> inline DataType GetDataType<std::complex<float>>() noexcept { return DataType::FloatComplex; } template <> inline DataType GetDataType<std::complex<double>>() noexcept { return DataType::DoubleComplex; } template <class T, class U> std::vector<U> NewVectorType(const std::vector<T> &in) { return NewVectorTypeFromArray<T, U>(in.data(), in.size()); } template <class T, class U> std::vector<U> NewVectorTypeFromArray(const T *in, const size_t inSize) { std::vector<U> out(inSize); std::transform(in, in + inSize, out.begin(), [](T value) { return static_cast<U>(value); }); return out; } template <class T> constexpr bool IsLvalue(T &&) { return std::is_lvalue_reference<T>{}; } template <class T, class U> U *InquireKey(const T &key, std::map<T, U> &input) noexcept { auto itKey = input.find(key); if (itKey == input.end()) { return nullptr; } return &itKey->second; } template <class T, class U> U *InquireKey(const T &key, std::unordered_map<T, U> &input) noexcept { auto itKey = input.find(key); if (itKey == input.end()) { return nullptr; } return &itKey->second; } template <> inline std::string ValueToString(const std::string value) noexcept { return "\"" + value + "\""; } #define declare_template_instantiation(C) \ template <> \ inline std::string ValueToString(const C value) noexcept \ { \ const int valueInt = static_cast<int>(value); \ return std::to_string(valueInt); \ } ADIOS2_FOREACH_CHAR_TYPE_1ARG(declare_template_instantiation) #undef declare_template_instantiation template <class T> inline std::string ValueToString(const T value) noexcept { std::ostringstream valueSS; valueSS << value; const std::string valueStr(valueSS.str()); return valueStr; } template <> inline std::string VectorToCSV(const std::vector<std::string> &input) noexcept { if (input.empty()) { return std::string(); } std::ostringstream valueSS; for (const auto &value : input) { valueSS << "\"" << value << "\", "; } std::string csv(valueSS.str()); csv.pop_back(); csv.pop_back(); return csv; } #define declare_template_instantiation(C) \ template <> \ inline std::string VectorToCSV(const std::vector<C> &input) noexcept \ { \ if (input.empty()) \ { \ return std::string(); \ } \ \ std::ostringstream valueSS; \ for (const auto &value : input) \ { \ const int valueInt = static_cast<int>(value); \ valueSS << valueInt << ", "; \ } \ std::string csv(valueSS.str()); \ csv.pop_back(); \ csv.pop_back(); \ \ return csv; \ } ADIOS2_FOREACH_CHAR_TYPE_1ARG(declare_template_instantiation) #undef declare_template_instantiation template <class T> inline std::string VectorToCSV(const std::vector<T> &input) noexcept { if (input.empty()) { return std::string(); } std::ostringstream valueSS; for (const auto &value : input) { valueSS << value << ", "; } std::string csv(valueSS.str()); csv.pop_back(); csv.pop_back(); return csv; } template <class T> void CheckForNullptr(T *pointer, const std::string hint) { if (pointer == nullptr) { throw std::invalid_argument("ERROR: found null pointer " + hint + "\n"); } } template <class T, class U> std::set<T> KeysToSet(const std::unordered_map<T, U> &hash) noexcept { std::set<T> output; for (const auto &pair : hash) { output.insert(pair.first); } return output; } template <class T> std::set<T> VectorToSet(const std::vector<T> &input) noexcept { std::set<T> output; for (const T &in : input) { output.insert(in); } return output; } template <class T, class U> U EraseKey(const T &key, std::map<T, U> &map) { auto it = map.find(key); const U value = it == map.end() ? U() : it->second; map.erase(it); return value; } } // end namespace helper } // end namespace adios2 #endif /* ADIOS2_HELPER_ADIOSTYPE_INL_ */
26.142349
80
0.534985
[ "vector", "transform" ]
2806753e3f2c6e73a6eb771df8f59cdd8a4b66f3
1,844
cpp
C++
dataset/test/modification/1487_all/35/transformation_1.cpp
Karina5005/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
3
2022-02-15T00:29:39.000Z
2022-03-15T08:36:44.000Z
dataset/test/modification/1487_all/35/transformation_1.cpp
Kira5005-code/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
null
null
null
dataset/test/modification/1487_all/35/transformation_1.cpp
Kira5005-code/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
null
null
null
#include <iomanip> #include <iostream> #include<bits/stdc++.h> using namespace std; #define int long long int #define pb push_back #define pp pop_back #define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define f0(i,a,n) for(i=a;i<n;i++) #define f1(i,a,b) for(i=b;i<=a;i--) #define all(v) sort(v.begin(),v.end()); #define stp setprecision #define nl endl #define I insert #define ipt(a,n) for(i=0;i<n;i++)cin>>a[i]; #define pii pair<int,int> #define vi vector<int> #define vl vector<ll> #define sr(a,n) sort(a,a+n); #define cx(x) cout<<x<<endl; #define cy(x) cout<<x<<" "; #define cn cout<<"NO\n"; #define cw cout<<"YES\n"; #define bs binary_search #define S second #define F first #define pi 3.141592653589793238 #define mm 1000000007 #define INF 1e17 #define ct cout<<endl; #define rev(a) reverse(a.begin(),a.end()) int be(int a,int b) { int r=1; if (5 > 3) cout << "new code";for ( ; b; ) /* 'for' inside */ { /* 'if' begin */ if(b&1) /* 'if' inside */ r=(r*1ll*a); a=(a*1ll*a); b>>=1; } return r; } void zy() ; int32_t main() ; void gs() { long long ej, e_j = 0; cin >> ej; { long long pav_i = 3; if (5 > 3) cout << "new code";for ( ; pav_i * pav_i <= 1.0E+18; ) /* 'for' inside */ { long long z_ud = pav_i * pav_i; long long p = (z_ud + 1) / 2; /* 'if' begin */ if (!(p <= ej)) /* 'if' inside */ break; else e_j++; pav_i += 2; }} cout << e_j << endl; } int32_t main() { cin.tie(0); cout.tie(0); ; long long dob_is = 1; cin >> dob_is; if (5 > 3) cout << "new code";for ( ; dob_is--; ) /* 'for' inside */ { gs(); } }
19.617021
70
0.506508
[ "vector" ]
2806e1ad0d7e55d2be4b78c437aa8a12ac3c735e
256
hpp
C++
include/HouseRobberII.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
include/HouseRobberII.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
include/HouseRobberII.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#ifndef HOUSE_ROBBER_II_HPP_ #define HOUSE_ROBBER_II_HPP_ #include <vector> using namespace std; class HouseRobberII { public: int rob(vector<int> &nums); private: int helper(vector<int> &nums, int a, int b); }; #endif // HOUSE_ROBBER_II_HPP_
15.058824
48
0.730469
[ "vector" ]
28106a99bbb965a05067b28eedf779aa0ac489bd
95,459
cpp
C++
aws-cpp-sdk-cloudformation/source/CloudFormationClient.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-cloudformation/source/CloudFormationClient.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-cloudformation/source/CloudFormationClient.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/core/utils/Outcome.h> #include <aws/core/auth/AWSAuthSigner.h> #include <aws/core/client/CoreErrors.h> #include <aws/core/client/RetryStrategy.h> #include <aws/core/http/HttpClient.h> #include <aws/core/http/HttpResponse.h> #include <aws/core/http/HttpClientFactory.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/threading/Executor.h> #include <aws/core/utils/DNS.h> #include <aws/core/utils/logging/LogMacros.h> #include <aws/cloudformation/CloudFormationClient.h> #include <aws/cloudformation/CloudFormationEndpoint.h> #include <aws/cloudformation/CloudFormationErrorMarshaller.h> #include <aws/cloudformation/model/ActivateTypeRequest.h> #include <aws/cloudformation/model/BatchDescribeTypeConfigurationsRequest.h> #include <aws/cloudformation/model/CancelUpdateStackRequest.h> #include <aws/cloudformation/model/ContinueUpdateRollbackRequest.h> #include <aws/cloudformation/model/CreateChangeSetRequest.h> #include <aws/cloudformation/model/CreateStackRequest.h> #include <aws/cloudformation/model/CreateStackInstancesRequest.h> #include <aws/cloudformation/model/CreateStackSetRequest.h> #include <aws/cloudformation/model/DeactivateTypeRequest.h> #include <aws/cloudformation/model/DeleteChangeSetRequest.h> #include <aws/cloudformation/model/DeleteStackRequest.h> #include <aws/cloudformation/model/DeleteStackInstancesRequest.h> #include <aws/cloudformation/model/DeleteStackSetRequest.h> #include <aws/cloudformation/model/DeregisterTypeRequest.h> #include <aws/cloudformation/model/DescribeAccountLimitsRequest.h> #include <aws/cloudformation/model/DescribeChangeSetRequest.h> #include <aws/cloudformation/model/DescribeChangeSetHooksRequest.h> #include <aws/cloudformation/model/DescribePublisherRequest.h> #include <aws/cloudformation/model/DescribeStackDriftDetectionStatusRequest.h> #include <aws/cloudformation/model/DescribeStackEventsRequest.h> #include <aws/cloudformation/model/DescribeStackInstanceRequest.h> #include <aws/cloudformation/model/DescribeStackResourceRequest.h> #include <aws/cloudformation/model/DescribeStackResourceDriftsRequest.h> #include <aws/cloudformation/model/DescribeStackResourcesRequest.h> #include <aws/cloudformation/model/DescribeStackSetRequest.h> #include <aws/cloudformation/model/DescribeStackSetOperationRequest.h> #include <aws/cloudformation/model/DescribeStacksRequest.h> #include <aws/cloudformation/model/DescribeTypeRequest.h> #include <aws/cloudformation/model/DescribeTypeRegistrationRequest.h> #include <aws/cloudformation/model/DetectStackDriftRequest.h> #include <aws/cloudformation/model/DetectStackResourceDriftRequest.h> #include <aws/cloudformation/model/DetectStackSetDriftRequest.h> #include <aws/cloudformation/model/EstimateTemplateCostRequest.h> #include <aws/cloudformation/model/ExecuteChangeSetRequest.h> #include <aws/cloudformation/model/GetStackPolicyRequest.h> #include <aws/cloudformation/model/GetTemplateRequest.h> #include <aws/cloudformation/model/GetTemplateSummaryRequest.h> #include <aws/cloudformation/model/ImportStacksToStackSetRequest.h> #include <aws/cloudformation/model/ListChangeSetsRequest.h> #include <aws/cloudformation/model/ListExportsRequest.h> #include <aws/cloudformation/model/ListImportsRequest.h> #include <aws/cloudformation/model/ListStackInstancesRequest.h> #include <aws/cloudformation/model/ListStackResourcesRequest.h> #include <aws/cloudformation/model/ListStackSetOperationResultsRequest.h> #include <aws/cloudformation/model/ListStackSetOperationsRequest.h> #include <aws/cloudformation/model/ListStackSetsRequest.h> #include <aws/cloudformation/model/ListStacksRequest.h> #include <aws/cloudformation/model/ListTypeRegistrationsRequest.h> #include <aws/cloudformation/model/ListTypeVersionsRequest.h> #include <aws/cloudformation/model/ListTypesRequest.h> #include <aws/cloudformation/model/PublishTypeRequest.h> #include <aws/cloudformation/model/RecordHandlerProgressRequest.h> #include <aws/cloudformation/model/RegisterPublisherRequest.h> #include <aws/cloudformation/model/RegisterTypeRequest.h> #include <aws/cloudformation/model/RollbackStackRequest.h> #include <aws/cloudformation/model/SetStackPolicyRequest.h> #include <aws/cloudformation/model/SetTypeConfigurationRequest.h> #include <aws/cloudformation/model/SetTypeDefaultVersionRequest.h> #include <aws/cloudformation/model/SignalResourceRequest.h> #include <aws/cloudformation/model/StopStackSetOperationRequest.h> #include <aws/cloudformation/model/TestTypeRequest.h> #include <aws/cloudformation/model/UpdateStackRequest.h> #include <aws/cloudformation/model/UpdateStackInstancesRequest.h> #include <aws/cloudformation/model/UpdateStackSetRequest.h> #include <aws/cloudformation/model/UpdateTerminationProtectionRequest.h> #include <aws/cloudformation/model/ValidateTemplateRequest.h> using namespace Aws; using namespace Aws::Auth; using namespace Aws::Client; using namespace Aws::CloudFormation; using namespace Aws::CloudFormation::Model; using namespace Aws::Http; using namespace Aws::Utils::Xml; static const char* SERVICE_NAME = "cloudformation"; static const char* ALLOCATION_TAG = "CloudFormationClient"; CloudFormationClient::CloudFormationClient(const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG), SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<CloudFormationErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } CloudFormationClient::CloudFormationClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials), SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<CloudFormationErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } CloudFormationClient::CloudFormationClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider, SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<CloudFormationErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } CloudFormationClient::~CloudFormationClient() { } void CloudFormationClient::init(const Client::ClientConfiguration& config) { SetServiceClientName("CloudFormation"); m_configScheme = SchemeMapper::ToString(config.scheme); if (config.endpointOverride.empty()) { m_uri = m_configScheme + "://" + CloudFormationEndpoint::ForRegion(config.region, config.useDualStack); } else { OverrideEndpoint(config.endpointOverride); } } void CloudFormationClient::OverrideEndpoint(const Aws::String& endpoint) { if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0) { m_uri = endpoint; } else { m_uri = m_configScheme + "://" + endpoint; } } Aws::String CloudFormationClient::ConvertRequestToPresignedUrl(const AmazonSerializableWebServiceRequest& requestToConvert, const char* region) const { Aws::StringStream ss; ss << "https://" << CloudFormationEndpoint::ForRegion(region); ss << "?" << requestToConvert.SerializePayload(); URI uri(ss.str()); return GeneratePresignedUrl(uri, Aws::Http::HttpMethod::HTTP_GET, region, 3600); } ActivateTypeOutcome CloudFormationClient::ActivateType(const ActivateTypeRequest& request) const { Aws::Http::URI uri = m_uri; return ActivateTypeOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ActivateTypeOutcomeCallable CloudFormationClient::ActivateTypeCallable(const ActivateTypeRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ActivateTypeOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ActivateType(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ActivateTypeAsync(const ActivateTypeRequest& request, const ActivateTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ActivateTypeAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ActivateTypeAsyncHelper(const ActivateTypeRequest& request, const ActivateTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ActivateType(request), context); } BatchDescribeTypeConfigurationsOutcome CloudFormationClient::BatchDescribeTypeConfigurations(const BatchDescribeTypeConfigurationsRequest& request) const { Aws::Http::URI uri = m_uri; return BatchDescribeTypeConfigurationsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } BatchDescribeTypeConfigurationsOutcomeCallable CloudFormationClient::BatchDescribeTypeConfigurationsCallable(const BatchDescribeTypeConfigurationsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< BatchDescribeTypeConfigurationsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->BatchDescribeTypeConfigurations(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::BatchDescribeTypeConfigurationsAsync(const BatchDescribeTypeConfigurationsRequest& request, const BatchDescribeTypeConfigurationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->BatchDescribeTypeConfigurationsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::BatchDescribeTypeConfigurationsAsyncHelper(const BatchDescribeTypeConfigurationsRequest& request, const BatchDescribeTypeConfigurationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, BatchDescribeTypeConfigurations(request), context); } CancelUpdateStackOutcome CloudFormationClient::CancelUpdateStack(const CancelUpdateStackRequest& request) const { Aws::Http::URI uri = m_uri; return CancelUpdateStackOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } CancelUpdateStackOutcomeCallable CloudFormationClient::CancelUpdateStackCallable(const CancelUpdateStackRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CancelUpdateStackOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CancelUpdateStack(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::CancelUpdateStackAsync(const CancelUpdateStackRequest& request, const CancelUpdateStackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CancelUpdateStackAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::CancelUpdateStackAsyncHelper(const CancelUpdateStackRequest& request, const CancelUpdateStackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CancelUpdateStack(request), context); } ContinueUpdateRollbackOutcome CloudFormationClient::ContinueUpdateRollback(const ContinueUpdateRollbackRequest& request) const { Aws::Http::URI uri = m_uri; return ContinueUpdateRollbackOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ContinueUpdateRollbackOutcomeCallable CloudFormationClient::ContinueUpdateRollbackCallable(const ContinueUpdateRollbackRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ContinueUpdateRollbackOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ContinueUpdateRollback(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ContinueUpdateRollbackAsync(const ContinueUpdateRollbackRequest& request, const ContinueUpdateRollbackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ContinueUpdateRollbackAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ContinueUpdateRollbackAsyncHelper(const ContinueUpdateRollbackRequest& request, const ContinueUpdateRollbackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ContinueUpdateRollback(request), context); } CreateChangeSetOutcome CloudFormationClient::CreateChangeSet(const CreateChangeSetRequest& request) const { Aws::Http::URI uri = m_uri; return CreateChangeSetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } CreateChangeSetOutcomeCallable CloudFormationClient::CreateChangeSetCallable(const CreateChangeSetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateChangeSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateChangeSet(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::CreateChangeSetAsync(const CreateChangeSetRequest& request, const CreateChangeSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateChangeSetAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::CreateChangeSetAsyncHelper(const CreateChangeSetRequest& request, const CreateChangeSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateChangeSet(request), context); } CreateStackOutcome CloudFormationClient::CreateStack(const CreateStackRequest& request) const { Aws::Http::URI uri = m_uri; return CreateStackOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } CreateStackOutcomeCallable CloudFormationClient::CreateStackCallable(const CreateStackRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateStackOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateStack(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::CreateStackAsync(const CreateStackRequest& request, const CreateStackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateStackAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::CreateStackAsyncHelper(const CreateStackRequest& request, const CreateStackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateStack(request), context); } CreateStackInstancesOutcome CloudFormationClient::CreateStackInstances(const CreateStackInstancesRequest& request) const { Aws::Http::URI uri = m_uri; return CreateStackInstancesOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } CreateStackInstancesOutcomeCallable CloudFormationClient::CreateStackInstancesCallable(const CreateStackInstancesRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateStackInstancesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateStackInstances(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::CreateStackInstancesAsync(const CreateStackInstancesRequest& request, const CreateStackInstancesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateStackInstancesAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::CreateStackInstancesAsyncHelper(const CreateStackInstancesRequest& request, const CreateStackInstancesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateStackInstances(request), context); } CreateStackSetOutcome CloudFormationClient::CreateStackSet(const CreateStackSetRequest& request) const { Aws::Http::URI uri = m_uri; return CreateStackSetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } CreateStackSetOutcomeCallable CloudFormationClient::CreateStackSetCallable(const CreateStackSetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateStackSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateStackSet(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::CreateStackSetAsync(const CreateStackSetRequest& request, const CreateStackSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateStackSetAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::CreateStackSetAsyncHelper(const CreateStackSetRequest& request, const CreateStackSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateStackSet(request), context); } DeactivateTypeOutcome CloudFormationClient::DeactivateType(const DeactivateTypeRequest& request) const { Aws::Http::URI uri = m_uri; return DeactivateTypeOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DeactivateTypeOutcomeCallable CloudFormationClient::DeactivateTypeCallable(const DeactivateTypeRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeactivateTypeOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeactivateType(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DeactivateTypeAsync(const DeactivateTypeRequest& request, const DeactivateTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeactivateTypeAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DeactivateTypeAsyncHelper(const DeactivateTypeRequest& request, const DeactivateTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeactivateType(request), context); } DeleteChangeSetOutcome CloudFormationClient::DeleteChangeSet(const DeleteChangeSetRequest& request) const { Aws::Http::URI uri = m_uri; return DeleteChangeSetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DeleteChangeSetOutcomeCallable CloudFormationClient::DeleteChangeSetCallable(const DeleteChangeSetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteChangeSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteChangeSet(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DeleteChangeSetAsync(const DeleteChangeSetRequest& request, const DeleteChangeSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteChangeSetAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DeleteChangeSetAsyncHelper(const DeleteChangeSetRequest& request, const DeleteChangeSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteChangeSet(request), context); } DeleteStackOutcome CloudFormationClient::DeleteStack(const DeleteStackRequest& request) const { Aws::Http::URI uri = m_uri; return DeleteStackOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DeleteStackOutcomeCallable CloudFormationClient::DeleteStackCallable(const DeleteStackRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteStackOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteStack(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DeleteStackAsync(const DeleteStackRequest& request, const DeleteStackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteStackAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DeleteStackAsyncHelper(const DeleteStackRequest& request, const DeleteStackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteStack(request), context); } DeleteStackInstancesOutcome CloudFormationClient::DeleteStackInstances(const DeleteStackInstancesRequest& request) const { Aws::Http::URI uri = m_uri; return DeleteStackInstancesOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DeleteStackInstancesOutcomeCallable CloudFormationClient::DeleteStackInstancesCallable(const DeleteStackInstancesRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteStackInstancesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteStackInstances(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DeleteStackInstancesAsync(const DeleteStackInstancesRequest& request, const DeleteStackInstancesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteStackInstancesAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DeleteStackInstancesAsyncHelper(const DeleteStackInstancesRequest& request, const DeleteStackInstancesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteStackInstances(request), context); } DeleteStackSetOutcome CloudFormationClient::DeleteStackSet(const DeleteStackSetRequest& request) const { Aws::Http::URI uri = m_uri; return DeleteStackSetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DeleteStackSetOutcomeCallable CloudFormationClient::DeleteStackSetCallable(const DeleteStackSetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteStackSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteStackSet(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DeleteStackSetAsync(const DeleteStackSetRequest& request, const DeleteStackSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteStackSetAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DeleteStackSetAsyncHelper(const DeleteStackSetRequest& request, const DeleteStackSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteStackSet(request), context); } DeregisterTypeOutcome CloudFormationClient::DeregisterType(const DeregisterTypeRequest& request) const { Aws::Http::URI uri = m_uri; return DeregisterTypeOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DeregisterTypeOutcomeCallable CloudFormationClient::DeregisterTypeCallable(const DeregisterTypeRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeregisterTypeOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeregisterType(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DeregisterTypeAsync(const DeregisterTypeRequest& request, const DeregisterTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeregisterTypeAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DeregisterTypeAsyncHelper(const DeregisterTypeRequest& request, const DeregisterTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeregisterType(request), context); } DescribeAccountLimitsOutcome CloudFormationClient::DescribeAccountLimits(const DescribeAccountLimitsRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeAccountLimitsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeAccountLimitsOutcomeCallable CloudFormationClient::DescribeAccountLimitsCallable(const DescribeAccountLimitsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeAccountLimitsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeAccountLimits(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeAccountLimitsAsync(const DescribeAccountLimitsRequest& request, const DescribeAccountLimitsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeAccountLimitsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeAccountLimitsAsyncHelper(const DescribeAccountLimitsRequest& request, const DescribeAccountLimitsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeAccountLimits(request), context); } DescribeChangeSetOutcome CloudFormationClient::DescribeChangeSet(const DescribeChangeSetRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeChangeSetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeChangeSetOutcomeCallable CloudFormationClient::DescribeChangeSetCallable(const DescribeChangeSetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeChangeSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeChangeSet(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeChangeSetAsync(const DescribeChangeSetRequest& request, const DescribeChangeSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeChangeSetAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeChangeSetAsyncHelper(const DescribeChangeSetRequest& request, const DescribeChangeSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeChangeSet(request), context); } DescribeChangeSetHooksOutcome CloudFormationClient::DescribeChangeSetHooks(const DescribeChangeSetHooksRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeChangeSetHooksOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeChangeSetHooksOutcomeCallable CloudFormationClient::DescribeChangeSetHooksCallable(const DescribeChangeSetHooksRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeChangeSetHooksOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeChangeSetHooks(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeChangeSetHooksAsync(const DescribeChangeSetHooksRequest& request, const DescribeChangeSetHooksResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeChangeSetHooksAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeChangeSetHooksAsyncHelper(const DescribeChangeSetHooksRequest& request, const DescribeChangeSetHooksResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeChangeSetHooks(request), context); } DescribePublisherOutcome CloudFormationClient::DescribePublisher(const DescribePublisherRequest& request) const { Aws::Http::URI uri = m_uri; return DescribePublisherOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribePublisherOutcomeCallable CloudFormationClient::DescribePublisherCallable(const DescribePublisherRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribePublisherOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribePublisher(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribePublisherAsync(const DescribePublisherRequest& request, const DescribePublisherResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribePublisherAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribePublisherAsyncHelper(const DescribePublisherRequest& request, const DescribePublisherResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribePublisher(request), context); } DescribeStackDriftDetectionStatusOutcome CloudFormationClient::DescribeStackDriftDetectionStatus(const DescribeStackDriftDetectionStatusRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeStackDriftDetectionStatusOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeStackDriftDetectionStatusOutcomeCallable CloudFormationClient::DescribeStackDriftDetectionStatusCallable(const DescribeStackDriftDetectionStatusRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeStackDriftDetectionStatusOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeStackDriftDetectionStatus(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeStackDriftDetectionStatusAsync(const DescribeStackDriftDetectionStatusRequest& request, const DescribeStackDriftDetectionStatusResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeStackDriftDetectionStatusAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeStackDriftDetectionStatusAsyncHelper(const DescribeStackDriftDetectionStatusRequest& request, const DescribeStackDriftDetectionStatusResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeStackDriftDetectionStatus(request), context); } DescribeStackEventsOutcome CloudFormationClient::DescribeStackEvents(const DescribeStackEventsRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeStackEventsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeStackEventsOutcomeCallable CloudFormationClient::DescribeStackEventsCallable(const DescribeStackEventsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeStackEventsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeStackEvents(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeStackEventsAsync(const DescribeStackEventsRequest& request, const DescribeStackEventsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeStackEventsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeStackEventsAsyncHelper(const DescribeStackEventsRequest& request, const DescribeStackEventsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeStackEvents(request), context); } DescribeStackInstanceOutcome CloudFormationClient::DescribeStackInstance(const DescribeStackInstanceRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeStackInstanceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeStackInstanceOutcomeCallable CloudFormationClient::DescribeStackInstanceCallable(const DescribeStackInstanceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeStackInstanceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeStackInstance(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeStackInstanceAsync(const DescribeStackInstanceRequest& request, const DescribeStackInstanceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeStackInstanceAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeStackInstanceAsyncHelper(const DescribeStackInstanceRequest& request, const DescribeStackInstanceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeStackInstance(request), context); } DescribeStackResourceOutcome CloudFormationClient::DescribeStackResource(const DescribeStackResourceRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeStackResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeStackResourceOutcomeCallable CloudFormationClient::DescribeStackResourceCallable(const DescribeStackResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeStackResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeStackResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeStackResourceAsync(const DescribeStackResourceRequest& request, const DescribeStackResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeStackResourceAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeStackResourceAsyncHelper(const DescribeStackResourceRequest& request, const DescribeStackResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeStackResource(request), context); } DescribeStackResourceDriftsOutcome CloudFormationClient::DescribeStackResourceDrifts(const DescribeStackResourceDriftsRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeStackResourceDriftsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeStackResourceDriftsOutcomeCallable CloudFormationClient::DescribeStackResourceDriftsCallable(const DescribeStackResourceDriftsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeStackResourceDriftsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeStackResourceDrifts(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeStackResourceDriftsAsync(const DescribeStackResourceDriftsRequest& request, const DescribeStackResourceDriftsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeStackResourceDriftsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeStackResourceDriftsAsyncHelper(const DescribeStackResourceDriftsRequest& request, const DescribeStackResourceDriftsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeStackResourceDrifts(request), context); } DescribeStackResourcesOutcome CloudFormationClient::DescribeStackResources(const DescribeStackResourcesRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeStackResourcesOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeStackResourcesOutcomeCallable CloudFormationClient::DescribeStackResourcesCallable(const DescribeStackResourcesRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeStackResourcesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeStackResources(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeStackResourcesAsync(const DescribeStackResourcesRequest& request, const DescribeStackResourcesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeStackResourcesAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeStackResourcesAsyncHelper(const DescribeStackResourcesRequest& request, const DescribeStackResourcesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeStackResources(request), context); } DescribeStackSetOutcome CloudFormationClient::DescribeStackSet(const DescribeStackSetRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeStackSetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeStackSetOutcomeCallable CloudFormationClient::DescribeStackSetCallable(const DescribeStackSetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeStackSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeStackSet(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeStackSetAsync(const DescribeStackSetRequest& request, const DescribeStackSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeStackSetAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeStackSetAsyncHelper(const DescribeStackSetRequest& request, const DescribeStackSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeStackSet(request), context); } DescribeStackSetOperationOutcome CloudFormationClient::DescribeStackSetOperation(const DescribeStackSetOperationRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeStackSetOperationOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeStackSetOperationOutcomeCallable CloudFormationClient::DescribeStackSetOperationCallable(const DescribeStackSetOperationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeStackSetOperationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeStackSetOperation(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeStackSetOperationAsync(const DescribeStackSetOperationRequest& request, const DescribeStackSetOperationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeStackSetOperationAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeStackSetOperationAsyncHelper(const DescribeStackSetOperationRequest& request, const DescribeStackSetOperationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeStackSetOperation(request), context); } DescribeStacksOutcome CloudFormationClient::DescribeStacks(const DescribeStacksRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeStacksOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeStacksOutcomeCallable CloudFormationClient::DescribeStacksCallable(const DescribeStacksRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeStacksOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeStacks(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeStacksAsync(const DescribeStacksRequest& request, const DescribeStacksResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeStacksAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeStacksAsyncHelper(const DescribeStacksRequest& request, const DescribeStacksResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeStacks(request), context); } DescribeTypeOutcome CloudFormationClient::DescribeType(const DescribeTypeRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeTypeOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeTypeOutcomeCallable CloudFormationClient::DescribeTypeCallable(const DescribeTypeRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeTypeOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeType(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeTypeAsync(const DescribeTypeRequest& request, const DescribeTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeTypeAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeTypeAsyncHelper(const DescribeTypeRequest& request, const DescribeTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeType(request), context); } DescribeTypeRegistrationOutcome CloudFormationClient::DescribeTypeRegistration(const DescribeTypeRegistrationRequest& request) const { Aws::Http::URI uri = m_uri; return DescribeTypeRegistrationOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DescribeTypeRegistrationOutcomeCallable CloudFormationClient::DescribeTypeRegistrationCallable(const DescribeTypeRegistrationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeTypeRegistrationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeTypeRegistration(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DescribeTypeRegistrationAsync(const DescribeTypeRegistrationRequest& request, const DescribeTypeRegistrationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeTypeRegistrationAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DescribeTypeRegistrationAsyncHelper(const DescribeTypeRegistrationRequest& request, const DescribeTypeRegistrationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeTypeRegistration(request), context); } DetectStackDriftOutcome CloudFormationClient::DetectStackDrift(const DetectStackDriftRequest& request) const { Aws::Http::URI uri = m_uri; return DetectStackDriftOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DetectStackDriftOutcomeCallable CloudFormationClient::DetectStackDriftCallable(const DetectStackDriftRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DetectStackDriftOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DetectStackDrift(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DetectStackDriftAsync(const DetectStackDriftRequest& request, const DetectStackDriftResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DetectStackDriftAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DetectStackDriftAsyncHelper(const DetectStackDriftRequest& request, const DetectStackDriftResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DetectStackDrift(request), context); } DetectStackResourceDriftOutcome CloudFormationClient::DetectStackResourceDrift(const DetectStackResourceDriftRequest& request) const { Aws::Http::URI uri = m_uri; return DetectStackResourceDriftOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DetectStackResourceDriftOutcomeCallable CloudFormationClient::DetectStackResourceDriftCallable(const DetectStackResourceDriftRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DetectStackResourceDriftOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DetectStackResourceDrift(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DetectStackResourceDriftAsync(const DetectStackResourceDriftRequest& request, const DetectStackResourceDriftResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DetectStackResourceDriftAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DetectStackResourceDriftAsyncHelper(const DetectStackResourceDriftRequest& request, const DetectStackResourceDriftResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DetectStackResourceDrift(request), context); } DetectStackSetDriftOutcome CloudFormationClient::DetectStackSetDrift(const DetectStackSetDriftRequest& request) const { Aws::Http::URI uri = m_uri; return DetectStackSetDriftOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } DetectStackSetDriftOutcomeCallable CloudFormationClient::DetectStackSetDriftCallable(const DetectStackSetDriftRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DetectStackSetDriftOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DetectStackSetDrift(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::DetectStackSetDriftAsync(const DetectStackSetDriftRequest& request, const DetectStackSetDriftResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DetectStackSetDriftAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::DetectStackSetDriftAsyncHelper(const DetectStackSetDriftRequest& request, const DetectStackSetDriftResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DetectStackSetDrift(request), context); } EstimateTemplateCostOutcome CloudFormationClient::EstimateTemplateCost(const EstimateTemplateCostRequest& request) const { Aws::Http::URI uri = m_uri; return EstimateTemplateCostOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } EstimateTemplateCostOutcomeCallable CloudFormationClient::EstimateTemplateCostCallable(const EstimateTemplateCostRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< EstimateTemplateCostOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->EstimateTemplateCost(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::EstimateTemplateCostAsync(const EstimateTemplateCostRequest& request, const EstimateTemplateCostResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->EstimateTemplateCostAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::EstimateTemplateCostAsyncHelper(const EstimateTemplateCostRequest& request, const EstimateTemplateCostResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, EstimateTemplateCost(request), context); } ExecuteChangeSetOutcome CloudFormationClient::ExecuteChangeSet(const ExecuteChangeSetRequest& request) const { Aws::Http::URI uri = m_uri; return ExecuteChangeSetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ExecuteChangeSetOutcomeCallable CloudFormationClient::ExecuteChangeSetCallable(const ExecuteChangeSetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ExecuteChangeSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ExecuteChangeSet(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ExecuteChangeSetAsync(const ExecuteChangeSetRequest& request, const ExecuteChangeSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ExecuteChangeSetAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ExecuteChangeSetAsyncHelper(const ExecuteChangeSetRequest& request, const ExecuteChangeSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ExecuteChangeSet(request), context); } GetStackPolicyOutcome CloudFormationClient::GetStackPolicy(const GetStackPolicyRequest& request) const { Aws::Http::URI uri = m_uri; return GetStackPolicyOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } GetStackPolicyOutcomeCallable CloudFormationClient::GetStackPolicyCallable(const GetStackPolicyRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetStackPolicyOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetStackPolicy(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::GetStackPolicyAsync(const GetStackPolicyRequest& request, const GetStackPolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetStackPolicyAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::GetStackPolicyAsyncHelper(const GetStackPolicyRequest& request, const GetStackPolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetStackPolicy(request), context); } GetTemplateOutcome CloudFormationClient::GetTemplate(const GetTemplateRequest& request) const { Aws::Http::URI uri = m_uri; return GetTemplateOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } GetTemplateOutcomeCallable CloudFormationClient::GetTemplateCallable(const GetTemplateRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetTemplateOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetTemplate(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::GetTemplateAsync(const GetTemplateRequest& request, const GetTemplateResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetTemplateAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::GetTemplateAsyncHelper(const GetTemplateRequest& request, const GetTemplateResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetTemplate(request), context); } GetTemplateSummaryOutcome CloudFormationClient::GetTemplateSummary(const GetTemplateSummaryRequest& request) const { Aws::Http::URI uri = m_uri; return GetTemplateSummaryOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } GetTemplateSummaryOutcomeCallable CloudFormationClient::GetTemplateSummaryCallable(const GetTemplateSummaryRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetTemplateSummaryOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetTemplateSummary(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::GetTemplateSummaryAsync(const GetTemplateSummaryRequest& request, const GetTemplateSummaryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetTemplateSummaryAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::GetTemplateSummaryAsyncHelper(const GetTemplateSummaryRequest& request, const GetTemplateSummaryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetTemplateSummary(request), context); } ImportStacksToStackSetOutcome CloudFormationClient::ImportStacksToStackSet(const ImportStacksToStackSetRequest& request) const { Aws::Http::URI uri = m_uri; return ImportStacksToStackSetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ImportStacksToStackSetOutcomeCallable CloudFormationClient::ImportStacksToStackSetCallable(const ImportStacksToStackSetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ImportStacksToStackSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ImportStacksToStackSet(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ImportStacksToStackSetAsync(const ImportStacksToStackSetRequest& request, const ImportStacksToStackSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ImportStacksToStackSetAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ImportStacksToStackSetAsyncHelper(const ImportStacksToStackSetRequest& request, const ImportStacksToStackSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ImportStacksToStackSet(request), context); } ListChangeSetsOutcome CloudFormationClient::ListChangeSets(const ListChangeSetsRequest& request) const { Aws::Http::URI uri = m_uri; return ListChangeSetsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListChangeSetsOutcomeCallable CloudFormationClient::ListChangeSetsCallable(const ListChangeSetsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListChangeSetsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListChangeSets(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListChangeSetsAsync(const ListChangeSetsRequest& request, const ListChangeSetsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListChangeSetsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListChangeSetsAsyncHelper(const ListChangeSetsRequest& request, const ListChangeSetsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListChangeSets(request), context); } ListExportsOutcome CloudFormationClient::ListExports(const ListExportsRequest& request) const { Aws::Http::URI uri = m_uri; return ListExportsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListExportsOutcomeCallable CloudFormationClient::ListExportsCallable(const ListExportsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListExportsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListExports(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListExportsAsync(const ListExportsRequest& request, const ListExportsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListExportsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListExportsAsyncHelper(const ListExportsRequest& request, const ListExportsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListExports(request), context); } ListImportsOutcome CloudFormationClient::ListImports(const ListImportsRequest& request) const { Aws::Http::URI uri = m_uri; return ListImportsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListImportsOutcomeCallable CloudFormationClient::ListImportsCallable(const ListImportsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListImportsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListImports(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListImportsAsync(const ListImportsRequest& request, const ListImportsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListImportsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListImportsAsyncHelper(const ListImportsRequest& request, const ListImportsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListImports(request), context); } ListStackInstancesOutcome CloudFormationClient::ListStackInstances(const ListStackInstancesRequest& request) const { Aws::Http::URI uri = m_uri; return ListStackInstancesOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListStackInstancesOutcomeCallable CloudFormationClient::ListStackInstancesCallable(const ListStackInstancesRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListStackInstancesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListStackInstances(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListStackInstancesAsync(const ListStackInstancesRequest& request, const ListStackInstancesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListStackInstancesAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListStackInstancesAsyncHelper(const ListStackInstancesRequest& request, const ListStackInstancesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListStackInstances(request), context); } ListStackResourcesOutcome CloudFormationClient::ListStackResources(const ListStackResourcesRequest& request) const { Aws::Http::URI uri = m_uri; return ListStackResourcesOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListStackResourcesOutcomeCallable CloudFormationClient::ListStackResourcesCallable(const ListStackResourcesRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListStackResourcesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListStackResources(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListStackResourcesAsync(const ListStackResourcesRequest& request, const ListStackResourcesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListStackResourcesAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListStackResourcesAsyncHelper(const ListStackResourcesRequest& request, const ListStackResourcesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListStackResources(request), context); } ListStackSetOperationResultsOutcome CloudFormationClient::ListStackSetOperationResults(const ListStackSetOperationResultsRequest& request) const { Aws::Http::URI uri = m_uri; return ListStackSetOperationResultsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListStackSetOperationResultsOutcomeCallable CloudFormationClient::ListStackSetOperationResultsCallable(const ListStackSetOperationResultsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListStackSetOperationResultsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListStackSetOperationResults(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListStackSetOperationResultsAsync(const ListStackSetOperationResultsRequest& request, const ListStackSetOperationResultsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListStackSetOperationResultsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListStackSetOperationResultsAsyncHelper(const ListStackSetOperationResultsRequest& request, const ListStackSetOperationResultsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListStackSetOperationResults(request), context); } ListStackSetOperationsOutcome CloudFormationClient::ListStackSetOperations(const ListStackSetOperationsRequest& request) const { Aws::Http::URI uri = m_uri; return ListStackSetOperationsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListStackSetOperationsOutcomeCallable CloudFormationClient::ListStackSetOperationsCallable(const ListStackSetOperationsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListStackSetOperationsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListStackSetOperations(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListStackSetOperationsAsync(const ListStackSetOperationsRequest& request, const ListStackSetOperationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListStackSetOperationsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListStackSetOperationsAsyncHelper(const ListStackSetOperationsRequest& request, const ListStackSetOperationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListStackSetOperations(request), context); } ListStackSetsOutcome CloudFormationClient::ListStackSets(const ListStackSetsRequest& request) const { Aws::Http::URI uri = m_uri; return ListStackSetsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListStackSetsOutcomeCallable CloudFormationClient::ListStackSetsCallable(const ListStackSetsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListStackSetsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListStackSets(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListStackSetsAsync(const ListStackSetsRequest& request, const ListStackSetsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListStackSetsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListStackSetsAsyncHelper(const ListStackSetsRequest& request, const ListStackSetsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListStackSets(request), context); } ListStacksOutcome CloudFormationClient::ListStacks(const ListStacksRequest& request) const { Aws::Http::URI uri = m_uri; return ListStacksOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListStacksOutcomeCallable CloudFormationClient::ListStacksCallable(const ListStacksRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListStacksOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListStacks(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListStacksAsync(const ListStacksRequest& request, const ListStacksResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListStacksAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListStacksAsyncHelper(const ListStacksRequest& request, const ListStacksResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListStacks(request), context); } ListTypeRegistrationsOutcome CloudFormationClient::ListTypeRegistrations(const ListTypeRegistrationsRequest& request) const { Aws::Http::URI uri = m_uri; return ListTypeRegistrationsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListTypeRegistrationsOutcomeCallable CloudFormationClient::ListTypeRegistrationsCallable(const ListTypeRegistrationsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListTypeRegistrationsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListTypeRegistrations(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListTypeRegistrationsAsync(const ListTypeRegistrationsRequest& request, const ListTypeRegistrationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListTypeRegistrationsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListTypeRegistrationsAsyncHelper(const ListTypeRegistrationsRequest& request, const ListTypeRegistrationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListTypeRegistrations(request), context); } ListTypeVersionsOutcome CloudFormationClient::ListTypeVersions(const ListTypeVersionsRequest& request) const { Aws::Http::URI uri = m_uri; return ListTypeVersionsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListTypeVersionsOutcomeCallable CloudFormationClient::ListTypeVersionsCallable(const ListTypeVersionsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListTypeVersionsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListTypeVersions(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListTypeVersionsAsync(const ListTypeVersionsRequest& request, const ListTypeVersionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListTypeVersionsAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListTypeVersionsAsyncHelper(const ListTypeVersionsRequest& request, const ListTypeVersionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListTypeVersions(request), context); } ListTypesOutcome CloudFormationClient::ListTypes(const ListTypesRequest& request) const { Aws::Http::URI uri = m_uri; return ListTypesOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ListTypesOutcomeCallable CloudFormationClient::ListTypesCallable(const ListTypesRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListTypesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListTypes(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ListTypesAsync(const ListTypesRequest& request, const ListTypesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListTypesAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ListTypesAsyncHelper(const ListTypesRequest& request, const ListTypesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListTypes(request), context); } PublishTypeOutcome CloudFormationClient::PublishType(const PublishTypeRequest& request) const { Aws::Http::URI uri = m_uri; return PublishTypeOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } PublishTypeOutcomeCallable CloudFormationClient::PublishTypeCallable(const PublishTypeRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< PublishTypeOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PublishType(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::PublishTypeAsync(const PublishTypeRequest& request, const PublishTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->PublishTypeAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::PublishTypeAsyncHelper(const PublishTypeRequest& request, const PublishTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, PublishType(request), context); } RecordHandlerProgressOutcome CloudFormationClient::RecordHandlerProgress(const RecordHandlerProgressRequest& request) const { Aws::Http::URI uri = m_uri; return RecordHandlerProgressOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } RecordHandlerProgressOutcomeCallable CloudFormationClient::RecordHandlerProgressCallable(const RecordHandlerProgressRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< RecordHandlerProgressOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->RecordHandlerProgress(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::RecordHandlerProgressAsync(const RecordHandlerProgressRequest& request, const RecordHandlerProgressResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->RecordHandlerProgressAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::RecordHandlerProgressAsyncHelper(const RecordHandlerProgressRequest& request, const RecordHandlerProgressResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, RecordHandlerProgress(request), context); } RegisterPublisherOutcome CloudFormationClient::RegisterPublisher(const RegisterPublisherRequest& request) const { Aws::Http::URI uri = m_uri; return RegisterPublisherOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } RegisterPublisherOutcomeCallable CloudFormationClient::RegisterPublisherCallable(const RegisterPublisherRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< RegisterPublisherOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->RegisterPublisher(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::RegisterPublisherAsync(const RegisterPublisherRequest& request, const RegisterPublisherResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->RegisterPublisherAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::RegisterPublisherAsyncHelper(const RegisterPublisherRequest& request, const RegisterPublisherResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, RegisterPublisher(request), context); } RegisterTypeOutcome CloudFormationClient::RegisterType(const RegisterTypeRequest& request) const { Aws::Http::URI uri = m_uri; return RegisterTypeOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } RegisterTypeOutcomeCallable CloudFormationClient::RegisterTypeCallable(const RegisterTypeRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< RegisterTypeOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->RegisterType(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::RegisterTypeAsync(const RegisterTypeRequest& request, const RegisterTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->RegisterTypeAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::RegisterTypeAsyncHelper(const RegisterTypeRequest& request, const RegisterTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, RegisterType(request), context); } RollbackStackOutcome CloudFormationClient::RollbackStack(const RollbackStackRequest& request) const { Aws::Http::URI uri = m_uri; return RollbackStackOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } RollbackStackOutcomeCallable CloudFormationClient::RollbackStackCallable(const RollbackStackRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< RollbackStackOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->RollbackStack(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::RollbackStackAsync(const RollbackStackRequest& request, const RollbackStackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->RollbackStackAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::RollbackStackAsyncHelper(const RollbackStackRequest& request, const RollbackStackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, RollbackStack(request), context); } SetStackPolicyOutcome CloudFormationClient::SetStackPolicy(const SetStackPolicyRequest& request) const { Aws::Http::URI uri = m_uri; return SetStackPolicyOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } SetStackPolicyOutcomeCallable CloudFormationClient::SetStackPolicyCallable(const SetStackPolicyRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< SetStackPolicyOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->SetStackPolicy(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::SetStackPolicyAsync(const SetStackPolicyRequest& request, const SetStackPolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->SetStackPolicyAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::SetStackPolicyAsyncHelper(const SetStackPolicyRequest& request, const SetStackPolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, SetStackPolicy(request), context); } SetTypeConfigurationOutcome CloudFormationClient::SetTypeConfiguration(const SetTypeConfigurationRequest& request) const { Aws::Http::URI uri = m_uri; return SetTypeConfigurationOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } SetTypeConfigurationOutcomeCallable CloudFormationClient::SetTypeConfigurationCallable(const SetTypeConfigurationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< SetTypeConfigurationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->SetTypeConfiguration(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::SetTypeConfigurationAsync(const SetTypeConfigurationRequest& request, const SetTypeConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->SetTypeConfigurationAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::SetTypeConfigurationAsyncHelper(const SetTypeConfigurationRequest& request, const SetTypeConfigurationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, SetTypeConfiguration(request), context); } SetTypeDefaultVersionOutcome CloudFormationClient::SetTypeDefaultVersion(const SetTypeDefaultVersionRequest& request) const { Aws::Http::URI uri = m_uri; return SetTypeDefaultVersionOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } SetTypeDefaultVersionOutcomeCallable CloudFormationClient::SetTypeDefaultVersionCallable(const SetTypeDefaultVersionRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< SetTypeDefaultVersionOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->SetTypeDefaultVersion(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::SetTypeDefaultVersionAsync(const SetTypeDefaultVersionRequest& request, const SetTypeDefaultVersionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->SetTypeDefaultVersionAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::SetTypeDefaultVersionAsyncHelper(const SetTypeDefaultVersionRequest& request, const SetTypeDefaultVersionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, SetTypeDefaultVersion(request), context); } SignalResourceOutcome CloudFormationClient::SignalResource(const SignalResourceRequest& request) const { Aws::Http::URI uri = m_uri; return SignalResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } SignalResourceOutcomeCallable CloudFormationClient::SignalResourceCallable(const SignalResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< SignalResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->SignalResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::SignalResourceAsync(const SignalResourceRequest& request, const SignalResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->SignalResourceAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::SignalResourceAsyncHelper(const SignalResourceRequest& request, const SignalResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, SignalResource(request), context); } StopStackSetOperationOutcome CloudFormationClient::StopStackSetOperation(const StopStackSetOperationRequest& request) const { Aws::Http::URI uri = m_uri; return StopStackSetOperationOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } StopStackSetOperationOutcomeCallable CloudFormationClient::StopStackSetOperationCallable(const StopStackSetOperationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< StopStackSetOperationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->StopStackSetOperation(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::StopStackSetOperationAsync(const StopStackSetOperationRequest& request, const StopStackSetOperationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->StopStackSetOperationAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::StopStackSetOperationAsyncHelper(const StopStackSetOperationRequest& request, const StopStackSetOperationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, StopStackSetOperation(request), context); } TestTypeOutcome CloudFormationClient::TestType(const TestTypeRequest& request) const { Aws::Http::URI uri = m_uri; return TestTypeOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } TestTypeOutcomeCallable CloudFormationClient::TestTypeCallable(const TestTypeRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< TestTypeOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->TestType(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::TestTypeAsync(const TestTypeRequest& request, const TestTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->TestTypeAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::TestTypeAsyncHelper(const TestTypeRequest& request, const TestTypeResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, TestType(request), context); } UpdateStackOutcome CloudFormationClient::UpdateStack(const UpdateStackRequest& request) const { Aws::Http::URI uri = m_uri; return UpdateStackOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } UpdateStackOutcomeCallable CloudFormationClient::UpdateStackCallable(const UpdateStackRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateStackOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateStack(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::UpdateStackAsync(const UpdateStackRequest& request, const UpdateStackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateStackAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::UpdateStackAsyncHelper(const UpdateStackRequest& request, const UpdateStackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateStack(request), context); } UpdateStackInstancesOutcome CloudFormationClient::UpdateStackInstances(const UpdateStackInstancesRequest& request) const { Aws::Http::URI uri = m_uri; return UpdateStackInstancesOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } UpdateStackInstancesOutcomeCallable CloudFormationClient::UpdateStackInstancesCallable(const UpdateStackInstancesRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateStackInstancesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateStackInstances(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::UpdateStackInstancesAsync(const UpdateStackInstancesRequest& request, const UpdateStackInstancesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateStackInstancesAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::UpdateStackInstancesAsyncHelper(const UpdateStackInstancesRequest& request, const UpdateStackInstancesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateStackInstances(request), context); } UpdateStackSetOutcome CloudFormationClient::UpdateStackSet(const UpdateStackSetRequest& request) const { Aws::Http::URI uri = m_uri; return UpdateStackSetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } UpdateStackSetOutcomeCallable CloudFormationClient::UpdateStackSetCallable(const UpdateStackSetRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateStackSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateStackSet(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::UpdateStackSetAsync(const UpdateStackSetRequest& request, const UpdateStackSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateStackSetAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::UpdateStackSetAsyncHelper(const UpdateStackSetRequest& request, const UpdateStackSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateStackSet(request), context); } UpdateTerminationProtectionOutcome CloudFormationClient::UpdateTerminationProtection(const UpdateTerminationProtectionRequest& request) const { Aws::Http::URI uri = m_uri; return UpdateTerminationProtectionOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } UpdateTerminationProtectionOutcomeCallable CloudFormationClient::UpdateTerminationProtectionCallable(const UpdateTerminationProtectionRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateTerminationProtectionOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateTerminationProtection(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::UpdateTerminationProtectionAsync(const UpdateTerminationProtectionRequest& request, const UpdateTerminationProtectionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateTerminationProtectionAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::UpdateTerminationProtectionAsyncHelper(const UpdateTerminationProtectionRequest& request, const UpdateTerminationProtectionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateTerminationProtection(request), context); } ValidateTemplateOutcome CloudFormationClient::ValidateTemplate(const ValidateTemplateRequest& request) const { Aws::Http::URI uri = m_uri; return ValidateTemplateOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST)); } ValidateTemplateOutcomeCallable CloudFormationClient::ValidateTemplateCallable(const ValidateTemplateRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ValidateTemplateOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ValidateTemplate(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CloudFormationClient::ValidateTemplateAsync(const ValidateTemplateRequest& request, const ValidateTemplateResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ValidateTemplateAsyncHelper( request, handler, context ); } ); } void CloudFormationClient::ValidateTemplateAsyncHelper(const ValidateTemplateRequest& request, const ValidateTemplateResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ValidateTemplate(request), context); }
54.299772
278
0.804324
[ "model" ]
281092ba902e24e704829b24647c47f6c7b66129
16,475
hpp
C++
include/morpheus/ADT/CommNetFactory.hpp
msurkovsky/morpheus
b938de5c5863f8fa08cd768576a08a6aa7d55e65
[ "MIT" ]
1
2019-08-16T11:01:00.000Z
2019-08-16T11:01:00.000Z
include/morpheus/ADT/CommNetFactory.hpp
It4innovations/morpheus
b938de5c5863f8fa08cd768576a08a6aa7d55e65
[ "MIT" ]
null
null
null
include/morpheus/ADT/CommNetFactory.hpp
It4innovations/morpheus
b938de5c5863f8fa08cd768576a08a6aa7d55e65
[ "MIT" ]
1
2019-08-16T11:00:56.000Z
2019-08-16T11:00:56.000Z
#ifndef COMM_NET_FACTORY_H #define COMM_NET_FACTORY_H #include "llvm/IR/DebugInfo.h" #include "llvm/IR/DebugLoc.h" #include "morpheus/Utils.hpp" #include "morpheus/ADT/CommunicationNet.hpp" #include <functional> namespace cn { using namespace llvm; // ------------------------------------------------------------------------------ // EmptyCN struct EmptyCN final : public PluginCNBase { ~EmptyCN() = default; EmptyCN(const CallSite &cs) : call_name(cs.getCalledFunction()->getName()) { entry_place().name += call_name; exit_place().name += call_name; add_cf_edge(entry_place(), exit_place()); } EmptyCN(const EmptyCN &) = delete; EmptyCN(EmptyCN &&) = default; void connect(AddressableCN &) { // no connection } string call_name; }; // ------------------------------------------------------------------------------ // CN_MPI_Isend struct CN_MPI_SendBase : public PluginCNBase { // MPI_Isend( // const void* buf, // data set to 'send_data' -- this is done within the corresponding annotation // int count, // information on the input-arc from send_data -- where I can find it? // MPI_Datatype datatype, // data type of 'send_data' place // int dest, // it goes to the setting place // int tag, // it goes to the setting place // MPI_Comm comm // THIS IS IGNORED AND IT IS SUPPOSED TO BE MPI_COMM_WORLD // MPI_Request *request // locally stored request that is accompanied with CN's type: MessageRequest // ); std::string name_prefix; Place &send_params; // INPUT Place &send_reqst; // OUTPUT Place &send_exit; // unit exit place Transition &send; virtual ~CN_MPI_SendBase() = default; CN_MPI_SendBase(const CallSite &cs) : name_prefix("send" + get_id()), send_params(add_place("<empty>", "", name_prefix + "_params")), send_reqst(add_place("(MPI_Request, MessageRequest)", "", name_prefix + "_reqst")), send_exit(add_place("Unit", "", name_prefix + "_exit")), send(add_transition({}, name_prefix)) { size = cs.getArgument(1); datatype = cs.getArgument(2); dest = cs.getArgument(3); tag = cs.getArgument(4); auto non_empty_str = [] (const string &str) { return !str.empty(); }; send_params.type = Utils::pp_vector<string>({ Utils::compute_data_buffer_type(*datatype), Utils::compute_envelope_type(nullptr, dest, *tag, ",\\l ", "(", ")")}, ",", "(", ")", non_empty_str); add_input_edge(send_params, send, Utils::pp_vector<string>({ Utils::compute_data_buffer_value(*datatype, *size), Utils::compute_envelope_value(nullptr, dest, *tag, false) }, ",", "(", ")", non_empty_str)); add_output_edge(send, send_reqst, "(rqst,\\l " + Utils::compute_msg_rqst_value( nullptr, dest, *tag, "buffered", "\\l ", "{", "}") + ")"); add_cf_edge(send, send_exit); add_cf_edge(entry_place(), send_params); add_cf_edge(send_exit, exit_place()); } CN_MPI_SendBase(const CN_MPI_SendBase &) = delete; CN_MPI_SendBase(CN_MPI_SendBase &&) = default; virtual void connect(AddressableCN &acn) { add_output_edge(send, acn.asr, ("{data=" + Utils::compute_data_buffer_value(*datatype, *size) + "," " envelope={\\l " + Utils::compute_msg_rqst_value( nullptr, dest, *tag, "buffered", "\\l ") + "}}")); } protected: Value const *size; Value const *datatype; Value const *dest; Value const *tag; }; struct CN_MPI_Isend : public CN_MPI_SendBase { virtual ~CN_MPI_Isend() = default; CN_MPI_Isend(const CallSite &cs) : CN_MPI_SendBase(cs) { mpi_rqst = cs.getArgument(6); assert(mpi_rqst->getType()->isPointerTy() && "MPI_Request has to be treated as pointer"); GetElementPtrInst const *gep = dyn_cast<GetElementPtrInst>(mpi_rqst); if (gep) { mpi_rqst = gep->getPointerOperand(); add_unresolved_place(send_reqst, *mpi_rqst, create_collective_resolve_fn_()); } else { add_unresolved_place(send_reqst, *mpi_rqst, create_resolve_fn_()); } } CN_MPI_Isend(const CN_MPI_Isend &) = delete; CN_MPI_Isend(CN_MPI_Isend &&) = default; private: UnresolvedPlace::ResolveFnTy create_resolve_fn_() { return [] (CommunicationNet &cn, Place &initiated_rqst, Transition &t_wait, UnresolvedConnect &uc) { cn.add_input_edge(initiated_rqst, t_wait, "(reqst, {id=id, buffered=buffered})"); uc.close_connect(cn, &AddressableCN::get_completed_send_request, "[not(buffered)] {id=id}"); }; } UnresolvedPlace::ResolveFnTy create_collective_resolve_fn_() { return [] (CommunicationNet &cn, Place &, Transition &, UnresolvedConnect &uc) { uc.close_connect(cn, &AddressableCN::get_completed_send_request, ("take(requests|(_, {id=id}),\\l" " size,\\l" " msg_tokens)\\l")); }; } Value const *mpi_rqst; }; // ------------------------------------------------------------------------------ // CN_MPI_Irecv struct CN_MPI_RecvBase : public PluginCNBase { // common base class for both blocking and non-blocking calls // MPI_Irecv( // void* buff; // OUT; data set to 'recv_data' -- this is done via corresponding wait // int count, // IN // MPI_Datatype datatype, // IN; data type of 'recv_data' place // int source, // IN; it goes to the setting place // int tag, // IN; it goes to the setting place // MPI_Comm comm, // IN; IGNORED (for the current version it is supposed to be MPI_COMM_WORLD) // - MPI_Request *request // OUT; locally stored request it is accompanied with CNs' type: MessageRequest // ); std::string name_prefix; Place &recv_params; Place &recv_data; Place &recv_reqst; Place &recv_exit; Transition &recv; virtual ~CN_MPI_RecvBase() = default; CN_MPI_RecvBase(const CallSite &cs): name_prefix("recv" + get_id()), recv_params(add_place("<empty>", "", name_prefix + "_params")), recv_data(add_place("<empty>", "", name_prefix + "_data")), recv_reqst(add_place("(MPI_Request, MessageRequest)", "", name_prefix + "_reqst")), recv_exit(add_place("Unit", "", name_prefix + "_exit")), recv(add_transition({}, name_prefix)) { size = cs.getArgument(1); datatype = cs.getArgument(2); source = cs.getArgument(3); tag = cs.getArgument(4); recv_params.type = Utils::compute_envelope_type(source, nullptr, *tag, ",", "(", ")"); recv_data.type = Utils::compute_data_buffer_type(*datatype); add_input_edge(recv_params, recv, Utils::compute_envelope_value(source, nullptr, *tag, false, ",", "(", ")")); add_output_edge(recv, recv_reqst, "(rqst,\\l " + Utils::compute_msg_rqst_value( source, nullptr, *tag, "false", "\\l ", "{", "}") + ")"); add_cf_edge(recv, recv_exit); add_cf_edge(entry_place(), recv_params); add_cf_edge(recv_exit, exit_place()); } CN_MPI_RecvBase(const CN_MPI_RecvBase &) = delete; CN_MPI_RecvBase(CN_MPI_RecvBase &&) = default; virtual void connect(AddressableCN &acn) { add_output_edge(recv, acn.arr, Utils::compute_msg_rqst_value(source, nullptr, *tag, "false", "\\l ","{", "}")); } protected: Value const *size; Value const *datatype; Value const *source; Value const *tag; }; struct CN_MPI_Irecv : public CN_MPI_RecvBase { virtual ~CN_MPI_Irecv() = default; CN_MPI_Irecv(const CallSite &cs) : CN_MPI_RecvBase(cs) { mpi_rqst = cs.getArgument(6); assert(mpi_rqst->getType()->isPointerTy() && "MPI_Request has to be treated as pointer"); GetElementPtrInst const *gep = dyn_cast<GetElementPtrInst>(mpi_rqst); if (gep) { mpi_rqst = gep->getPointerOperand(); std::unique_ptr<unsigned> idx; if (gep->getNumIndices() == 2) { auto idx_it = gep->indices().begin(); ConstantInt *i = dyn_cast<ConstantInt>(*idx_it); assert (i->getValue().getLimitedValue() == 0 && "Limitation: can process only request stored within a vector\n"); std::advance(idx_it, 1); // get the actual index into the array i = dyn_cast<ConstantInt>(*idx_it); idx = std::make_unique<unsigned>(i->getValue().getLimitedValue()); } string arc_expr; if (idx) { arc_expr = "msg_tokens[" + std::to_string(*idx) + "]|{data=data} => data"; } else { arc_expr = "msg_tokens|{data=data} =>* data"; } add_unresolved_place( recv_data, *mpi_rqst, create_collective_resolve_fn_(recv_data, arc_expr)); } else { add_unresolved_place( recv_reqst, *mpi_rqst, create_resolve_fn_(recv_data, Utils::compute_data_buffer_value(*datatype, *size))); } } CN_MPI_Irecv(const CN_MPI_Irecv &) = delete; CN_MPI_Irecv(CN_MPI_Irecv &&) = default; private: UnresolvedPlace::ResolveFnTy create_resolve_fn_(Place &recv_data, string ae_to_recv_data) { return [&recv_data, ae_to_recv_data] (CommunicationNet &cn, Place &initiated_rqst, Transition &t_wait, UnresolvedConnect &uc) { cn.add_input_edge(initiated_rqst, t_wait, "(reqst, {id=id})"); cn.add_output_edge(t_wait, recv_data, ae_to_recv_data); uc.close_connect(cn, &AddressableCN::get_completed_recv_request, "{data=data, envelope={id=id}}"); }; } UnresolvedPlace::ResolveFnTy create_collective_resolve_fn_(Place &recv_data, string ae_to_recv_data) { // NOTE: resolve for collective waits does not need to be connected as it is placed on right // position because of its place within the code. return [&recv_data, ae_to_recv_data](CommunicationNet &cn, Place &, Transition &t_wait, UnresolvedConnect &uc) { cn.add_output_edge(t_wait, recv_data, ae_to_recv_data); uc.close_connect(cn, &AddressableCN::get_completed_recv_request, ("take(requests|(_, {id=id}) =>* {envelope={id=id}},\\l" " size,\\l" " msg_tokens)\\l")); }; } Value const *mpi_rqst; }; // ------------------------------------------------------------------------------ // CN_MPI_Wait struct CN_MPI_Wait final : public PluginCNBase { // MPI_Wait( // MPI_Request *request // INOUT // MPI_Status *status // OUT // ) std::string name_prefix; Transition &wait; // TODO: add status place (but only if needed) // NOTE: An empty constructor serves to create wait without a "real" request // it is resolved by knowledge of particular (blocking) call. CN_MPI_Wait() : name_prefix("wait" + get_id()), wait(add_transition({}, name_prefix)), unresolved_transition(nullptr) { add_cf_edge(entry_place(), wait); add_cf_edge(wait, exit_place()); } CN_MPI_Wait(const CallSite &cs) : CN_MPI_Wait() { mpi_rqst = cs.getArgument(0); unresolved_transition = &add_unresolved_transition(wait, *mpi_rqst); } CN_MPI_Wait(const CN_MPI_Wait &) = delete; CN_MPI_Wait(CN_MPI_Wait &&) = default; void connect(AddressableCN &acn) override { if (unresolved_transition) { UnresolvedConnect uc(&acn); IncompleteEdge &edge = uc.incomplete_edge; edge.endpoint = &wait; edge.type = SHUFFLE; unresolved_transition->unresolved_connect = uc; } } private: Value const *mpi_rqst; UnresolvedTransition *unresolved_transition; }; // ------------------------------------------------------------------------------ // CN_MPI_Send struct CN_MPI_Send final : public CN_MPI_SendBase { virtual ~CN_MPI_Send() = default; CN_MPI_Send(const CallSite &cs) : CN_MPI_SendBase(cs), cn_wait(), t_wait(cn_wait.wait) { add_input_edge(send_reqst, t_wait, ("(reqst, {\\l" " id=id,\\l" " buffered=buffered})")); add_cf_edge(exit_place(), cn_wait.entry_place()); set_exit(cn_wait.exit_place()); takeover(std::move(cn_wait)); } CN_MPI_Send(const CN_MPI_Send &) = delete; CN_MPI_Send(CN_MPI_Send &&) = default; void connect(AddressableCN &acn) override { CN_MPI_SendBase::connect(acn); add_input_edge(acn.csr, t_wait, "[not(buffered)] {id=id}", SHUFFLE); } private: CN_MPI_Wait cn_wait; Transition &t_wait; }; // ------------------------------------------------------------------------------ // CN_MPI_Recv struct CN_MPI_Recv final : public CN_MPI_RecvBase { virtual ~CN_MPI_Recv() = default; CN_MPI_Recv(const CallSite &cs) : CN_MPI_RecvBase(cs), cn_wait(), t_wait(cn_wait.wait) { Value const *size = cs.getArgument(1); Value const *datatype = cs.getArgument(2); add_input_edge(recv_reqst, t_wait, "(reqst, {id=id})"); add_output_edge(t_wait, recv_data, Utils::compute_data_buffer_value(*datatype, *size)); add_cf_edge(exit_place(), cn_wait.entry_place()); set_exit(cn_wait.exit_place()); takeover(std::move(cn_wait)); } CN_MPI_Recv(const CN_MPI_Recv &) = delete; CN_MPI_Recv(CN_MPI_Recv &&) = default; void connect (AddressableCN &acn) { CN_MPI_RecvBase::connect(acn); add_input_edge(acn.crr, t_wait, "{data=data, envelope={id=id}}", SHUFFLE); } private: CN_MPI_Wait cn_wait; Transition &t_wait; }; // ----------------------------------------------------------------------------- // CN_MPI_Waitall struct CN_MPI_Waitall final : public PluginCNBase { // MPI_Waitall( // int count // IN // MPI_Request array_of_requests[] // INOUT // MPI_Status array_of_statuses[] // OUT // ) std::string name_prefix; Place &waitall_count; Place &waitall_rqsts; Transition &waitall; // TODO: place with statuses CN_MPI_Waitall(const CallSite &cs) : name_prefix("waitall" + get_id()), waitall_count(add_place("Int", "", name_prefix + "_count")), waitall_rqsts(add_place("(MPI_Request, MessageRequest)", "", name_prefix + "_reqsts")), waitall(add_transition({}, name_prefix)) { // connect entry and exit points add_cf_edge(entry_place(), waitall_rqsts); add_cf_edge(waitall, exit_place()); add_input_edge(waitall_count, waitall, "size"); add_input_edge(waitall_rqsts, waitall, ("take(_,\\l" " size,\\l" " requests)\\l")); mpi_rqsts = cs.getArgument(1); GetElementPtrInst const *gep = dyn_cast<GetElementPtrInst>(mpi_rqsts); if (gep) { mpi_rqsts = gep->getPointerOperand(); } unresolved_transition = &add_unresolved_transition(waitall, *mpi_rqsts); } CN_MPI_Waitall(const CN_MPI_Waitall &) = delete; CN_MPI_Waitall(CN_MPI_Waitall &&) = default; void connect(AddressableCN &acn) override { if (unresolved_transition) { UnresolvedConnect uc(&acn); IncompleteEdge &edge = uc.incomplete_edge; edge.endpoint = &waitall; edge.type = SHUFFLE; unresolved_transition->unresolved_connect = uc; } } private: Value const *mpi_rqsts; UnresolvedTransition *unresolved_transition; }; // =========================================================================== // CNs factory PluginCNGeneric createCommSubnet(const CallSite &cs) { Function *f = cs.getCalledFunction(); assert (f->hasName() && "The CNFactory expects call site with a named function"); StringRef call_name = f->getName(); if (call_name == "MPI_Isend") { return CN_MPI_Isend(cs); } else if (call_name == "MPI_Send") { return CN_MPI_Send(cs); } else if (call_name == "MPI_Irecv") { return CN_MPI_Irecv(cs); } else if (call_name == "MPI_Recv") { return CN_MPI_Recv(cs); } else if (call_name == "MPI_Wait") { return CN_MPI_Wait(cs); } else if (call_name == "MPI_Waitall") { return CN_MPI_Waitall(cs); } return EmptyCN(cs); } } // end of anonymous namespace #endif // COMM_NET_FACTORY_H
31.928295
115
0.604127
[ "vector" ]
2810b24cb7a43a5e78323a2c2c79f5272c0cc219
18,976
cpp
C++
FreeBSD/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
4
2016-08-22T22:02:55.000Z
2017-03-04T22:56:44.000Z
FreeBSD/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
21
2016-08-11T09:43:43.000Z
2017-01-29T12:52:56.000Z
FreeBSD/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp
TigerBSD/TigerBSD
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
null
null
null
//===-- AppleObjCRuntime.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "AppleObjCRuntime.h" #include "AppleObjCTrampolineHandler.h" #include "clang/AST/Type.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/ConstString.h" #include "lldb/Core/Error.h" #include "lldb/Core/Log.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleList.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Scalar.h" #include "lldb/Core/Section.h" #include "lldb/Core/StreamString.h" #include "lldb/Core/ValueObject.h" #include "lldb/Expression/FunctionCaller.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StopInfo.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include <vector> using namespace lldb; using namespace lldb_private; #define PO_FUNCTION_TIMEOUT_USEC 15*1000*1000 AppleObjCRuntime::~AppleObjCRuntime() { } AppleObjCRuntime::AppleObjCRuntime(Process *process) : ObjCLanguageRuntime (process), m_read_objc_library (false), m_objc_trampoline_handler_ap (), m_Foundation_major() { ReadObjCLibraryIfNeeded (process->GetTarget().GetImages()); } bool AppleObjCRuntime::GetObjectDescription (Stream &str, ValueObject &valobj) { CompilerType compiler_type(valobj.GetCompilerType()); bool is_signed; // ObjC objects can only be pointers (or numbers that actually represents pointers // but haven't been typecast, because reasons..) if (!compiler_type.IsIntegerType (is_signed) && !compiler_type.IsPointerType ()) return false; // Make the argument list: we pass one arg, the address of our pointer, to the print function. Value val; if (!valobj.ResolveValue(val.GetScalar())) return false; // Value Objects may not have a process in their ExecutionContextRef. But we need to have one // in the ref we pass down to eventually call description. Get it from the target if it isn't // present. ExecutionContext exe_ctx; if (valobj.GetProcessSP()) { exe_ctx = ExecutionContext(valobj.GetExecutionContextRef()); } else { exe_ctx.SetContext(valobj.GetTargetSP(), true); if (!exe_ctx.HasProcessScope()) return false; } return GetObjectDescription(str, val, exe_ctx.GetBestExecutionContextScope()); } bool AppleObjCRuntime::GetObjectDescription (Stream &strm, Value &value, ExecutionContextScope *exe_scope) { if (!m_read_objc_library) return false; ExecutionContext exe_ctx; exe_scope->CalculateExecutionContext(exe_ctx); Process *process = exe_ctx.GetProcessPtr(); if (!process) return false; // We need other parts of the exe_ctx, but the processes have to match. assert (m_process == process); // Get the function address for the print function. const Address *function_address = GetPrintForDebuggerAddr(); if (!function_address) return false; Target *target = exe_ctx.GetTargetPtr(); CompilerType compiler_type = value.GetCompilerType(); if (compiler_type) { if (!ClangASTContext::IsObjCObjectPointerType(compiler_type)) { strm.Printf ("Value doesn't point to an ObjC object.\n"); return false; } } else { // If it is not a pointer, see if we can make it into a pointer. ClangASTContext *ast_context = target->GetScratchClangASTContext(); CompilerType opaque_type = ast_context->GetBasicType(eBasicTypeObjCID); if (!opaque_type) opaque_type = ast_context->GetBasicType(eBasicTypeVoid).GetPointerType(); //value.SetContext(Value::eContextTypeClangType, opaque_type_ptr); value.SetCompilerType (opaque_type); } ValueList arg_value_list; arg_value_list.PushValue(value); // This is the return value: ClangASTContext *ast_context = target->GetScratchClangASTContext(); CompilerType return_compiler_type = ast_context->GetCStringType(true); Value ret; // ret.SetContext(Value::eContextTypeClangType, return_compiler_type); ret.SetCompilerType (return_compiler_type); if (exe_ctx.GetFramePtr() == NULL) { Thread *thread = exe_ctx.GetThreadPtr(); if (thread == NULL) { exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread()); thread = exe_ctx.GetThreadPtr(); } if (thread) { exe_ctx.SetFrameSP(thread->GetSelectedFrame()); } } // Now we're ready to call the function: StreamString error_stream; lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS; if (!m_print_object_caller_up) { Error error; m_print_object_caller_up.reset(exe_scope->CalculateTarget()->GetFunctionCallerForLanguage (eLanguageTypeObjC, return_compiler_type, *function_address, arg_value_list, "objc-object-description", error)); if (error.Fail()) { m_print_object_caller_up.reset(); strm.Printf("Could not get function runner to call print for debugger function: %s.", error.AsCString()); return false; } m_print_object_caller_up->InsertFunction(exe_ctx, wrapper_struct_addr, error_stream); } else { m_print_object_caller_up->WriteFunctionArguments(exe_ctx, wrapper_struct_addr, arg_value_list, error_stream); } EvaluateExpressionOptions options; options.SetUnwindOnError(true); options.SetTryAllThreads(true); options.SetStopOthers(true); options.SetIgnoreBreakpoints(true); options.SetTimeoutUsec(PO_FUNCTION_TIMEOUT_USEC); ExpressionResults results = m_print_object_caller_up->ExecuteFunction (exe_ctx, &wrapper_struct_addr, options, error_stream, ret); if (results != eExpressionCompleted) { strm.Printf("Error evaluating Print Object function: %d.\n", results); return false; } addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS); char buf[512]; size_t cstr_len = 0; size_t full_buffer_len = sizeof (buf) - 1; size_t curr_len = full_buffer_len; while (curr_len == full_buffer_len) { Error error; curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf, sizeof(buf), error); strm.Write (buf, curr_len); cstr_len += curr_len; } return cstr_len > 0; } lldb::ModuleSP AppleObjCRuntime::GetObjCModule () { ModuleSP module_sp (m_objc_module_wp.lock()); if (module_sp) return module_sp; Process *process = GetProcess(); if (process) { const ModuleList& modules = process->GetTarget().GetImages(); for (uint32_t idx = 0; idx < modules.GetSize(); idx++) { module_sp = modules.GetModuleAtIndex(idx); if (AppleObjCRuntime::AppleIsModuleObjCLibrary(module_sp)) { m_objc_module_wp = module_sp; return module_sp; } } } return ModuleSP(); } Address * AppleObjCRuntime::GetPrintForDebuggerAddr() { if (!m_PrintForDebugger_addr.get()) { const ModuleList &modules = m_process->GetTarget().GetImages(); SymbolContextList contexts; SymbolContext context; if ((!modules.FindSymbolsWithNameAndType(ConstString ("_NSPrintForDebugger"), eSymbolTypeCode, contexts)) && (!modules.FindSymbolsWithNameAndType(ConstString ("_CFPrintForDebugger"), eSymbolTypeCode, contexts))) return NULL; contexts.GetContextAtIndex(0, context); m_PrintForDebugger_addr.reset(new Address(context.symbol->GetAddress())); } return m_PrintForDebugger_addr.get(); } bool AppleObjCRuntime::CouldHaveDynamicValue (ValueObject &in_value) { return in_value.GetCompilerType().IsPossibleDynamicType (NULL, false, // do not check C++ true); // check ObjC } bool AppleObjCRuntime::GetDynamicTypeAndAddress (ValueObject &in_value, lldb::DynamicValueType use_dynamic, TypeAndOrName &class_type_or_name, Address &address, Value::ValueType &value_type) { return false; } TypeAndOrName AppleObjCRuntime::FixUpDynamicType (const TypeAndOrName& type_and_or_name, ValueObject& static_value) { CompilerType static_type(static_value.GetCompilerType()); Flags static_type_flags(static_type.GetTypeInfo()); TypeAndOrName ret(type_and_or_name); if (type_and_or_name.HasType()) { // The type will always be the type of the dynamic object. If our parent's type was a pointer, // then our type should be a pointer to the type of the dynamic object. If a reference, then the original type // should be okay... CompilerType orig_type = type_and_or_name.GetCompilerType(); CompilerType corrected_type = orig_type; if (static_type_flags.AllSet(eTypeIsPointer)) corrected_type = orig_type.GetPointerType (); ret.SetCompilerType(corrected_type); } else { // If we are here we need to adjust our dynamic type name to include the correct & or * symbol std::string corrected_name (type_and_or_name.GetName().GetCString()); if (static_type_flags.AllSet(eTypeIsPointer)) corrected_name.append(" *"); // the parent type should be a correctly pointer'ed or referenc'ed type ret.SetCompilerType(static_type); ret.SetName(corrected_name.c_str()); } return ret; } bool AppleObjCRuntime::AppleIsModuleObjCLibrary (const ModuleSP &module_sp) { if (module_sp) { const FileSpec &module_file_spec = module_sp->GetFileSpec(); static ConstString ObjCName ("libobjc.A.dylib"); if (module_file_spec) { if (module_file_spec.GetFilename() == ObjCName) return true; } } return false; } // we use the version of Foundation to make assumptions about the ObjC runtime on a target uint32_t AppleObjCRuntime::GetFoundationVersion () { if (!m_Foundation_major.hasValue()) { const ModuleList& modules = m_process->GetTarget().GetImages(); uint32_t major = UINT32_MAX; for (uint32_t idx = 0; idx < modules.GetSize(); idx++) { lldb::ModuleSP module_sp = modules.GetModuleAtIndex(idx); if (!module_sp) continue; if (strcmp(module_sp->GetFileSpec().GetFilename().AsCString(""),"Foundation") == 0) { module_sp->GetVersion(&major,1); m_Foundation_major = major; return major; } } return LLDB_INVALID_MODULE_VERSION; } else return m_Foundation_major.getValue(); } bool AppleObjCRuntime::IsModuleObjCLibrary (const ModuleSP &module_sp) { return AppleIsModuleObjCLibrary(module_sp); } bool AppleObjCRuntime::ReadObjCLibrary (const ModuleSP &module_sp) { // Maybe check here and if we have a handler already, and the UUID of this module is the same as the one in the // current module, then we don't have to reread it? m_objc_trampoline_handler_ap.reset(new AppleObjCTrampolineHandler (m_process->shared_from_this(), module_sp)); if (m_objc_trampoline_handler_ap.get() != NULL) { m_read_objc_library = true; return true; } else return false; } ThreadPlanSP AppleObjCRuntime::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others) { ThreadPlanSP thread_plan_sp; if (m_objc_trampoline_handler_ap.get()) thread_plan_sp = m_objc_trampoline_handler_ap->GetStepThroughDispatchPlan (thread, stop_others); return thread_plan_sp; } //------------------------------------------------------------------ // Static Functions //------------------------------------------------------------------ ObjCLanguageRuntime::ObjCRuntimeVersions AppleObjCRuntime::GetObjCVersion (Process *process, ModuleSP &objc_module_sp) { if (!process) return ObjCRuntimeVersions::eObjC_VersionUnknown; Target &target = process->GetTarget(); if (target.GetArchitecture().GetTriple().getVendor() != llvm::Triple::VendorType::Apple) return ObjCRuntimeVersions::eObjC_VersionUnknown; const ModuleList &target_modules = target.GetImages(); Mutex::Locker modules_locker(target_modules.GetMutex()); size_t num_images = target_modules.GetSize(); for (size_t i = 0; i < num_images; i++) { ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i); // One tricky bit here is that we might get called as part of the initial module loading, but // before all the pre-run libraries get winnowed from the module list. So there might actually // be an old and incorrect ObjC library sitting around in the list, and we don't want to look at that. // That's why we call IsLoadedInTarget. if (AppleIsModuleObjCLibrary (module_sp) && module_sp->IsLoadedInTarget(&target)) { objc_module_sp = module_sp; ObjectFile *ofile = module_sp->GetObjectFile(); if (!ofile) return ObjCRuntimeVersions::eObjC_VersionUnknown; SectionList *sections = module_sp->GetSectionList(); if (!sections) return ObjCRuntimeVersions::eObjC_VersionUnknown; SectionSP v1_telltale_section_sp = sections->FindSectionByName(ConstString ("__OBJC")); if (v1_telltale_section_sp) { return ObjCRuntimeVersions::eAppleObjC_V1; } return ObjCRuntimeVersions::eAppleObjC_V2; } } return ObjCRuntimeVersions::eObjC_VersionUnknown; } void AppleObjCRuntime::SetExceptionBreakpoints () { const bool catch_bp = false; const bool throw_bp = true; const bool is_internal = true; if (!m_objc_exception_bp_sp) { m_objc_exception_bp_sp = LanguageRuntime::CreateExceptionBreakpoint (m_process->GetTarget(), GetLanguageType(), catch_bp, throw_bp, is_internal); if (m_objc_exception_bp_sp) m_objc_exception_bp_sp->SetBreakpointKind("ObjC exception"); } else m_objc_exception_bp_sp->SetEnabled(true); } void AppleObjCRuntime::ClearExceptionBreakpoints () { if (!m_process) return; if (m_objc_exception_bp_sp.get()) { m_objc_exception_bp_sp->SetEnabled (false); } } bool AppleObjCRuntime::ExceptionBreakpointsAreSet () { return m_objc_exception_bp_sp && m_objc_exception_bp_sp->IsEnabled(); } bool AppleObjCRuntime::ExceptionBreakpointsExplainStop (lldb::StopInfoSP stop_reason) { if (!m_process) return false; if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint) return false; uint64_t break_site_id = stop_reason->GetValue(); return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint (break_site_id, m_objc_exception_bp_sp->GetID()); } bool AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing() { if (!m_process) return false; Target &target(m_process->GetTarget()); static ConstString s_method_signature("-[NSDictionary objectForKeyedSubscript:]"); static ConstString s_arclite_method_signature("__arclite_objectForKeyedSubscript"); SymbolContextList sc_list; if (target.GetImages().FindSymbolsWithNameAndType(s_method_signature, eSymbolTypeCode, sc_list) || target.GetImages().FindSymbolsWithNameAndType(s_arclite_method_signature, eSymbolTypeCode, sc_list)) return true; else return false; } lldb::SearchFilterSP AppleObjCRuntime::CreateExceptionSearchFilter () { Target &target = m_process->GetTarget(); if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) { FileSpecList filter_modules; filter_modules.Append(FileSpec("libobjc.A.dylib", false)); return target.GetSearchFilterForModuleList(&filter_modules); } else { return LanguageRuntime::CreateExceptionSearchFilter(); } } void AppleObjCRuntime::ReadObjCLibraryIfNeeded (const ModuleList &module_list) { if (!HasReadObjCLibrary ()) { Mutex::Locker locker (module_list.GetMutex ()); size_t num_modules = module_list.GetSize(); for (size_t i = 0; i < num_modules; i++) { auto mod = module_list.GetModuleAtIndex (i); if (IsModuleObjCLibrary (mod)) { ReadObjCLibrary (mod); break; } } } } void AppleObjCRuntime::ModulesDidLoad (const ModuleList &module_list) { ReadObjCLibraryIfNeeded (module_list); }
34.190991
126
0.607715
[ "object", "vector" ]
2817e684072a965e95c1142240d21d10a6934fa7
21,332
cpp
C++
Source/Voxel/Private/VoxelRender/LODManager/VoxelRenderOctree.cpp
SolarStormInteractive/VoxelPlugin
b0b8a1838262227fa586fbcb1b46a6184cdf1e8c
[ "MIT" ]
null
null
null
Source/Voxel/Private/VoxelRender/LODManager/VoxelRenderOctree.cpp
SolarStormInteractive/VoxelPlugin
b0b8a1838262227fa586fbcb1b46a6184cdf1e8c
[ "MIT" ]
null
null
null
Source/Voxel/Private/VoxelRender/LODManager/VoxelRenderOctree.cpp
SolarStormInteractive/VoxelPlugin
b0b8a1838262227fa586fbcb1b46a6184cdf1e8c
[ "MIT" ]
null
null
null
// Copyright 2020 Phyronnaz #include "VoxelRenderOctree.h" #include "VoxelDebug/VoxelDebugManager.h" #include "VoxelMessages.h" #include "Async/Async.h" DECLARE_DWORD_ACCUMULATOR_STAT(TEXT("Voxel Render Octrees Count"), STAT_VoxelRenderOctreesCount, STATGROUP_VoxelCounters); DEFINE_VOXEL_MEMORY_STAT(STAT_VoxelRenderOctreesMemory); static TAutoConsoleVariable<int32> CVarMaxRenderOctreeChunks( TEXT("voxel.renderer.MaxRenderOctreeChunks"), 1000000, TEXT("Max render octree chunks. Allows to stop the creation of the octree before it gets too big & freezes your computer"), ECVF_Default); static TAutoConsoleVariable<int32> CVarLogRenderOctreeBuildTime( TEXT("voxel.renderer.LogRenderOctreeBuildTime"), 0, TEXT("If true, will log the render octree build times"), ECVF_Default); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// FVoxelRenderOctreeAsyncBuilder::FVoxelRenderOctreeAsyncBuilder(uint8 OctreeDepth, const FVoxelIntBox& WorldBounds) : FVoxelAsyncWork(STATIC_FNAME("Render Octree Build"), 1e9) , OctreeDepth(OctreeDepth) , WorldBounds(WorldBounds) { SetIsDone(true); } void FVoxelRenderOctreeAsyncBuilder::Init(const FVoxelRenderOctreeSettings& InOctreeSettings, TVoxelSharedPtr<FVoxelRenderOctree> InOctree) { VOXEL_FUNCTION_COUNTER(); OctreeSettings = InOctreeSettings; OldOctree = InOctree; SetIsDone(false); Counter = FPlatformTime::Seconds(); Log = "Render octree build stats:"; } #define LOG_TIME_IMPL(Name, Counter) Log += "\n\t" Name ": " + FString::SanitizeFloat((FPlatformTime::Seconds() - Counter) * 1000.f) + "ms"; Counter = FPlatformTime::Seconds(); #define LOG_TIME(Name) LOG_TIME_IMPL("\t" Name, Counter) void FVoxelRenderOctreeAsyncBuilder::ReportBuildTime() { VOXEL_FUNCTION_COUNTER(); LOG_TIME("Waiting for game thread"); if (CVarLogRenderOctreeBuildTime.GetValueOnGameThread()) { LOG_VOXEL(Log, TEXT("%s"), *Log); } if (bTooManyChunks) { FVoxelMessages::Error(FString::Printf(TEXT( "Render octree update was stopped!\n" "Max render octree chunks count reached: voxel.renderer.MaxRenderOctreeChunks < %d.\n" "This is caused by too demanding LOD settings.\n" "You can try the following: \n" "- reduce World Size\n" "- increase Max LOD\n" "- reduce invokers distances"), NumberOfChunks)); } } void FVoxelRenderOctreeAsyncBuilder::DoWork() { VOXEL_ASYNC_FUNCTION_COUNTER(); LOG_TIME_IMPL("Waiting in thread pool", Counter); double WorkStartTime = FPlatformTime::Seconds(); { VOXEL_ASYNC_SCOPE_COUNTER("Deleting previous octree"); OctreeToDelete.Reset(); LOG_TIME("Deleting previous octree"); } { VOXEL_ASYNC_SCOPE_COUNTER("Resetting arrays"); ChunkUpdates.Reset(); NewOctree.Reset(); LOG_TIME("Resetting arrays"); } { VOXEL_ASYNC_SCOPE_COUNTER("Cloning octree"); NewOctree = OldOctree.IsValid() ? MakeVoxelShared<FVoxelRenderOctree>(&*OldOctree) : MakeVoxelShared<FVoxelRenderOctree>(OctreeDepth); LOG_TIME("Cloning octree"); } { VOXEL_ASYNC_SCOPE_COUNTER("ResetDivisionType"); NewOctree->ResetDivisionType(); LOG_TIME("ResetDivisionType"); } bool bChanged; { VOXEL_ASYNC_SCOPE_COUNTER("UpdateSubdividedByDistance"); bChanged = NewOctree->UpdateSubdividedByDistance(OctreeSettings); LOG_TIME("UpdateSubdividedByDistance"); Log += "; Need to recompute neighbors: " + FString(bChanged ? "true" : "false"); } if (bChanged) { VOXEL_ASYNC_SCOPE_COUNTER("UpdateSubdividedByNeighbors"); int32 UpdateSubdividedByNeighborsCounter = 0; while (NewOctree->UpdateSubdividedByNeighbors(OctreeSettings)) { UpdateSubdividedByNeighborsCounter++; } LOG_TIME("UpdateSubdividedByNeighbors"); Log += "; Iterations: " + FString::FromInt(UpdateSubdividedByNeighborsCounter); } else { VOXEL_ASYNC_SCOPE_COUNTER("ReuseOldNeighbors"); NewOctree->ReuseOldNeighbors(); } { VOXEL_ASYNC_SCOPE_COUNTER("UpdateSubdividedByOthers"); NewOctree->UpdateSubdividedByOthers(OctreeSettings); LOG_TIME("UpdateSubdividedByOthers"); } { VOXEL_ASYNC_SCOPE_COUNTER("DeleteChunks"); NewOctree->DeleteChunks(ChunkUpdates); LOG_TIME("DeleteChunks"); } { VOXEL_ASYNC_SCOPE_COUNTER("GetUpdates"); NewOctree->GetUpdates(NewOctree->UpdateIndex + 1, bChanged, OctreeSettings, ChunkUpdates); LOG_TIME("GetUpdates"); } { VOXEL_ASYNC_SCOPE_COUNTER("Sort By LODs"); // Make sure that LOD 0 chunks are processed first ChunkUpdates.Sort([](const auto& A, const auto& B) { return A.LOD < B.LOD; }); LOG_TIME("Sort By LODs"); } if (OldOctree.IsValid()) { VOXEL_ASYNC_SCOPE_COUNTER("Find previous chunks"); for (auto& ChunkUpdate : ChunkUpdates) { if (ChunkUpdate.NewSettings.bVisible && !ChunkUpdate.OldSettings.bVisible) { OldOctree->GetVisibleChunksOverlappingBounds(ChunkUpdate.Bounds, ChunkUpdate.PreviousChunks); } } } LOG_TIME("Find previous chunks"); { VOXEL_ASYNC_SCOPE_COUNTER("Deleting old octree"); OldOctree.Reset(); LOG_TIME("Deleting old octree"); } NumberOfChunks = NewOctree->CurrentChunksCount; bTooManyChunks = NewOctree->IsCanceled(); if (bTooManyChunks) { NewOctree.Reset(); } LOG_TIME_IMPL("Total time working", WorkStartTime); } uint32 FVoxelRenderOctreeAsyncBuilder::GetPriority() const { return 0; } #undef LOG_TIME /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #define CHECK_MAX_CHUNKS_COUNT_IMPL(ReturnValue) if (IsCanceled()) { return ReturnValue; } #define CHECK_MAX_CHUNKS_COUNT() CHECK_MAX_CHUNKS_COUNT_IMPL(;) #define CHECK_MAX_CHUNKS_COUNT_BOOL() CHECK_MAX_CHUNKS_COUNT_IMPL(false) FVoxelRenderOctree::FVoxelRenderOctree(uint8 LOD) : TSimpleVoxelOctree(LOD) , Root(this) , ChunkId(GetId()) , OctreeBounds(GetBounds()) { check(LOD > 0); check(ChunkId <= Root->RootIdCounter); Root->CurrentChunksCount++; INC_DWORD_STAT_BY(STAT_VoxelRenderOctreesCount, 1); INC_VOXEL_MEMORY_STAT_BY(STAT_VoxelRenderOctreesMemory, sizeof(FVoxelRenderOctree)); } FVoxelRenderOctree::FVoxelRenderOctree(const FVoxelRenderOctree* Source) : TSimpleVoxelOctree(Source->Height) , RootIdCounter(Source->RootIdCounter) , Root(this) , ChunkId(Source->ChunkId) , OctreeBounds(GetBounds()) , UpdateIndex(Source->UpdateIndex) { check(ChunkId <= Root->RootIdCounter); Root->CurrentChunksCount++; ChunkSettings = Source->ChunkSettings; if (Source->HasChildren()) { CreateChildren(Source->GetChildren()); } INC_DWORD_STAT_BY(STAT_VoxelRenderOctreesCount, 1); INC_VOXEL_MEMORY_STAT_BY(STAT_VoxelRenderOctreesMemory, sizeof(FVoxelRenderOctree)); } FVoxelRenderOctree::FVoxelRenderOctree(const FVoxelRenderOctree& Parent, uint8 ChildIndex) : TSimpleVoxelOctree(Parent, ChildIndex) , Root(Parent.Root) , ChunkId(GetId()) , OctreeBounds(GetBounds()) , UpdateIndex(Parent.UpdateIndex) { check(ChunkId <= Root->RootIdCounter); Root->CurrentChunksCount++; INC_DWORD_STAT_BY(STAT_VoxelRenderOctreesCount, 1); INC_VOXEL_MEMORY_STAT_BY(STAT_VoxelRenderOctreesMemory, sizeof(FVoxelRenderOctree)); } FVoxelRenderOctree::FVoxelRenderOctree(const FVoxelRenderOctree& Parent, uint8 ChildIndex, const ChildrenArray& SourceChildren) : TSimpleVoxelOctree(Parent, ChildIndex) , Root(Parent.Root) , ChunkId(SourceChildren[ChildIndex].ChunkId) , OctreeBounds(GetBounds()) , UpdateIndex(Parent.UpdateIndex) { Root->CurrentChunksCount++; auto& Source = SourceChildren[ChildIndex]; ChunkSettings = Source.ChunkSettings; if (Source.HasChildren()) { CreateChildren(Source.GetChildren()); } INC_DWORD_STAT_BY(STAT_VoxelRenderOctreesCount, 1); INC_VOXEL_MEMORY_STAT_BY(STAT_VoxelRenderOctreesMemory, sizeof(FVoxelRenderOctree)); } FVoxelRenderOctree::~FVoxelRenderOctree() { Root->CurrentChunksCount--; DEC_DWORD_STAT_BY(STAT_VoxelRenderOctreesCount, 1); DEC_VOXEL_MEMORY_STAT_BY(STAT_VoxelRenderOctreesMemory, sizeof(FVoxelRenderOctree)); } /////////////////////////////////////////////////////////////////////////////// void FVoxelRenderOctree::ResetDivisionType() { ChunkSettings.OldDivisionType = ChunkSettings.DivisionType; ChunkSettings.DivisionType = EDivisionType::Uninitialized; if (!!HasChildren()) { for (auto& Child : GetChildren()) { Child.ResetDivisionType(); } } } bool FVoxelRenderOctree::UpdateSubdividedByDistance(const FVoxelRenderOctreeSettings& Settings) { CHECK_MAX_CHUNKS_COUNT_BOOL(); if (ShouldSubdivideByDistance(Settings)) { ChunkSettings.DivisionType = EDivisionType::ByDistance; if (!HasChildren()) { CreateChildren(); } bool bChanged = ChunkSettings.OldDivisionType != EDivisionType::ByDistance; for (auto& Child : GetChildren()) { bChanged |= Child.UpdateSubdividedByDistance(Settings); } return bChanged; } else { return ChunkSettings.OldDivisionType == EDivisionType::ByDistance; } } bool FVoxelRenderOctree::UpdateSubdividedByNeighbors(const FVoxelRenderOctreeSettings& Settings) { CHECK_MAX_CHUNKS_COUNT_BOOL(); bool bShouldContinue = false; if (ChunkSettings.DivisionType == EDivisionType::Uninitialized && ShouldSubdivideByNeighbors(Settings)) { ChunkSettings.DivisionType = EDivisionType::ByNeighbors; if (!HasChildren()) { CreateChildren(); } bShouldContinue = true; } if (ChunkSettings.DivisionType != EDivisionType::Uninitialized) { for (auto& Child : GetChildren()) { bShouldContinue |= Child.UpdateSubdividedByNeighbors(Settings); } } return bShouldContinue; } void FVoxelRenderOctree::ReuseOldNeighbors() { if (ChunkSettings.OldDivisionType == EDivisionType::ByNeighbors) { ChunkSettings.DivisionType = EDivisionType::ByNeighbors; } if (!!HasChildren()) { for (auto& Child : GetChildren()) { Child.ReuseOldNeighbors(); } } } void FVoxelRenderOctree::UpdateSubdividedByOthers(const FVoxelRenderOctreeSettings& Settings) { CHECK_MAX_CHUNKS_COUNT(); if (ChunkSettings.DivisionType == EDivisionType::Uninitialized && ShouldSubdivideByOthers(Settings)) { ChunkSettings.DivisionType = EDivisionType::ByOthers; if (!HasChildren()) { CreateChildren(); } } if (ChunkSettings.DivisionType != EDivisionType::Uninitialized) { for (auto& Child : GetChildren()) { Child.UpdateSubdividedByOthers(Settings); } } } void FVoxelRenderOctree::DeleteChunks(TArray<FVoxelChunkUpdate>& ChunkUpdates) { CHECK_MAX_CHUNKS_COUNT(); if (ChunkSettings.DivisionType == EDivisionType::Uninitialized) { if (HasChildren()) { for (auto& Child : GetChildren()) { ensure(Child.ChunkSettings.DivisionType == EDivisionType::Uninitialized); Child.DeleteChunks(ChunkUpdates); if (Child.ChunkSettings.Settings.HasRenderChunk()) { //ensureVoxelSlowNoSideEffects(!ChunkUpdates.FindByPredicate([&](const FVoxelChunkUpdate& ChunkUpdate) { return ChunkUpdate.Id == Child.ChunkId; })); ChunkUpdates.Emplace( FVoxelChunkUpdate { Child.ChunkId, Child.Height, Child.OctreeBounds, Child.ChunkSettings.Settings, {}, {} }); } } DestroyChildren(); } } else { for (auto& Child : GetChildren()) { Child.DeleteChunks(ChunkUpdates); } } } /////////////////////////////////////////////////////////////////////////////// void FVoxelRenderOctree::GetUpdates( uint32 InUpdateIndex, bool bRecomputeTransitionMasks, const FVoxelRenderOctreeSettings& Settings, TArray<FVoxelChunkUpdate>& ChunkUpdates, bool bInVisible) { CHECK_MAX_CHUNKS_COUNT(); UpdateIndex++; check(UpdateIndex == InUpdateIndex); if (!OctreeBounds.Intersect(Settings.WorldBounds)) { return; } FVoxelChunkSettings NewSettings{}; // NOTE: we DO want bEnableRender = false to disable VisibleChunks settings NewSettings.bVisible = Settings.bEnableRender && Height <= Settings.ChunksCullingLOD && bInVisible; if (!HasChildren()) { check(ChunkSettings.DivisionType == EDivisionType::Uninitialized); } else { check(ChunkSettings.DivisionType != EDivisionType::Uninitialized); bool bChildrenVisible; if (ChunkSettings.DivisionType == EDivisionType::ByDistance || ChunkSettings.DivisionType == EDivisionType::ByNeighbors) { // There are visible children NewSettings.bVisible = false; bChildrenVisible = true; } else { check(ChunkSettings.DivisionType == EDivisionType::ByOthers); bChildrenVisible = false; } for (auto& Child : GetChildren()) { Child.GetUpdates(UpdateIndex, bRecomputeTransitionMasks, Settings, ChunkUpdates, bChildrenVisible); } } NewSettings.bEnableCollisions = Settings.bEnableCollisions && ((Height == 0 && IsInvokerInRange(Settings.Invokers, [](const FVoxelInvokerSettings& Invoker) { return Invoker.bUseForCollisions; }, [](const FVoxelInvokerSettings& Invoker) { return Invoker.CollisionsBounds; }) ) || (NewSettings.bVisible && Settings.bComputeVisibleChunksCollisions && Height <= Settings.VisibleChunksCollisionsMaxLOD) ); NewSettings.bEnableNavmesh = Settings.bEnableNavmesh && ((Height == 0 && IsInvokerInRange(Settings.Invokers, [](const FVoxelInvokerSettings& Invoker) { return Invoker.bUseForNavmesh; }, [](const FVoxelInvokerSettings& Invoker) { return Invoker.NavmeshBounds; }) ) || (NewSettings.bVisible && Settings.bComputeVisibleChunksNavmesh && Height <= Settings.VisibleChunksNavmeshMaxLOD) ); check(NewSettings.TransitionsMask == 0); if (NewSettings.HasRenderChunk()) { if (NewSettings.bVisible && Settings.bEnableTransitions) { if (bRecomputeTransitionMasks) { for (int32 DirectionIndex = 0; DirectionIndex < 6; DirectionIndex++) { const auto Direction = EVoxelDirectionFlag::Type(1 << DirectionIndex); const FVoxelRenderOctree* AdjacentChunk = GetVisibleAdjacentChunk(Direction, 0); if (AdjacentChunk && AdjacentChunk->OctreeBounds.Intersect(Settings.WorldBounds)) { check( (AdjacentChunk->Height == Height - 1) || (AdjacentChunk->Height == Height) || (AdjacentChunk->Height == Height + 1) ); if (Settings.bInvertTransitions ? (AdjacentChunk->Height > Height) : (AdjacentChunk->Height < Height)) { NewSettings.TransitionsMask |= Direction; } } } } else { NewSettings.TransitionsMask = ChunkSettings.Settings.TransitionsMask; } } } if (ChunkSettings.Settings != NewSettings && (ChunkSettings.Settings.HasRenderChunk() || NewSettings.HasRenderChunk())) { // Too slow ensureVoxelSlowNoSideEffects(!ChunkUpdates.FindByPredicate([&](const FVoxelChunkUpdate& ChunkUpdate) { return ChunkUpdate.Id == ChunkId; })); ChunkUpdates.Emplace( FVoxelChunkUpdate { ChunkId, Height, OctreeBounds, ChunkSettings.Settings, NewSettings, {} }); } ChunkSettings.Settings = NewSettings; } void FVoxelRenderOctree::GetChunksToUpdateForBounds(const FVoxelIntBox& Bounds, TArray<uint64>& ChunksToUpdate, const FVoxelOnChunkUpdate& OnChunkUpdate) const { if (!OctreeBounds.Intersect(Bounds)) { return; } if (ChunkSettings.Settings.HasRenderChunk()) { OnChunkUpdate.Broadcast(OctreeBounds); ChunksToUpdate.Add(ChunkId); } if (!!HasChildren()) { for (auto& Child : GetChildren()) { Child.GetChunksToUpdateForBounds(Bounds, ChunksToUpdate, OnChunkUpdate); } } } void FVoxelRenderOctree::GetVisibleChunksOverlappingBounds(const FVoxelIntBox& Bounds, TArray<uint64, TInlineAllocator<8>>& VisibleChunks) const { if (!OctreeBounds.Intersect(Bounds)) { return; } if (ChunkSettings.Settings.bVisible) { VisibleChunks.Add(ChunkId); } if (!!HasChildren()) { for (auto& Child : GetChildren()) { Child.GetVisibleChunksOverlappingBounds(Bounds, VisibleChunks); } } } FORCEINLINE bool FVoxelRenderOctree::IsCanceled() const { return Root->CurrentChunksCount >= CVarMaxRenderOctreeChunks.GetValueOnAnyThread(); } /////////////////////////////////////////////////////////////////////////////// bool FVoxelRenderOctree::ShouldSubdivideByDistance(const FVoxelRenderOctreeSettings& Settings) const { if (!Settings.bEnableRender) { return false; } if (Height == 0) { return false; } if (!OctreeBounds.Intersect(Settings.WorldBounds)) { return false; } if (Height <= Settings.MinLOD) { return false; } if (Height > Settings.MaxLOD) { return true; } for (auto& Invoker : Settings.Invokers) { if (Invoker.bUseForLOD && OctreeBounds.Intersect(Invoker.LODBounds) && Height > Invoker.LODToSet) { return true; } } return false; } bool FVoxelRenderOctree::ShouldSubdivideByNeighbors(const FVoxelRenderOctreeSettings& Settings) const { if (Height == 0) { return false; } if (!OctreeBounds.Intersect(Settings.WorldBounds)) { return false; } for (int32 DirectionIndex = 0; DirectionIndex < 6; DirectionIndex++) { const auto Direction = EVoxelDirectionFlag::Type(1 << DirectionIndex); for (int32 Index = 0; Index < 4; Index++) // Iterate the 4 adjacent subdivided chunks { const FVoxelRenderOctree* AdjacentChunk = GetVisibleAdjacentChunk(Direction, Index); if (!AdjacentChunk) { continue; } if (AdjacentChunk->Height + 1 < Height) { return true; } if (AdjacentChunk->Height >= Height) { check(Index == 0); break; // No need to continue, 4 indices are the same chunk } } } return false; } bool FVoxelRenderOctree::ShouldSubdivideByOthers(const FVoxelRenderOctreeSettings& Settings) const { if (!Settings.bEnableCollisions && !Settings.bEnableNavmesh) { return false; } if (Height == 0) { return false; } if (!OctreeBounds.Intersect(Settings.WorldBounds)) { return false; } if (Settings.bEnableCollisions && IsInvokerInRange(Settings.Invokers, [](const FVoxelInvokerSettings& Invoker) { return Invoker.bUseForCollisions; }, [](const FVoxelInvokerSettings& Invoker) { return Invoker.CollisionsBounds; })) { return true; } if (Settings.bEnableNavmesh && IsInvokerInRange(Settings.Invokers, [](const FVoxelInvokerSettings& Invoker) { return Invoker.bUseForNavmesh; }, [](const FVoxelInvokerSettings& Invoker) { return Invoker.NavmeshBounds; })) { return true; } return false; } /////////////////////////////////////////////////////////////////////////////// inline bool IsVisibleParent(const FVoxelRenderOctree* Chunk) { return Chunk->ChunkSettings.DivisionType == FVoxelRenderOctree::EDivisionType::ByDistance || Chunk->ChunkSettings.DivisionType == FVoxelRenderOctree::EDivisionType::ByNeighbors; } const FVoxelRenderOctree* FVoxelRenderOctree::GetVisibleAdjacentChunk(EVoxelDirectionFlag::Type Direction, int32 Index) const { const int32 HalfSize = Size() / 2; const int32 HalfHalfSize = Size() / 4; int32 S = HalfSize + HalfHalfSize; // Size / 2: on the border; Size / 4: center of child chunk int32 X, Y; if (Index & 0x1) { X = -HalfHalfSize; } else { X = HalfHalfSize; } if (Index & 0x2) { Y = -HalfHalfSize; } else { Y = HalfHalfSize; } FIntVector P; switch (Direction) { case EVoxelDirectionFlag::XMin: P = Position + FIntVector(-S, X, Y); break; case EVoxelDirectionFlag::XMax: P = Position + FIntVector(S, X, Y); break; case EVoxelDirectionFlag::YMin: P = Position + FIntVector(X, -S, Y); break; case EVoxelDirectionFlag::YMax: P = Position + FIntVector(X, S, Y); break; case EVoxelDirectionFlag::ZMin: P = Position + FIntVector(X, Y, -S); break; case EVoxelDirectionFlag::ZMax: P = Position + FIntVector(X, Y, S); break; default: check(false); P = FIntVector::ZeroValue; } if (Root->OctreeBounds.Contains(P)) { const FVoxelRenderOctree* Ptr = Root; while (IsVisibleParent(Ptr)) { Ptr = &Ptr->GetChild(P); } check(Ptr->OctreeBounds.Contains(P)); return Ptr; } else { return nullptr; } } template<typename T1, typename T2> bool FVoxelRenderOctree::IsInvokerInRange(const TArray<FVoxelInvokerSettings>& Invokers, T1 SelectInvoker, T2 GetInvokerBounds) const { for (auto& Invoker : Invokers) { if (SelectInvoker(Invoker)) { if (OctreeBounds.Intersect(GetInvokerBounds(Invoker))) { return true; } } } return false; } /////////////////////////////////////////////////////////////////////////////// uint64 FVoxelRenderOctree::GetId() { return ++Root->RootIdCounter; }
26.665
179
0.678933
[ "render" ]
2818ebedca8e5b09f30a6cfa636a7c686c9e6a1a
4,015
hpp
C++
Code/PROJECT XYZ/Code/include/Engine/Graphics/View.hpp
SonarSystems/Project-XYZ
428e270c49d76b4a029a6691e426f321da1c5d21
[ "Unlicense" ]
12
2020-11-23T08:00:49.000Z
2021-07-10T23:48:52.000Z
Code/PROJECT XYZ/Code/include/Engine/Graphics/View.hpp
SonarSystems/Project-XYZ
428e270c49d76b4a029a6691e426f321da1c5d21
[ "Unlicense" ]
null
null
null
Code/PROJECT XYZ/Code/include/Engine/Graphics/View.hpp
SonarSystems/Project-XYZ
428e270c49d76b4a029a6691e426f321da1c5d21
[ "Unlicense" ]
4
2020-12-01T16:42:34.000Z
2021-06-10T16:33:29.000Z
#pragma once #include "Core/Game.hpp" namespace Sonar { class View { public: /** * \brief Default class constructor (creates a default view of 0, 0, 1000, 1000) * * \param data Game data object */ View( GameDataRef data ); View( GameDataRef data, const sf::View &view ); /** * \brief Explicit class constructor * * \param data Game data object * \param rectangle View's new rectangle to set to */ explicit View( GameDataRef data, const glm::vec4 &rectangle ); /** * \brief Class constructor with center and size parameters * * \param data Game data object * \param center Center of the view * \param size Size of the view */ View( GameDataRef data, const glm::vec2 &center, const glm::vec2 &size ); /** * \brief Class destructor */ ~View( ); /** * \brief Draw the classes objects */ void Draw( ); /** * \brief Update the classes objects * * \param dt Delta time (difference between frames) */ void Update( const float &dt ); /** * \brief Set the center of the view * * \param x X position * \param y Y position */ void SetCenter( const float &x, const float &y ); /** * \brief Set the center of the view * * \param center Center of the view */ void SetCenter( const glm::vec2 &center ); /** * \brief Set the size of the view * * \param width Width of the view * \param height Height of the view */ void SetSize( const float &width, const float &height ); /** * \brief Set the size of the view * * \param size Size of the view */ void SetSize( const glm::vec2 &size ); /** * \brief Set the rotation of the view * * \param angle New rotation angle of the view */ void SetRotation( const float &angle ); /** * \brief Set the viewport of the view * * \param viewport View's new viewport */ void SetViewport( const glm::vec4 &viewport ); /** * \brief Reset the view * * \param rectangle View's new rectangle to reset to */ void Reset( const glm::vec4 &rectangle ); /** * \brief Get the view's center * * \return Output returns the view's center vector */ const glm::vec2 GetCenter( ) const; /** * \brief Get the view's size * * \return Output returns the view's size vector */ const glm::vec2 GetSize( ) const; /** * \brief Get the view's rotation angle * * \return Output returns the view's rotation angle */ const float GetRotation( ) const; /** * \brief Get the view's viewport * * \return Output returns the view's viewport vector */ const glm::vec4 GetViewport( ) const; /** * \brief Move the view * * \param offsetX Offset in x axis * \param offsetY Offset in y axis */ void Move( const float &offsetX, const float &offsetY ); /** * \brief Move the view * * \param offset Offset in x and y axis */ void Move( const glm::vec2 &offset ); /** * \brief Rotate the view * * \param angle Angle to rotate by (relative to current rotation angle) */ void Rotate( const float &angle ); /** * \brief Zoom into the view * * \param factor Zoom factor (relative to current zoom factor) */ void Zoom( const float &factor ); /** * \brief Get the view's SFML Transform object (COULD ABTRAST LATER INTO Sonar::Transform) * * \return Output returns the view's transform */ const sf::Transform &GetTransform( ) const; /** * \brief Get the view's SFML Inverse Transform object (COULD ABTRAST LATER INTO Sonar::Transform) * * \return Output returns the view's inverse transform */ const sf::Transform &GetInverseTransform( ) const; /** * \brief Get the view's underlying SFML View object * * \return Output returns the SFML View object */ const sf::View &GetSFMLViewObject( ) const; private: /** * \brief Game data object */ GameDataRef _data; /** * \brief Local SFML View object */ sf::View *_view; }; }
20.589744
99
0.620922
[ "object", "vector", "transform" ]
2819deeae6eefff3768834dc2a43348e5c61a795
3,769
cc
C++
third_party/tflite_support/src/tensorflow_lite_support/custom_ops/tflite_inference_main.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/tflite_support/src/tensorflow_lite_support/custom_ops/tflite_inference_main.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/tflite_support/src/tensorflow_lite_support/custom_ops/tflite_inference_main.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // This program runs the tflite model specified in --model with random inputs. // For string type, the input is filled with a fixed string. #include <string> #include <glog/logging.h> #include "tensorflow/core/platform/init_main.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/kernels/register.h" #include "tensorflow/lite/model.h" #include "tensorflow/lite/model_builder.h" #include "tensorflow/lite/string_util.h" #include "tensorflow/lite/tools/command_line_flags.h" void FillRandomString(tflite::DynamicBuffer* buffer, const TfLiteIntArray* dim_array, const std::function<std::string()>& random_func) { int num_elements = 1; for (size_t i = 0; i < dim_array->size; i++) { num_elements *= dim_array->data[i]; } for (int i = 0; i < num_elements; ++i) { auto str = random_func(); buffer->AddString(str.data(), str.length()); } } void RunWithRandomInputs(const std::string& filename) { std::unique_ptr<tflite::FlatBufferModel> model = tflite::FlatBufferModel::BuildFromFile(filename.c_str()); // Build the interpreter tflite::ops::builtin::BuiltinOpResolver resolver; std::unique_ptr<tflite::Interpreter> interpreter; if (tflite::InterpreterBuilder(*model, resolver)(&interpreter) != kTfLiteOk) { LOG(FATAL) << "Could not initialize interpreter for TFLite model."; } // Resize input tensors, if desired. if (interpreter->AllocateTensors() != kTfLiteOk) { LOG(FATAL) << "Could not allocate tensor."; } // Fill the random data. std::vector<std::vector<uint8_t>> sample; for (int tensor_idx : interpreter->inputs()) { auto tensor = interpreter->tensor(tensor_idx); if (tensor->type == kTfLiteString) { tflite::DynamicBuffer buffer; FillRandomString(&buffer, tensor->dims, []() { return "we're have some friends over saturday to hang out in the " "yard"; }); buffer.WriteToTensor(tensor, /*new_shape=*/nullptr); } else { std::vector<uint8_t> data(tensor->bytes); for (auto it = data.begin(); it != data.end(); ++it) { *it = random(); } sample.push_back(data); tensor->data.raw = reinterpret_cast<char*>(sample.rbegin()->data()); } } // Running inference. if (interpreter->Invoke() != kTfLiteOk) { LOG(FATAL) << "Failed to run the model."; } // Get the output. for (int tensor_idx : interpreter->outputs()) { auto tensor = interpreter->tensor(tensor_idx); LOG(INFO) << "Output type: " << TfLiteTypeGetName(tensor->type); } } int main(int argc, char** argv) { // Parse flags to get the filename. std::string filename; std::vector<tflite::Flag> flag_list{tflite::Flag::CreateFlag( "model", &filename, "The tflite model to run sample inference.", tflite::Flag::kRequired)}; tflite::Flags::Parse(&argc, const_cast<const char**>(argv), flag_list); tensorflow::port::InitMain(argv[0], &argc, &argv); // Run the model with random inputs. RunWithRandomInputs(filename); return 0; }
35.556604
80
0.67047
[ "vector", "model" ]
28209f981aafe507decee67d1204e47db8836ee2
5,580
cpp
C++
tesseract_process_managers/src/utils/task_info_statistics.cpp
tesseract-robotics/tesseract_planning
af95de9cbe841126a3f8d3ba774683cf20d223b3
[ "BSD-3-Clause", "BSD-2-Clause", "Apache-2.0" ]
5
2021-11-20T05:41:25.000Z
2022-02-22T23:14:46.000Z
tesseract_process_managers/src/utils/task_info_statistics.cpp
tesseract-robotics/tesseract_planning
af95de9cbe841126a3f8d3ba774683cf20d223b3
[ "BSD-3-Clause", "BSD-2-Clause", "Apache-2.0" ]
50
2021-11-02T19:13:09.000Z
2022-03-28T14:24:30.000Z
tesseract_process_managers/src/utils/task_info_statistics.cpp
tesseract-robotics/tesseract_planning
af95de9cbe841126a3f8d3ba774683cf20d223b3
[ "BSD-3-Clause", "BSD-2-Clause", "Apache-2.0" ]
5
2021-11-01T13:59:51.000Z
2022-03-25T08:06:01.000Z
/** * @file task_info_utils.cpp * @brief Task Info Utils * * @author Matthew Powelson * @date June 22. 2021 * @version TODO * @bug No known bugs * * @par License * Software License Agreement (Apache License) * @par * 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 * @par * 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 <tesseract_common/macros.h> TESSERACT_COMMON_IGNORE_WARNINGS_PUSH #include <boost/serialization/vector.hpp> TESSERACT_COMMON_IGNORE_WARNINGS_POP #include <tesseract_common/serialization.h> #include <tesseract_process_managers/utils/task_info_statistics.h> using namespace tesseract_planning; void TaskInfoStatistics::insert(const std::vector<TaskInfo>& task_info_vec) { if (task_info_vec.empty()) return; if (task_name.empty() && occurances == 0) task_name = task_info_vec.front().task_name; for (const TaskInfo& task_info : task_info_vec) { if (task_name != task_info.task_name) CONSOLE_BRIDGE_logError("Incorrect TaskInfo passed into TaskInfoStatistics"); // Calculate statistics min_time = std::min(min_time, task_info.elapsed_time); max_time = std::max(max_time, task_info.elapsed_time); const double old_sum = avg_time * static_cast<double>(occurances); occurances++; avg_time = (old_sum + task_info.elapsed_time) / static_cast<double>(occurances); return_val_map[task_info.return_value] += 1; } } void TaskInfoProfiler::load(const tesseract_common::fs::path& directory) { // Each file will contain the TaskInfos for a planning run std::vector<std::vector<TaskInfo>> task_info_vecs; for (auto& entry : boost::make_iterator_range(tesseract_common::fs::directory_iterator(directory), {})) { const std::string filepath = entry.path().string(); try { auto task_info = tesseract_common::Serialization::fromArchiveFileXML<std::vector<TaskInfo>>(filepath); task_info_vecs.push_back(task_info); } catch (const std::exception& e) { tesseract_common::printNestedException(e); } } load(task_info_vecs); } void TaskInfoProfiler::load(const std::vector<std::vector<TaskInfo>>& task_info_vecs) { // Sort into map by task names std::unordered_map<std::string, std::vector<TaskInfo>> sorted_infos = sortTaskInfosByTaskName(task_info_vecs); // Loop over TaskNames and insert into the TaskInfoStatistics for (const auto& kv : sorted_infos) { stats_map[kv.first].insert(kv.second); } } void TaskInfoProfiler::load(const std::map<std::size_t, TaskInfo::UPtr>& task_info_map) { for (const auto& kv : task_info_map) { stats_map[kv.second->task_name].insert({ *kv.second }); } } void TaskInfoProfiler::clear() { stats_map.clear(); } void TaskInfoProfiler::print(std::ostream& os) const { using std::setw; const std::vector<std::string> column_names = { "Task Name", "Occurrences", "Min Time (s)", "Max Time (s)", "Avg Time (s)", "Return values", "Return value %" }; const int column_width = 20; // Print column headers os << "|"; for (const std::string& column_name : column_names) { // Make the name column extra long if (column_name == "Task Name") os << setw(column_width * 2) << column_name; else os << setw(column_width) << column_name; os << "|"; } os << "\n|" << std::string((column_names.size() + 1) * (column_width + 1) - 2, '-') << "| \n"; // Print statistics for (const auto& kv : stats_map) { os << "|"; // Name os << setw(column_width * 2) << kv.first.substr(0, column_width * 2) << "|"; // Occurrences os << setw(column_width) << kv.second.occurances << "|"; // Time os << setw(column_width) << kv.second.min_time << "|" << setw(column_width) << kv.second.max_time << "|" << setw(column_width) << kv.second.avg_time << "|"; // Return value std::string ret_val_str; std::string ret_val_perc_str; for (const auto& ret_kv : kv.second.return_val_map) { ret_val_str += std::to_string(ret_kv.first) + ", "; double ret_val_percent = static_cast<double>(ret_kv.second) / static_cast<double>(kv.second.occurances) * 100.; ret_val_perc_str += std::to_string(ret_val_percent).substr(0, 5) + ", "; } os << setw(column_width) << ret_val_str << "|" << setw(column_width) << ret_val_perc_str << "|"; os << "\n"; } } std::unordered_map<std::string, TaskDisplayInfo> TaskInfoProfiler::getTaskDisplayInfo() { std::unordered_map<std::string, TaskDisplayInfo> task_info_map; // Calculate and print statistics for (const auto& kv : stats_map) { if (kv.second.occurances == 0) continue; // Task Info task_info_map[kv.first].task_info = "Avg time: " + std::to_string(kv.second.avg_time).substr(0, 5) + "s"; // Edge info for (const auto& ret_kv : kv.second.return_val_map) { double percent = static_cast<double>(ret_kv.second) / static_cast<double>(kv.second.occurances) * 100.; task_info_map[kv.first].edge_info[ret_kv.first] = std::to_string(percent).substr(0, 5) + "%"; } } return task_info_map; }
32.823529
117
0.677419
[ "vector" ]
2822003986b73ca8a05f098b65598cd182bfbdf7
1,005
cpp
C++
ICPC/Regional2022/F.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
ICPC/Regional2022/F.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
ICPC/Regional2022/F.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define endl "\n" using namespace std; #define loop(i, a, b) for(int i = a; i <b; ++i) const int maxN = 3*1e5 + 5; int n, arre[maxN]; vector<int> adj[maxN]; bool visited[maxN]; char resp[maxN]; void dfsB(int u, int fa){ visited[u] = true; resp[u] = 'B'; for(int h : adj[u]){ if(visited[h]|| h == n) continue; dfsB(h, u); } } void dfsA(int u, int fa){ visited[u] = true; resp[u] = 'A'; for(int h : adj[u]){ if(visited[h]) continue; dfsA(h, u); } } void solve(){ int m; cin>>n>>m; int a,b ; loop(i, 0, m){ cin>>a>>b; adj[a].push_back(b); adj[b].push_back(a); } dfsB(n-1, 0); dfsA(n, 0); loop(i, 1, n+1) cout<<resp[i]; cout<<endl; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); if(fopen("case.txt", "r")) freopen("case.txt", "r", stdin); int t = 1; //cin>>t; loop(i, 0, t){ solve(); } return 0; }
16.47541
63
0.481592
[ "vector" ]
282757cd9b165dfa7eb61be9287f97c4474c6402
47,716
cpp
C++
SampleProject/Builds/Il2CppOutputProject/Source/il2cppOutput/Il2CppGenericComDefinitions9.cpp
frenchmajorcsminor/MapsSDK-Unity
0b3c0713d63279bd9fa62837fa7559d7f3cbd439
[ "MIT" ]
null
null
null
SampleProject/Builds/Il2CppOutputProject/Source/il2cppOutput/Il2CppGenericComDefinitions9.cpp
frenchmajorcsminor/MapsSDK-Unity
0b3c0713d63279bd9fa62837fa7559d7f3cbd439
[ "MIT" ]
null
null
null
SampleProject/Builds/Il2CppOutputProject/Source/il2cppOutput/Il2CppGenericComDefinitions9.cpp
frenchmajorcsminor/MapsSDK-Unity
0b3c0713d63279bd9fa62837fa7559d7f3cbd439
[ "MIT" ]
null
null
null
#include "pch-cpp.hpp" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <limits> // Windows.Foundation.IAsyncOperation`1<Windows.Devices.Geolocation.GeolocationAccessStatus> struct IAsyncOperation_1_t983C1FADD56063AA63BF0F974502D17BF40B25CB; // Windows.Foundation.IAsyncOperation`1<Windows.Devices.Geolocation.Geoposition> struct IAsyncOperation_1_tF9BEEC9FD6489F963576EC8A23FE4CD2D7CC166D; // Windows.Foundation.IAsyncOperation`1<Windows.Perception.People.HandMeshObserver> struct IAsyncOperation_1_t0874BF21C52B1A21763C1277695B2A724D9E4F56; // Windows.Foundation.IAsyncOperation`1<Windows.Storage.Streams.IBuffer> struct IAsyncOperation_1_t7BC0C2EC9F472CCFAA748C4A0487D3F7BE568542; // Windows.Foundation.IAsyncOperation`1<Windows.Storage.Streams.IRandomAccessStreamWithContentType> struct IAsyncOperation_1_tF4C439C2CDF5077E54DFEA6B03E7B4D3785DFB69; // Windows.Foundation.IAsyncOperation`1<System.Object> struct IAsyncOperation_1_tE95B7CD98CE930F006BBD07D7BB5109224B1BFFC; // Windows.Foundation.IAsyncOperation`1<Windows.Media.SpeechSynthesis.SpeechSynthesisStream> struct IAsyncOperation_1_t3E5E0E44D9FA75713CF0BF6622C9059660699044; // Windows.Foundation.IAsyncOperation`1<Windows.Storage.StorageFile> struct IAsyncOperation_1_t4DF8D93870801CBDF1404B858B231D7BD74E042E; // Windows.Foundation.IAsyncOperation`1<System.UInt32> struct IAsyncOperation_1_tDF3123F2E9343D6DBBFE6A5D008A395E62CE246A; // System.Char[] struct CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34; // System.Delegate[] struct DelegateU5BU5D_t677D8FE08A5F99E8EE49150B73966CD6E9BF7DB8; // System.DelegateData struct DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288; // System.Reflection.MethodInfo struct MethodInfo_t; // System.String struct String_t; // System.Void struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5; struct Delegate_t_marshaled_com; struct Delegate_t_marshaled_pinvoke; struct IAsyncOperationCompletedHandler_1_t328808A8D9489316F5F1EF92341677DA0C501125_ComCallableWrapper; struct IAsyncOperationCompletedHandler_1_t50A8267D0DBE1135A9F535DCB4D7BB3B34AFC49F_ComCallableWrapper; struct IAsyncOperationCompletedHandler_1_t5827CD05C17566D3B54709AE10684C908E69902A_ComCallableWrapper; struct IAsyncOperationCompletedHandler_1_t64C3960950122A6E6F672D32D1A0CB7E6BAFA061_ComCallableWrapper; struct IAsyncOperationCompletedHandler_1_t724E59A84CDD5D96D15EAFD97BEFEBDB721F190D_ComCallableWrapper; struct IAsyncOperationCompletedHandler_1_t9941802FAFCAEA5AFAF80CD47D7361C7AF9973FB_ComCallableWrapper; struct IAsyncOperationCompletedHandler_1_tBCC0665255E588FBCD19564784FB229A445C8FD7_ComCallableWrapper; struct IAsyncOperationCompletedHandler_1_tF454F1E4B28A15E6AC9801C8A1708668213E16BE_ComCallableWrapper; struct IAsyncOperationCompletedHandler_1_tFFC79BA1F00AF8AF192CB11D7A8381654658E1B4_ComCallableWrapper; struct IAsyncOperation_1_t0874BF21C52B1A21763C1277695B2A724D9E4F56; struct IAsyncOperation_1_t3E5E0E44D9FA75713CF0BF6622C9059660699044; struct IAsyncOperation_1_t4DF8D93870801CBDF1404B858B231D7BD74E042E; struct IAsyncOperation_1_t7BC0C2EC9F472CCFAA748C4A0487D3F7BE568542; struct IAsyncOperation_1_t983C1FADD56063AA63BF0F974502D17BF40B25CB; struct IAsyncOperation_1_tDF3123F2E9343D6DBBFE6A5D008A395E62CE246A; struct IAsyncOperation_1_tE95B7CD98CE930F006BBD07D7BB5109224B1BFFC; struct IAsyncOperation_1_tF4C439C2CDF5077E54DFEA6B03E7B4D3785DFB69; struct IAsyncOperation_1_tF9BEEC9FD6489F963576EC8A23FE4CD2D7CC166D; struct IBuffer_t33ECA22EB7DDA1EF333215FF8109DC736AF11FBC; struct IGeoposition_t07DE01962DB1F4A51A9469F39BE260F5556C88AF; struct IHandMeshObserver_tA497D8D462D45DC786DB2F94B0417A99F847F9BC; struct IRandomAccessStreamWithContentType_t1A0E3C6A5101EFCA76339E14C24FE9832E43324E; struct ISpeechSynthesisStream_tFA8C7E1F51E829B22F715363FDDD74892B9DFF40; struct IStorageFile_t826BC1B02A924A68B9C973131C3B1A8C02B1C6B8; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Windows.Foundation.IAsyncOperation`1<Windows.Devices.Geolocation.Geoposition> struct NOVTABLE IAsyncOperation_1_tF9BEEC9FD6489F963576EC8A23FE4CD2D7CC166D : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_put_Completed_m28EE7298FCD81461F934F1121B78AC78A92D5FBC(IAsyncOperationCompletedHandler_1_t50A8267D0DBE1135A9F535DCB4D7BB3B34AFC49F_ComCallableWrapper* ___handler0) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_get_Completed_m2B95F4D57DB93E3DC613E4ABA13F3953265A4625(IAsyncOperationCompletedHandler_1_t50A8267D0DBE1135A9F535DCB4D7BB3B34AFC49F_ComCallableWrapper** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_GetResults_m8AD5EE5F5EC810BE6D297CCE30E4034C2FD49672(IGeoposition_t07DE01962DB1F4A51A9469F39BE260F5556C88AF** comReturnValue) = 0; }; // Windows.Foundation.IAsyncOperation`1<Windows.Perception.People.HandMeshObserver> struct NOVTABLE IAsyncOperation_1_t0874BF21C52B1A21763C1277695B2A724D9E4F56 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_put_Completed_mDA59D6F156299EB4DEAE15EF336162510C2C66D2(IAsyncOperationCompletedHandler_1_t9941802FAFCAEA5AFAF80CD47D7361C7AF9973FB_ComCallableWrapper* ___handler0) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_get_Completed_m87D10B3592C176980FB3334BA160D0A8F0D497AF(IAsyncOperationCompletedHandler_1_t9941802FAFCAEA5AFAF80CD47D7361C7AF9973FB_ComCallableWrapper** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_GetResults_m9F8155B9E4016EE9EDA3702AC225E58827E50954(IHandMeshObserver_tA497D8D462D45DC786DB2F94B0417A99F847F9BC** comReturnValue) = 0; }; // Windows.Foundation.IAsyncOperation`1<Windows.Storage.Streams.IBuffer> struct NOVTABLE IAsyncOperation_1_t7BC0C2EC9F472CCFAA748C4A0487D3F7BE568542 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_put_Completed_m636C0ED780C29F9308810FE929CA212D97320EEC(IAsyncOperationCompletedHandler_1_t5827CD05C17566D3B54709AE10684C908E69902A_ComCallableWrapper* ___handler0) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_get_Completed_mC26D339653FCAF503A9CDE46865002AF5F59E43B(IAsyncOperationCompletedHandler_1_t5827CD05C17566D3B54709AE10684C908E69902A_ComCallableWrapper** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_GetResults_m76919B4691E63BD26224C1E0CA35EFC12D402B86(IBuffer_t33ECA22EB7DDA1EF333215FF8109DC736AF11FBC** comReturnValue) = 0; }; // Windows.Foundation.IAsyncOperation`1<Windows.Storage.Streams.IRandomAccessStreamWithContentType> struct NOVTABLE IAsyncOperation_1_tF4C439C2CDF5077E54DFEA6B03E7B4D3785DFB69 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_put_Completed_m7373A22163C85062B4E7CB4799145DA42CDB58C8(IAsyncOperationCompletedHandler_1_tFFC79BA1F00AF8AF192CB11D7A8381654658E1B4_ComCallableWrapper* ___handler0) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_get_Completed_mE284B394E3CF92BFA421B0C4F259545E384E89AB(IAsyncOperationCompletedHandler_1_tFFC79BA1F00AF8AF192CB11D7A8381654658E1B4_ComCallableWrapper** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_GetResults_mE9148F0A4AE311A33EFF7F958FC377E0AB7ADFCA(IRandomAccessStreamWithContentType_t1A0E3C6A5101EFCA76339E14C24FE9832E43324E** comReturnValue) = 0; }; // Windows.Foundation.IAsyncOperation`1<System.Object> struct NOVTABLE IAsyncOperation_1_tE95B7CD98CE930F006BBD07D7BB5109224B1BFFC : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_put_Completed_mD5886CE3E4920A01936A06BA1915CF30037129CB(IAsyncOperationCompletedHandler_1_t724E59A84CDD5D96D15EAFD97BEFEBDB721F190D_ComCallableWrapper* ___handler0) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_get_Completed_m9DF4E847B615A86C716939BC2C5FE61C8E517348(IAsyncOperationCompletedHandler_1_t724E59A84CDD5D96D15EAFD97BEFEBDB721F190D_ComCallableWrapper** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_GetResults_mD27969D80A6AA31B8C41D824318BA5044197404F(Il2CppIInspectable** comReturnValue) = 0; }; // Windows.Foundation.IAsyncOperation`1<Windows.Media.SpeechSynthesis.SpeechSynthesisStream> struct NOVTABLE IAsyncOperation_1_t3E5E0E44D9FA75713CF0BF6622C9059660699044 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_put_Completed_m6EEDEF55FBB339809F0A37C221B14CD560466329(IAsyncOperationCompletedHandler_1_t328808A8D9489316F5F1EF92341677DA0C501125_ComCallableWrapper* ___handler0) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_get_Completed_m8F318F58A249E654F7C48BB70641962B43B51BE7(IAsyncOperationCompletedHandler_1_t328808A8D9489316F5F1EF92341677DA0C501125_ComCallableWrapper** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_GetResults_m26719A728F871544E5A81D675AC0C3745DCD7053(ISpeechSynthesisStream_tFA8C7E1F51E829B22F715363FDDD74892B9DFF40** comReturnValue) = 0; }; // Windows.Foundation.IAsyncOperation`1<Windows.Storage.StorageFile> struct NOVTABLE IAsyncOperation_1_t4DF8D93870801CBDF1404B858B231D7BD74E042E : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_put_Completed_m108CBA2BE6D19F6A961970FF1AC3DE4761942818(IAsyncOperationCompletedHandler_1_t64C3960950122A6E6F672D32D1A0CB7E6BAFA061_ComCallableWrapper* ___handler0) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_get_Completed_m9773816D15B923B84BCE4CB70D52BBB55D61421B(IAsyncOperationCompletedHandler_1_t64C3960950122A6E6F672D32D1A0CB7E6BAFA061_ComCallableWrapper** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_GetResults_m8071D5CC72DC722A092D03B8725B40398F216758(IStorageFile_t826BC1B02A924A68B9C973131C3B1A8C02B1C6B8** comReturnValue) = 0; }; // Windows.Foundation.IAsyncOperation`1<System.UInt32> struct NOVTABLE IAsyncOperation_1_tDF3123F2E9343D6DBBFE6A5D008A395E62CE246A : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_put_Completed_mC7C94BF5E03D8C5AA20FF9BE77223E1ECE3B0BD4(IAsyncOperationCompletedHandler_1_tF454F1E4B28A15E6AC9801C8A1708668213E16BE_ComCallableWrapper* ___handler0) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_get_Completed_m27E355E8C0523DE3F33321676087FB75E057B44A(IAsyncOperationCompletedHandler_1_tF454F1E4B28A15E6AC9801C8A1708668213E16BE_ComCallableWrapper** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_GetResults_m28613513B6F3DE14AC503BC914AFF74AEC8E4CEC(uint32_t* comReturnValue) = 0; }; // System.Object // System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52 : public RuntimeObject { public: public: }; // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_com { }; // System.Enum struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA : public ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52 { public: public: }; struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields { public: // System.Char[] System.Enum::enumSeperatorCharArray CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* ___enumSeperatorCharArray_0; public: inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields, ___enumSeperatorCharArray_0)); } inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; } inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; } inline void set_enumSeperatorCharArray_0(CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* value) { ___enumSeperatorCharArray_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___enumSeperatorCharArray_0), (void*)value); } }; // Native definition for P/Invoke marshalling of System.Enum struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_com { }; // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; // System.Void struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5 { public: union { struct { }; uint8_t Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5__padding[1]; }; public: }; // Windows.Foundation.AsyncStatus struct AsyncStatus_t44B315E6BDEB08B67F7FC4D7963A1C6EFA1CDB27 { public: // System.Int32 Windows.Foundation.AsyncStatus::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(AsyncStatus_t44B315E6BDEB08B67F7FC4D7963A1C6EFA1CDB27, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // System.Delegate struct Delegate_t : public RuntimeObject { public: // System.IntPtr System.Delegate::method_ptr Il2CppMethodPointer ___method_ptr_0; // System.IntPtr System.Delegate::invoke_impl intptr_t ___invoke_impl_1; // System.Object System.Delegate::m_target RuntimeObject * ___m_target_2; // System.IntPtr System.Delegate::method intptr_t ___method_3; // System.IntPtr System.Delegate::delegate_trampoline intptr_t ___delegate_trampoline_4; // System.IntPtr System.Delegate::extra_arg intptr_t ___extra_arg_5; // System.IntPtr System.Delegate::method_code intptr_t ___method_code_6; // System.Reflection.MethodInfo System.Delegate::method_info MethodInfo_t * ___method_info_7; // System.Reflection.MethodInfo System.Delegate::original_method_info MethodInfo_t * ___original_method_info_8; // System.DelegateData System.Delegate::data DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 * ___data_9; // System.Boolean System.Delegate::method_is_virtual bool ___method_is_virtual_10; public: inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_ptr_0)); } inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; } inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; } inline void set_method_ptr_0(Il2CppMethodPointer value) { ___method_ptr_0 = value; } inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t, ___invoke_impl_1)); } inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; } inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; } inline void set_invoke_impl_1(intptr_t value) { ___invoke_impl_1 = value; } inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t, ___m_target_2)); } inline RuntimeObject * get_m_target_2() const { return ___m_target_2; } inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; } inline void set_m_target_2(RuntimeObject * value) { ___m_target_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_target_2), (void*)value); } inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_3)); } inline intptr_t get_method_3() const { return ___method_3; } inline intptr_t* get_address_of_method_3() { return &___method_3; } inline void set_method_3(intptr_t value) { ___method_3 = value; } inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t, ___delegate_trampoline_4)); } inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; } inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; } inline void set_delegate_trampoline_4(intptr_t value) { ___delegate_trampoline_4 = value; } inline static int32_t get_offset_of_extra_arg_5() { return static_cast<int32_t>(offsetof(Delegate_t, ___extra_arg_5)); } inline intptr_t get_extra_arg_5() const { return ___extra_arg_5; } inline intptr_t* get_address_of_extra_arg_5() { return &___extra_arg_5; } inline void set_extra_arg_5(intptr_t value) { ___extra_arg_5 = value; } inline static int32_t get_offset_of_method_code_6() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_code_6)); } inline intptr_t get_method_code_6() const { return ___method_code_6; } inline intptr_t* get_address_of_method_code_6() { return &___method_code_6; } inline void set_method_code_6(intptr_t value) { ___method_code_6 = value; } inline static int32_t get_offset_of_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_info_7)); } inline MethodInfo_t * get_method_info_7() const { return ___method_info_7; } inline MethodInfo_t ** get_address_of_method_info_7() { return &___method_info_7; } inline void set_method_info_7(MethodInfo_t * value) { ___method_info_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___method_info_7), (void*)value); } inline static int32_t get_offset_of_original_method_info_8() { return static_cast<int32_t>(offsetof(Delegate_t, ___original_method_info_8)); } inline MethodInfo_t * get_original_method_info_8() const { return ___original_method_info_8; } inline MethodInfo_t ** get_address_of_original_method_info_8() { return &___original_method_info_8; } inline void set_original_method_info_8(MethodInfo_t * value) { ___original_method_info_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___original_method_info_8), (void*)value); } inline static int32_t get_offset_of_data_9() { return static_cast<int32_t>(offsetof(Delegate_t, ___data_9)); } inline DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 * get_data_9() const { return ___data_9; } inline DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 ** get_address_of_data_9() { return &___data_9; } inline void set_data_9(DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 * value) { ___data_9 = value; Il2CppCodeGenWriteBarrier((void**)(&___data_9), (void*)value); } inline static int32_t get_offset_of_method_is_virtual_10() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_is_virtual_10)); } inline bool get_method_is_virtual_10() const { return ___method_is_virtual_10; } inline bool* get_address_of_method_is_virtual_10() { return &___method_is_virtual_10; } inline void set_method_is_virtual_10(bool value) { ___method_is_virtual_10 = value; } }; // Native definition for P/Invoke marshalling of System.Delegate struct Delegate_t_marshaled_pinvoke { intptr_t ___method_ptr_0; intptr_t ___invoke_impl_1; Il2CppIUnknown* ___m_target_2; intptr_t ___method_3; intptr_t ___delegate_trampoline_4; intptr_t ___extra_arg_5; intptr_t ___method_code_6; MethodInfo_t * ___method_info_7; MethodInfo_t * ___original_method_info_8; DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 * ___data_9; int32_t ___method_is_virtual_10; }; // Native definition for COM marshalling of System.Delegate struct Delegate_t_marshaled_com { intptr_t ___method_ptr_0; intptr_t ___invoke_impl_1; Il2CppIUnknown* ___m_target_2; intptr_t ___method_3; intptr_t ___delegate_trampoline_4; intptr_t ___extra_arg_5; intptr_t ___method_code_6; MethodInfo_t * ___method_info_7; MethodInfo_t * ___original_method_info_8; DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 * ___data_9; int32_t ___method_is_virtual_10; }; // Windows.Devices.Geolocation.GeolocationAccessStatus struct GeolocationAccessStatus_t398172213338F6FB868A52CB6821BDE44A34E3A7 { public: // System.Int32 Windows.Devices.Geolocation.GeolocationAccessStatus::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(GeolocationAccessStatus_t398172213338F6FB868A52CB6821BDE44A34E3A7, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // Windows.Foundation.IAsyncOperation`1<Windows.Devices.Geolocation.GeolocationAccessStatus> struct NOVTABLE IAsyncOperation_1_t983C1FADD56063AA63BF0F974502D17BF40B25CB : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_put_Completed_m51FE22DEDF53940A5D5E253070E62A0F76ACCCAB(IAsyncOperationCompletedHandler_1_tBCC0665255E588FBCD19564784FB229A445C8FD7_ComCallableWrapper* ___handler0) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_get_Completed_m62D3487FCD345F8919CAC335E0D1B37692827F8D(IAsyncOperationCompletedHandler_1_tBCC0665255E588FBCD19564784FB229A445C8FD7_ComCallableWrapper** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IAsyncOperation_1_GetResults_mED50D9F32702559AC834BE6D0438FC4C6B12BCD2(int32_t* comReturnValue) = 0; }; // System.MulticastDelegate struct MulticastDelegate_t : public Delegate_t { public: // System.Delegate[] System.MulticastDelegate::delegates DelegateU5BU5D_t677D8FE08A5F99E8EE49150B73966CD6E9BF7DB8* ___delegates_11; public: inline static int32_t get_offset_of_delegates_11() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___delegates_11)); } inline DelegateU5BU5D_t677D8FE08A5F99E8EE49150B73966CD6E9BF7DB8* get_delegates_11() const { return ___delegates_11; } inline DelegateU5BU5D_t677D8FE08A5F99E8EE49150B73966CD6E9BF7DB8** get_address_of_delegates_11() { return &___delegates_11; } inline void set_delegates_11(DelegateU5BU5D_t677D8FE08A5F99E8EE49150B73966CD6E9BF7DB8* value) { ___delegates_11 = value; Il2CppCodeGenWriteBarrier((void**)(&___delegates_11), (void*)value); } }; // Native definition for P/Invoke marshalling of System.MulticastDelegate struct MulticastDelegate_t_marshaled_pinvoke : public Delegate_t_marshaled_pinvoke { Delegate_t_marshaled_pinvoke** ___delegates_11; }; // Native definition for COM marshalling of System.MulticastDelegate struct MulticastDelegate_t_marshaled_com : public Delegate_t_marshaled_com { Delegate_t_marshaled_com** ___delegates_11; }; // Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Devices.Geolocation.GeolocationAccessStatus> struct AsyncOperationCompletedHandler_1_tBCC0665255E588FBCD19564784FB229A445C8FD7 : public MulticastDelegate_t { public: public: }; // COM Callable Wrapper interface definition for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Devices.Geolocation.GeolocationAccessStatus> struct IAsyncOperationCompletedHandler_1_tBCC0665255E588FBCD19564784FB229A445C8FD7_ComCallableWrapper : Il2CppIUnknown { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL Invoke(IAsyncOperation_1_t983C1FADD56063AA63BF0F974502D17BF40B25CB* ___asyncInfo0, int32_t ___asyncStatus1) = 0; }; // Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Devices.Geolocation.Geoposition> struct AsyncOperationCompletedHandler_1_t50A8267D0DBE1135A9F535DCB4D7BB3B34AFC49F : public MulticastDelegate_t { public: public: }; // COM Callable Wrapper interface definition for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Devices.Geolocation.Geoposition> struct IAsyncOperationCompletedHandler_1_t50A8267D0DBE1135A9F535DCB4D7BB3B34AFC49F_ComCallableWrapper : Il2CppIUnknown { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL Invoke(IAsyncOperation_1_tF9BEEC9FD6489F963576EC8A23FE4CD2D7CC166D* ___asyncInfo0, int32_t ___asyncStatus1) = 0; }; // Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Perception.People.HandMeshObserver> struct AsyncOperationCompletedHandler_1_t9941802FAFCAEA5AFAF80CD47D7361C7AF9973FB : public MulticastDelegate_t { public: public: }; // COM Callable Wrapper interface definition for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Perception.People.HandMeshObserver> struct IAsyncOperationCompletedHandler_1_t9941802FAFCAEA5AFAF80CD47D7361C7AF9973FB_ComCallableWrapper : Il2CppIUnknown { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL Invoke(IAsyncOperation_1_t0874BF21C52B1A21763C1277695B2A724D9E4F56* ___asyncInfo0, int32_t ___asyncStatus1) = 0; }; // Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Storage.Streams.IBuffer> struct AsyncOperationCompletedHandler_1_t5827CD05C17566D3B54709AE10684C908E69902A : public MulticastDelegate_t { public: public: }; // COM Callable Wrapper interface definition for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Storage.Streams.IBuffer> struct IAsyncOperationCompletedHandler_1_t5827CD05C17566D3B54709AE10684C908E69902A_ComCallableWrapper : Il2CppIUnknown { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL Invoke(IAsyncOperation_1_t7BC0C2EC9F472CCFAA748C4A0487D3F7BE568542* ___asyncInfo0, int32_t ___asyncStatus1) = 0; }; // Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Storage.Streams.IRandomAccessStreamWithContentType> struct AsyncOperationCompletedHandler_1_tFFC79BA1F00AF8AF192CB11D7A8381654658E1B4 : public MulticastDelegate_t { public: public: }; // COM Callable Wrapper interface definition for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Storage.Streams.IRandomAccessStreamWithContentType> struct IAsyncOperationCompletedHandler_1_tFFC79BA1F00AF8AF192CB11D7A8381654658E1B4_ComCallableWrapper : Il2CppIUnknown { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL Invoke(IAsyncOperation_1_tF4C439C2CDF5077E54DFEA6B03E7B4D3785DFB69* ___asyncInfo0, int32_t ___asyncStatus1) = 0; }; // Windows.Foundation.AsyncOperationCompletedHandler`1<System.Object> struct AsyncOperationCompletedHandler_1_t724E59A84CDD5D96D15EAFD97BEFEBDB721F190D : public MulticastDelegate_t { public: public: }; // COM Callable Wrapper interface definition for Windows.Foundation.AsyncOperationCompletedHandler`1<System.Object> struct IAsyncOperationCompletedHandler_1_t724E59A84CDD5D96D15EAFD97BEFEBDB721F190D_ComCallableWrapper : Il2CppIUnknown { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL Invoke(IAsyncOperation_1_tE95B7CD98CE930F006BBD07D7BB5109224B1BFFC* ___asyncInfo0, int32_t ___asyncStatus1) = 0; }; // Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Media.SpeechSynthesis.SpeechSynthesisStream> struct AsyncOperationCompletedHandler_1_t328808A8D9489316F5F1EF92341677DA0C501125 : public MulticastDelegate_t { public: public: }; // COM Callable Wrapper interface definition for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Media.SpeechSynthesis.SpeechSynthesisStream> struct IAsyncOperationCompletedHandler_1_t328808A8D9489316F5F1EF92341677DA0C501125_ComCallableWrapper : Il2CppIUnknown { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL Invoke(IAsyncOperation_1_t3E5E0E44D9FA75713CF0BF6622C9059660699044* ___asyncInfo0, int32_t ___asyncStatus1) = 0; }; // Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Storage.StorageFile> struct AsyncOperationCompletedHandler_1_t64C3960950122A6E6F672D32D1A0CB7E6BAFA061 : public MulticastDelegate_t { public: public: }; // COM Callable Wrapper interface definition for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Storage.StorageFile> struct IAsyncOperationCompletedHandler_1_t64C3960950122A6E6F672D32D1A0CB7E6BAFA061_ComCallableWrapper : Il2CppIUnknown { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL Invoke(IAsyncOperation_1_t4DF8D93870801CBDF1404B858B231D7BD74E042E* ___asyncInfo0, int32_t ___asyncStatus1) = 0; }; // Windows.Foundation.AsyncOperationCompletedHandler`1<System.UInt32> struct AsyncOperationCompletedHandler_1_tF454F1E4B28A15E6AC9801C8A1708668213E16BE : public MulticastDelegate_t { public: public: }; // COM Callable Wrapper interface definition for Windows.Foundation.AsyncOperationCompletedHandler`1<System.UInt32> struct IAsyncOperationCompletedHandler_1_tF454F1E4B28A15E6AC9801C8A1708668213E16BE_ComCallableWrapper : Il2CppIUnknown { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL Invoke(IAsyncOperation_1_tDF3123F2E9343D6DBBFE6A5D008A395E62CE246A* ___asyncInfo0, int32_t ___asyncStatus1) = 0; }; #ifdef __clang__ #pragma clang diagnostic pop #endif const Il2CppGuid IAsyncOperationCompletedHandler_1_tBCC0665255E588FBCD19564784FB229A445C8FD7_ComCallableWrapper::IID = { 0xf3524c93, 0xe5c7, 0x5b88, 0xbe, 0xdb, 0xd3, 0xe6, 0x37, 0xcf, 0xf2, 0x71 }; // Native invoker for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Devices.Geolocation.GeolocationAccessStatus> IL2CPP_EXTERN_C void AsyncOperationCompletedHandler_1_Invoke_m2EA47DE079A9A7ED56A2386FDC7720CA07E024F4_NativeInvoker (Il2CppComObject * __this, RuntimeObject* ___asyncInfo0, int32_t ___asyncStatus1, const RuntimeMethod* method) { IAsyncOperationCompletedHandler_1_tBCC0665255E588FBCD19564784FB229A445C8FD7_ComCallableWrapper* ____asyncOperationCompletedHandler_1_tBCC0665255E588FBCD19564784FB229A445C8FD7 = il2cpp_codegen_com_query_interface<IAsyncOperationCompletedHandler_1_tBCC0665255E588FBCD19564784FB229A445C8FD7_ComCallableWrapper>(static_cast<Il2CppComObject*>(__this)); // Marshaling of parameter '___asyncInfo0' to native representation IAsyncOperation_1_t983C1FADD56063AA63BF0F974502D17BF40B25CB* ____asyncInfo0_marshaled = NULL; if (___asyncInfo0 != NULL) { if (il2cpp_codegen_is_import_or_windows_runtime(___asyncInfo0)) { ____asyncInfo0_marshaled = il2cpp_codegen_com_query_interface<IAsyncOperation_1_t983C1FADD56063AA63BF0F974502D17BF40B25CB>(static_cast<Il2CppComObject*>(___asyncInfo0)); (____asyncInfo0_marshaled)->AddRef(); } else { ____asyncInfo0_marshaled = il2cpp_codegen_com_get_or_create_ccw<IAsyncOperation_1_t983C1FADD56063AA63BF0F974502D17BF40B25CB>(___asyncInfo0); } } else { ____asyncInfo0_marshaled = NULL; } // Native function invocation const il2cpp_hresult_t hr = ____asyncOperationCompletedHandler_1_tBCC0665255E588FBCD19564784FB229A445C8FD7->Invoke(____asyncInfo0_marshaled, ___asyncStatus1); il2cpp_codegen_com_raise_exception_if_failed(hr, false); // Marshaling cleanup of parameter '___asyncInfo0' native representation if (____asyncInfo0_marshaled != NULL) { (____asyncInfo0_marshaled)->Release(); ____asyncInfo0_marshaled = NULL; } } const Il2CppGuid IAsyncOperationCompletedHandler_1_t50A8267D0DBE1135A9F535DCB4D7BB3B34AFC49F_ComCallableWrapper::IID = { 0x7668a704, 0x244e, 0x5e12, 0x8d, 0xcb, 0x92, 0xa3, 0x29, 0x9e, 0xba, 0x26 }; // Native invoker for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Devices.Geolocation.Geoposition> IL2CPP_EXTERN_C void AsyncOperationCompletedHandler_1_Invoke_m0065C97E0CFF8752BF5A621F2F8D9134461E64D5_NativeInvoker (Il2CppComObject * __this, RuntimeObject* ___asyncInfo0, int32_t ___asyncStatus1, const RuntimeMethod* method) { IAsyncOperationCompletedHandler_1_t50A8267D0DBE1135A9F535DCB4D7BB3B34AFC49F_ComCallableWrapper* ____asyncOperationCompletedHandler_1_t50A8267D0DBE1135A9F535DCB4D7BB3B34AFC49F = il2cpp_codegen_com_query_interface<IAsyncOperationCompletedHandler_1_t50A8267D0DBE1135A9F535DCB4D7BB3B34AFC49F_ComCallableWrapper>(static_cast<Il2CppComObject*>(__this)); // Marshaling of parameter '___asyncInfo0' to native representation IAsyncOperation_1_tF9BEEC9FD6489F963576EC8A23FE4CD2D7CC166D* ____asyncInfo0_marshaled = NULL; if (___asyncInfo0 != NULL) { if (il2cpp_codegen_is_import_or_windows_runtime(___asyncInfo0)) { ____asyncInfo0_marshaled = il2cpp_codegen_com_query_interface<IAsyncOperation_1_tF9BEEC9FD6489F963576EC8A23FE4CD2D7CC166D>(static_cast<Il2CppComObject*>(___asyncInfo0)); (____asyncInfo0_marshaled)->AddRef(); } else { ____asyncInfo0_marshaled = il2cpp_codegen_com_get_or_create_ccw<IAsyncOperation_1_tF9BEEC9FD6489F963576EC8A23FE4CD2D7CC166D>(___asyncInfo0); } } else { ____asyncInfo0_marshaled = NULL; } // Native function invocation const il2cpp_hresult_t hr = ____asyncOperationCompletedHandler_1_t50A8267D0DBE1135A9F535DCB4D7BB3B34AFC49F->Invoke(____asyncInfo0_marshaled, ___asyncStatus1); il2cpp_codegen_com_raise_exception_if_failed(hr, false); // Marshaling cleanup of parameter '___asyncInfo0' native representation if (____asyncInfo0_marshaled != NULL) { (____asyncInfo0_marshaled)->Release(); ____asyncInfo0_marshaled = NULL; } } const Il2CppGuid IAsyncOperationCompletedHandler_1_t9941802FAFCAEA5AFAF80CD47D7361C7AF9973FB_ComCallableWrapper::IID = { 0x75e7a8a7, 0xb66d, 0x5e6b, 0xa0, 0x60, 0xee, 0xf7, 0x0, 0x2d, 0x9e, 0x62 }; // Native invoker for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Perception.People.HandMeshObserver> IL2CPP_EXTERN_C void AsyncOperationCompletedHandler_1_Invoke_m123B07E27A7EA48E9543A5673F4525B6CE9FAD21_NativeInvoker (Il2CppComObject * __this, RuntimeObject* ___asyncInfo0, int32_t ___asyncStatus1, const RuntimeMethod* method) { IAsyncOperationCompletedHandler_1_t9941802FAFCAEA5AFAF80CD47D7361C7AF9973FB_ComCallableWrapper* ____asyncOperationCompletedHandler_1_t9941802FAFCAEA5AFAF80CD47D7361C7AF9973FB = il2cpp_codegen_com_query_interface<IAsyncOperationCompletedHandler_1_t9941802FAFCAEA5AFAF80CD47D7361C7AF9973FB_ComCallableWrapper>(static_cast<Il2CppComObject*>(__this)); // Marshaling of parameter '___asyncInfo0' to native representation IAsyncOperation_1_t0874BF21C52B1A21763C1277695B2A724D9E4F56* ____asyncInfo0_marshaled = NULL; if (___asyncInfo0 != NULL) { if (il2cpp_codegen_is_import_or_windows_runtime(___asyncInfo0)) { ____asyncInfo0_marshaled = il2cpp_codegen_com_query_interface<IAsyncOperation_1_t0874BF21C52B1A21763C1277695B2A724D9E4F56>(static_cast<Il2CppComObject*>(___asyncInfo0)); (____asyncInfo0_marshaled)->AddRef(); } else { ____asyncInfo0_marshaled = il2cpp_codegen_com_get_or_create_ccw<IAsyncOperation_1_t0874BF21C52B1A21763C1277695B2A724D9E4F56>(___asyncInfo0); } } else { ____asyncInfo0_marshaled = NULL; } // Native function invocation const il2cpp_hresult_t hr = ____asyncOperationCompletedHandler_1_t9941802FAFCAEA5AFAF80CD47D7361C7AF9973FB->Invoke(____asyncInfo0_marshaled, ___asyncStatus1); il2cpp_codegen_com_raise_exception_if_failed(hr, false); // Marshaling cleanup of parameter '___asyncInfo0' native representation if (____asyncInfo0_marshaled != NULL) { (____asyncInfo0_marshaled)->Release(); ____asyncInfo0_marshaled = NULL; } } const Il2CppGuid IAsyncOperationCompletedHandler_1_t5827CD05C17566D3B54709AE10684C908E69902A_ComCallableWrapper::IID = { 0x51c3d2fd, 0xb8a1, 0x5620, 0xb7, 0x46, 0x7e, 0xe6, 0xd5, 0x33, 0xac, 0xa3 }; // Native invoker for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Storage.Streams.IBuffer> IL2CPP_EXTERN_C void AsyncOperationCompletedHandler_1_Invoke_m563FAAA70D97A1BED9C43795F25149F67FB5A88A_NativeInvoker (Il2CppComObject * __this, RuntimeObject* ___asyncInfo0, int32_t ___asyncStatus1, const RuntimeMethod* method) { IAsyncOperationCompletedHandler_1_t5827CD05C17566D3B54709AE10684C908E69902A_ComCallableWrapper* ____asyncOperationCompletedHandler_1_t5827CD05C17566D3B54709AE10684C908E69902A = il2cpp_codegen_com_query_interface<IAsyncOperationCompletedHandler_1_t5827CD05C17566D3B54709AE10684C908E69902A_ComCallableWrapper>(static_cast<Il2CppComObject*>(__this)); // Marshaling of parameter '___asyncInfo0' to native representation IAsyncOperation_1_t7BC0C2EC9F472CCFAA748C4A0487D3F7BE568542* ____asyncInfo0_marshaled = NULL; if (___asyncInfo0 != NULL) { if (il2cpp_codegen_is_import_or_windows_runtime(___asyncInfo0)) { ____asyncInfo0_marshaled = il2cpp_codegen_com_query_interface<IAsyncOperation_1_t7BC0C2EC9F472CCFAA748C4A0487D3F7BE568542>(static_cast<Il2CppComObject*>(___asyncInfo0)); (____asyncInfo0_marshaled)->AddRef(); } else { ____asyncInfo0_marshaled = il2cpp_codegen_com_get_or_create_ccw<IAsyncOperation_1_t7BC0C2EC9F472CCFAA748C4A0487D3F7BE568542>(___asyncInfo0); } } else { ____asyncInfo0_marshaled = NULL; } // Native function invocation const il2cpp_hresult_t hr = ____asyncOperationCompletedHandler_1_t5827CD05C17566D3B54709AE10684C908E69902A->Invoke(____asyncInfo0_marshaled, ___asyncStatus1); il2cpp_codegen_com_raise_exception_if_failed(hr, false); // Marshaling cleanup of parameter '___asyncInfo0' native representation if (____asyncInfo0_marshaled != NULL) { (____asyncInfo0_marshaled)->Release(); ____asyncInfo0_marshaled = NULL; } } const Il2CppGuid IAsyncOperationCompletedHandler_1_tFFC79BA1F00AF8AF192CB11D7A8381654658E1B4_ComCallableWrapper::IID = { 0x3dddecf4, 0x1d39, 0x58e8, 0x83, 0xb1, 0xdb, 0xed, 0x54, 0x1c, 0x7f, 0x35 }; // Native invoker for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Storage.Streams.IRandomAccessStreamWithContentType> IL2CPP_EXTERN_C void AsyncOperationCompletedHandler_1_Invoke_m5A7D02F556AA673CC6285691DBDB66636C0048E1_NativeInvoker (Il2CppComObject * __this, RuntimeObject* ___asyncInfo0, int32_t ___asyncStatus1, const RuntimeMethod* method) { IAsyncOperationCompletedHandler_1_tFFC79BA1F00AF8AF192CB11D7A8381654658E1B4_ComCallableWrapper* ____asyncOperationCompletedHandler_1_tFFC79BA1F00AF8AF192CB11D7A8381654658E1B4 = il2cpp_codegen_com_query_interface<IAsyncOperationCompletedHandler_1_tFFC79BA1F00AF8AF192CB11D7A8381654658E1B4_ComCallableWrapper>(static_cast<Il2CppComObject*>(__this)); // Marshaling of parameter '___asyncInfo0' to native representation IAsyncOperation_1_tF4C439C2CDF5077E54DFEA6B03E7B4D3785DFB69* ____asyncInfo0_marshaled = NULL; if (___asyncInfo0 != NULL) { if (il2cpp_codegen_is_import_or_windows_runtime(___asyncInfo0)) { ____asyncInfo0_marshaled = il2cpp_codegen_com_query_interface<IAsyncOperation_1_tF4C439C2CDF5077E54DFEA6B03E7B4D3785DFB69>(static_cast<Il2CppComObject*>(___asyncInfo0)); (____asyncInfo0_marshaled)->AddRef(); } else { ____asyncInfo0_marshaled = il2cpp_codegen_com_get_or_create_ccw<IAsyncOperation_1_tF4C439C2CDF5077E54DFEA6B03E7B4D3785DFB69>(___asyncInfo0); } } else { ____asyncInfo0_marshaled = NULL; } // Native function invocation const il2cpp_hresult_t hr = ____asyncOperationCompletedHandler_1_tFFC79BA1F00AF8AF192CB11D7A8381654658E1B4->Invoke(____asyncInfo0_marshaled, ___asyncStatus1); il2cpp_codegen_com_raise_exception_if_failed(hr, false); // Marshaling cleanup of parameter '___asyncInfo0' native representation if (____asyncInfo0_marshaled != NULL) { (____asyncInfo0_marshaled)->Release(); ____asyncInfo0_marshaled = NULL; } } const Il2CppGuid IAsyncOperationCompletedHandler_1_t724E59A84CDD5D96D15EAFD97BEFEBDB721F190D_ComCallableWrapper::IID = { 0x3f08262e, 0xa2e1, 0x5134, 0x92, 0x97, 0xe9, 0x21, 0x1f, 0x48, 0x1a, 0x2d }; // Native invoker for Windows.Foundation.AsyncOperationCompletedHandler`1<System.Object> IL2CPP_EXTERN_C void AsyncOperationCompletedHandler_1_Invoke_m6E5E207CF8B2D8B4C8E07778F76258F8BBBA8242_NativeInvoker (Il2CppComObject * __this, RuntimeObject* ___asyncInfo0, int32_t ___asyncStatus1, const RuntimeMethod* method) { IAsyncOperationCompletedHandler_1_t724E59A84CDD5D96D15EAFD97BEFEBDB721F190D_ComCallableWrapper* ____asyncOperationCompletedHandler_1_t724E59A84CDD5D96D15EAFD97BEFEBDB721F190D = il2cpp_codegen_com_query_interface<IAsyncOperationCompletedHandler_1_t724E59A84CDD5D96D15EAFD97BEFEBDB721F190D_ComCallableWrapper>(static_cast<Il2CppComObject*>(__this)); // Marshaling of parameter '___asyncInfo0' to native representation IAsyncOperation_1_tE95B7CD98CE930F006BBD07D7BB5109224B1BFFC* ____asyncInfo0_marshaled = NULL; if (___asyncInfo0 != NULL) { if (il2cpp_codegen_is_import_or_windows_runtime(___asyncInfo0)) { ____asyncInfo0_marshaled = il2cpp_codegen_com_query_interface<IAsyncOperation_1_tE95B7CD98CE930F006BBD07D7BB5109224B1BFFC>(static_cast<Il2CppComObject*>(___asyncInfo0)); (____asyncInfo0_marshaled)->AddRef(); } else { ____asyncInfo0_marshaled = il2cpp_codegen_com_get_or_create_ccw<IAsyncOperation_1_tE95B7CD98CE930F006BBD07D7BB5109224B1BFFC>(___asyncInfo0); } } else { ____asyncInfo0_marshaled = NULL; } // Native function invocation const il2cpp_hresult_t hr = ____asyncOperationCompletedHandler_1_t724E59A84CDD5D96D15EAFD97BEFEBDB721F190D->Invoke(____asyncInfo0_marshaled, ___asyncStatus1); il2cpp_codegen_com_raise_exception_if_failed(hr, false); // Marshaling cleanup of parameter '___asyncInfo0' native representation if (____asyncInfo0_marshaled != NULL) { (____asyncInfo0_marshaled)->Release(); ____asyncInfo0_marshaled = NULL; } } const Il2CppGuid IAsyncOperationCompletedHandler_1_t328808A8D9489316F5F1EF92341677DA0C501125_ComCallableWrapper::IID = { 0xc972b996, 0x6165, 0x50d4, 0xaf, 0x60, 0xa8, 0xc3, 0xdf, 0x51, 0xd0, 0x92 }; // Native invoker for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Media.SpeechSynthesis.SpeechSynthesisStream> IL2CPP_EXTERN_C void AsyncOperationCompletedHandler_1_Invoke_m594BBE478487BEB1B0FBD8DF96D3202AB85F1836_NativeInvoker (Il2CppComObject * __this, RuntimeObject* ___asyncInfo0, int32_t ___asyncStatus1, const RuntimeMethod* method) { IAsyncOperationCompletedHandler_1_t328808A8D9489316F5F1EF92341677DA0C501125_ComCallableWrapper* ____asyncOperationCompletedHandler_1_t328808A8D9489316F5F1EF92341677DA0C501125 = il2cpp_codegen_com_query_interface<IAsyncOperationCompletedHandler_1_t328808A8D9489316F5F1EF92341677DA0C501125_ComCallableWrapper>(static_cast<Il2CppComObject*>(__this)); // Marshaling of parameter '___asyncInfo0' to native representation IAsyncOperation_1_t3E5E0E44D9FA75713CF0BF6622C9059660699044* ____asyncInfo0_marshaled = NULL; if (___asyncInfo0 != NULL) { if (il2cpp_codegen_is_import_or_windows_runtime(___asyncInfo0)) { ____asyncInfo0_marshaled = il2cpp_codegen_com_query_interface<IAsyncOperation_1_t3E5E0E44D9FA75713CF0BF6622C9059660699044>(static_cast<Il2CppComObject*>(___asyncInfo0)); (____asyncInfo0_marshaled)->AddRef(); } else { ____asyncInfo0_marshaled = il2cpp_codegen_com_get_or_create_ccw<IAsyncOperation_1_t3E5E0E44D9FA75713CF0BF6622C9059660699044>(___asyncInfo0); } } else { ____asyncInfo0_marshaled = NULL; } // Native function invocation const il2cpp_hresult_t hr = ____asyncOperationCompletedHandler_1_t328808A8D9489316F5F1EF92341677DA0C501125->Invoke(____asyncInfo0_marshaled, ___asyncStatus1); il2cpp_codegen_com_raise_exception_if_failed(hr, false); // Marshaling cleanup of parameter '___asyncInfo0' native representation if (____asyncInfo0_marshaled != NULL) { (____asyncInfo0_marshaled)->Release(); ____asyncInfo0_marshaled = NULL; } } const Il2CppGuid IAsyncOperationCompletedHandler_1_t64C3960950122A6E6F672D32D1A0CB7E6BAFA061_ComCallableWrapper::IID = { 0xe521c894, 0x2c26, 0x5946, 0x9e, 0x61, 0x2b, 0x5e, 0x18, 0x8d, 0x1, 0xed }; // Native invoker for Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Storage.StorageFile> IL2CPP_EXTERN_C void AsyncOperationCompletedHandler_1_Invoke_m83B24403F3DD218240FAB1AFBA30634F2468AFEE_NativeInvoker (Il2CppComObject * __this, RuntimeObject* ___asyncInfo0, int32_t ___asyncStatus1, const RuntimeMethod* method) { IAsyncOperationCompletedHandler_1_t64C3960950122A6E6F672D32D1A0CB7E6BAFA061_ComCallableWrapper* ____asyncOperationCompletedHandler_1_t64C3960950122A6E6F672D32D1A0CB7E6BAFA061 = il2cpp_codegen_com_query_interface<IAsyncOperationCompletedHandler_1_t64C3960950122A6E6F672D32D1A0CB7E6BAFA061_ComCallableWrapper>(static_cast<Il2CppComObject*>(__this)); // Marshaling of parameter '___asyncInfo0' to native representation IAsyncOperation_1_t4DF8D93870801CBDF1404B858B231D7BD74E042E* ____asyncInfo0_marshaled = NULL; if (___asyncInfo0 != NULL) { if (il2cpp_codegen_is_import_or_windows_runtime(___asyncInfo0)) { ____asyncInfo0_marshaled = il2cpp_codegen_com_query_interface<IAsyncOperation_1_t4DF8D93870801CBDF1404B858B231D7BD74E042E>(static_cast<Il2CppComObject*>(___asyncInfo0)); (____asyncInfo0_marshaled)->AddRef(); } else { ____asyncInfo0_marshaled = il2cpp_codegen_com_get_or_create_ccw<IAsyncOperation_1_t4DF8D93870801CBDF1404B858B231D7BD74E042E>(___asyncInfo0); } } else { ____asyncInfo0_marshaled = NULL; } // Native function invocation const il2cpp_hresult_t hr = ____asyncOperationCompletedHandler_1_t64C3960950122A6E6F672D32D1A0CB7E6BAFA061->Invoke(____asyncInfo0_marshaled, ___asyncStatus1); il2cpp_codegen_com_raise_exception_if_failed(hr, false); // Marshaling cleanup of parameter '___asyncInfo0' native representation if (____asyncInfo0_marshaled != NULL) { (____asyncInfo0_marshaled)->Release(); ____asyncInfo0_marshaled = NULL; } } const Il2CppGuid IAsyncOperationCompletedHandler_1_tF454F1E4B28A15E6AC9801C8A1708668213E16BE_ComCallableWrapper::IID = { 0x9343b6e7, 0xe3d2, 0x5e4a, 0xab, 0x2d, 0x2b, 0xce, 0x49, 0x19, 0xa6, 0xa4 }; // Native invoker for Windows.Foundation.AsyncOperationCompletedHandler`1<System.UInt32> IL2CPP_EXTERN_C void AsyncOperationCompletedHandler_1_Invoke_m7ADFDF924B9ED1DEE270E030BB6FF916F47C2245_NativeInvoker (Il2CppComObject * __this, RuntimeObject* ___asyncInfo0, int32_t ___asyncStatus1, const RuntimeMethod* method) { IAsyncOperationCompletedHandler_1_tF454F1E4B28A15E6AC9801C8A1708668213E16BE_ComCallableWrapper* ____asyncOperationCompletedHandler_1_tF454F1E4B28A15E6AC9801C8A1708668213E16BE = il2cpp_codegen_com_query_interface<IAsyncOperationCompletedHandler_1_tF454F1E4B28A15E6AC9801C8A1708668213E16BE_ComCallableWrapper>(static_cast<Il2CppComObject*>(__this)); // Marshaling of parameter '___asyncInfo0' to native representation IAsyncOperation_1_tDF3123F2E9343D6DBBFE6A5D008A395E62CE246A* ____asyncInfo0_marshaled = NULL; if (___asyncInfo0 != NULL) { if (il2cpp_codegen_is_import_or_windows_runtime(___asyncInfo0)) { ____asyncInfo0_marshaled = il2cpp_codegen_com_query_interface<IAsyncOperation_1_tDF3123F2E9343D6DBBFE6A5D008A395E62CE246A>(static_cast<Il2CppComObject*>(___asyncInfo0)); (____asyncInfo0_marshaled)->AddRef(); } else { ____asyncInfo0_marshaled = il2cpp_codegen_com_get_or_create_ccw<IAsyncOperation_1_tDF3123F2E9343D6DBBFE6A5D008A395E62CE246A>(___asyncInfo0); } } else { ____asyncInfo0_marshaled = NULL; } // Native function invocation const il2cpp_hresult_t hr = ____asyncOperationCompletedHandler_1_tF454F1E4B28A15E6AC9801C8A1708668213E16BE->Invoke(____asyncInfo0_marshaled, ___asyncStatus1); il2cpp_codegen_com_raise_exception_if_failed(hr, false); // Marshaling cleanup of parameter '___asyncInfo0' native representation if (____asyncInfo0_marshaled != NULL) { (____asyncInfo0_marshaled)->Release(); ____asyncInfo0_marshaled = NULL; } }
49.344364
348
0.865622
[ "object" ]
282ed1209367bf1f88a156945430fee079a1f83f
1,863
cc
C++
src/service2/test-service.cc
entn-at/ASR-decoder
a679ffb20081581897e1783734ac609adfbc332d
[ "MIT" ]
15
2017-12-14T08:23:50.000Z
2022-03-28T06:37:30.000Z
src/service2/test-service.cc
entn-at/ASR-decoder
a679ffb20081581897e1783734ac609adfbc332d
[ "MIT" ]
3
2019-07-08T05:38:14.000Z
2020-09-25T05:29:14.000Z
src/service2/test-service.cc
entn-at/ASR-decoder
a679ffb20081581897e1783734ac609adfbc332d
[ "MIT" ]
12
2018-03-28T02:15:47.000Z
2022-03-28T07:03:35.000Z
#include <iostream> #include <stdlib.h> #include <netinet/in.h> #include <sys/socket.h> #include <netinet/tcp.h> #include <unistd.h> #include <error.h> #include <netdb.h> #include <sys/types.h> #include <arpa/inet.h> #include <string.h> #include <pthread.h> #include <assert.h> #include <vector> #include "src/service2/thread-pool.h" #include "src/service2/test-work-thread.h" #include "src/service2/test-task.h" #include "src/util/log-message.h" #include "src/service2/socket-class.h" #include "src/service2/pthread-util.h" using namespace std; #ifdef NAMESPACE using namespace datemoon; #endif int main(int argc, char *argv[]) { ThreadSigPipeIng(); const char *usage = "This is a test service code.\n"; ConfigParseOptions conf(usage); SocketConf net_conf; net_conf.Register(&conf); conf.Read(argc, argv); //conf.PrintUsage(); SocketBase net_io(&net_conf); if(net_io.Init() < 0) { LOG_ERR << "net_io.Init failed!!!"; return -1; } if (0 != net_io.Bind()) { LOG_ERR << "net_io.Bind failed !!!"; return -1; } if ( 0 != net_io.Listen()) { LOG_ERR << "net_io.Listen failed!!!"; return -1; } int nthread = 3; ThreadPoolBase<ThreadBase> pool(nthread); { // create thread vector<ThreadBase*> tmp_threads; for(int i =0;i<nthread;++i) { TestWorkThread *asr_t = new TestWorkThread(&pool); tmp_threads.push_back(asr_t); } pool.Init(tmp_threads); } LOG_COM << "init thread pool ok"; while(1) { int connectfd = net_io.Accept(); if(connectfd < 0) { if(connectfd == -2) { printf("."); fflush(stdout); //printf("no cli connect requst %d %d %d %d.\n", connectfd,errno,EINPROGRESS,EAGAIN); } else printf("cli connect error.\n"); } else { printf("connect %d.\n",connectfd); TestServiceTask *ta = new TestServiceTask(connectfd); pool.AddTask(ta); } } return 0; }
19.010204
89
0.658615
[ "vector" ]
283382426d212af22c69e1e7d9bfbe2b2d339d62
1,525
cpp
C++
multiview/multiview_cpp/src/perceive/cost-functions/tracklets/tracks-index.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
5
2021-09-03T23:12:08.000Z
2022-03-04T21:43:32.000Z
multiview/multiview_cpp/src/perceive/cost-functions/tracklets/tracks-index.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
3
2021-09-08T02:57:46.000Z
2022-02-26T05:33:02.000Z
multiview/multiview_cpp/src/perceive/cost-functions/tracklets/tracks-index.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
2
2021-09-26T03:14:40.000Z
2022-01-26T06:42:52.000Z
#include "tracks-index.hpp" #define This TracksIndex namespace perceive { // ------------------------------------------------------------------------ init // void This::init(const vector<Track>& tracks) noexcept { // Get the maximum 't' value from a path of any track int max_t = -1; for(const auto& tt : tracks) for(const auto& tp : tt.path) if(max_t < tp.t) max_t = tp.t; data_.resize(size_t(max_t + 1)); for(auto i = 0u; i < tracks.size(); ++i) { const auto& tt = tracks[i]; for(auto j = 0u; j < tt.path.size(); ++j) { const int t = tt.path[j].t; Expects(t >= 0 and t <= max_t); Expects(unsigned(t) < data_.size()); FrameItem item; item.track_index = int(i); item.tp_index = int(j); data_[size_t(t)].push_back(item); } } } // ------------------------------------------------------------------------- get // std::pair<const Track*, const TrackPoint*> This::get(const vector<Track>& tracks, const FrameItem& frame_item) const noexcept { // (safely) load the track if(unsigned(frame_item.track_index) >= tracks.size()) return {nullptr, nullptr}; const auto tt_ptr = &tracks[size_t(frame_item.track_index)]; // (safely) load the track-point if(unsigned(frame_item.tp_index) >= tt_ptr->path.size()) return {nullptr, nullptr}; const auto tp_ptr = &tt_ptr->path[size_t(frame_item.tp_index)]; // We're done return {tt_ptr, tp_ptr}; } } // namespace perceive
27.727273
80
0.54623
[ "vector" ]
28351877d95ca4d637285bee93e8d3b566c86d58
30,923
hpp
C++
apps/dev/drawing.hpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
27
2020-08-17T17:25:59.000Z
2022-03-01T05:49:12.000Z
apps/dev/drawing.hpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
4
2020-08-26T13:54:59.000Z
2020-09-21T07:19:22.000Z
apps/dev/drawing.hpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
5
2020-08-26T23:26:48.000Z
2021-01-04T09:06:07.000Z
#ifndef POLYVEC_USE_POTRACE #define POLYVEC_USE_POTRACE #endif #include "common_includes.hpp" #include <polyvec/core/log.hpp> #include <polyvec/polygon-tracer/boundary-graph.hpp> #include <polyvec/core/types.hpp> #include <polyvec/curve-tracer/curve_bezier.hpp> #include <polyvec/geometry/smooth_curve.hpp> #include <polyvec/curve-tracer/spline.hpp> #include <polyvec/geometry/angle.hpp> #include <polyvec/geometry/path.hpp> #include <polyvec/misc.hpp> #include <polyvec/utils/matrix.hpp> #include <polyvec/core/log.hpp> #include <polyvec/polygon-tracer/error-metrics.hpp> #include <polyvec/io/pdf.hpp> #include <algorithm> #define RASTER_STYLE Style::fill ( colors::black ) #define BOUNDARY_STYLE Style::outline ( colors::gray, 5. ) #define PATH_STYLE Style::outline(colors::black, 1. ) #define TANGENT_STYLE Style::outline(colors::turtle_purple, .1 ) #define TANGENT_PROJECT_STYLE Style::outline(colors::turtle_purple, .05 ) #define CURVATURE_STYLE Style::outline(colors::calm_blue, 3. ) #define CURVATURE_STYLE_CLAMPED Style::outline(colors::royal_blue, 3. ) #define ERROR_MIN_COLOR colors::forest_green #define ERROR_MAX_COLOR colors::red #define ACCURACY_LEGEND_LEN 20 namespace polyvec { inline void draw_triplet ( const Eigen::Vector2d& p0, const Eigen::Vector2d& p1, const Eigen::Vector2d& p2, const real3& color, const double thickness ) { draw::point ( p0, thickness * 2, Style::fill ( colors::forest_green ) ); draw::point ( p1, thickness * 2, Style::fill ( colors::forest_green ) ); draw::point ( p2, thickness * 2, Style::fill ( colors::forest_green ) ); draw::line ( p0, p1, Style::outline ( color, thickness ) ); draw::line ( p1, p2, Style::outline ( color, thickness ) ); } inline void draw_curve_primitives_accuracy ( const Eigen::MatrixXd& B, const std::vector<polyfit::BoundaryGraph::Edge>& E, const std::vector<polyfit::Vertex>& VE, std::vector<CurvePrimitive>& primitives ) { using namespace polyfit; using namespace std; for ( int i = 0; i < primitives.size(); ++i ) { auto& c = primitives[i].curve; if ( primitives[i].corner == -1 ) { PF_ASSERT ( c->get_curve()->get_type() == GLOBFIT_CURVE_LINE ); draw::line ( c->get_curve()->pos ( 0. ), c->get_curve()->pos ( 1. ), Style::outline ( colors::forest_green, 1. ) ); continue; } double e_edge = E[VE[primitives[i].corner]].d_max; double e_curve = primitives[i].error.accuracy.max_error(); double e_max = .75; double delta = min ( e_max, abs ( e_curve - e_edge ) ); PF_LOGF ( "corner %d error-edge %f error-curve %f", primitives[i].corner, e_edge, e_curve ); vec3 color_min = colors::forest_green; vec3 color_max = colors::red; const string text = misc::sfmt ( "(%d) poly-d-max %.3f curve-d-max %.3f curve-d-acc %.3f", primitives[i].corner, e_edge, e_curve, primitives[i].error.accuracy ); vec3 color = misc::lerp ( color_min, color_max, delta / e_max ); draw::curve ( c->get_curve().get(), 5., color ); draw::text ( c->get_curve()->pos ( .35 ), text, draw::font_pdf / 3, Style::text() ); } } inline void draw_curve_primitives_curvature ( std::vector<CurvePrimitive>& prims ) { using namespace Eigen; const double min_curvature_radius = VectorOptions::get()->spline_fit_curvature_g0_thr; const double max_curvature_vis = 2.; for ( int i = 0; i < prims.size(); ++i ) { auto& curve = prims[i].curve; draw::curve ( curve->get_curve().get(), 5., colors::black ); if ( curve->get_curve()->get_type() == GLOBFIT_CURVE_LINE ) { continue; } const double t_step = .025; double t = t_step; double max_curvature_radius_vis = 10.; double k_min = INFINITY; double k_max = -INFINITY; while ( t < Curve::END + constants::Eps ) { t = misc::saturate ( t ); const Vector2d pos = curve->get_curve()->pos ( t ); Vector2d normal = curve->get_curve()->dposdt ( t ).normalized(); normal = Vector2d ( -normal.y(), normal.x() ); double k; SmoothCurveUtil::curvature_eval ( curve->get_curve()->dposdt ( t ), curve->get_curve()->dposdtdt ( t ), k ); k = std::min ( abs ( k ), max_curvature_radius_vis ); const double r = 1. / k; real3 color; if ( r < min_curvature_radius ) { color = colors::red; } else { color = misc::lerp ( ERROR_MAX_COLOR, ERROR_MIN_COLOR, r / max_curvature_vis ); } k_min = std::min ( r, k_min ); k_max = std::max ( r, k_max ); draw::line ( pos, pos + normal * std::min ( r, 5. ), Style::outline ( color, .75 ) ); t += t_step; } const str text = misc::sfmt ( "max %.3f min %.3f", k_max, k_min ); draw::text ( curve->get_curve()->pos ( .35 ), text, draw::font_pdf / 3, Style::text() ); } } inline void draw_curve_primitives_closed ( const std::vector<CurvePrimitive>& primitives, const Eigen::Vector4d& color) { std::vector<GlobFitCurve*> curves; for ( const CurvePrimitive& prim : primitives ) { curves.emplace_back ( prim.curve->get_curve().get() ); } draw::curves_fill ( curves, color ); } inline void draw_curve_primitives_closed(const std::vector<CurvePrimitive>& primitives, const Eigen::Vector3d& color = colors::black) { draw_curve_primitives_closed(primitives, Eigen::Vector4d(color(0), color(1), color(2), 1.0)); } inline void draw_pdf ( const str& uri, const std::function<void() >& fn ) { DevicePDF* pdf = new DevicePDF ( uri.c_str(), 1, 1 ); fn(); pdf->draw ( 0, 0 ); delete pdf; } inline void draw_curve_primitives_corner_error ( const Eigen::Matrix2Xd& P, const std::vector<CurvePrimitive>& C ) { using namespace polyfit; using namespace Eigen; const double max_error_accuracy = VectorOptions::get()->spline_fit_distance_point_g0_thr; ( void ) max_error_accuracy; const double min_curvature_radius = VectorOptions::get()->spline_fit_curvature_g0_thr; const double max_curvature_vis = 3.; for ( int i = 0; i < ( int ) C.size(); ++i ) { draw::curve ( C[i].curve->get_curve().get(), 1., i % 2 ? colors::forest_green : colors::talking_orange ); //draw::text(C[i].curve->pos(.5), std::to_string(i), draw::font_pdf, Style::text()); PF_LOGF ( "Curve %d corner %d", i, C[i].corner ); PF_LOGF ( "accuracy pos %f neg %f tot %f", C[i].error.accuracy.e_pos, C[i].error.accuracy.e_neg, C[i].error.accuracy ); if ( C[i].corner != -1 ) { int c = C[i].corner; vec2 pp = CircularAt ( P, c - 1 ); vec2 p = CircularAt ( P, c ); vec2 pn = CircularAt ( P, c + 1 ); //draw::line(p, p + misc::lerp(p, pp, .1), Style::outline(colors::red, 1.)); //draw::line(p, p + misc::lerp(p, pn, .1), Style::outline(colors::red, 1.)); double a = acos ( ( pp - p ).normalized().dot ( ( pn - p ).normalized() ) ); PF_LOGF ( "points %f %f %f %f %f %f", pp.x(), pp.y(), p.x(), p.y(), pn.x(), pn.y() ); PF_LOGF ( "angle %f / %f ", a, PF_RAD ( 135 ) ); if ( a < PF_RAD ( 135 ) ) { GlobFitCurve* curve = C[i].curve->get_curve().get(); const double t_step = .025; double t = t_step; double max_curvature_radius_vis = 10.; while ( t < Curve::END + constants::Eps ) { t = misc::saturate ( t ); const Vector2d pos = curve->pos ( t ); Vector2d normal = curve->dposdt ( t ).normalized(); normal = Vector2d ( -normal.y(), normal.x() ); double k; SmoothCurveUtil::curvature_eval ( curve->dposdt ( t ), curve->dposdtdt ( t ), k ); k = std::min ( abs ( k ), max_curvature_radius_vis ); const double r = 1. / k; real3 color; if ( r < min_curvature_radius ) { color = colors::red; } else { color = misc::lerp ( ERROR_MAX_COLOR, ERROR_MIN_COLOR, r / max_curvature_vis ); } draw::line ( pos, pos + normal * std::min ( r, 5. ), Style::outline ( color, .45 ) ); t += t_step; } } } draw::text ( C[i].curve->get_curve()->pos ( .5 ), misc::sfmt ( "accuracy pos %.3f neg %.3f", C[i].error.accuracy.e_pos, C[i].error.accuracy.e_neg ), draw::font_pdf / 2, Style::text() ); } } inline void draw_curve_indices ( const std::vector<CurvePrimitive>& primitives ) { for ( int i = 0; i < primitives.size(); ++i ) { const auto& c = primitives[i].curve.get(); draw::text ( ( c->get_curve()->pos ( 0. ) + c->get_curve()->pos ( 1. ) ) / 2, std::to_string ( i ), draw::font_pdf, Style::text() ); } } struct AlternatingColorFunctor { real3 operator() ( int primitiveId, const CurvePrimitive& prim ) { return primitiveId % 2 ? colors::forest_green : colors::talking_orange; } }; struct AlternatingCornerColorFunctor { real3 operator() ( int primitiveId, const CurvePrimitive& prim ) { return prim.corner % 2 ? colors::forest_green : colors::talking_orange; } }; struct ErrorHighlightFunctor { real3 operator() ( int primitiveId, const CurvePrimitive& prim ) { const double max_error_accuracy = VectorOptions::get()->spline_fit_distance_point_g0_thr; const double min_curvature_radius = VectorOptions::get()->spline_fit_curvature_g0_thr; bool accuracyValid = prim.error.accuracy.max_error() < max_error_accuracy; bool curvatureValid = prim.error.curvature.r_min > min_curvature_radius; if ( !accuracyValid && !curvatureValid ) { return colors::red; } else if ( !accuracyValid ) { return colors::fuchsia; } else if ( !curvatureValid ) { return colors::blue; } else { return colors::forest_green; } } }; struct TangentFitColorFunctor { const real3 colors[TANGENT_FIT_SAMPLES_COUNT] = { colors::forest_green, colors::talking_orange, colors::red }; const std::vector<TangentFitType>& tangent_fits; TangentFitColorFunctor(const std::vector<TangentFitType>& tangent_fits) : tangent_fits(tangent_fits) { } real3 operator() ( int primitiveId, const CurvePrimitive& prim ) { PF_ASSERT(prim.corner >= 0 && prim.corner < (int)tangent_fits.size()); return colors[(int)tangent_fits[prim.corner]]; } }; struct ConstantColorFunctor { const real3 color; ConstantColorFunctor(const real3 color) : color(color) { } real3 operator() (int primitiveId, const CurvePrimitive& prim) { return color; } }; struct PrimitiveTypeColorFunctor { PrimitiveTypeColorFunctor() { } real3 operator() (int primitiveId, const CurvePrimitive& prim) { switch (prim.curve->get_curve()->get_type()) { case GLOBFIT_CURVE_BEZIER: return real3(62.f/255, 106.f/255, 175.f/255); case GLOBFIT_CURVE_LINE: return real3(122.f/255, 181.f/255, 66.f/255); default: return colors::black; } } }; //TColorFunctor: real3(int primitiveId, const CurvePrimitive& prim) template <typename TColorFunctor> inline void draw_curve_primitives ( const std::vector<CurvePrimitive>& primitives, TColorFunctor&& color, bool visualize_parametrization = false) { using namespace Eigen; const double max_curvature_vis = 3.; for ( int i = 0; i < ( int ) primitives.size(); ++i ) { const auto& prim = primitives[i]; //draw::text(primitives[i].curve->get_curve()->pos(.5), std::to_string(i), draw::font_pdf, Style::text()); auto this_color = std::forward<TColorFunctor> ( color ) ( i, prim ); draw::curve ( primitives[i].curve->get_curve().get(), .2, this_color ); if (visualize_parametrization) { draw::point(prim.curve->get_curve()->pos(0.25), 0.4, Style::fill(colors::red)); draw::point(prim.curve->get_curve()->pos(0.50), 0.4, Style::fill(colors::red)); draw::point(prim.curve->get_curve()->pos(0.75), 0.4, Style::fill(colors::red)); } #if 0 // curvature GlobFitCurve* curve = primitives[i].curve.get(); const double t_step = .025; double t = t_step; double max_curvature_radius_vis = 10.; while ( t < Curve::END + constants::Eps ) { t = misc::saturate ( t ); const Vector2d pos = curve->pos ( t ); Vector2d normal = curve->dposdt ( t ).normalized(); normal = Vector2d ( -normal.y(), normal.x() ); double k; SmoothCurveUtil::curvature_eval ( curve->dposdt ( t ), curve->dposdtdt ( t ), k ); k = std::min ( abs ( k ), max_curvature_radius_vis ); const double r = 1. / k; real3 color; if ( r < min_curvature_radius ) { color = colors::red; } else { color = misc::lerp ( ERROR_MAX_COLOR, ERROR_MIN_COLOR, r / max_curvature_vis ); } draw::line ( pos, pos + normal * std::min ( r, 5. ), Style::outline ( color, .1 ) ); t += t_step; } #endif #if 0 // bezier control points if ( primitives[i].curve->get_type() == GLOBFIT_CURVE_BEZIER ) { auto c0 = primitives[i].curve->as_bezier()->get_bezier().get_control_points().col ( 0 ); auto c1 = primitives[i].curve->as_bezier()->get_bezier().get_control_points().col ( 1 ); auto c2 = primitives[i].curve->as_bezier()->get_bezier().get_control_points().col ( 2 ); auto c3 = primitives[i].curve->as_bezier()->get_bezier().get_control_points().col ( 3 ); draw::line ( c0, c1, Style::outline ( colors::talking_orange, .05 ) ); draw::line ( c1, c2, Style::outline ( colors::talking_orange, .05 ) ); draw::line ( c2, c3, Style::outline ( colors::talking_orange, .05 ) ); } #endif #if 0 // fitting data //if (prim.fit_midpoints && i == primitives.size() - 1) { if ( prim.fitting_info ) { for ( int j = 0; j < ( int ) prim.fitting_info->fit_midpoints.size(); ++j ) { draw::point ( prim.fitting_info->fit_midpoints.at ( j ), .1, Style::fill ( i % 2 ? colors::forest_green : colors::talking_orange ) ); } } //} if ( prim.fitting_info && ( i == ( int ) primitives.size() - 1 ) ) { for ( int j = 0; j < ( int ) prim.fitting_info->fit_tangents.size(); ++j ) { //if (prim.fit_tangent_points) { //draw::point(prim.fit_tangent_points->at(j), .02, Style::fill(colors::forest_green)); //} //draw::line(prim.fit_tangent_points->at(j), prim.fit_tangent_points->at(j) + prim.fit_tangents->at(j), Style::outline(colors::calm_blue, .1)); } } #endif } } inline void draw_sequence_error_tangents ( CurvePrimitiveSequence& seq ) { using namespace Eigen; for ( Index i = 0; i < ( Index ) seq.primitives.size(); ++i ) { CurvePrimitive& primitive = seq.primitives[i]; draw::curve ( primitive.curve->get_curve().get(), .1, i % 2 ? colors::forest_green : colors::talking_orange ); double max_tangent_error = 0.1; for ( Index j = 0; j < ( int ) primitive.fitting_info.dense_tangents.fit_tangents.size(); ++j ) { const Vector2d tangent_target = primitive.fitting_info.dense_tangents.fit_tangents.at ( j ); const double tangent_t = misc::saturate ( primitive.fit_tangents_t[j] ); Vector2d tangent_curve; SmoothCurveUtil::tangent_eval ( primitive.curve->get_curve()->dposdt ( tangent_t ), tangent_curve ); const Vector2d tangent_error = ( tangent_target - tangent_curve ).cwiseAbs(); //dbg::info(FMT("Tangent error %.5f %.5f", tangent_error.x(), tangent_error.y())); const Vector3d error_color = misc::lerp ( ERROR_MIN_COLOR, ERROR_MAX_COLOR, misc::saturate ( tangent_error.maxCoeff() / max_tangent_error ) ); const Vector2d curve_pt = primitive.curve->get_curve()->pos ( tangent_t ); Vector2d dir = tangent_target.normalized(); dir = Vector2d ( -dir.y(), dir.x() ); draw::line ( curve_pt, curve_pt + dir, Style::outline ( error_color, .01 ) ); } //draw::curve(primitive.curve.get(), .025, misc::lerp(ERROR_MIN_COLOR, ERROR_MAX_COLOR, error_t)); } } inline void draw_text ( int row, const str& text, const real3& color = colors::black ) { const double h = ( draw::font_pdf ) * 16; //draw::box ( { 0., 0., 128., 32. }, colors::black ); draw::text ( {5., h * row + 2.5 }, text, h, Style::text ( color ) ); } inline void draw_raster_closed ( const Eigen::Matrix2Xd& raster, const real4& color ) { std::vector<real2> points; for ( int i = 0; i < raster.cols(); ++i ) { points.emplace_back ( raster.col ( i ) ); } draw::polygon ( points, Style::fill ( color ) ); } inline void draw_raster_closed ( const Eigen::Matrix2Xd& raster, const real3& color = colors::black ) { std::vector<real2> points; for ( int i = 0; i < raster.cols(); ++i ) { points.emplace_back ( raster.col ( i ) ); } draw::polygon ( points, Style::fill ( color ) ); } inline void draw_raster_dashed(const Eigen::Matrix2Xd& raster, const real4& color) { for (int i = 0; i < raster.cols(); ++i) { // dbg::info(FMT("Point %f %f", raster.col(i), raster.col((i + 1) % raster.cols()))); draw::line(raster.col(i), raster.col((i + 1) % raster.cols()), Style::outline(color.segment(0, 3), 2., LineType::Dash)); } } inline void draw_raster ( const Eigen::Matrix2Xd& raster, const real4& color ) { for ( int i = 0; i < raster.cols(); ++i ) { // dbg::info(FMT("Point %f %f", raster.col(i), raster.col((i + 1) % raster.cols()))); draw::line ( raster.col ( i ), raster.col ( ( i + 1 ) % raster.cols() ), Style::outline ( color.segment ( 0, 3 ), 6. ) ); } } inline void draw_raster(const Eigen::Matrix2Xd& raster, const real3& color) { real4 color4; color4.segment(0, 3) = color; color4(3) = 1.0; draw_raster(raster, color4); } inline void draw_raster ( const Eigen::Matrix2Xd& raster, const Style& style = BOUNDARY_STYLE ) { draw::polyline(raster, style); } inline void draw_raster_background ( const Eigen::Matrix2Xd& raster, const Style& style, bool dots = true ) { Eigen::Vector2d min, max; min.setConstant ( std::numeric_limits<double>::infinity() ); max = -min; for ( int i = 0; i < raster.cols(); ++i ) { for ( int j = 0; j < 2; ++j ) { if ( raster.coeff ( j, i ) < min ( j ) ) { min ( j ) = raster.coeff ( j, i ); } if ( raster.coeff ( j, i ) > max ( j ) ) { max ( j ) = raster.coeff ( j, i ); } } } min.x() = std::floor ( min.x() + 0.5 - 1 ); min.y() = std::floor ( min.y() + 0.5 - 1 ); max.x() = std::ceil ( max.x() + 0.5 + 1 ); max.y() = std::ceil ( max.y() + 0.5 + 1 ); for ( int i = ( int ) min ( 0 ); i <= ( int ) max ( 0 ); ++i ) { draw::line ( Eigen::Vector2d ( ( double ) i - 0.5, min ( 1 ) - 0.5 ), Eigen::Vector2d ( ( double ) i - 0.5, max ( 1 ) - 0.5 ), style ); } for ( int i = ( int ) min ( 1 ); i <= ( int ) max ( 1 ); ++i ) { draw::line ( Eigen::Vector2d ( min ( 0 ) - 0.5, ( double ) i - 0.5 ), Eigen::Vector2d ( max ( 0 ) - 0.5, ( double ) i - 0.5 ), style ); } if(dots) for ( int i = min ( 0 ); i < max ( 0 ); ++i ) for ( int j = min ( 1 ); j < max ( 1 ); ++j ) { draw::point ( Eigen::Vector2d ( i, j ), 0.03, Style::fill ( style.line_color ) ); } } inline void draw_points ( const Eigen::Matrix2Xd& P ) { for ( int i = 0; i < P.cols(); ++i ) { draw::point ( P.col ( i ), 1., Style::fill ( colors::black ) ); } } inline void draw_raster_path ( const Eigen::Matrix2Xd& raster, const real3& color = colors::black, const double w = .5 ) { for ( int i = 0; i < raster.cols(); ++i ) { // dbg::info(FMT("Point %f %f", raster.col(i), raster.col((i + 1) % raster.cols()))); draw::line ( raster.col ( i ), raster.col ( ( i + 1 ) % raster.cols() ), Style::outline ( color, w ) ); } } inline void draw_accuracy_legend() { const double t_step = .01; double t = t_step; while ( t <= 1. + constants::Eps ) { real3 color = misc::lerp ( ERROR_MIN_COLOR, ERROR_MAX_COLOR, t ); real2 pos_prev = misc::lerp ( real2 ( 0., 0. ), real2 ( ACCURACY_LEGEND_LEN, 0. ), t - t_step ); real2 pos = misc::lerp ( real2 ( 0., 0. ), real2 ( ACCURACY_LEGEND_LEN, 0. ), t ); draw::line ( pos_prev, pos, Style::outline ( color, 1. ) ); t += t_step; } } inline void draw_curves_curvature ( const std::vector<CurvePrimitive>& curves ) { using namespace Eigen; for ( int i = 0; i < curves.size(); ++i ) { auto curve = curves[i].curve->get_curve(); const double t_step = .025; double t = t_step; double max_r = 20.; while ( t < Curve::END + constants::Eps ) { t = misc::saturate ( t ); const Vector2d pos = curve->pos ( t ); Vector2d normal = curve->dposdt ( t ).normalized(); normal = Vector2d ( -normal.y(), normal.x() ); double k; SmoothCurveUtil::curvature_eval ( curve->dposdt ( t ), curve->dposdtdt ( t ), k ); if(std::abs(k) >= PF_EPS) { bool clamped = false; double r = 0.2 * 1.0 / k; if (r < -max_r) { r = -max_r; clamped = true; } if (r > max_r) { r = max_r; clamped = true; } draw::line(pos, pos + normal * r, clamped ? CURVATURE_STYLE_CLAMPED : CURVATURE_STYLE); } t += t_step; } } } inline void draw_curves_invalid ( const std::vector<GlobFitCurve*>& curves, const std::vector<bool>& invalid ) { assert_break ( ( int ) curves.size() == ( int ) invalid.size() ); for ( int i = 0; i < curves.size(); ++i ) { if ( invalid[i] ) { draw::curve ( curves[i], .25, colors::red ); } else { draw::curve ( curves[i], .25, colors::black ); } } } inline void draw_path ( const Eigen::Matrix2Xd& path ) { for ( int i = 0; i < path.cols(); ++i ) { draw::line ( path.col ( i ), path.col ( ( i + 1 ) % path.cols() ), PATH_STYLE ); } } inline void draw_path ( const Eigen::Matrix2Xd& path, const bool is_closed, const Style& style ) { const int end_index = ( int ) ( is_closed ? path.cols() : ( int ) path.cols() -1 ); for ( int i = 0; i < end_index; ++i ) { draw::line ( path.col ( i ), path.col ( ( i + 1 ) % path.cols() ), style ); } } inline void draw_raster_convexities(const Eigen::Matrix2Xd& raster) { std::vector<int> convexities; polyfit::PathUtils::compute_convexities(raster, convexities); for (size_t i = 0; i < raster.cols(); ++i) { draw::text(raster.col(i), std::to_string(convexities[i]), draw::font_pdf, Style::text()); } } inline void draw_raster_indices ( const Eigen::Matrix2Xd& raster ) { for ( int i = 0; i < raster.cols(); ++i ) { // dbg::info(FMT("Point %f %f", raster.col(i), raster.col((i + 1) % raster.cols()))); //draw::line(raster.col(i), raster.col((i + 1) % raster.cols()), BOUNDARY_STYLE); const real2 p0 = raster.col(i); const real2 p1 = raster.col((i + 1) % raster.cols()); real2 off = (p0 - p1).normalized(); off = real2(off(1), -off(0)); draw::text ( raster.col ( i ), std::to_string ( i ), draw::font_pdf / 4, Style::text() ); } } inline void draw_raster_polygon_indices(const Eigen::Matrix2Xd& raster, const Eigen::VectorXi& polygon) { for (int i = 0; i < polygon.size(); ++i) { const std::string label = misc::sfmt("%d(%d)", i, polygon(i)); draw::text(raster.col(polygon(i)), label, draw::font_pdf, Style::text()); } } inline void draw_control_polygon ( const std::vector<GlobFitCurve*>& curves ) { for ( int i = 0; i < curves.size(); ++i ) { auto bezier = dynamic_cast<BezierCurve*> ( curves[i] ); if ( bezier == nullptr ) { continue; } const Eigen::Vector2d c0 = bezier->get_control_points().col ( 0 ); const Eigen::Vector2d c1 = bezier->get_control_points().col ( 1 ); const Eigen::Vector2d c2 = bezier->get_control_points().col ( 2 ); const Eigen::Vector2d c3 = bezier->get_control_points().col ( 3 ); draw::line ( c0, c1, Style::outline ( colors::talking_orange, .1 ) ); draw::line ( c1, c2, Style::outline ( colors::talking_orange, .1 ) ); draw::line ( c2, c3, Style::outline ( colors::talking_orange, .1 ) ); } } inline void draw_polygon ( const Eigen::Matrix2Xd& raster, const std::vector<Eigen::Index>& polygon ) { for ( int j = 0; j < polygon.size(); ++j ) { int corner_j = ( int ) polygon[j]; int corner_j_next = ( int ) polygon[j + 1]; if ( corner_j >= raster.cols() ) { corner_j -= ( int ) raster.cols(); } if ( corner_j_next >= raster.cols() ) { corner_j_next -= ( int ) raster.cols(); } real2 src, dst; if ( corner_j >= raster.cols() ) { src = .5 * ( raster.col ( corner_j - raster.size() ) + raster.col ( corner_j - raster.size() + 1 ) ); } else { src = raster.col ( corner_j ); } if ( corner_j_next >= raster.size() ) { dst = .5 * ( raster.col ( corner_j_next - raster.size() ) + raster.col ( corner_j_next - raster.size() + 1 ) ); } else { dst = raster.col ( corner_j_next ); } draw::line ( src, dst, Style::outline ( colors::talking_orange, 1. ) ); // Drawing the line of the polygon file to which the corner corresponds //draw::text ( src, std::to_string ( j + 1 ), draw::font_pdf * 3, Style::text() ); //draw::text ( src, std::to_string ( polygon[j] ), draw::font_pdf * 1, Style::text() ); real3 color; ( void ) color; double radius = 1.; ( void ) radius; #if 0 if ( labels[j] == 0 ) { color = colors::red; radius = 2.5; } else if ( labels[j] == 2 ) { color = colors::forest_green; } else { assert_break ( false ); } draw::point ( src, radius, Style::fill ( color ) ); #endif } } inline void draw_curves ( const std::vector<Eigen::Matrix2Xd>& curves ) { auto build_bezier = [&] ( const Eigen::Matrix<double, 2, 4> ctrl ) { ::polyvec::BezierCurve bz; bz.set_control_points ( ctrl ); return bz; }; for ( int i = 0; i < ( int ) curves.size(); ++i ) { if ( curves[i].cols() == 4 ) { Eigen::Vector3d color = i % 2 == 0 ? colors::talking_orange : colors::enemys_blood; auto bz = build_bezier ( curves[i] ); auto tess = bz.get_tesselation2(); for ( int j = 0; j < ( int ) tess.cols() - 1; ++j ) draw::line ( tess.col ( j ), tess.col ( j + 1 ), Style::outline ( color, 7 ) ); } else { Eigen::Vector3d color = i % 2 == 0 ? colors::forest_green : colors::green; draw::line ( curves[i].col ( 0 ), curves[i].col ( 1 ), Style::outline ( color, 7 ) ); } } } inline void draw_curves_fill ( const std::vector<Eigen::Matrix2Xd>& curves ) { auto build_bezier = [&] ( const Eigen::Matrix<double, 2, 4> ctrl ) { ::polyvec::BezierCurve bz; bz.set_control_points ( ctrl ); return bz; }; std::vector<real2> polygon; for ( int i = 0; i < ( int ) curves.size(); ++i ) { if ( curves[i].cols() == 4 ) { auto bz = build_bezier ( curves[i] ); auto tess = bz.get_tesselation2(); for ( int j = 0; j < ( int ) tess.cols() - 1; ++j ) { polygon.push_back ( tess.col ( j ) ); } } else { for ( int j = 0; j < ( int ) curves[i].cols() - 1; ++j ) { polygon.push_back ( curves[i].col ( j ) ); } } } draw::polygon ( polygon, Style::fill ( colors::dark_gray ) ); } }
40.741765
163
0.528054
[ "geometry", "vector" ]
2835af311a2b6c4d22cb83b52e631e77dfae235d
6,060
cpp
C++
src/graph/Utils.cpp
seogi81/ComputeLibrary
6653b538e8c515a58491952515a405077c685e0f
[ "MIT" ]
null
null
null
src/graph/Utils.cpp
seogi81/ComputeLibrary
6653b538e8c515a58491952515a405077c685e0f
[ "MIT" ]
null
null
null
src/graph/Utils.cpp
seogi81/ComputeLibrary
6653b538e8c515a58491952515a405077c685e0f
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018-2020 Arm Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "arm_compute/graph/Utils.h" #include "arm_compute/graph/GraphContext.h" #include "arm_compute/graph/backends/BackendRegistry.h" #include "arm_compute/graph/mutators/GraphMutators.h" namespace arm_compute { namespace graph { bool is_target_supported(Target target) { return backends::BackendRegistry::get().contains(target) && backends::BackendRegistry::get().find_backend(target)->is_backend_supported(); } Target get_default_target() { if(is_target_supported(Target::NEON)) { return Target::NEON; } if(is_target_supported(Target::CL)) { return Target::CL; } if(is_target_supported(Target::GC)) { return Target::GC; } ARM_COMPUTE_ERROR("No backend exists!"); } void force_target_to_graph(Graph &g, Target target) { auto &nodes = g.nodes(); for(auto &node : nodes) { if(node) { node->set_assigned_target(target); } } auto &tensors = g.tensors(); for(auto &tensor : tensors) { if(tensor) { tensor->desc().target = target; } } } PassManager create_default_pass_manager(Target target, const GraphConfig &cfg) { PassManager pm; const bool is_target_gc = target == Target::GC; // Passes that mutate graph IR if(cfg.convert_to_uint8) { pm.append(std::make_unique<SyntheticDataTypeMutator>(), !is_target_gc); } pm.append(std::make_unique<NodeFusionMutator>(), !is_target_gc); pm.append(std::make_unique<GroupedConvolutionMutator>()); pm.append(std::make_unique<InPlaceOperationMutator>(), !is_target_gc); // Passes that mutate backend information pm.append(std::make_unique<DepthConcatSubTensorMutator>(), !is_target_gc); pm.append(std::make_unique<SplitLayerSubTensorMutator>(), !is_target_gc); pm.append(std::make_unique<NodeExecutionMethodMutator>()); return pm; } void release_default_graph_context(GraphContext &ctx) { for(const auto &backend : backends::BackendRegistry::get().backends()) { if(backend.second->is_backend_supported()) { backend.second->release_backend_context(ctx); } } } void setup_requested_backend_context(GraphContext &ctx, Target target) { if(backends::BackendRegistry::get().contains(target)) { const auto &backend = backends::BackendRegistry::get().find_backend(target); if(backend->is_backend_supported()) { backend->setup_backend_context(ctx); } } } size_t get_dimension_size(const TensorDescriptor &descriptor, const DataLayoutDimension data_layout_dimension) { ARM_COMPUTE_ERROR_ON_MSG(descriptor.layout == DataLayout::UNKNOWN, "Cannot retrieve the dimension index for an unknown layout!"); return descriptor.shape[get_dimension_idx(descriptor.layout, data_layout_dimension)]; } size_t get_dimension_idx(DataLayout data_layout, const DataLayoutDimension data_layout_dimension) { ARM_COMPUTE_ERROR_ON_MSG(data_layout == DataLayout::UNKNOWN, "Cannot retrieve the dimension index for an unknown layout!"); /* Return the index based on the data layout * [N C H W] * [3 2 1 0] * [N H W C] */ switch(data_layout_dimension) { case DataLayoutDimension::CHANNEL: return (data_layout == DataLayout::NCHW) ? 2 : 0; break; case DataLayoutDimension::HEIGHT: return (data_layout == DataLayout::NCHW) ? 1 : 2; break; case DataLayoutDimension::WIDTH: return (data_layout == DataLayout::NCHW) ? 0 : 1; break; case DataLayoutDimension::BATCHES: return 3; break; default: break; } ARM_COMPUTE_ERROR("Data layout index not supported!"); } std::vector<NodeIdxPair> get_driving_nodes(const INode &node) { std::vector<NodeIdxPair> driving_nodes; const Graph *g = node.graph(); ARM_COMPUTE_ERROR_ON(g == nullptr); for(auto &output_edge_id : node.output_edges()) { auto output_edge = g->edge(output_edge_id); if(output_edge != nullptr) { ARM_COMPUTE_ERROR_ON(output_edge->consumer() == nullptr); driving_nodes.push_back({ output_edge->consumer_id(), output_edge->consumer_idx() }); } } return driving_nodes; } void configure_tensor(Tensor *tensor) { if(tensor != nullptr && tensor->handle() == nullptr) { Target target = tensor->desc().target; backends::IDeviceBackend &backend = backends::BackendRegistry::get().get_backend(target); std::unique_ptr<ITensorHandle> handle = backend.create_tensor(*tensor); ARM_COMPUTE_ERROR_ON_MSG(!handle, "Couldn't create backend handle!"); tensor->set_handle(std::move(handle)); } } } // namespace graph } // namespace arm_compute
31.727749
142
0.677558
[ "shape", "vector" ]
283a329c863c90ac8d4e14dd6e4c352e42f6e5de
3,036
cxx
C++
src/Cxx/Plotting/BoxChart.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
81
2020-08-10T01:44:30.000Z
2022-03-23T06:46:36.000Z
src/Cxx/Plotting/BoxChart.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
2
2020-09-12T17:33:52.000Z
2021-04-15T17:33:09.000Z
src/Cxx/Plotting/BoxChart.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
27
2020-08-17T07:09:30.000Z
2022-02-15T03:44:58.000Z
#include <vtkAxis.h> #include <vtkChartBox.h> #include <vtkComputeQuartiles.h> #include <vtkContextScene.h> #include <vtkContextView.h> #include <vtkIntArray.h> #include <vtkLookupTable.h> #include <vtkNew.h> #include <vtkPlotBox.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkStatisticsAlgorithm.h> #include <vtkStringArray.h> #include <vtkTable.h> #include <vtkTextProperty.h> //---------------------------------------------------------------------------- int main(int, char*[]) { // Set up a 2D scene, add an XY chart to it vtkNew<vtkContextView> view; view->GetRenderWindow()->SetSize(400, 400); view->GetRenderWindow()->SetMultiSamples(0); vtkNew<vtkChartBox> chart; view->GetScene()->AddItem(chart); // Creates a vtkPlotBox input table int numParam = 5; vtkNew<vtkTable> inputBoxPlotTable; for (int i = 0; i < numParam; i++) { char num[10]; sprintf(num, "Run %d", i + 1); vtkNew<vtkIntArray> arrIndex; arrIndex->SetName(num); inputBoxPlotTable->AddColumn(arrIndex); } inputBoxPlotTable->SetNumberOfRows(20); double values[20][5] = { {850, 960, 880, 890, 890}, {740, 940, 880, 810, 840}, {900, 960, 880, 810, 780}, {1070, 940, 860, 820, 810}, {930, 880, 720, 800, 760}, {850, 800, 720, 770, 810}, {950, 850, 620, 760, 790}, {980, 880, 860, 740, 810}, {980, 900, 970, 750, 820}, {880, 840, 950, 760, 850}, {1000, 830, 880, 910, 870}, {980, 790, 910, 920, 870}, {930, 810, 850, 890, 810}, {650, 880, 870, 860, 740}, {760, 880, 840, 880, 810}, {810, 830, 840, 720, 940}, {1000, 800, 850, 840, 950}, {1000, 790, 840, 850, 800}, {960, 760, 840, 850, 810}, {960, 800, 840, 780, 870}}; for (int j = 0; j < 20; ++j) { for (int i = 0; i < 5; ++i) { inputBoxPlotTable->SetValue(j, i, values[j][i]); } } vtkNew<vtkComputeQuartiles> quartiles; quartiles->SetInputData(vtkStatisticsAlgorithm::INPUT_DATA, inputBoxPlotTable); quartiles->Update(); vtkTable* outTable = quartiles->GetOutput(); vtkNew<vtkLookupTable> lookup; lookup->SetNumberOfColors(5); lookup->SetRange(0, 4); lookup->Build(); chart->GetPlot(0)->SetInputData(outTable); chart->SetShowLegend(true); chart->SetColumnVisibilityAll(true); chart->SetTitle("Michelson-Morley experiment"); chart->GetTitleProperties()->SetFontSize(16); chart->GetYAxis()->SetTitle("Speed of Light (km/s - 299000)"); // Set the labels vtkNew<vtkStringArray> labels; labels->SetNumberOfValues(5); labels->SetValue(0, "Run 1"); labels->SetValue(1, "Run 2"); labels->SetValue(2, "Run 3"); labels->SetValue(3, "Run 4"); labels->SetValue(4, "Run 5"); chart->GetPlot(0)->SetLabels(labels); // Render the scene view->GetRenderWindow()->SetMultiSamples(0); view->GetRenderer()->SetBackground(.8, .8, .8); view->GetInteractor()->Initialize(); view->Render(); view->GetInteractor()->Start(); return EXIT_SUCCESS; }
30.979592
78
0.626153
[ "render" ]
283d307200931f7bc47fe75fbf5cce75ed255463
77,676
cpp
C++
nn/common/CpuExecutor.cpp
cuiyanx/ml
058328ae1893c0173923ba88c68fc72e18faa073
[ "Apache-2.0" ]
null
null
null
nn/common/CpuExecutor.cpp
cuiyanx/ml
058328ae1893c0173923ba88c68fc72e18faa073
[ "Apache-2.0" ]
null
null
null
nn/common/CpuExecutor.cpp
cuiyanx/ml
058328ae1893c0173923ba88c68fc72e18faa073
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "CpuExecutor" #include "CpuExecutor.h" #include "NeuralNetworks.h" #include "Operations.h" #include <sys/mman.h> namespace android { namespace nn { // TODO: short term, make share memory mapping and updating a utility function. // TODO: long term, implement mmap_fd as a hidl IMemory service. RunTimePoolInfo::RunTimePoolInfo(const hidl_memory& hidlMemory, bool* fail) { sp<IMemory> memory; uint8_t* buffer = nullptr; auto memType = hidlMemory.name(); if (memType == "ashmem") { memory = mapMemory(hidlMemory); if (memory == nullptr) { LOG(ERROR) << "Can't map shared memory."; if (fail) *fail = true; return; } memory->update(); buffer = reinterpret_cast<uint8_t*>(static_cast<void*>(memory->getPointer())); if (buffer == nullptr) { LOG(ERROR) << "Can't access shared memory."; if (fail) *fail = true; return; } } else if (memType == "mmap_fd") { size_t size = hidlMemory.size(); int fd = hidlMemory.handle()->data[0]; int prot = hidlMemory.handle()->data[1]; size_t offset = getSizeFromInts(hidlMemory.handle()->data[2], hidlMemory.handle()->data[3]); buffer = static_cast<uint8_t*>(mmap(nullptr, size, prot, MAP_SHARED, fd, offset)); if (buffer == MAP_FAILED) { LOG(ERROR) << "RunTimePoolInfo::set(): Can't mmap the file descriptor."; if (fail) *fail = true; return; } } else { LOG(ERROR) << "RunTimePoolInfo::set(): unsupported hidl_memory type"; if (fail) *fail = true; return; } mHidlMemory = hidlMemory; mBuffer = buffer; mMemory = memory; } RunTimePoolInfo::RunTimePoolInfo(uint8_t* buffer) { mBuffer = buffer; } RunTimePoolInfo::RunTimePoolInfo(RunTimePoolInfo&& other) { moveFrom(std::move(other)); other.mBuffer = nullptr; } RunTimePoolInfo& RunTimePoolInfo::operator=(RunTimePoolInfo&& other) { if (this != &other) { release(); moveFrom(std::move(other)); other.mBuffer = nullptr; } return *this; } void RunTimePoolInfo::moveFrom(RunTimePoolInfo &&other) { mHidlMemory = std::move(other.mHidlMemory); mBuffer = std::move(other.mBuffer); mMemory = std::move(other.mMemory); } void RunTimePoolInfo::release() { if (mBuffer == nullptr) { return; } auto memType = mHidlMemory.name(); if (memType == "ashmem") { // nothing to do } else if (memType == "mmap_fd") { size_t size = mHidlMemory.size(); if (munmap(mBuffer, size)) { LOG(ERROR) << "RunTimePoolInfo::release(): Can't munmap"; } } else if (memType == "") { // Represents a POINTER argument; nothing to do } else { LOG(ERROR) << "RunTimePoolInfo::release(): unsupported hidl_memory type"; } mHidlMemory = hidl_memory(); mMemory = nullptr; mBuffer = nullptr; } // Making sure the output data are correctly updated after execution. bool RunTimePoolInfo::update() const { auto memType = mHidlMemory.name(); if (memType == "ashmem") { mMemory->commit(); return true; } else if (memType == "mmap_fd") { int prot = mHidlMemory.handle()->data[1]; if (prot & PROT_WRITE) { size_t size = mHidlMemory.size(); return msync(mBuffer, size, MS_SYNC) == 0; } } // No-op for other types of memory. return true; } bool setRunTimePoolInfosFromHidlMemories(std::vector<RunTimePoolInfo>* poolInfos, const hidl_vec<hidl_memory>& pools) { poolInfos->clear(); poolInfos->reserve(pools.size()); bool fail = false; for (const auto& pool : pools) { poolInfos->emplace_back(pool, &fail); } if (fail) { LOG(ERROR) << "Could not map pools"; poolInfos->clear(); return false; } return true; } // Updates the RunTimeOperandInfo with the newly calculated shape. // Allocate the buffer if we need to. static bool setInfoAndAllocateIfNeeded(RunTimeOperandInfo* info, const Shape& shape) { // For user-provided model output operands, the parameters must match the Shape // calculated from the preparation step. if (info->lifetime == OperandLifeTime::MODEL_OUTPUT) { if (info->type != shape.type || info->dimensions != shape.dimensions) { LOG(ERROR) << "Invalid type or dimensions for model output"; return false; } if (info->type == OperandType::TENSOR_QUANT8_ASYMM && (info->scale != shape.scale || info->zeroPoint != shape.offset)) { LOG(ERROR) << "Invalid scale or zeroPoint for model output"; return false; } } info->type = shape.type; info->dimensions = shape.dimensions; info->scale = shape.scale; info->zeroPoint = shape.offset; if (info->lifetime == OperandLifeTime::TEMPORARY_VARIABLE && info->buffer == nullptr) { uint32_t length = sizeOfData(info->type, info->dimensions); info->buffer = new uint8_t[length]; if (info->buffer == nullptr) { return false; } } return true; } // Ignore the .pools entry in model and request. This will have been taken care of // by the caller. int CpuExecutor::run(const V1_0::Model& model, const Request& request, const std::vector<RunTimePoolInfo>& modelPoolInfos, const std::vector<RunTimePoolInfo>& requestPoolInfos) { return run(convertToV1_1(model), request, modelPoolInfos, requestPoolInfos); } int CpuExecutor::run(const V1_1::Model& model, const Request& request, const std::vector<RunTimePoolInfo>& modelPoolInfos, const std::vector<RunTimePoolInfo>& requestPoolInfos) { VLOG(CPUEXE) << "CpuExecutor::run() with request(" << SHOW_IF_DEBUG(toString(request)) << ")"; mModel = &model; mRequest = &request; // TODO check if mRequest is needed initializeRunTimeInfo(modelPoolInfos, requestPoolInfos); // The model has serialized the operation in execution order. for (const auto& operation : model.operations) { int n = executeOperation(operation); if (n != ANEURALNETWORKS_NO_ERROR) { return n; } } for (auto& runtimeInfo : modelPoolInfos) { runtimeInfo.update(); } for (auto& runtimeInfo : requestPoolInfos) { runtimeInfo.update(); } mModel = nullptr; mRequest = nullptr; VLOG(CPUEXE) << "Completed run normally"; return ANEURALNETWORKS_NO_ERROR; } bool CpuExecutor::initializeRunTimeInfo(const std::vector<RunTimePoolInfo>& modelPoolInfos, const std::vector<RunTimePoolInfo>& requestPoolInfos) { VLOG(CPUEXE) << "CpuExecutor::initializeRunTimeInfo"; const size_t count = mModel->operands.size(); mOperands.resize(count); // Start by setting the runtime info to what's in the model. for (size_t i = 0; i < count; i++) { const Operand& from = mModel->operands[i]; RunTimeOperandInfo& to = mOperands[i]; to.type = from.type; to.dimensions = from.dimensions; to.scale = from.scale; to.zeroPoint = from.zeroPoint; to.length = from.location.length; to.lifetime = from.lifetime; switch (from.lifetime) { case OperandLifeTime::TEMPORARY_VARIABLE: to.buffer = nullptr; to.numberOfUsesLeft = from.numberOfConsumers; break; case OperandLifeTime::CONSTANT_COPY: to.buffer = const_cast<uint8_t*>(&mModel->operandValues[from.location.offset]); to.numberOfUsesLeft = 0; break; case OperandLifeTime::CONSTANT_REFERENCE: { auto poolIndex = from.location.poolIndex; nnAssert(poolIndex < modelPoolInfos.size()); auto& r = modelPoolInfos[poolIndex]; to.buffer = r.getBuffer() + from.location.offset; to.numberOfUsesLeft = 0; break; } case OperandLifeTime::MODEL_INPUT: case OperandLifeTime::MODEL_OUTPUT: case OperandLifeTime::NO_VALUE: to.buffer = nullptr; to.numberOfUsesLeft = 0; break; default: nnAssert(false); break; } } // Adjust the runtime info for the arguments passed to the model, // modifying the buffer location, and possibly the dimensions. auto updateForArguments = [this, &requestPoolInfos](const std::vector<uint32_t>& indexes, const hidl_vec<RequestArgument>& arguments) { nnAssert(indexes.size() == arguments.size()); for (size_t i = 0; i < indexes.size(); i++) { const uint32_t operandIndex = indexes[i]; const RequestArgument& from = arguments[i]; RunTimeOperandInfo& to = mOperands[operandIndex]; if (from.dimensions.size() > 0) { // It's the responsibility of the caller to validate that // from.dimensions only modifies the dimensions that were // unspecified in the model. That's the case in SampleDriver.cpp // with the call to validateRequest(). // TODO make sure that's the case for the default CPU path. to.dimensions = from.dimensions; } if (from.hasNoValue) { to.lifetime = OperandLifeTime::NO_VALUE; nnAssert(to.buffer == nullptr); } else { auto poolIndex = from.location.poolIndex; nnAssert(poolIndex < requestPoolInfos.size()); auto& r = requestPoolInfos[poolIndex]; to.buffer = r.getBuffer() + from.location.offset; } } }; updateForArguments(mModel->inputIndexes, mRequest->inputs); updateForArguments(mModel->outputIndexes, mRequest->outputs); return true; } void CpuExecutor::freeNoLongerUsedOperands(const std::vector<uint32_t>& inputs) { for (uint32_t i : inputs) { auto& info = mOperands[i]; // Check if it's a static or model input/output. if (info.numberOfUsesLeft == 0) { continue; } info.numberOfUsesLeft--; if (info.numberOfUsesLeft == 0) { nnAssert(info.buffer != nullptr); delete[] info.buffer; info.buffer = nullptr; } } } int CpuExecutor::executeOperation(const Operation& operation) { // VLOG(CPUEXE) << "CpuExecutor::executeOperation(" << toString(operation) << ")"; const hidl_vec<uint32_t>& ins = operation.inputs; const hidl_vec<uint32_t>& outs = operation.outputs; bool success = false; // Function to verify that the number of input and output parameters // matches what is expected. Also checks that all the parameters have // values. This function is to be used only for operations that do not // accept optional arguments. // TODO Have a version that works for optional arguments. auto allParametersPresent = [&operation, &ins, &outs, this](size_t requiredIns, size_t requiredOuts) -> bool { auto verify = [&operation, this](size_t requiredCount, const hidl_vec<uint32_t>& indexes, const char* type) -> bool { size_t actualCount = indexes.size(); if (actualCount != requiredCount) { LOG(ERROR) << getOperationName(operation.type) << ": Invalid number of " << type << " operands. Got " << actualCount << " of " << requiredCount; return false; } for (size_t i = 0; i < actualCount; i++) { if (mOperands[indexes[i]].lifetime == OperandLifeTime::NO_VALUE) { LOG(ERROR) << getOperationName(operation.type) << " " << type << " operand " << i << " is required but missing."; return false; } } return true; }; return verify(requiredIns, ins, "in") && verify(requiredOuts, outs, "out"); }; switch (operation.type) { case OperationType::OEM_OPERATION: { LOG(ERROR) << "OEM operation not supported for CPU execution"; success = false; } break; case OperationType::ADD: { if (!allParametersPresent(3, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& in1 = mOperands[ins[0]]; const RunTimeOperandInfo& in2 = mOperands[ins[1]]; int32_t activation = getScalarData<int32_t>(mOperands[ins[2]]); RunTimeOperandInfo& out = mOperands[outs[0]]; Shape outShape = out.shape(); if (in1.type == OperandType::TENSOR_FLOAT32) { success = addMulPrepare(in1.shape(), in2.shape(), &outShape) && setInfoAndAllocateIfNeeded(&out, outShape) && addFloat32(reinterpret_cast<const float*>(in1.buffer), in1.shape(), reinterpret_cast<const float*>(in2.buffer), in2.shape(), activation, reinterpret_cast<float*>(out.buffer), outShape); } else if (in1.type == OperandType::TENSOR_QUANT8_ASYMM) { success = addMulPrepare(in1.shape(), in2.shape(), &outShape) && setInfoAndAllocateIfNeeded(&out, outShape) && addQuant8(reinterpret_cast<const uint8_t*>(in1.buffer), in1.shape(), reinterpret_cast<const uint8_t*>(in2.buffer), in2.shape(), activation, reinterpret_cast<uint8_t*>(out.buffer), outShape); } } break; case OperationType::MUL: { if (!allParametersPresent(3, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& in1 = mOperands[ins[0]]; const RunTimeOperandInfo& in2 = mOperands[ins[1]]; int32_t activation = getScalarData<int32_t>(mOperands[ins[2]]); RunTimeOperandInfo& out = mOperands[outs[0]]; Shape outShape = out.shape(); if (in1.type == OperandType::TENSOR_FLOAT32) { success = addMulPrepare(in1.shape(), in2.shape(), &outShape) && setInfoAndAllocateIfNeeded(&out, outShape) && mulFloat32(reinterpret_cast<const float*>(in1.buffer), in1.shape(), reinterpret_cast<const float*>(in2.buffer), in2.shape(), activation, reinterpret_cast<float*>(out.buffer), outShape); } else if (in1.type == OperandType::TENSOR_QUANT8_ASYMM) { success = addMulPrepare(in1.shape(), in2.shape(), &outShape) && setInfoAndAllocateIfNeeded(&out, outShape) && mulQuant8(reinterpret_cast<const uint8_t*>(in1.buffer), in1.shape(), reinterpret_cast<const uint8_t*>(in2.buffer), in2.shape(), activation, reinterpret_cast<uint8_t*>(out.buffer), outShape); } } break; case OperationType::FLOOR: { if (!allParametersPresent(1, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = floorPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && floorFloat32(reinterpret_cast<const float*>(input.buffer), reinterpret_cast<float*>(output.buffer), outShape); } } break; case OperationType::DEQUANTIZE: { if (!allParametersPresent(1, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = dequantizePrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && dequantizeQuant8ToFloat32( reinterpret_cast<const uint8_t*>(input.buffer), reinterpret_cast<float*>(output.buffer), input.shape()); } } break; case OperationType::DEPTHWISE_CONV_2D: { const size_t inCount = ins.size(); if ((inCount != 11 && inCount != 8) || !allParametersPresent(inCount, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; const RunTimeOperandInfo& filter = mOperands[ins[1]]; const RunTimeOperandInfo& bias = mOperands[ins[2]]; int32_t padding_left, padding_right; int32_t padding_top, padding_bottom; int32_t stride_width, stride_height; int32_t depth_multiplier; int32_t activation; if (inCount == 11) { padding_left = getScalarData<int32_t>(mOperands[ins[3]]); padding_right = getScalarData<int32_t>(mOperands[ins[4]]); padding_top = getScalarData<int32_t>(mOperands[ins[5]]); padding_bottom = getScalarData<int32_t>(mOperands[ins[6]]); stride_width = getScalarData<int32_t>(mOperands[ins[7]]); stride_height = getScalarData<int32_t>(mOperands[ins[8]]); depth_multiplier = getScalarData<int32_t>(mOperands[ins[9]]); activation = getScalarData<int32_t>(mOperands[ins[10]]); } else { int32_t padding_implicit = getScalarData<int32_t>(mOperands[ins[3]]); stride_width = getScalarData<int32_t>(mOperands[ins[4]]); stride_height = getScalarData<int32_t>(mOperands[ins[5]]); depth_multiplier = getScalarData<int32_t>(mOperands[ins[6]]); activation = getScalarData<int32_t>(mOperands[ins[7]]); Shape inputShape = input.shape(); Shape filterShape = filter.shape(); int32_t input_width = getSizeOfDimension(inputShape, 2); int32_t input_height = getSizeOfDimension(inputShape, 1); int32_t filter_width = getSizeOfDimension(filterShape, 2); int32_t filter_height = getSizeOfDimension(filterShape, 1); calculateExplicitPadding(input_width, stride_width, filter_width, padding_implicit, &padding_left, &padding_right); calculateExplicitPadding(input_height, stride_height, filter_height, padding_implicit, &padding_top, &padding_bottom); } RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = depthwiseConvPrepare(input.shape(), filter.shape(), bias.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && depthwiseConvFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), reinterpret_cast<const float*>(filter.buffer), filter.shape(), reinterpret_cast<const float*>(bias.buffer), bias.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, depth_multiplier, activation, reinterpret_cast<float*>(output.buffer), outShape); } else if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = depthwiseConvPrepare(input.shape(), filter.shape(), bias.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && depthwiseConvQuant8(reinterpret_cast<const uint8_t*>(input.buffer), input.shape(), reinterpret_cast<const uint8_t*>(filter.buffer), filter.shape(), reinterpret_cast<const int32_t*>(bias.buffer), bias.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, depth_multiplier, activation, reinterpret_cast<uint8_t*>(output.buffer), outShape); } } break; case OperationType::CONV_2D: { const size_t inCount = ins.size(); if ((inCount != 10 && inCount != 7) || !allParametersPresent(inCount, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; const RunTimeOperandInfo& filter = mOperands[ins[1]]; const RunTimeOperandInfo& bias = mOperands[ins[2]]; int32_t padding_left, padding_right; int32_t padding_top, padding_bottom; int32_t stride_width, stride_height; int32_t activation; if (inCount == 10) { padding_left = getScalarData<int32_t>(mOperands[ins[3]]); padding_right = getScalarData<int32_t>(mOperands[ins[4]]); padding_top = getScalarData<int32_t>(mOperands[ins[5]]); padding_bottom = getScalarData<int32_t>(mOperands[ins[6]]); stride_width = getScalarData<int32_t>(mOperands[ins[7]]); stride_height = getScalarData<int32_t>(mOperands[ins[8]]); activation = getScalarData<int32_t>(mOperands[ins[9]]); } else { int32_t padding_implicit = getScalarData<int32_t>(mOperands[ins[3]]); stride_width = getScalarData<int32_t>(mOperands[ins[4]]); stride_height = getScalarData<int32_t>(mOperands[ins[5]]); activation = getScalarData<int32_t>(mOperands[ins[6]]); Shape inputShape = input.shape(); Shape filterShape = filter.shape(); int32_t input_width = getSizeOfDimension(inputShape, 2); int32_t input_height = getSizeOfDimension(inputShape, 1); int32_t filter_width = getSizeOfDimension(filterShape, 2); int32_t filter_height = getSizeOfDimension(filterShape, 1); calculateExplicitPadding(input_width, stride_width, filter_width, padding_implicit, &padding_left, &padding_right); calculateExplicitPadding(input_height, stride_height, filter_height, padding_implicit, &padding_top, &padding_bottom); } RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = convPrepare(input.shape(), filter.shape(), bias.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && convFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), reinterpret_cast<const float*>(filter.buffer), filter.shape(), reinterpret_cast<const float*>(bias.buffer), bias.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, activation, reinterpret_cast<float*>(output.buffer), outShape); } else if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = convPrepare(input.shape(), filter.shape(), bias.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && convQuant8(reinterpret_cast<const uint8_t*>(input.buffer), input.shape(), reinterpret_cast<const uint8_t*>(filter.buffer), filter.shape(), reinterpret_cast<const int32_t*>(bias.buffer), bias.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, activation, reinterpret_cast<uint8_t*>(output.buffer), outShape); } } break; case OperationType::AVERAGE_POOL_2D: { const size_t inCount = ins.size(); if ((inCount != 10 && inCount != 7) || !allParametersPresent(inCount, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; int32_t padding_left, padding_right; int32_t padding_top, padding_bottom; int32_t stride_width, stride_height; int32_t filter_width, filter_height; int32_t activation; if (inCount == 10) { padding_left = getScalarData<int32_t>(mOperands[ins[1]]); padding_right = getScalarData<int32_t>(mOperands[ins[2]]); padding_top = getScalarData<int32_t>(mOperands[ins[3]]); padding_bottom = getScalarData<int32_t>(mOperands[ins[4]]); stride_width = getScalarData<int32_t>(mOperands[ins[5]]); stride_height = getScalarData<int32_t>(mOperands[ins[6]]); filter_width = getScalarData<int32_t>(mOperands[ins[7]]); filter_height = getScalarData<int32_t>(mOperands[ins[8]]); activation = getScalarData<int32_t>(mOperands[ins[9]]); } else { int32_t padding_implicit = getScalarData<int32_t>(mOperands[ins[1]]); stride_width = getScalarData<int32_t>(mOperands[ins[2]]); stride_height = getScalarData<int32_t>(mOperands[ins[3]]); filter_width = getScalarData<int32_t>(mOperands[ins[4]]); filter_height = getScalarData<int32_t>(mOperands[ins[5]]); activation = getScalarData<int32_t>(mOperands[ins[6]]); Shape inputShape = input.shape(); int32_t input_width = getSizeOfDimension(inputShape, 2); int32_t input_height = getSizeOfDimension(inputShape, 1); calculateExplicitPadding(input_width, stride_width, filter_width, padding_implicit, &padding_left, &padding_right); calculateExplicitPadding(input_height, stride_height, filter_height, padding_implicit, &padding_top, &padding_bottom); } RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = genericPoolingPrepare(input.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, filter_width, filter_height, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && averagePoolFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, filter_width, filter_height, activation, reinterpret_cast<float*>(output.buffer), outShape); } else if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = genericPoolingPrepare(input.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, filter_width, filter_height, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && averagePoolQuant8(reinterpret_cast<const uint8_t*>(input.buffer), input.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, filter_width, filter_height, activation, reinterpret_cast<uint8_t*>(output.buffer), outShape); } } break; case OperationType::L2_POOL_2D: { const size_t inCount = ins.size(); if ((inCount != 10 && inCount != 7) || !allParametersPresent(inCount, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; int32_t padding_left, padding_right; int32_t padding_top, padding_bottom; int32_t stride_width, stride_height; int32_t filter_width, filter_height; int32_t activation; if (inCount == 10) { padding_left = getScalarData<int32_t>(mOperands[ins[1]]); padding_right = getScalarData<int32_t>(mOperands[ins[2]]); padding_top = getScalarData<int32_t>(mOperands[ins[3]]); padding_bottom = getScalarData<int32_t>(mOperands[ins[4]]); stride_width = getScalarData<int32_t>(mOperands[ins[5]]); stride_height = getScalarData<int32_t>(mOperands[ins[6]]); filter_width = getScalarData<int32_t>(mOperands[ins[7]]); filter_height = getScalarData<int32_t>(mOperands[ins[8]]); activation = getScalarData<int32_t>(mOperands[ins[9]]); } else { int32_t padding_implicit = getScalarData<int32_t>(mOperands[ins[1]]); stride_width = getScalarData<int32_t>(mOperands[ins[2]]); stride_height = getScalarData<int32_t>(mOperands[ins[3]]); filter_width = getScalarData<int32_t>(mOperands[ins[4]]); filter_height = getScalarData<int32_t>(mOperands[ins[5]]); activation = getScalarData<int32_t>(mOperands[ins[6]]); Shape inputShape = input.shape(); int32_t input_width = getSizeOfDimension(inputShape, 2); int32_t input_height = getSizeOfDimension(inputShape, 1); calculateExplicitPadding(input_width, stride_width, filter_width, padding_implicit, &padding_left, &padding_right); calculateExplicitPadding(input_height, stride_height, filter_height, padding_implicit, &padding_top, &padding_bottom); } RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = genericPoolingPrepare(input.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, filter_width, filter_height, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && l2PoolFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, filter_width, filter_height, activation, reinterpret_cast<float*>(output.buffer), outShape); } } break; case OperationType::MAX_POOL_2D: { const size_t inCount = ins.size(); if ((inCount != 10 && inCount != 7) || !allParametersPresent(inCount, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; int32_t padding_left, padding_right; int32_t padding_top, padding_bottom; int32_t stride_width, stride_height; int32_t filter_width, filter_height; int32_t activation; if (inCount == 10) { padding_left = getScalarData<int32_t>(mOperands[ins[1]]); padding_right = getScalarData<int32_t>(mOperands[ins[2]]); padding_top = getScalarData<int32_t>(mOperands[ins[3]]); padding_bottom = getScalarData<int32_t>(mOperands[ins[4]]); stride_width = getScalarData<int32_t>(mOperands[ins[5]]); stride_height = getScalarData<int32_t>(mOperands[ins[6]]); filter_width = getScalarData<int32_t>(mOperands[ins[7]]); filter_height = getScalarData<int32_t>(mOperands[ins[8]]); activation = getScalarData<int32_t>(mOperands[ins[9]]); } else { int32_t padding_implicit = getScalarData<int32_t>(mOperands[ins[1]]); stride_width = getScalarData<int32_t>(mOperands[ins[2]]); stride_height = getScalarData<int32_t>(mOperands[ins[3]]); filter_width = getScalarData<int32_t>(mOperands[ins[4]]); filter_height = getScalarData<int32_t>(mOperands[ins[5]]); activation = getScalarData<int32_t>(mOperands[ins[6]]); Shape inputShape = input.shape(); int32_t input_width = getSizeOfDimension(inputShape, 2); int32_t input_height = getSizeOfDimension(inputShape, 1); calculateExplicitPadding(input_width, stride_width, filter_width, padding_implicit, &padding_left, &padding_right); calculateExplicitPadding(input_height, stride_height, filter_height, padding_implicit, &padding_top, &padding_bottom); } RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = genericPoolingPrepare(input.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, filter_width, filter_height, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && maxPoolFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, filter_width, filter_height, activation, reinterpret_cast<float*>(output.buffer), outShape); } else if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = genericPoolingPrepare(input.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, filter_width, filter_height, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && maxPoolQuant8(reinterpret_cast<const uint8_t*>(input.buffer), input.shape(), padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, filter_width, filter_height, activation, reinterpret_cast<uint8_t*>(output.buffer), outShape); } } break; case OperationType::RELU: { if (!allParametersPresent(1, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = genericActivationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && reluFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), reinterpret_cast<float*>(output.buffer), outShape); } else if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = genericActivationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && reluQuant8(reinterpret_cast<const uint8_t*>(input.buffer), input.shape(), reinterpret_cast<uint8_t*>(output.buffer), outShape); } } break; case OperationType::RELU1: { if (!allParametersPresent(1, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = genericActivationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && relu1Float32(reinterpret_cast<const float*>(input.buffer), input.shape(), reinterpret_cast<float*>(output.buffer), outShape); } else if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = genericActivationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && relu1Quant8(reinterpret_cast<const uint8_t*>(input.buffer), input.shape(), reinterpret_cast<uint8_t*>(output.buffer), outShape); } } break; case OperationType::RELU6: { if (!allParametersPresent(1, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = genericActivationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && relu6Float32(reinterpret_cast<const float*>(input.buffer), input.shape(), reinterpret_cast<float*>(output.buffer), outShape); } else if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = genericActivationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && relu6Quant8(reinterpret_cast<const uint8_t*>(input.buffer), input.shape(), reinterpret_cast<uint8_t*>(output.buffer), outShape); } } break; case OperationType::TANH: { if (!allParametersPresent(1, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = genericActivationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && tanhFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), reinterpret_cast<float*>(output.buffer), outShape); } } break; case OperationType::LOGISTIC: { if (!allParametersPresent(1, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = genericActivationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && logisticFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), reinterpret_cast<float*>(output.buffer), outShape); } else if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = genericActivationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && logisticQuant8(reinterpret_cast<const uint8_t*>(input.buffer), input.shape(), reinterpret_cast<uint8_t*>(output.buffer), outShape); } } break; case OperationType::SOFTMAX: { if (!allParametersPresent(2, 1)) { return ANEURALNETWORKS_BAD_DATA; } RunTimeOperandInfo& input = mOperands[ins[0]]; float beta = getScalarData<float>(mOperands[ins[1]]); if (beta <= 0.0f) { LOG(ERROR) << "beta must be positive for softmax"; return ANEURALNETWORKS_BAD_DATA; } RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = genericActivationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && softmaxFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), beta, reinterpret_cast<float*>(output.buffer), output.shape()); } else if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = genericActivationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && softmaxQuant8(reinterpret_cast<const uint8_t*>(input.buffer), input.shape(), beta, reinterpret_cast<uint8_t*>(output.buffer), output.shape()); } } break; case OperationType::FULLY_CONNECTED: { if (!allParametersPresent(4, 1)) { return ANEURALNETWORKS_BAD_DATA; } RunTimeOperandInfo& input = mOperands[ins[0]]; RunTimeOperandInfo& weights = mOperands[ins[1]]; RunTimeOperandInfo& bias = mOperands[ins[2]]; int32_t activation = getScalarData<int32_t>(mOperands[ins[3]]); RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = fullyConnectedPrepare(input.shape(), weights.shape(), bias.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && fullyConnectedFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), reinterpret_cast<const float*>(weights.buffer), weights.shape(), reinterpret_cast<const float*>(bias.buffer), bias.shape(), activation, reinterpret_cast<float*>(output.buffer), outShape); } else if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = fullyConnectedPrepare(input.shape(), weights.shape(), bias.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && fullyConnectedQuant8(reinterpret_cast<const uint8_t*>(input.buffer), input.shape(), reinterpret_cast<const uint8_t*>(weights.buffer), weights.shape(), reinterpret_cast<const int32_t*>(bias.buffer), bias.shape(), activation, reinterpret_cast<uint8_t*>(output.buffer), outShape); } } break; case OperationType::CONCATENATION: { if (outs.size() != 1 || ins.size() < 2) { return ANEURALNETWORKS_BAD_DATA; } int numInputTensors = ins.size() - 1; int32_t axis = getScalarData<int32_t>(mOperands[ins[numInputTensors]]); RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); const RunTimeOperandInfo& firstInput = mOperands[ins[0]]; if (firstInput.type == OperandType::TENSOR_FLOAT32) { std::vector<Shape> inputShapes(numInputTensors); std::vector<const float*> inputDataPtrs(numInputTensors); for (int i=0; i<numInputTensors; i++) { RunTimeOperandInfo& input = mOperands[ins[i]]; inputShapes[i] = input.shape(); inputDataPtrs[i] = reinterpret_cast<const float*>(input.buffer); } success = concatenationPrepare(inputShapes, axis, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && concatenationFloat32(inputDataPtrs, inputShapes, axis, reinterpret_cast<float*>(output.buffer), outShape); } else if (firstInput.type == OperandType::TENSOR_QUANT8_ASYMM) { std::vector<Shape> inputShapes(numInputTensors); std::vector<const uint8_t*> inputDataPtrs(numInputTensors); for (int i=0; i<numInputTensors; i++) { RunTimeOperandInfo& input = mOperands[ins[i]]; inputShapes[i] = input.shape(); inputDataPtrs[i] = reinterpret_cast<const uint8_t*>(input.buffer); } success = concatenationPrepare(inputShapes, axis, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && concatenationQuant8(inputDataPtrs, inputShapes, axis, reinterpret_cast<uint8_t*>(output.buffer), outShape); } } break; case OperationType::L2_NORMALIZATION: { if (!allParametersPresent(1, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = genericNormalizationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && l2normFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), reinterpret_cast<float*>(output.buffer), outShape); } else if (input.type == OperandType::TENSOR_QUANT8_ASYMM) { success = genericNormalizationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && l2normQuant8(reinterpret_cast<const uint8_t*>(input.buffer), input.shape(), reinterpret_cast<uint8_t*>(output.buffer), outShape); } } break; case OperationType::LOCAL_RESPONSE_NORMALIZATION: { if (!allParametersPresent(5, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; int32_t radius = getScalarData<int32_t>(mOperands[ins[1]]); float bias = getScalarData<float>(mOperands[ins[2]]); float alpha = getScalarData<float>(mOperands[ins[3]]); float beta = getScalarData<float>(mOperands[ins[4]]); RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = genericNormalizationPrepare(input.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && localResponseNormFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), radius, bias, alpha, beta, reinterpret_cast<float*>(output.buffer), outShape); } } break; case OperationType::RESHAPE: { if (!allParametersPresent(2, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; const RunTimeOperandInfo& targetShape = mOperands[ins[1]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); success = reshapePrepare(input.shape(), reinterpret_cast<const int32_t*>(targetShape.buffer), getNumberOfElements(targetShape.shape()), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && reshapeGeneric(reinterpret_cast<const void*>(input.buffer), input.shape(), reinterpret_cast<void*>(output.buffer), outShape); } break; case OperationType::RESIZE_BILINEAR: { if (!allParametersPresent(3, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; int32_t width = getScalarData<int32_t>(mOperands[ins[1]]); int32_t height = getScalarData<int32_t>(mOperands[ins[2]]); RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); if (input.type == OperandType::TENSOR_FLOAT32) { success = resizeBilinearPrepare(input.shape(), width, height, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && resizeBilinearFloat32(reinterpret_cast<const float*>(input.buffer), input.shape(), reinterpret_cast<float*>(output.buffer), outShape); } } break; case OperationType::DEPTH_TO_SPACE: { if (!allParametersPresent(2, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; int32_t blockSize = getScalarData<int32_t>(mOperands[ins[1]]); RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); success = depthToSpacePrepare(input.shape(), blockSize, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && depthToSpaceGeneric(input.buffer, input.shape(), blockSize, output.buffer, outShape); } break; case OperationType::SPACE_TO_DEPTH: { if (!allParametersPresent(2, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; int32_t blockSize = getScalarData<int32_t>(mOperands[ins[1]]); RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); success = spaceToDepthPrepare(input.shape(), blockSize, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && spaceToDepthGeneric(input.buffer, input.shape(), blockSize, output.buffer, outShape); } break; case OperationType::EMBEDDING_LOOKUP: { const RunTimeOperandInfo &values = mOperands[ins[EmbeddingLookup::kValueTensor]]; const RunTimeOperandInfo &lookups = mOperands[ins[EmbeddingLookup::kLookupTensor]]; RunTimeOperandInfo &output = mOperands[outs[EmbeddingLookup::kOutputTensor]]; Shape outputShape; EmbeddingLookup lookup(operation, mOperands); success = embeddingLookupPrepare(values.shape(), lookups.shape(), &outputShape) && setInfoAndAllocateIfNeeded(&output, outputShape) && lookup.Eval(); } break; case OperationType::HASHTABLE_LOOKUP: { const RunTimeOperandInfo &lookups = mOperands[ins[HashtableLookup::kLookupTensor]]; const RunTimeOperandInfo &keys = mOperands[ins[HashtableLookup::kKeyTensor]]; const RunTimeOperandInfo &values = mOperands[ins[HashtableLookup::kValueTensor]]; RunTimeOperandInfo &output = mOperands[outs[HashtableLookup::kOutputTensor]]; RunTimeOperandInfo &hits = mOperands[outs[HashtableLookup::kHitsTensor]]; Shape outputShape, hitShape; HashtableLookup lookup(operation, mOperands); success = hashtableLookupPrepare(lookups.shape(), keys.shape(), values.shape(), &outputShape, &hitShape) && setInfoAndAllocateIfNeeded(&output, outputShape) && setInfoAndAllocateIfNeeded(&hits, hitShape) && lookup.Eval(); } break; case OperationType::LSH_PROJECTION: { RunTimeOperandInfo &output = mOperands[outs[LSHProjection::kOutputTensor]]; Shape outputShape; LSHProjection lsh(operation, mOperands); success = LSHProjection::Prepare(operation, mOperands, &outputShape) && setInfoAndAllocateIfNeeded(&output, outputShape) && lsh.Eval(); } break; case OperationType::LSTM: { RunTimeOperandInfo &scratch = mOperands[outs[LSTMCell::kScratchBufferTensor]]; RunTimeOperandInfo &outputStateOut = mOperands[outs[LSTMCell::kOutputStateOutTensor]]; RunTimeOperandInfo &cellStateOut = mOperands[outs[LSTMCell::kCellStateOutTensor]]; RunTimeOperandInfo &output = mOperands[outs[LSTMCell::kOutputTensor]]; Shape scratchShape, outputStateShape, cellStateShape, outputShape; LSTMCell lstm_cell(operation, mOperands); success = LSTMCell::Prepare(operation, mOperands, &scratchShape, &outputStateShape, &cellStateShape, &outputShape) && setInfoAndAllocateIfNeeded(&scratch, scratchShape) && setInfoAndAllocateIfNeeded(&outputStateOut, outputStateShape) && setInfoAndAllocateIfNeeded(&cellStateOut, cellStateShape) && setInfoAndAllocateIfNeeded(&output, outputShape) && lstm_cell.Eval(); } break; case OperationType::RNN: { RunTimeOperandInfo &hiddenStateOut = mOperands[outs[RNN::kHiddenStateOutTensor]]; RunTimeOperandInfo &output = mOperands[outs[RNN::kOutputTensor]]; Shape hiddenStateShape, outputShape; RNN rnn_cell(operation, mOperands); success = RNN::Prepare(operation, mOperands, &hiddenStateShape, &outputShape) && setInfoAndAllocateIfNeeded(&hiddenStateOut, hiddenStateShape) && setInfoAndAllocateIfNeeded(&output, outputShape) && rnn_cell.Eval(); } break; case OperationType::SVDF: { RunTimeOperandInfo &stateOut = mOperands[outs[SVDF::kStateOutTensor]]; RunTimeOperandInfo &output = mOperands[outs[SVDF::kOutputTensor]]; Shape stateShape, outputShape; SVDF svdf(operation, mOperands); success = SVDF::Prepare(operation, mOperands, &stateShape, &outputShape) && setInfoAndAllocateIfNeeded(&stateOut, stateShape) && setInfoAndAllocateIfNeeded(&output, outputShape) && svdf.Eval(); } break; case OperationType::BATCH_TO_SPACE_ND: { if (!allParametersPresent(2, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; const RunTimeOperandInfo& blockSize = mOperands[ins[1]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); success = batchToSpacePrepare(input.shape(), reinterpret_cast<const int32_t*>(blockSize.buffer), blockSize.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && batchToSpaceGeneric(input.buffer, input.shape(), reinterpret_cast<const int32_t*>(blockSize.buffer), output.buffer, outShape); } break; case OperationType::SPACE_TO_BATCH_ND: { if (!allParametersPresent(3, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; const RunTimeOperandInfo& blockSize = mOperands[ins[1]]; const RunTimeOperandInfo& paddings = mOperands[ins[2]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); success = spaceToBatchPrepare(input.shape(), reinterpret_cast<const int32_t*>(blockSize.buffer), blockSize.shape(), reinterpret_cast<const int32_t*>(paddings.buffer), paddings.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && spaceToBatchGeneric(input.buffer, input.shape(), reinterpret_cast<const int32_t*>(blockSize.buffer), reinterpret_cast<const int32_t*>(paddings.buffer), paddings.shape(), output.buffer, outShape); } break; case OperationType::PAD: { if (!allParametersPresent(2, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; const RunTimeOperandInfo& paddings = mOperands[ins[1]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); success = padPrepare(input.shape(), reinterpret_cast<const int32_t*>(paddings.buffer), paddings.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && padGeneric(input.buffer, input.shape(), reinterpret_cast<const int32_t*>(paddings.buffer), output.buffer, outShape); } break; case OperationType::SQUEEZE: { if (!allParametersPresent(2, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; const RunTimeOperandInfo& squeezeDims = mOperands[ins[1]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); success = squeezePrepare(input.shape(), reinterpret_cast<const int32_t*>(squeezeDims.buffer), squeezeDims.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && squeezeGeneric(input.buffer, input.shape(), output.buffer, outShape); } break; case OperationType::TRANSPOSE: { if (!allParametersPresent(2, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; const RunTimeOperandInfo& perms = mOperands[ins[1]]; RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); success = transposePrepare(input.shape(), reinterpret_cast<const int32_t*>(perms.buffer), perms.shape(), &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && transposeGeneric(input.buffer, input.shape(), reinterpret_cast<const int32_t*>(perms.buffer), perms.shape(), output.buffer, outShape); } break; case OperationType::STRIDED_SLICE: { if (!allParametersPresent(7, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; const RunTimeOperandInfo& begins = mOperands[ins[1]]; const RunTimeOperandInfo& ends = mOperands[ins[2]]; const RunTimeOperandInfo& strides = mOperands[ins[3]]; int32_t beginMask = getScalarData<int32_t>(mOperands[ins[4]]); int32_t endMask = getScalarData<int32_t>(mOperands[ins[5]]); int32_t shrinkAxisMask = getScalarData<int32_t>(mOperands[ins[6]]); RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); success = stridedSlicePrepare(input.shape(), reinterpret_cast<const int32_t*>(begins.buffer), begins.shape(), reinterpret_cast<const int32_t*>(ends.buffer), ends.shape(), reinterpret_cast<const int32_t*>(strides.buffer), strides.shape(), beginMask, endMask, shrinkAxisMask, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && stridedSliceGeneric(input.buffer, input.shape(), reinterpret_cast<const int32_t*>(begins.buffer), reinterpret_cast<const int32_t*>(ends.buffer), reinterpret_cast<const int32_t*>(strides.buffer), beginMask, endMask, shrinkAxisMask, output.buffer, outShape); } break; case OperationType::DIV: { if (!allParametersPresent(3, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& in1 = mOperands[ins[0]]; const RunTimeOperandInfo& in2 = mOperands[ins[1]]; int32_t activation = getScalarData<int32_t>(mOperands[ins[2]]); RunTimeOperandInfo& out = mOperands[outs[0]]; Shape outShape = out.shape(); if (in1.type == OperandType::TENSOR_FLOAT32) { success = addMulPrepare(in1.shape(), in2.shape(), &outShape) && setInfoAndAllocateIfNeeded(&out, outShape) && divFloat32(reinterpret_cast<const float*>(in1.buffer), in1.shape(), reinterpret_cast<const float*>(in2.buffer), in2.shape(), activation, reinterpret_cast<float*>(out.buffer), outShape); } } break; case OperationType::SUB: { if (!allParametersPresent(3, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& in1 = mOperands[ins[0]]; const RunTimeOperandInfo& in2 = mOperands[ins[1]]; int32_t activation = getScalarData<int32_t>(mOperands[ins[2]]); RunTimeOperandInfo& out = mOperands[outs[0]]; Shape outShape = out.shape(); if (in1.type == OperandType::TENSOR_FLOAT32) { success = addMulPrepare(in1.shape(), in2.shape(), &outShape) && setInfoAndAllocateIfNeeded(&out, outShape) && subFloat32(reinterpret_cast<const float*>(in1.buffer), in1.shape(), reinterpret_cast<const float*>(in2.buffer), in2.shape(), activation, reinterpret_cast<float*>(out.buffer), outShape); } } break; case OperationType::MEAN: { if (!allParametersPresent(3, 1)) { return ANEURALNETWORKS_BAD_DATA; } const RunTimeOperandInfo& input = mOperands[ins[0]]; const RunTimeOperandInfo& axis = mOperands[ins[1]]; int32_t keepDims = getScalarData<int32_t>(mOperands[ins[2]]); RunTimeOperandInfo& output = mOperands[outs[0]]; Shape outShape = output.shape(); success = meanPrepare(input.shape(), reinterpret_cast<const int32_t*>(axis.buffer), axis.shape(), keepDims > 0, &outShape) && setInfoAndAllocateIfNeeded(&output, outShape) && meanGeneric(input.buffer, input.shape(), reinterpret_cast<const int32_t*>(axis.buffer), axis.shape(), keepDims > 0, output.buffer, outShape); } break; default: nnAssert(false); break; } if (!success) { LOG(ERROR) << getOperationName(operation.type) << " failed."; return ANEURALNETWORKS_OP_FAILED; } freeNoLongerUsedOperands(ins); return ANEURALNETWORKS_NO_ERROR; } } // namespace nn } // namespace android
50.603257
100
0.497953
[ "shape", "vector", "model" ]
283e81224670c795dac9068246ff2cf09b244955
206
cpp
C++
source/Graph/Core/Series.Domain.cpp
FinIsOro/grapher
dfeabdf7bc25dbb3c45705bde2f5f645ba9cb2e6
[ "MIT" ]
null
null
null
source/Graph/Core/Series.Domain.cpp
FinIsOro/grapher
dfeabdf7bc25dbb3c45705bde2f5f645ba9cb2e6
[ "MIT" ]
null
null
null
source/Graph/Core/Series.Domain.cpp
FinIsOro/grapher
dfeabdf7bc25dbb3c45705bde2f5f645ba9cb2e6
[ "MIT" ]
null
null
null
#include <Graph/Core/Series.hpp> namespace graph { const std::vector<float>& Series::Domain::values() const { return _values; } size_t Series::Domain::length() const { return _values.size(); } }
14.714286
57
0.679612
[ "vector" ]
2844680c362dd60e23904054a9bb939e1c0730b0
2,792
cpp
C++
api/gmxapi/cpp/workflow/tests/workflow.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
384
2015-01-02T19:44:15.000Z
2022-03-27T15:13:15.000Z
api/gmxapi/cpp/workflow/tests/workflow.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
9
2015-04-07T20:48:00.000Z
2022-01-24T21:29:26.000Z
api/gmxapi/cpp/workflow/tests/workflow.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
258
2015-01-19T11:19:57.000Z
2022-03-18T08:59:52.000Z
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #include <memory> #include "workflow.h" #include "workflow_impl.h" #include "testingconfiguration.h" namespace gmxapi { namespace testing { namespace { //! Create a work spec, then the implementation graph, then the container TEST_F(GmxApiTest, BuildApiWorkflowImpl) { makeTprFile(100); // Create work spec auto node = std::make_unique<gmxapi::MDNodeSpecification>(runner_.tprFileName_); EXPECT_NE(node, nullptr); // Create key std::string key{ "MD" }; key.append(runner_.tprFileName_); // Create graph (workflow implementation object) gmxapi::Workflow::Impl impl; impl[key] = std::move(node); EXPECT_EQ(impl.count(key), 1); EXPECT_EQ(impl.size(), 1); // Create workflow container EXPECT_NO_THROW(gmxapi::Workflow work{ std::move(impl) }); } //! Create from create() method(s) TEST_F(GmxApiTest, CreateApiWorkflow) { makeTprFile(100); auto work = gmxapi::Workflow::create(runner_.tprFileName_); EXPECT_NE(work, nullptr); } } // end anonymous namespace } // end namespace testing } // end namespace gmxapi
32.465116
84
0.727794
[ "object" ]
28452eaaa5264b1ab6d78543590d0cf44bb1344c
13,304
hpp
C++
Hakken/Pods/Realm/include-ios/tightdb/util/bind.hpp
ssathy2/Hakken
3bef6400d08faf9a2b0f12a97c9d9272af6d6cf4
[ "MIT" ]
4
2015-06-17T20:26:08.000Z
2015-07-02T02:10:12.000Z
Hakken/Pods/Realm/include-ios/tightdb/util/bind.hpp
ssathy2/Hakken
3bef6400d08faf9a2b0f12a97c9d9272af6d6cf4
[ "MIT" ]
null
null
null
Hakken/Pods/Realm/include-ios/tightdb/util/bind.hpp
ssathy2/Hakken
3bef6400d08faf9a2b0f12a97c9d9272af6d6cf4
[ "MIT" ]
null
null
null
/************************************************************************* * * TIGHTDB CONFIDENTIAL * __________________ * * [2011] - [2012] TightDB Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of TightDB Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to TightDB Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from TightDB Incorporated. * **************************************************************************/ #ifndef TIGHTDB_UTIL_BIND_HPP #define TIGHTDB_UTIL_BIND_HPP namespace tightdb { namespace _impl { template<class A> class FunOneArgBinder0 { public: FunOneArgBinder0(void (*fun)(A), const A& a): m_fun(fun), m_a(a) { } void operator()() const { (*m_fun)(m_a); } private: void (*const m_fun)(A); const A m_a; }; template<class A, class B> class FunOneArgBinder1 { public: FunOneArgBinder1(void (*fun)(A,B), const A& a): m_fun(fun), m_a(a) { } void operator()(B b) const { (*m_fun)(m_a, b); } private: void (*const m_fun)(A,B); const A m_a; }; template<class A, class B, class C> class FunOneArgBinder2 { public: FunOneArgBinder2(void (*fun)(A,B,C), const A& a): m_fun(fun), m_a(a) { } void operator()(B b, C c) const { (*m_fun)(m_a, b, c); } private: void (*const m_fun)(A,B,C); const A m_a; }; template<class A, class B> class FunTwoArgBinder0 { public: FunTwoArgBinder0(void (*fun)(A,B), const A& a, const B& b): m_fun(fun), m_a(a), m_b(b) { } void operator()() const { (*m_fun)(m_a, m_b); } private: void (*const m_fun)(A,B); const A m_a; const B m_b; }; template<class A, class B, class C> class FunTwoArgBinder1 { public: FunTwoArgBinder1(void (*fun)(A,B,C), const A& a, const B& b): m_fun(fun), m_a(a), m_b(b) { } void operator()(C c) const { (*m_fun)(m_a, m_b, c); } private: void (*const m_fun)(A,B,C); const A m_a; const B m_b; }; template<class A, class B, class C, class D> class FunTwoArgBinder2 { public: FunTwoArgBinder2(void (*fun)(A,B,C,D), const A& a, const B& b): m_fun(fun), m_a(a), m_b(b) { } void operator()(C c, D d) const { (*m_fun)(m_a, m_b, c, d); } private: void (*const m_fun)(A,B,C,D); const A m_a; const B m_b; }; template<class A, class B, class C> class FunThreeArgBinder0 { public: FunThreeArgBinder0(void (*fun)(A,B,C), const A& a, const B& b, const C& c): m_fun(fun), m_a(a), m_b(b), m_c(c) { } void operator()() const { (*m_fun)(m_a, m_b, m_c); } private: void (*const m_fun)(A,B,C); const A m_a; const B m_b; const C m_c; }; template<class A, class B, class C, class D> class FunThreeArgBinder1 { public: FunThreeArgBinder1(void (*fun)(A,B,C,D), const A& a, const B& b, const C& c): m_fun(fun), m_a(a), m_b(b), m_c(c) { } void operator()(D d) const { (*m_fun)(m_a, m_b, m_c, d); } private: void (*const m_fun)(A,B,C,D); const A m_a; const B m_b; const C m_c; }; template<class A, class B, class C, class D, class E> class FunThreeArgBinder2 { public: FunThreeArgBinder2(void (*fun)(A,B,C,D,E), const A& a, const B& b, const C& c): m_fun(fun), m_a(a), m_b(b), m_c(c) { } void operator()(D d, E e) const { (*m_fun)(m_a, m_b, m_c, d, e); } private: void (*const m_fun)(A,B,C,D,E); const A m_a; const B m_b; const C m_c; }; template<class O> class MemFunObjZeroArgBinder0 { public: MemFunObjZeroArgBinder0(void (O::*mem_fun)(), O* obj): m_mem_fun(mem_fun), m_obj(obj) { } void operator()() const { (m_obj->*m_mem_fun)(); } private: void (O::*const m_mem_fun)(); O* const m_obj; }; template<class O, class A> class MemFunObjZeroArgBinder1 { public: MemFunObjZeroArgBinder1(void (O::*mem_fun)(A), O* obj): m_mem_fun(mem_fun), m_obj(obj) { } void operator()(A a) const { (m_obj->*m_mem_fun)(a); } private: void (O::*const m_mem_fun)(A); O* const m_obj; }; template<class O, class A, class B> class MemFunObjZeroArgBinder2 { public: MemFunObjZeroArgBinder2(void (O::*mem_fun)(A,B), O* obj): m_mem_fun(mem_fun), m_obj(obj) { } void operator()(A a, B b) const { (m_obj->*m_mem_fun)(a,b); } private: void (O::*const m_mem_fun)(A,B); O* const m_obj; }; template<class O, class A> class MemFunObjOneArgBinder0 { public: MemFunObjOneArgBinder0(void (O::*mem_fun)(A), O* obj, const A& a): m_mem_fun(mem_fun), m_obj(obj), m_a(a) { } void operator()() const { (m_obj->*m_mem_fun)(m_a); } private: void (O::*const m_mem_fun)(A); O* const m_obj; const A m_a; }; template<class O, class A, class B> class MemFunObjOneArgBinder1 { public: MemFunObjOneArgBinder1(void (O::*mem_fun)(A,B), O* obj, const A& a): m_mem_fun(mem_fun), m_obj(obj), m_a(a) { } void operator()(B b) const { (m_obj->*m_mem_fun)(m_a, b); } private: void (O::*const m_mem_fun)(A,B); O* const m_obj; const A m_a; }; template<class O, class A, class B, class C> class MemFunObjOneArgBinder2 { public: MemFunObjOneArgBinder2(void (O::*mem_fun)(A,B,C), O* obj, const A& a): m_mem_fun(mem_fun), m_obj(obj), m_a(a) { } void operator()(B b, C c) const { (m_obj->*m_mem_fun)(m_a, b, c); } private: void (O::*const m_mem_fun)(A,B,C); O* const m_obj; const A m_a; }; template<class O, class A, class B> class MemFunObjTwoArgBinder0 { public: MemFunObjTwoArgBinder0(void (O::*mem_fun)(A,B), O* obj, const A& a, const B& b): m_mem_fun(mem_fun), m_obj(obj), m_a(a), m_b(b) { } void operator()() const { (m_obj->*m_mem_fun)(m_a, m_b); } private: void (O::*const m_mem_fun)(A,B); O* const m_obj; const A m_a; const B m_b; }; template<class O, class A, class B, class C> class MemFunObjTwoArgBinder1 { public: MemFunObjTwoArgBinder1(void (O::*mem_fun)(A,B,C), O* obj, const A& a, const B& b): m_mem_fun(mem_fun), m_obj(obj), m_a(a), m_b(b) { } void operator()(C c) const { (m_obj->*m_mem_fun)(m_a, m_b, c); } private: void (O::*const m_mem_fun)(A,B,C); O* const m_obj; const A m_a; const B m_b; }; template<class O, class A, class B, class C, class D> class MemFunObjTwoArgBinder2 { public: MemFunObjTwoArgBinder2(void (O::*mem_fun)(A,B,C,D), O* obj, const A& a, const B& b): m_mem_fun(mem_fun), m_obj(obj), m_a(a), m_b(b) { } void operator()(C c, D d) const { (m_obj->*m_mem_fun)(m_a, m_b, c, d); } private: void (O::*const m_mem_fun)(A,B,C,D); O* const m_obj; const A m_a; const B m_b; }; } // namespace _impl namespace util { /// Produce a nullary function by binding the argument of a unary /// function. template<class A> inline _impl::FunOneArgBinder0<A> bind(void (*fun)(A), const A& a) { return _impl::FunOneArgBinder0<A>(fun, a); } /// Produce a unary function by binding the first argument of a binary /// function. template<class A, class B> inline _impl::FunOneArgBinder1<A,B> bind(void (*fun)(A,B), const A& a) { return _impl::FunOneArgBinder1<A,B>(fun, a); } /// Produce a binary function by binding the first argument of a /// ternary function. template<class A, class B, class C> inline _impl::FunOneArgBinder2<A,B,C> bind(void (*fun)(A,B,C), const A& a) { return _impl::FunOneArgBinder2<A,B,C>(fun, a); } /// Produce a nullary function by binding both arguments of a binary /// function. template<class A, class B> inline _impl::FunTwoArgBinder0<A,B> bind(void (*fun)(A,B), const A& a, const B& b) { return _impl::FunTwoArgBinder0<A,B>(fun, a, b); } /// Produce a unary function by binding the first two arguments of a /// ternary function. template<class A, class B, class C> inline _impl::FunTwoArgBinder1<A,B,C> bind(void (*fun)(A,B,C), const A& a, const B& b) { return _impl::FunTwoArgBinder1<A,B,C>(fun, a, b); } /// Produce a binary function by binding the first two arguments of a /// quaternary function (4-ary). template<class A, class B, class C, class D> inline _impl::FunTwoArgBinder2<A,B,C,D> bind(void (*fun)(A,B,C,D), const A& a, const B& b) { return _impl::FunTwoArgBinder2<A,B,C,D>(fun, a, b); } /// Produce a nullary function by binding all three arguments of a /// ternary function. template<class A, class B, class C> inline _impl::FunThreeArgBinder0<A,B,C> bind(void (*fun)(A,B,C), const A& a, const B& b, const C& c) { return _impl::FunThreeArgBinder0<A,B,C>(fun, a, b, c); } /// Produce a unary function by binding the first three arguments of a /// quaternary function (4-ary). template<class A, class B, class C, class D> inline _impl::FunThreeArgBinder1<A,B,C,D> bind(void (*fun)(A,B,C,D), const A& a, const B& b, const C& c) { return _impl::FunThreeArgBinder1<A,B,C,D>(fun, a, b, c); } /// Produce a binary function by binding the first three arguments of /// a quinary function (5-ary). template<class A, class B, class C, class D, class E> inline _impl::FunThreeArgBinder2<A,B,C,D,E> bind(void (*fun)(A,B,C,D,E), const A& a, const B& b, const C& c) { return _impl::FunThreeArgBinder2<A,B,C,D,E>(fun, a, b, c); } /// Produce a nullary function by binding the object of a nullary /// class member function. template<class O> inline _impl::MemFunObjZeroArgBinder0<O> bind(void (O::*mem_fun)(), O* obj) { return _impl::MemFunObjZeroArgBinder0<O>(mem_fun, obj); } /// Produce a unary function by binding the object of a unary class /// member function. template<class O, class A> inline _impl::MemFunObjZeroArgBinder1<O,A> bind(void (O::*mem_fun)(A), O* obj) { return _impl::MemFunObjZeroArgBinder1<O,A>(mem_fun, obj); } /// Produce a binary function by binding the object of a binary class /// member function. template<class O, class A, class B> inline _impl::MemFunObjZeroArgBinder2<O,A,B> bind(void (O::*mem_fun)(A,B), O* obj) { return _impl::MemFunObjZeroArgBinder2<O,A,B>(mem_fun, obj); } /// Produce a nullary function by binding the object and the argument /// of a unary class member function. template<class O, class A> inline _impl::MemFunObjOneArgBinder0<O,A> bind(void (O::*mem_fun)(A), O* obj, const A& a) { return _impl::MemFunObjOneArgBinder0<O,A>(mem_fun, obj, a); } /// Produce a unary function by binding the object and first argument /// of a binary class member function. template<class O, class A, class B> inline _impl::MemFunObjOneArgBinder1<O,A,B> bind(void (O::*mem_fun)(A,B), O* obj, const A& a) { return _impl::MemFunObjOneArgBinder1<O,A,B>(mem_fun, obj, a); } /// Produce a binary function by binding the object and first argument /// of a ternary class member function. template<class O, class A, class B, class C> inline _impl::MemFunObjOneArgBinder2<O,A,B,C> bind(void (O::*mem_fun)(A,B,C), O* obj, const A& a) { return _impl::MemFunObjOneArgBinder2<O,A,B,C>(mem_fun, obj, a); } /// Produce a nullary function by binding the object and both /// arguments of a binary class member function. template<class O, class A, class B> inline _impl::MemFunObjTwoArgBinder0<O,A,B> bind(void (O::*mem_fun)(A,B), O* obj, const A& a, const B& b) { return _impl::MemFunObjTwoArgBinder0<O,A,B>(mem_fun, obj, a, b); } /// Produce a unary function by binding the object and the first two /// arguments of a ternary class member function. template<class O, class A, class B, class C> inline _impl::MemFunObjTwoArgBinder1<O,A,B,C> bind(void (O::*mem_fun)(A,B,C), O* obj, const A& a, const B& b) { return _impl::MemFunObjTwoArgBinder1<O,A,B,C>(mem_fun, obj, a, b); } /// Produce a binary function by binding the object and the first two /// arguments of a quaternary class member function (4-ary). template<class O, class A, class B, class C, class D> inline _impl::MemFunObjTwoArgBinder2<O,A,B,C,D> bind(void (O::*mem_fun)(A,B,C,D), O* obj, const A& a, const B& b) { return _impl::MemFunObjTwoArgBinder2<O,A,B,C,D>(mem_fun, obj, a, b); } } // namespace util } // namespace tightdb #endif // TIGHTDB_UTIL_BIND_HPP
24.820896
97
0.598918
[ "object" ]
28470664523efd2f2499f16b3db8060d17879be8
1,286
cpp
C++
getTimeOfDayClass.cpp
gampu/Practice
455a686d3266dea6546401f4a1275f22106a44ce
[ "MIT" ]
null
null
null
getTimeOfDayClass.cpp
gampu/Practice
455a686d3266dea6546401f4a1275f22106a44ce
[ "MIT" ]
null
null
null
getTimeOfDayClass.cpp
gampu/Practice
455a686d3266dea6546401f4a1275f22106a44ce
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<string> #include<algorithm> #include<cstdlib> #include<cassert> #include<unistd.h> #include<string.h> #include<sys/time.h> #include<fcntl.h> #include<sys/utsname.h> #include<sys/ioctl.h> #include<sys/inotify.h> #include<sched.h> #include<signal.h> #include<thread> /* Practice code to understand gettimeofday syscall with OOP design */ /* Environment pointer */ char **environ; /* Error function */ void err( const char *str ) { std::cout << errno << "\n"; perror( str ); exit( 0 ); } /* Time Class */ class Time { public: /* Structure to store time at instantiation*/ struct timeval t; Time( void ) { /* Get current time and store it in t */ if( gettimeofday( &t, NULL ) != 0 ) { /* If problem occurs, throw runtime error */ throw std::runtime_error( "gettimeofday" ); } } /* A friendly member function to output the timeval struct */ friend std::ostream& operator<<( std::ostream& out, const Time& T ) { out << T.t.tv_sec << " " << T.t.tv_usec << "\n"; return out; } }; int main( int argc, char *argv[] ) { /* Create a time object and output it */ Time t; std::cout << t << "\n"; return 0; }
20.412698
71
0.594868
[ "object", "vector" ]
2849b0720c9eabcfbfc0401083b5bf2352988400
798
cpp
C++
src/monte_carlo/distribution1d.cpp
Twinklebear/tray
eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b
[ "MIT" ]
61
2015-01-01T10:58:21.000Z
2022-01-05T14:22:15.000Z
src/monte_carlo/distribution1d.cpp
Twinklebear/tray
eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b
[ "MIT" ]
null
null
null
src/monte_carlo/distribution1d.cpp
Twinklebear/tray
eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b
[ "MIT" ]
3
2016-04-11T19:07:47.000Z
2018-05-31T12:40:50.000Z
#include <cmath> #include <algorithm> #include "monte_carlo/distribution1d.h" Distribution1D::Distribution1D(const std::vector<float> &fcn) : function(fcn), cdf(function.size() + 1), integral(0) { //Compute the integral of the function for (size_t i = 1; i < cdf.size(); ++i){ cdf[i] = cdf[i - 1] + function[i - 1] / function.size(); } integral = cdf.back(); //Normalize the CDF by the integral for (auto &c : cdf){ c /= integral; } } Distribution1D::Distribution1D(){} int Distribution1D::sample_discrete(float u, float *pdf_val) const { auto a = std::lower_bound(cdf.begin(), cdf.end(), u); int b = std::min(static_cast<int>(std::distance(cdf.begin(), a)), static_cast<int>(cdf.size() - 2)); if (pdf_val){ *pdf_val = function[b] / (integral * function.size()); } return b; }
28.5
101
0.660401
[ "vector" ]
284ae6ed2640397b24d322941d808509643b7b3a
17,445
cpp
C++
Eudora71/Eudora/MimeStorage.cpp
dusong7/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
10
2018-05-23T10:43:48.000Z
2021-12-02T17:59:48.000Z
Eudora71/Eudora/MimeStorage.cpp
dusong7/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
1
2019-03-19T03:56:36.000Z
2021-05-26T18:36:03.000Z
Eudora71/Eudora/MimeStorage.cpp
evilneuro/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
11
2018-05-23T10:43:53.000Z
2021-12-27T15:42:58.000Z
// MimeStorage.cpp // // Copyright (c) 1997-2000 by QUALCOMM, Incorporated /* Copyright (c) 2016, Computer History Museum All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) 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 Computer History Museum nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // #include "stdafx.h" #include "etf2html.h" #include "Eudora.h" #include "Fileutil.h" #include "msgutils.h" #include "MimeStorage.h" #include "ContentConcentrator.h" #include "resource.h" #include "rs.h" #include "rpc.h" #include "trnslate.h" #include "Text2HTML.h" #include "QCGraphics.h" #include "utils.h" #include "msgdoc.h" #include "summary.h" #include "tocdoc.h" #include "DebugNewHelpers.h" /***** QCMessage Implementation *****/ QCMessage::QCMessage(CMessageDoc* ParentDoc) { m_ParentDoc = ParentDoc; m_theMess = NULL; m_HasHeaders = TRUE; } QCMessage::~QCMessage() { delete [] m_theMess; } RESULT QCMessage::Init( const char * messageid, const char * buf, BOOL HeadersIncluded ) { m_HasHeaders = HeadersIncluded; // used as seed for CID generation m_MessageId = messageid; // make a copy of the message delete [] m_theMess; m_theMess = DEBUG_NEW_NOTHROW char[ strlen( buf ) + 1 ]; if ( ! m_theMess ) return ERR_BAD_NEW; #ifdef _DEBUG { char szName[126] = "QCMsg: "; char *sub = HeaderContents(IDS_HEADER_SUBJECT, buf); if(!sub) sub = HeaderContents(IDS_HEADER_FROM, buf); if(sub) strncpy(szName+strlen(szName), sub, 26); else strncpy(szName+strlen(szName), buf, 26); delete [] sub; } #endif // save off the message text memcpy( m_theMess, buf, strlen( buf ) + 1 ); // create a list of "Embedded Content" m_theMap.BuildURIMap( m_theMess ); return SUCCESS; } RESULT QCMessage::InitMap( const char * ECHeaders ) { m_theMap.BuildURIMap( ECHeaders ); return SUCCESS; } void QCMessage::InitMap(URIMap & in_sourceMap) { m_theMap.FreeURIMap(); in_sourceMap.TransferMembers(m_theMap); m_theMap.NukeCIDs(); } // Empty the dest message's map, then transfer all contents // of our map to dest. void QCMessage::TransferMap(QCMessage & dest) { dest.m_theMap.FreeURIMap(); m_theMap.TransferMembers(dest.m_theMap); } RESULT QCMessage::Flush() { delete [] m_theMess; m_theMess = NULL; m_MessageId.Empty(); m_CIDReference = 0; m_HasHeaders = TRUE; m_theMap.FreeURIMap(); return SUCCESS; } RESULT QCMessage::NukeCIDs() { m_theMap.NukeCIDs(); return SUCCESS; } RESULT QCMessage::IsRealCID( const char * CID ) { if( m_theMap.IsRealCID( CID ) ) return SUCCESS; return ERR_NOT_CID; } // where id is a URI RESULT QCMessage::GetPart( PART_ID id, QCMimePart ** ppPart ) { *ppPart = NULL; // lookup the part char path[ MAX_PATH ]; m_theMap.ResolveURIToPath( id, path, sizeof( path ) ); if ( *path ) { *ppPart = DEBUG_NEW_MFCOBJ_NOTHROW QCMimePart( id, path, _O_RDONLY ); if ( *ppPart ) return SUCCESS; } return ERR_BAD_CREATE; } // where id is a URI, and pPath is filled with a full path to the "guts" // of the part. ** this hack by Ben ** RESULT QCMessage::GetPartAsFile( PART_ID id, char* pPath, int pathLen, bool bValidateFile ) { // lookup the part (ResolveURI won't stuff all over pPath unless // it gets somethin' worth sniffin'.) if ( m_theMap.ResolveURIToPath( id, pPath, pathLen, bValidateFile ) ) return SUCCESS; else return ERR_BAD_CREATE; } RESULT QCMessage::AddPart( const char * path, // use an existing file QCMimePart ** ppPart, bool bIsEmoticon) { // create a URLMap entry/CID for the part char cid[ 256 ]; if ( m_theMap.AddCIDMap(m_MessageId, path, cid, sizeof(cid), bIsEmoticon) ) { *ppPart = DEBUG_NEW_MFCOBJ_NOTHROW QCMimePart( cid, (LPCTSTR)path, _O_RDWR | _O_EXCL ); if ( *ppPart ) return SUCCESS; } return ERR_BAD_CREATE; } RESULT QCMessage::RemovePart( PART_ID pid ) { RESULT r = ERR_BAD_DELETE; QCMimePart* p = 0; if ( SUCCEEDED(r = GetPart( pid, &p )) ) { if ( SUCCEEDED(r = p->Delete()) ) { // remove the cid map entry m_theMap.RemoveCIDMap( pid ); delete p; } } return r; } RESULT QCMessage::NewPart( const char * extension, // create a new file with this extension QCMimePart ** ppPart ) { *ppPart = NULL; // create a temp file char EmbeddedDir[_MAX_PATH + 1]; wsprintf(EmbeddedDir,"%s%s",(const char *)EudoraDir, (const char *)CRString(IDS_EMBEDDED_FOLDER)); // use an extension based on content-type char tmpPath[_MAX_PATH]; GetTmpFile( EmbeddedDir, extension, tmpPath ); // create a URLMap entry/CID for the part char cid[ 256 ]; if ( m_theMap.AddCIDMap(m_MessageId, tmpPath, cid, sizeof(cid), false) ) { *ppPart = DEBUG_NEW_MFCOBJ_NOTHROW QCMimePart( cid, tmpPath, _O_CREAT | _O_TRUNC | _O_RDWR ); if ( *ppPart ) return SUCCESS; } return ERR_BAD_CREATE; } RESULT QCMessage::GetRawMessage( CString & Message ) { // return m_theMess including any X-EmbeddedContent headers if ( ! m_theMess ) return ERR_NOT_INIT; Message = m_theMess; return SUCCESS; } RESULT QCMessage::GetFullMessage( CString & Message ) { CRString ECHeader(IDS_HEADER_EMBEDDED_CONTENT); BOOL bInEC = FALSE; // Optimization so that only one large memory allocation // is done instead of lots of small ones Message.ReleaseBuffer(0); Message.GetBuffer(::SafeStrlenMT(m_theMess)); // return m_theMess minus any X-EmbeddedContent headers if ( ! m_theMess ) return ERR_NOT_INIT; char * pLine = m_theMess; char * NextLine; while (*pLine) { // prepare for the next line - skip '\r\n' NextLine = strchr(pLine, '\r'); if (!NextLine) NextLine = pLine + strlen(pLine); else { if (*++NextLine == '\n') NextLine++; } if ( strnicmp( ECHeader, pLine, ECHeader.GetLength()) == 0 ) bInEC = TRUE; else if ( bInEC && strncmp( " <", pLine, 3 ) != 0 ) bInEC = FALSE; // Exit out if we hit the body if (*NextLine == '\r' || *NextLine == '\n') { Message += (bInEC? NextLine : pLine); break; } if ( ! bInEC ) { // Little trick here of temporarily creating a null-terminated string // out of the line in order to save on an extra memory allocation char SaveChar = *NextLine; *NextLine = 0; Message += pLine; *NextLine = SaveChar; } pLine = NextLine; } return SUCCESS; } RESULT QCMessage::GetHeaders( CString & Headers ) { Headers = ""; if ( ! m_theMess ) return ERR_NOT_INIT; const char * pBody = ::FindBody( m_theMess ); if ( pBody ) { Headers = CString( m_theMess, pBody - m_theMess ); } else { Headers = m_theMess; } return SUCCESS; } RESULT QCMessage::GetBody( CString & Body ) { Body = ""; if ( ! m_theMess ) return ERR_NOT_INIT; const char * pBody = ::FindBody( m_theMess ); if ( pBody ) Body = pBody; return SUCCESS; } RESULT QCMessage::GetMessageForDisplay( ContentConcentrator::ContextT in_context, CString & out_szBody, CString * out_pszHeaders, bool * out_bWasConcentrated, bool in_bAlwaysStripHTMLCode, bool in_bStripDocumentLevelTags, bool in_bRelaxLocalFileRefStripping, bool in_bMorphHTML ) { if (out_pszHeaders) out_pszHeaders->Empty(); out_szBody.Empty(); if ( ! m_theMess ) { ASSERT(0); return ERR_NOT_INIT; } CString szConcentratedMessage; const char * szMessageForDisplay = NULL; // We need to be able to determine when we're dealing with a composition message, // whine like crazy if we don't always have the information necessary! ASSERT(m_ParentDoc); ASSERT(m_ParentDoc->m_Sum); // Assume that we're not concentrating bool bWasConcentrated = false; if ( m_ParentDoc && m_ParentDoc->m_Sum ) { // Assume that we'll allow concentration bool bAllowConcentration = true; // Don't allow concentration for full message view composition windows // or any messages in the Out mailbox. if (in_context == ContentConcentrator::kCCFullViewContext) bAllowConcentration = !m_ParentDoc->m_Sum->IsComp(); else bAllowConcentration = (m_ParentDoc->m_Sum->m_TheToc->m_Type != MBT_OUT); if (bAllowConcentration) { bWasConcentrated = ContentConcentrator::Instance()->ConcentrateMessage( in_context, m_ParentDoc->m_Sum, m_theMess, szConcentratedMessage ); if (bWasConcentrated) szMessageForDisplay = static_cast<LPCTSTR>(szConcentratedMessage); } } // Pass back whether or not we concentrated if the caller cares if (out_bWasConcentrated) *out_bWasConcentrated = bWasConcentrated; if (!bWasConcentrated || !szMessageForDisplay) // We didn't concentrate - default to full content szMessageForDisplay = m_theMess; const char * pStartBody; // Find the end of the headers if (m_HasHeaders) { pStartBody = ::FindBody(szMessageForDisplay); if (pStartBody && out_pszHeaders) { int nHeadersLength = pStartBody - szMessageForDisplay; char * szHeadersBuffer = out_pszHeaders->GetBuffer(nHeadersLength); strncpy(szHeadersBuffer, szMessageForDisplay, nHeadersLength); out_pszHeaders->ReleaseBuffer(nHeadersLength); } } else { pStartBody = szMessageForDisplay; } if (!pStartBody) { // Previously SK said: "this one comes up when a new message is open and we process the out.mbx" // So let's try only ASSERT'ing here when it's not for use in composition ASSERT(in_context == ContentConcentrator::kCCNoConcentrationContext); return ERR_NOT_INIT; } ::GetBodyAsHTML( out_szBody, pStartBody, in_bAlwaysStripHTMLCode, in_bStripDocumentLevelTags, in_bRelaxLocalFileRefStripping ); // Build the URI map no matter what, because we'll need it even // if conversion from CID's to local file URLs happens later. URIMap uriMap; int nURIs = uriMap.BuildURIMap(m_theMess); // If we have embeded content, then convert cid's to local file URLs (if the // caller wants us to) and add any orphaned URIs to the body as attachments. if (nURIs) { if (in_bMorphHTML) { // Convert CIDs to local file URLs MorphMHTML(out_szBody, uriMap); } else { // Do much of the work of MorphMHTML, but don't make the results // permanent. Leave out_szBody untouched and discard the cooked // HTML. The only point of this is to figure out which URIs // are orphaned/unreferenced (if any). char * pDiscardCookedHTML = NULL; ConvertURIs(out_szBody, &pDiscardCookedHTML, uriMap); free(pDiscardCookedHTML); } // Add orphaned URIs to the body as attachments. // // Fixes bug where Exchange sometimes incorrectly formats messages using // multipart/related instead of multipart/mixed. To handle this we check // for references to the related parts, and display any unreferenced parts // as attachments. uriMap.AddOrphanedURIsToBodyAsAttachments(out_szBody); } return SUCCESS; } int QCMessage::GetAttachments( CString & Attachments ) { // Body of routine moved to msgutils.cpp for common use. return ::GetAttachments(m_theMess, Attachments); } RESULT QCMessage::GetEmbeddedObjectHeaders(CString & Headers, bool bIncludeEmoticons) { m_theMap.BuildEmbeddedObjectHeaders(Headers, bIncludeEmoticons); return SUCCESS; } RESULT QCMessage::GetEmbeddedObjectPaths( CString & Paths ) { m_theMap.GetEmbeddedObjectPaths( Paths ); return SUCCESS; } /***** QCMimePart Implementation *****/ QCMimePart::QCMimePart( const char * cid, const char * path, int mode ) { m_csCID = cid; m_jjFile.Open( path, mode ); } // use to get at an embedded object RESULT QCMimePart::GetCID( CString& csCID ) { csCID = m_csCID; // BOG: SUCCESS == 0 return (csCID.GetLength() == 0); } RESULT QCMimePart::Seek( INT32 offset, INT32 mode /* = SEEK_SET */ ) { if ( m_jjFile.IsOpen() == S_OK ) { char szLogBuf[256]; sprintf(szLogBuf, "LOGNULL QCMimePart::Seek() JJFileMT::Seek(%ld %ld)", offset, mode); PutDebugLog(DEBUG_MASK_TOC_CORRUPT, szLogBuf); long lNewOffset = 0; if ( SUCCEEDED( m_jjFile.Seek( offset, mode, &lNewOffset ))) return lNewOffset; } return ERR_BAD_OPEN; } RESULT QCMimePart::Tell( INT32 * pOffset ) { if ( m_jjFile.IsOpen() == S_OK ) { long lOffset; if ( SUCCEEDED( m_jjFile.Tell( &lOffset ))) { *pOffset = lOffset; return SUCCESS; } } return ERR_BAD_OPEN; } RESULT QCMimePart::Read( CHAR * buf, INT32 bufsize, INT32 * pRead ) { *pRead = 0; if ( m_jjFile.IsOpen() == S_OK ) { long lRead; if ( SUCCEEDED(m_jjFile.RawRead( buf, bufsize, &lRead ))) { // BOG: yes keith, it was a leap of faith. tried this out, and // darn near filled up my disk. RawRead looks good, at least for // binary stuff. // *pRead = bufsize; // boy, this looks like a leap of faith *pRead = lRead; return SUCCESS; } else return ERR_BAD_READ; } return ERR_BAD_OPEN; } RESULT QCMimePart::Get( CHAR * value ) { if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED( m_jjFile.Get( value ))) return SUCCESS; else return ERR_BAD_READ; } return ERR_BAD_OPEN; } RESULT QCMimePart::Get( INT32 * value ) { if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED( m_jjFile.Get( value ))) return SUCCESS; else return ERR_BAD_READ; } return ERR_BAD_OPEN; } RESULT QCMimePart::Get( UINT32 * value ) { if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED( m_jjFile.Get( (INT32*)value ))) return SUCCESS; else return ERR_BAD_READ; } return ERR_BAD_OPEN; } RESULT QCMimePart::Get( CHAR * buf, INT32 bufsize ) { if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED( m_jjFile.Read( buf, bufsize ))) return SUCCESS; else return ERR_BAD_READ; } return ERR_BAD_OPEN; } RESULT QCMimePart::GetLine( CHAR * str, INT32 bufsize ) { if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED( m_jjFile.GetLine( str, bufsize ))) return SUCCESS; else return ERR_BAD_READ; } return ERR_BAD_OPEN; } // use when creating an embedded part RESULT QCMimePart::Write( CHAR * buf, INT32 bufsize, INT32 * pWritten ) { *pWritten = 0; if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED(m_jjFile.Put( buf, bufsize ))) { *pWritten = bufsize; // another leap of faith return SUCCESS; } else return ERR_BAD_WRITE; } return ERR_BAD_OPEN; } RESULT QCMimePart::Put( CHAR value ) { if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED( m_jjFile.Put( value ))) return SUCCESS; else return ERR_BAD_WRITE; } return ERR_BAD_OPEN; } RESULT QCMimePart::Put( INT32 value ) { if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED( m_jjFile.Put( value ))) return SUCCESS; else return ERR_BAD_WRITE; } return ERR_BAD_OPEN; } RESULT QCMimePart::Put( UINT32 value ) { if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED( m_jjFile.Put( (INT32)value ))) return SUCCESS; else return ERR_BAD_WRITE; } return ERR_BAD_OPEN; } RESULT QCMimePart::Put( const void * str /* = NULL */, INT32 len /* = -1L */ ) { if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED( m_jjFile.Put( (const char *)str, len ))) return SUCCESS; else return ERR_BAD_WRITE; } return ERR_BAD_OPEN; } RESULT QCMimePart::PutLine( const void * str /* = NULL */, INT32 len /* = -1L */ ) { if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED( m_jjFile.Put( (const char *)str, len ))) return SUCCESS; else return ERR_BAD_WRITE; } return ERR_BAD_OPEN; } RESULT QCMimePart::Close() { if ( m_jjFile.IsOpen() == S_OK ) { if ( SUCCEEDED( m_jjFile.Close())) return SUCCESS; else return ERR_BAD_CLOSE; } return ERR_BAD_OPEN; } RESULT QCMimePart::Delete( bool bDeleteAny /*= false*/ ) { char EmbeddedDir[_MAX_PATH + 1]; wsprintf(EmbeddedDir,"%s%s",(const char *)EudoraDir, (const char *)CRString(IDS_EMBEDDED_FOLDER)); CString filename; BSTR badFilename; bool bOurFile = false; if ( SUCCEEDED(m_jjFile.GetFName( &badFilename )) ) { filename = badFilename; if ( strstr( filename, EmbeddedDir ) ) bOurFile = true; ::SysFreeString( badFilename ); } if ( !bOurFile && !bDeleteAny ) return S_OK; else if ( SUCCEEDED(m_jjFile.Delete()) ) return S_OK; else return ERR_BAD_DELETE; }
22.509677
129
0.69722
[ "object" ]
284b4e8a7ccaa1f8025a767001ece432f3b71c87
1,051
cpp
C++
src/tools/peg_t1.cpp
melton1968/cxx-peg
512ad21685fc2c22f6cbd7324cbc02bb66aef687
[ "MIT" ]
null
null
null
src/tools/peg_t1.cpp
melton1968/cxx-peg
512ad21685fc2c22f6cbd7324cbc02bb66aef687
[ "MIT" ]
null
null
null
src/tools/peg_t1.cpp
melton1968/cxx-peg
512ad21685fc2c22f6cbd7324cbc02bb66aef687
[ "MIT" ]
null
null
null
// Copyright (C) 2019, 2021 by Mark Melton // #include <fmt/format.h> #include "core/tool.h" #include "core/mp/mp.h" #include "peg/peg.h" #include "peg/expr/expr.h" using namespace peg; namespace mp = core::mp; // struct Number : Range<'0','9'> {}; // struct Numbers : OneOrMore<Range<'0','9'>> {}; // struct Fact : LeftRecursion< // Or< // Seq<Fact, c::Multiply, Number>, // Seq<Fact, c::Divide, Number>, // Number>> // {}; // struct Expr : LeftRecursion< // Or< // Seq<Expr, c::Plus, Fact>, // Seq<Expr, c::Minus, Fact>, // Fact>> // {}; int tool_main(int argc, const char *argv[]) { auto opts = ArgParse ( argValues<'*',vector,string>("", "", 1) ); opts.parse(argc, argv); // for (auto& str : opts.get<'*'>()) // { // auto r = parse<Expr>(str); // cout << str << " : " << r.status() << " : " << r.match() << endl; // } // { // // [[maybe_unused]] expr::check_recursion_t<Expr> ignore; // expr::apply_rt<expr::printer, std::tuple<Expr>>::apply(cout); // } return 0; }
20.211538
73
0.540438
[ "vector" ]
284e81a48fac7a5a65d4cc93a50ce2c39f678fad
12,835
cc
C++
src/search_local/index_storage/rocksdb_helper/key_format.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
3
2021-08-18T09:59:42.000Z
2021-09-07T03:11:28.000Z
src/search_local/index_storage/rocksdb_helper/key_format.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
src/search_local/index_storage/rocksdb_helper/key_format.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
/* * ===================================================================================== * * Filename: key_format.cc * * Description: * * Version: 1.0 * Created: 09/08/2020 10:02:05 PM * Revision: none * Compiler: gcc * * Author: Norton, yangshuang68@jd.com * Company: JD.com, Inc. * * ===================================================================================== */ #include <iostream> #include "key_format.h" #include "protocol.h" #include "log.h" #include <utility> #define SEGMENT_SIZE 8 const std::string SEG_SYMBOL = "|"; const char ENCODER_MARKER = 127; const uint64_t signMask = 0x8000000000000000; uint64_t encode_into_cmp_uint(int64_t src) { return uint64_t(src) ^ signMask; } uint64_t htonll(uint64_t val) { return (((uint64_t)htonl(val)) << 32) + htonl(val >> 32); } uint64_t ntohll(uint64_t val) { return (((uint64_t)ntohl(val)) << 32) + ntohl(val >> 32); } std::string key_format::Encode( const std::map<uint8_t, DTCValue *> &fieldValues, const DTCTableDefinition *table_def, uint64_t &caseSensitiveFreeLen) { caseSensitiveFreeLen = 0; const uint8_t *uniq_fields = table_def->uniq_fields_list(); std::string temp_field; std::string rockdb_key; for (uint8_t i = 0; i < table_def->uniq_fields(); i++) { std::map<uint8_t, DTCValue *>::const_iterator key_value = fieldValues.find(uniq_fields[i]); if (key_value != fieldValues.end()) { switch (table_def->field_type(uniq_fields[i])) { case DField::Signed: rockdb_key.append(encode_bytes((int64_t)key_value->second->s64)); // rockdb_key.append(SEG_SYMBOL); break; case DField::Unsigned: rockdb_key.append(encode_bytes((uint64_t)key_value->second->u64)); // rockdb_key.append(SEG_SYMBOL); break; case DField::Float: rockdb_key.append(encode_bytes((double)key_value->second->flt)); // rockdb_key.append(SEG_SYMBOL); break; case DField::Binary: rockdb_key.append(encode_bytes(std::string(key_value->second->bin.ptr, key_value->second->bin.len))); // rockdb_key.append(SEG_SYMBOL); break; case DField::String: temp_field = std::move(encode_bytes(std::string(key_value->second->str.ptr, key_value->second->str.len))); caseSensitiveFreeLen += temp_field.length(); rockdb_key.append(std::move(temp_field)); // rockdb_key.append(SEG_SYMBOL); // caseSensitiveFreeLen += 1; break; } } } return rockdb_key; } std::string key_format::Encode( const std::vector<std::string> &fieldValues, const DTCTableDefinition *table_def, uint64_t &caseSensitiveFreeLen) { caseSensitiveFreeLen = 0; const uint8_t *uniq_fields = table_def->uniq_fields_list(); std::string temp_field; std::string rockdb_key; for (uint8_t i = 0; i < table_def->uniq_fields(); i++) { switch (table_def->field_type(uniq_fields[i])) { case DField::Signed: rockdb_key.append(encode_bytes((int64_t)strtoll(fieldValues[i].c_str(), NULL, 10))); // rockdb_key.append(SEG_SYMBOL); break; case DField::Unsigned: rockdb_key.append(encode_bytes((uint64_t)strtoull(fieldValues[i].c_str(), NULL, 10))); // rockdb_key.append(SEG_SYMBOL); break; case DField::Float: rockdb_key.append(encode_bytes(strtod(fieldValues[i].c_str(), NULL))); // rockdb_key.append(SEG_SYMBOL); break; case DField::Binary: rockdb_key.append(encode_bytes(fieldValues[i])); // rockdb_key.append(SEG_SYMBOL); case DField::String: temp_field = std::move(encode_bytes(fieldValues[i])); caseSensitiveFreeLen += temp_field.length(); rockdb_key.append(std::move(temp_field)); // rockdb_key.append(SEG_SYMBOL); // caseSensitiveFreeLen += 1; break; } } return rockdb_key; } std::string key_format::Encode( const std::vector<std::string> &fieldValues, const std::vector<int> &fieldTypes) { std::string temp_field; std::string rockdb_key; log_info("fieldTypes size:%d", fieldTypes.size()); for (size_t i = 0; i < fieldTypes.size(); i++) { switch (fieldTypes[i]) { case DField::Signed: rockdb_key.append(encode_bytes((int64_t)strtoll(fieldValues[i].c_str(), NULL, 10))); // rockdb_key.append(SEG_SYMBOL); break; case DField::Unsigned: rockdb_key.append(encode_bytes((uint64_t)strtoull(fieldValues[i].c_str(), NULL, 10))); // rockdb_key.append(SEG_SYMBOL); break; case DField::Float: rockdb_key.append(encode_bytes(strtod(fieldValues[i].c_str(), NULL))); // rockdb_key.append(SEG_SYMBOL); break; case DField::Binary: case DField::String: rockdb_key.append(encode_bytes(fieldValues[i])); // rockdb_key.append(SEG_SYMBOL); break; } } return rockdb_key; } void key_format::Decode( const std::string &src, const std::vector<int> &fieldTypes, std::vector<std::string> &fieldValues) { fieldValues.clear(); size_t pos = 0; for (size_t i = 0; i < fieldTypes.size(); i++) { std::string value; switch (fieldTypes[i]) { case DField::Signed: int64_t s64; DecodeBytes(src.substr(pos, 8), s64); pos += 8; // value = new DTCValue(s64); value = std::to_string(s64); break; case DField::Unsigned: uint64_t u64; DecodeBytes(src.substr(pos, 8), u64); pos += 8; // value = new DTCValue(u64); value = std::to_string(u64); break; case DField::Float: double d64; DecodeBytes(src.substr(pos, 8), d64); pos += 8; // value = new DTCValue(d64); value = std::to_string(d64); break; case DField::Binary: case DField::String: size_t begin_pos = pos; pos += SEGMENT_SIZE; // std::string str; // for (; src[ pos - 1] == ENCODER_MARKER && src[pos] != SEG_SYMBOL[0] && pos < src.length() ; pos += SEGMENT_SIZE) { // } for (; src[pos - 1] == ENCODER_MARKER; pos += SEGMENT_SIZE) { } // value = new DTCValue(str.c_str(), str.length()); DecodeBytes(src.substr(begin_pos, pos - begin_pos), value); // pos++; // value = std::move(str); break; } // fieldValues[uniq_fields[i]] = value; fieldValues.push_back(value); } } void key_format::decode_primary_key( const std::string &src, int keyType, std::string &pKey) { switch (keyType) { default: log_error("unsupport data type! type:%d", keyType); break; case DField::Signed: int64_t s64; DecodeBytes(src.substr(0, 8), s64); pKey = std::to_string(s64); break; case DField::Unsigned: uint64_t u64; DecodeBytes(src.substr(0, 8), u64); pKey = std::to_string(u64); break; case DField::Float: double d64; DecodeBytes(src.substr(0, 8), d64); pKey = std::to_string(d64); break; case DField::Binary: case DField::String: size_t pos = 0; pos += SEGMENT_SIZE; for (; src[pos - 1] == ENCODER_MARKER; pos += SEGMENT_SIZE) { } DecodeBytes(src.substr(0, pos), pKey); break; } return; } int key_format::get_field_len( const char *src, int fieldType) { int ret = -1; switch (fieldType) { default: log_error("unsupport data type! type:%d", fieldType); break; case DField::Signed: case DField::Unsigned: case DField::Float: ret = 8; break; case DField::Binary: case DField::String: size_t pos = 0; pos += SEGMENT_SIZE; for (; src[pos - 1] == ENCODER_MARKER; pos += SEGMENT_SIZE) { } ret = pos; break; } return ret; } // get the first field in the row with encode format int key_format::get_format_key( const std::string &src, int fieldType, std::string &key) { int ret = 0; switch (fieldType) { default: ret = -1; log_error("unsupport data type! type:%d", fieldType); break; case DField::Signed: case DField::Unsigned: case DField::Float: key = src.substr(0, 8); break; case DField::Binary: case DField::String: size_t pos = SEGMENT_SIZE; for (; src[pos - 1] == ENCODER_MARKER; pos += SEGMENT_SIZE) { } key = src.substr(0, pos); break; } return ret; } // compare all the field one by one with its explicit type int key_format::Compare( const std::string &ls, const std::string &rs, const std::vector<int> &fieldTypes) { int ret, type, lFieldLen, rFieldLen, compLen; char *lHead = (char *)ls.data(); char *rHead = (char *)rs.data(); for (size_t idx = 0; idx < fieldTypes.size(); idx++) { type = fieldTypes[idx]; switch (type) { default: ret = -2; log_error("unsupport data type! type:%d", type); break; case DField::Signed: case DField::Unsigned: case DField::Float: lFieldLen = rFieldLen = 8; break; case DField::Binary: case DField::String: lFieldLen = get_field_len(lHead, type); rFieldLen = get_field_len(rHead, type); break; } compLen = lFieldLen > rFieldLen ? rFieldLen : lFieldLen; if (type == DField::String) { // the case insensitive int my_strn_case_cmp(const char *, const char *, size_t); ret = my_strn_case_cmp(lHead, rHead, compLen); } else { // case sensitive compare ret = memcmp((void *)lHead, (void *)rHead, compLen); } if (ret != 0) return ret; else if (lFieldLen != rFieldLen) return lFieldLen < rFieldLen ? -1 : 1; // equal in the current field lHead += compLen; rHead += compLen; } return 0; } void key_format::Decode( const std::string &src, std::vector<std::string> &fieldValues, const DTCTableDefinition *table_def) { fieldValues.clear(); const uint8_t *uniq_fields = table_def->uniq_fields_list(); size_t pos = 0; for (uint8_t i = 0; i < table_def->uniq_fields(); i++) { // DTCValue *value = NULL; std::string value; switch (table_def->field_type(uniq_fields[i])) { case DField::Signed: int64_t s64; DecodeBytes(src.substr(pos, 8), s64); pos += 8; // value = new DTCValue(s64); value = std::to_string(s64); break; case DField::Unsigned: uint64_t u64; DecodeBytes(src.substr(pos, 8), u64); pos += 8; // value = new DTCValue(u64); value = std::to_string(u64); break; case DField::Float: double d64; DecodeBytes(src.substr(pos, 8), d64); pos += 8; // value = new DTCValue(d64); value = std::to_string(d64); break; case DField::Binary: case DField::String: size_t begin_pos = pos; pos += SEGMENT_SIZE; for (; src[pos - 1] == ENCODER_MARKER; pos += SEGMENT_SIZE) { } // value = new DTCValue(str.c_str(), str.length()); DecodeBytes(src.substr(begin_pos, pos - begin_pos), value); break; } // fieldValues[uniq_fields[i]] = value; fieldValues.push_back(value); } } std::string key_format::encode_bytes(const std::string &src) { unsigned char padding_bytes; size_t left_length = src.length(); size_t pos = 0; std::stringstream oss_dst; while (true) { unsigned char copy_len = SEGMENT_SIZE - 1 < left_length ? SEGMENT_SIZE - 1 : left_length; padding_bytes = SEGMENT_SIZE - 1 - copy_len; oss_dst << src.substr(pos, copy_len); pos += copy_len; left_length -= copy_len; if (padding_bytes) { oss_dst << std::string(padding_bytes, '\0'); oss_dst << (char)(ENCODER_MARKER - padding_bytes); break; } else { oss_dst << ENCODER_MARKER; } } return oss_dst.str(); } std::string key_format::encode_bytes(int64_t src) { uint64_t host_bytes = encode_into_cmp_uint(src); uint64_t net_bytes = htonll(host_bytes); char dst_bytes[8]; memcpy(dst_bytes, &net_bytes, sizeof(uint64_t)); std::string dst = std::string(8, '\0'); for (size_t i = 0; i < dst.length(); i++) { dst[i] = dst_bytes[i]; } return dst; } std::string key_format::encode_bytes(double src) { uint64_t u; memcpy(&u, &src, sizeof(double)); if (src >= 0) { u |= signMask; } else { u = ~u; } return encode_bytes(u); } std::string key_format::encode_bytes(uint64_t src) { uint64_t net_bytes = htonll(src); char dst_bytes[8]; memcpy(dst_bytes, &net_bytes, sizeof(uint64_t)); std::string dst = std::string(8, '\0'); for (size_t i = 0; i < dst.length(); i++) { dst[i] = dst_bytes[i]; } return dst; } void key_format::DecodeBytes(const std::string &src, int64_t &dst) { uint64_t net_bytes; memcpy(&net_bytes, src.c_str(), sizeof(uint64_t)); uint64_t host_bytes = ntohll(net_bytes); dst = int64_t(host_bytes ^ signMask); } void key_format::DecodeBytes(const std::string &src, std::string &dst) { if (src.length() == 0) { dst = ""; } //std::stringstream oss_dst; for (size_t i = 0; i < src.length(); i += SEGMENT_SIZE) { char padding_bytes = ENCODER_MARKER - src[i + 7]; //oss_dst << src.substr(i, SEGMENT_SIZE - 1 - padding_bytes); dst += src.substr(i, SEGMENT_SIZE - 1 - padding_bytes); } //dst = oss_dst.str(); } void key_format::DecodeBytes(const std::string &src, uint64_t &dst) { uint64_t net_bytes; memcpy(&net_bytes, src.c_str(), sizeof(uint64_t)); dst = ntohll(net_bytes); } void key_format::DecodeBytes(const std::string &src, double &dst) { uint64_t u; DecodeBytes(src, u); if ((u & signMask) > 0) { u &= (~signMask); } else { u = ~u; } memcpy(&dst, &u, sizeof(dst)); }
23.378871
122
0.651188
[ "vector" ]
28513d944f49866c7708a3b3c4ee9e958807d10d
1,253
cpp
C++
UICPC/13/UICPC Round #13 (Div 1)/UICPC Round #13 (Div 1)/solutions/Problem G - Rainbow Road Race/rainbowroadrace2.cpp
MilladMuhammadi/Competitive-Programming
9f84a2d2734a5efe0e1fde0062e51782cd5af2c6
[ "MIT" ]
null
null
null
UICPC/13/UICPC Round #13 (Div 1)/UICPC Round #13 (Div 1)/solutions/Problem G - Rainbow Road Race/rainbowroadrace2.cpp
MilladMuhammadi/Competitive-Programming
9f84a2d2734a5efe0e1fde0062e51782cd5af2c6
[ "MIT" ]
null
null
null
UICPC/13/UICPC Round #13 (Div 1)/UICPC Round #13 (Div 1)/solutions/Problem G - Rainbow Road Race/rainbowroadrace2.cpp
MilladMuhammadi/Competitive-Programming
9f84a2d2734a5efe0e1fde0062e51782cd5af2c6
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // Rainbow Road Race const int inf = INT_MAX; const int maxn = 7 * 7 * 7 + 3; map<char, int> mp{{'R', 0}, {'O', 1}, {'Y', 2}, {'G', 3}, {'V', 4}, {'B', 5}, {'I', 6}}; int n, m, dis[maxn][128+3]; vector<pair<int, pair<int, int>>> adj[maxn]; priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> dij; int main(){ cin >> n >> m; int x, y, w; char c; while(m--) cin >> x >> y >> w >> c, x--, y--, adj[x].push_back({y, {w, mp[c]}}), adj[y].push_back({x, {w, mp[c]}}); for(int i = 0; i < n; i++) for(int mask = 0; mask < 128; mask++) dis[i][mask] = inf; dis[0][0] = 0; dij.push({0, {0, 0}}); while(!dij.empty()){ int u = dij.top().second.first, mask = dij.top().second.second, w = dij.top().first; dij.pop(); if(dis[u][mask] < w) continue; for(pair<int, pair<int, int>> p : adj[u]){ int v = p.first, c = p.second.first, nmask = mask | (1 << p.second.second); if(w + c < dis[v][nmask]) dis[v][nmask] = w + c, dij.push({w + c, {v, nmask}}); } } cout << dis[0][127] << endl; }
32.128205
117
0.468476
[ "vector" ]
28547e8f1b49a91a224d345b00373e895a8a7c33
3,150
hpp
C++
include/codegen/include/System/IOAsyncResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/IOAsyncResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/IOAsyncResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.IAsyncResult #include "System/IAsyncResult.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: AsyncCallback class AsyncCallback; } // Forward declaring namespace: System::Threading namespace System::Threading { // Forward declaring type: ManualResetEvent class ManualResetEvent; // Forward declaring type: WaitHandle class WaitHandle; } // Completed forward declares // Type namespace: System namespace System { // Autogenerated type: System.IOAsyncResult class IOAsyncResult : public ::Il2CppObject, public System::IAsyncResult { public: // private System.AsyncCallback async_callback // Offset: 0x10 System::AsyncCallback* async_callback; // private System.Object async_state // Offset: 0x18 ::Il2CppObject* async_state; // private System.Threading.ManualResetEvent wait_handle // Offset: 0x20 System::Threading::ManualResetEvent* wait_handle; // private System.Boolean completed_synchronously // Offset: 0x28 bool completed_synchronously; // private System.Boolean completed // Offset: 0x29 bool completed; // protected System.Void .ctor(System.AsyncCallback async_callback, System.Object async_state) // Offset: 0xF6A100 static IOAsyncResult* New_ctor(System::AsyncCallback* async_callback, ::Il2CppObject* async_state); // public System.AsyncCallback get_AsyncCallback() // Offset: 0xF6A150 System::AsyncCallback* get_AsyncCallback(); // protected System.Void set_CompletedSynchronously(System.Boolean value) // Offset: 0xF6A26C void set_CompletedSynchronously(bool value); // public System.Boolean get_IsCompleted() // Offset: 0xF6A278 bool get_IsCompleted(); // protected System.Void set_IsCompleted(System.Boolean value) // Offset: 0xF6A280 void set_IsCompleted(bool value); // System.Void CompleteDisposed() // Offset: 0xFFFFFFFF void CompleteDisposed(); // public System.Object get_AsyncState() // Offset: 0xF6A158 // Implemented from: System.IAsyncResult // Base method: System.Object IAsyncResult::get_AsyncState() ::Il2CppObject* get_AsyncState(); // public System.Threading.WaitHandle get_AsyncWaitHandle() // Offset: 0xF6A160 // Implemented from: System.IAsyncResult // Base method: System.Threading.WaitHandle IAsyncResult::get_AsyncWaitHandle() System::Threading::WaitHandle* get_AsyncWaitHandle(); // Creating proxy method: System_IAsyncResult_get_AsyncWaitHandle // Maps to method: get_AsyncWaitHandle System::Threading::WaitHandle* System_IAsyncResult_get_AsyncWaitHandle(); }; // System.IOAsyncResult } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::IOAsyncResult*, "System", "IOAsyncResult"); #pragma pack(pop)
38.888889
103
0.728889
[ "object" ]
285e2cbbd9edace5050eaa066795c6341146750c
8,970
cpp
C++
OpenGLSolution/BRDF/Source/Graphics/Core/Camera.cpp
AlfonsoLRz/BRDFMeasurements
1c83db1dcd0e42d75422dec31486bfbf70df9112
[ "MIT" ]
null
null
null
OpenGLSolution/BRDF/Source/Graphics/Core/Camera.cpp
AlfonsoLRz/BRDFMeasurements
1c83db1dcd0e42d75422dec31486bfbf70df9112
[ "MIT" ]
null
null
null
OpenGLSolution/BRDF/Source/Graphics/Core/Camera.cpp
AlfonsoLRz/BRDFMeasurements
1c83db1dcd0e42d75422dec31486bfbf70df9112
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Camera.h" #include "Geometry/3D/Vector3.h" #include "Graphics/Core/OrthoProjection.h" #include "Graphics/Core/PerspProjection.h" // [ Static parameters initialization] std::vector<std::shared_ptr<CameraProjection>> Camera::CAMERA_PROJECTION { std::shared_ptr<CameraProjection>(new PerspProjection()), std::shared_ptr<CameraProjection>(new OrthoProjection()) }; const vec3 Camera::EYE = vec3(0.0f, 3.0f, 10.0f); const vec3 Camera::LOOK_AT = vec3(0.0f, 3.0f, 0.0f); const vec3 Camera::UP = vec3(0.0f, 1.0f, 0.0f); const float Camera::ZNEAR = 0.1f; const float Camera::ZFAR = 200.0f; const float Camera::FOV_X = 80.0f * glm::pi<float>() / 180.0f; const vec2 Camera::CANONICAL_VOL_CORNER = vec2(-5.0f, -5.0f); /// [Public methods] Camera::Camera(const uint16_t width, const uint16_t height): _backupCamera(nullptr) { _eye = EYE; _lookAt = LOOK_AT; _up = UP; _zNear = ZNEAR; _zFar = ZFAR; _width = width; _height = height; _aspect = this->computeAspect(); _bottomLeftCorner = vec2(CANONICAL_VOL_CORNER.x * _aspect, CANONICAL_VOL_CORNER.y); _fovX = FOV_X; _fovY = this->computeFovY(); _cameraType = PERSPECTIVE_PROJ; this->computeAxes(_n, _u, _v); _viewMatrix = this->computeViewMatrix(); _projectionMatrix = CAMERA_PROJECTION[_cameraType]->calculateProjectionMatrix(this); _viewProjectionMatrix = _projectionMatrix * _viewMatrix; this->saveCamera(); } Camera::Camera(const Camera& camera) : _backupCamera(nullptr) { this->copyCameraAttributes(&camera); } Camera::~Camera() { delete _backupCamera; } Camera& Camera::operator=(const Camera& camera) { if (this != &camera) { this->copyCameraAttributes(&camera); } return *this; } void Camera::reset() { this->copyCameraAttributes(_backupCamera); } void Camera::saveCamera() { delete _backupCamera; _backupCamera = new Camera(*this); } void Camera::setBottomLeftCorner(const vec2& bottomLeft) { _bottomLeftCorner = bottomLeft; this->computeProjectionMatrices(); } void Camera::setCameraType(const CameraTypes cameraType) { _cameraType = cameraType; this->computeViewMatrices(); this->computeProjectionMatrices(); } void Camera::setFovX(const float fovX) { _fovX = fovX; _fovY = this->computeFovY(); this->computeProjectionMatrices(); } void Camera::setFovY(const float fovY) { _fovY = fovY; this->computeProjectionMatrices(); } void Camera::setLookAt(const vec3& position) { _lookAt = position; this->computeAxes(_n, _u, _v); this->computeViewMatrices(); } void Camera::setPosition(const vec3& position) { _eye = position; this->computeAxes(_n, _u, _v); this->computeViewMatrices(); } void Camera::setRaspect(const uint16_t width, const uint16_t height) { _width = width; _height = height; _aspect = this->computeAspect(); _bottomLeftCorner = vec2(_bottomLeftCorner.y * _aspect, _bottomLeftCorner.y); this->computeProjectionMatrices(); } void Camera::setUp(const vec3& up) { _up = up; this->computeViewMatrices(); } void Camera::setZFar(const float zfar) { _zFar = zfar; this->computeProjectionMatrices(); } void Camera::setZNear(const float znear) { _zNear = znear; this->computeProjectionMatrices(); } // [Movements] void Camera::boom(float speed) { const glm::mat4 translationMatrix = glm::translate(mat4(1.0f), _v * speed); // Translation in y axis _eye = vec3(translationMatrix * vec4(_eye, 1.0f)); _lookAt = vec3(translationMatrix * vec4(_lookAt, 1.0f)); this->computeViewMatrices(); } void Camera::crane(float speed) { boom(-speed); // Implemented as another method to take advantage of nomenclature } void Camera::dolly(float speed) { const mat4 translationMatrix = glm::translate(mat4(1.0f), -_n * speed); // Translation in z axis _eye = vec3(translationMatrix * vec4(_eye, 1.0f)); _lookAt = vec3(translationMatrix * vec4(_lookAt, 1.0f)); this->computeViewMatrices(); } void Camera::orbitXZ(float speed) { const mat4 rotationMatrix = glm::rotate(mat4(1.0f), speed, _u); // We will pass over the scene, x or z axis could be used /** - Just in case we want to avoid this orbit movement to get over the y axis. At this moment it's implemented as a fully free movement float alpha = glm::acos(glm::dot(_n, vec3(0.0f, 1.0f, 0.0f))); if (-speed > alpha || (glm::pi<float>() - alpha) < speed) { return; } */ _eye = vec3(rotationMatrix * vec4(_eye - _lookAt, 1.0f)) + _lookAt; _u = vec3(rotationMatrix * vec4(_u, 0.0f)); _v = vec3(rotationMatrix * vec4(_v, 0.0f)); _n = vec3(rotationMatrix * vec4(_n, 0.0f)); _up = glm::normalize(glm::cross(_n, _u)); // Free rotation => we can look down or up this->computeViewMatrices(); } void Camera::orbitY(float speed) { const mat4 rotationMatrix = glm::rotate(glm::mat4(1.0f), speed, glm::vec3(0.0, 1.0f, 0.0f)); _u = vec3(rotationMatrix * vec4(_u, 0.0f)); _v = vec3(rotationMatrix * vec4(_v, 0.0f)); _n = vec3(rotationMatrix * vec4(_n, 0.0f)); _up = glm::normalize(glm::cross(_n, _u)); // This movement doesn't change UP, but it could occur as a result of previous operations _eye = vec3(rotationMatrix * vec4(_eye - _lookAt, 1.0f)) + _lookAt; this->computeViewMatrices(); } void Camera::pan(float speed) { const mat4 rotationMatrix = glm::rotate(glm::mat4(1.0f), speed, vec3(0.0f, 1.0f, 0.0f)); /** * Up vector can change, not in the original position tho. Example: orbit XZ (rotated camera) + pan */ _u = vec3(rotationMatrix * vec4(_u, 0.0f)); _v = vec3(rotationMatrix * vec4(_v, 0.0f)); _n = vec3(rotationMatrix * vec4(_n, 0.0f)); _up = glm::normalize(glm::cross(_n, _u)); _lookAt = vec3(rotationMatrix * vec4(_lookAt - _eye, 1.0f)) + _eye; this->computeViewMatrices(); } void Camera::tilt(float speed) { const mat4 rotationMatrix = glm::rotate(mat4(1.0f), speed, _u); const vec3 n = glm::vec3(rotationMatrix * glm::vec4(_n, 0.0f)); float alpha = glm::acos(glm::dot(n, glm::vec3(0.0f, 1.0f, 0.0f))); if (alpha < speed || alpha > (glm::pi<float>() - speed)) { return; } _v = glm::vec3(rotationMatrix * glm::vec4(_v, 0.0f)); _n = n; _up = glm::normalize(glm::cross(_n, _u)); // It could change because of the rotation _lookAt = glm::vec3(rotationMatrix * glm::vec4(_lookAt - _eye, 1.0f)) + _eye; this->computeViewMatrices(); } void Camera::truck(float speed) { const mat4 translationMatrix = glm::translate(mat4(1.0f), _u * speed); // Translation in x axis _eye = vec3(translationMatrix * vec4(_eye, 1.0f)); _lookAt = vec3(translationMatrix * vec4(_lookAt, 1.0f)); this->computeViewMatrices(); } void Camera::zoom(float speed) { CAMERA_PROJECTION[_cameraType]->zoom(this, speed); } /// [Private methods] float Camera::computeAspect() { return (float)_width / _height; } void Camera::computeAxes(vec3& n, vec3& u, vec3& v) { n = glm::normalize(_eye - _lookAt); // z axis if (Vector3::equal(n,-_up)) // x axis: UP x n is 0 as both vectors are parallel. Since up and n are normalized we can check if they are equal (with epsilon checkup) { u = glm::normalize(glm::cross(vec3(0.0f, 0.0f, -1.0f), n)); } else if (Vector3::equal(n, _up)) { u = glm::normalize(glm::cross(vec3(0.0f, 0.0f, 1.0f), n)); } else { u = glm::normalize(glm::cross(_up, n)); } v = glm::normalize(glm::cross(n, u)); // y axis } vec2 Camera::computeBottomLeftCorner() { const float halfWidth = _width / 2.0f; const float halfHeight = _height / 2.0f; return vec2(-halfWidth, -halfHeight); } float Camera::computeFovY() { return 2.0f * glm::atan(glm::tan(_fovX / 2.0f) / _aspect); } void Camera::computeProjectionMatrices() { _projectionMatrix = CAMERA_PROJECTION[_cameraType]->calculateProjectionMatrix(this); _viewProjectionMatrix = _projectionMatrix * _viewMatrix; } void Camera::computeViewMatrices() { _viewMatrix = computeViewMatrix(); _viewProjectionMatrix = _projectionMatrix * _viewMatrix; } glm::mat4 Camera::computeViewMatrix() { std::cout << "Position: " << _eye.x << ", " << _eye.y << ", " << _eye.z << "; look at: " << _lookAt.x << ", " << _lookAt.y << ", " << _lookAt.z << std::endl; return glm::lookAt(_eye, _lookAt, _up); } void Camera::copyCameraAttributes(const Camera* camera) { this->_eye = camera->_eye; this->_lookAt = camera->_lookAt; this->_up = camera->_up; this->_zNear = camera->_zNear; this->_zFar = camera->_zFar; this->_aspect = camera->_aspect; this->_width = camera->_width; this->_height = camera->_height; this->_n = camera->_n; this->_u = camera->_u; this->_v = camera->_v; this->_viewMatrix = camera->_viewMatrix; this->_projectionMatrix = camera->_projectionMatrix; this->_viewProjectionMatrix = camera->_viewProjectionMatrix; this->_fovX = camera->_fovX; this->_fovY = camera->_fovY; this->_bottomLeftCorner = camera->_bottomLeftCorner; if (camera->_backupCamera) { delete this->_backupCamera; this->_backupCamera = new Camera(*camera->_backupCamera); } }
24.642857
166
0.685284
[ "geometry", "vector", "3d" ]
286062ce1ba74287f0c5cc7627fa83e584b2c471
5,425
cpp
C++
src/KOnexAPI.cpp
ctring/konex
7bf55f68f9ddcba6e2007e9c8049899cdb707d69
[ "MIT" ]
null
null
null
src/KOnexAPI.cpp
ctring/konex
7bf55f68f9ddcba6e2007e9c8049899cdb707d69
[ "MIT" ]
null
null
null
src/KOnexAPI.cpp
ctring/konex
7bf55f68f9ddcba6e2007e9c8049899cdb707d69
[ "MIT" ]
null
null
null
#include "KOnexAPI.hpp" #include "Exception.hpp" #include "GroupableTimeSeriesSet.hpp" #include "distance/Distance.hpp" #include <vector> #include <iostream> using std::string; using std::vector; namespace konex { KOnexAPI::~KOnexAPI() { unloadAllDataset(); } dataset_info_t KOnexAPI::loadDataset(const string& filePath, int maxNumRow, int startCol, const string& separators) { auto newSet = new GroupableTimeSeriesSet(); try { newSet->loadData(filePath, maxNumRow, startCol, separators); } catch (KOnexException& e) { delete newSet; throw e; } int nextIndex = -1; for (auto i = 0; i < this->loadedDatasets.size(); i++) { if (this->loadedDatasets[i] == nullptr) { nextIndex = i; break; } } if (nextIndex < 0) { nextIndex = this->loadedDatasets.size(); this->loadedDatasets.push_back(nullptr); } this->loadedDatasets[nextIndex] = newSet; this->datasetCount++; return this->getDatasetInfo(nextIndex); } void KOnexAPI::saveDataset(int index, const string& filePath, char separator) { this->_checkDatasetIndex(index); this->loadedDatasets[index]->saveData(filePath, separator); } void KOnexAPI::unloadDataset(int index) { this->_checkDatasetIndex(index); delete loadedDatasets[index]; loadedDatasets[index] = nullptr; if (index == loadedDatasets.size() - 1) { loadedDatasets.pop_back(); } this->datasetCount--; } void KOnexAPI::unloadAllDataset() { for (auto i = 0; i < this->loadedDatasets.size(); i++) { delete this->loadedDatasets[i]; } this->loadedDatasets.clear(); this->datasetCount = 0; } int KOnexAPI::getDatasetCount() { return this->datasetCount; } dataset_info_t KOnexAPI::getDatasetInfo(int index) { this->_checkDatasetIndex(index); auto dataset = this->loadedDatasets[index]; return dataset_info_t(index, dataset->getFilePath(), dataset->getItemCount(), dataset->getItemLength(), dataset->isGrouped(), dataset->isNormalized()); } vector<dataset_info_t> KOnexAPI::getAllDatasetInfo() { vector<dataset_info_t> info; for (auto i = 0; i < this->loadedDatasets.size(); i++) { if (loadedDatasets[i] != nullptr) { info.push_back(getDatasetInfo(i)); } } return info; } std::pair<data_t, data_t> KOnexAPI::normalizeDataset(int idx) { this->_checkDatasetIndex(idx); return this->loadedDatasets[idx]->normalize(); } int KOnexAPI::groupDataset(int index, data_t threshold, const string& distance_name, int numThreads) { this->_checkDatasetIndex(index); return this->loadedDatasets[index]->groupAllLengths(distance_name, threshold, numThreads); } void KOnexAPI::saveGroup(int index, const string &path, bool groupSizeOnly) { this->_checkDatasetIndex(index); this->loadedDatasets[index]->saveGroups(path, groupSizeOnly); } int KOnexAPI::loadGroup(int index, const string& path) { this->_checkDatasetIndex(index); return this->loadedDatasets[index]->loadGroups(path); } void KOnexAPI::setWarpingBandRatio(double ratio) { konex::setWarpingBandRatio(ratio); } candidate_time_series_t KOnexAPI::getBestMatch(int result_idx, int query_idx, int index, int start, int end) { this->_checkDatasetIndex(result_idx); this->_checkDatasetIndex(query_idx); const TimeSeries& query = loadedDatasets[query_idx]->getTimeSeries(index, start, end); return loadedDatasets[result_idx]->getBestMatch(query); } vector<candidate_time_series_t> KOnexAPI::kSim(int k, int h, int result_idx, int query_idx, int index, int start, int end) { this->_checkDatasetIndex(result_idx); this->_checkDatasetIndex(query_idx); const TimeSeries& query = loadedDatasets[query_idx]->getTimeSeries(index, start, end); return loadedDatasets[result_idx]->kSim(query, k, h); } vector<candidate_time_series_t> KOnexAPI::kSimRaw(int k, int result_idx, int query_idx, int index, int start, int end, int PAABlockSize) { this->_checkDatasetIndex(result_idx); this->_checkDatasetIndex(query_idx); const TimeSeries& query = loadedDatasets[query_idx]->getTimeSeries(index, start, end); return loadedDatasets[result_idx]->kSimRaw(query, k, PAABlockSize); } dataset_info_t KOnexAPI::PAA(int idx, int n) { this->_checkDatasetIndex(idx); this->loadedDatasets[idx]->PAA(n); return this->getDatasetInfo(idx); } data_t KOnexAPI::distanceBetween(int ds1, int idx1, int start1, int end1, int ds2, int idx2, int start2, int end2, const std::string& distance_name) { this->_checkDatasetIndex(ds1); this->_checkDatasetIndex(ds2); TimeSeries ts1 = this->loadedDatasets[ds1]->getTimeSeries(idx1, start1, end1); TimeSeries ts2 = this->loadedDatasets[ds1]->getTimeSeries(idx2, start2, end2); const dist_t distance = getDistance(distance_name); return distance(ts1, ts2, INF); } void KOnexAPI::printTS(int ds, int idx, int start, int end) { this->_checkDatasetIndex(ds); TimeSeries ts = this->loadedDatasets[ds]->getTimeSeries(idx, start, end); ts.printData(std::cout); std::cout << std::endl; } void KOnexAPI::_checkDatasetIndex(int index) { if (index < 0 || index >= loadedDatasets.size() || loadedDatasets[index] == nullptr) { throw KOnexException("There is no dataset with given index"); } } } // namespace konex
26.334951
136
0.694931
[ "vector" ]
286136d1f56a59870caf5f292637cb093831fe14
19,446
cpp
C++
examples/level_set/ex1/example.cpp
syam-s/IBAMR
b6502f2f818835961d103fd2a2827d9336e68640
[ "BSD-3-Clause" ]
2
2020-03-03T12:29:36.000Z
2021-02-15T06:54:20.000Z
examples/level_set/ex1/example.cpp
syam-s/IBAMR
b6502f2f818835961d103fd2a2827d9336e68640
[ "BSD-3-Clause" ]
null
null
null
examples/level_set/ex1/example.cpp
syam-s/IBAMR
b6502f2f818835961d103fd2a2827d9336e68640
[ "BSD-3-Clause" ]
null
null
null
// --------------------------------------------------------------------- // // Copyright (c) 2017 - 2019 by the IBAMR developers // All rights reserved. // // This file is part of IBAMR. // // IBAMR is free software and is distributed under the 3-clause BSD // license. The full text of the license can be found in the file // COPYRIGHT at the top level directory of IBAMR. // // --------------------------------------------------------------------- // Config files #include <IBAMR_config.h> #include <IBTK_config.h> #include <SAMRAI_config.h> // Headers for basic PETSc functions #include <petscsys.h> // Headers for basic SAMRAI objects #include <BergerRigoutsos.h> #include <CartesianGridGeometry.h> #include <HyperbolicLevelIntegrator.h> #include <LoadBalancer.h> #include <StandardTagAndInitialize.h> // Headers for application-specific algorithm/data structure objects #include <ibamr/AdvectorExplicitPredictorPatchOps.h> #include <ibamr/AdvectorPredictorCorrectorHyperbolicPatchOps.h> #include <ibamr/RelaxationLSMethod.h> #include <ibtk/AppInitializer.h> #include <ibtk/HierarchyMathOps.h> #include <ibtk/muParserCartGridFunction.h> #include <LocationIndexRobinBcCoefs.h> #include <TimeRefinementIntegrator.h> // Set up application namespace declarations #include <ibamr/app_namespaces.h> // Application specific includes. #include "LSLocateInterface.h" /******************************************************************************* * For each run, the input filename and restart information (if needed) must * * be given on the command line. For non-restarted case, command line is: * * * * executable <input file name> * * * * For restarted run, command line is: * * * * executable <input file name> <restart directory> <restart number> * * * *******************************************************************************/ int main(int argc, char* argv[]) { // Initialize MPI and SAMRAI. SAMRAI_MPI::init(&argc, &argv); SAMRAI_MPI::setCallAbortInSerialInsteadOfExit(); SAMRAIManager::startup(); { // cleanup dynamically allocated objects prior to shutdown // Parse command line options, set some standard options from the input // file, initialize the restart database (if this is a restarted run), // and enable file logging. Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, "advect.log"); Pointer<Database> input_db = app_initializer->getInputDatabase(); Pointer<Database> main_db = app_initializer->getComponentDatabase("Main"); // Get various standard options set in the input file. const bool dump_viz_data = app_initializer->dumpVizData(); const int viz_dump_interval = app_initializer->getVizDumpInterval(); const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter(); const bool dump_restart_data = app_initializer->dumpRestartData(); const int restart_dump_interval = app_initializer->getRestartDumpInterval(); const string restart_dump_dirname = app_initializer->getRestartDumpDirectory(); const bool dump_timer_data = app_initializer->dumpTimerData(); const int timer_dump_interval = app_initializer->getTimerDumpInterval(); // Get solver configuration options. bool using_refined_timestepping = false; if (main_db->keyExists("timestepping")) { string timestepping_method = main_db->getString("timestepping"); if (timestepping_method == "SYNCHRONIZED") { using_refined_timestepping = false; } else { using_refined_timestepping = true; } } if (using_refined_timestepping) { pout << "using subcycled timestepping.\n"; } else { pout << "NOT using subcycled timestepping.\n"; } // Create major algorithm and data objects that comprise the // application. These objects are configured from the input database // and, if this is a restarted run, from the restart database. Pointer<AdvectorExplicitPredictorPatchOps> explicit_predictor = new AdvectorExplicitPredictorPatchOps( "AdvectorExplicitPredictorPatchOps", app_initializer->getComponentDatabase("AdvectorExplicitPredictorPatchOps")); Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>( "CartesianGeometry", app_initializer->getComponentDatabase("CartesianGeometry")); Pointer<AdvectorPredictorCorrectorHyperbolicPatchOps> hyp_patch_ops = new AdvectorPredictorCorrectorHyperbolicPatchOps( "AdvectorPredictorCorrectorHyperbolicPatchOps", app_initializer->getComponentDatabase("AdvectorPredictorCorrectorHyperbolicPatchOps"), explicit_predictor, grid_geometry); Pointer<HyperbolicLevelIntegrator<NDIM> > hyp_level_integrator = new HyperbolicLevelIntegrator<NDIM>("HyperbolicLevelIntegrator", app_initializer->getComponentDatabase("HyperbolicLevelIntegrator"), hyp_patch_ops, true, using_refined_timestepping); Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>("PatchHierarchy", grid_geometry); Pointer<StandardTagAndInitialize<NDIM> > error_detector = new StandardTagAndInitialize<NDIM>("StandardTagAndInitialize", hyp_level_integrator, app_initializer->getComponentDatabase("StandardTagAndInitialize")); Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>(); Pointer<LoadBalancer<NDIM> > load_balancer = new LoadBalancer<NDIM>("LoadBalancer", app_initializer->getComponentDatabase("LoadBalancer")); Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm = new GriddingAlgorithm<NDIM>("GriddingAlgorithm", app_initializer->getComponentDatabase("GriddingAlgorithm"), error_detector, box_generator, load_balancer); Pointer<TimeRefinementIntegrator<NDIM> > time_integrator = new TimeRefinementIntegrator<NDIM>("TimeRefinementIntegrator", app_initializer->getComponentDatabase("TimeRefinementIntegrator"), patch_hierarchy, hyp_level_integrator, gridding_algorithm); // Setup the advection velocity. const bool u_is_div_free = main_db->getBoolWithDefault("u_is_div_free", false); if (u_is_div_free) { pout << "advection velocity u is discretely divergence free.\n"; } else { pout << "advection velocity u is NOT discretely divergence free.\n"; } Pointer<FaceVariable<NDIM, double> > u_var = new FaceVariable<NDIM, double>("u"); Pointer<CartGridFunction> u_fcn = new muParserCartGridFunction( "u_fcn", app_initializer->getComponentDatabase("AdvectionVelocityFunction"), grid_geometry); hyp_patch_ops->registerAdvectionVelocity(u_var); hyp_patch_ops->setAdvectionVelocityIsDivergenceFree(u_var, u_is_div_free); hyp_patch_ops->setAdvectionVelocityFunction(u_var, u_fcn); // Setup the advected quantity. const ConvectiveDifferencingType difference_form = IBAMR::string_to_enum<ConvectiveDifferencingType>(main_db->getStringWithDefault( "difference_form", IBAMR::enum_to_string<ConvectiveDifferencingType>(ADVECTIVE))); pout << "solving the advection equation in " << IBAMR::enum_to_string<ConvectiveDifferencingType>(difference_form) << " form.\n"; Pointer<CellVariable<NDIM, double> > Q_var = new CellVariable<NDIM, double>("Q"); LocationIndexRobinBcCoefs<NDIM> physical_bc_coef( "physical_bc_coef", app_initializer->getComponentDatabase("LocationIndexRobinBcCoefs")); hyp_patch_ops->registerTransportedQuantity(Q_var); hyp_patch_ops->setAdvectionVelocity(Q_var, u_var); hyp_patch_ops->setConvectiveDifferencingType(Q_var, difference_form); hyp_patch_ops->setPhysicalBcCoefs(Q_var, &physical_bc_coef); // Set up visualization plot file writer. Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter(); if (uses_visit) hyp_patch_ops->registerVisItDataWriter(visit_data_writer); // Initialize hierarchy configuration and data on all patches. double dt_now = time_integrator->initializeHierarchy(); // Create inital level set CircularInterface circle; circle.R = input_db->getDouble("R"); input_db->getDoubleArray("X0", circle.X0.data(), NDIM); Pointer<VariableContext> current_ctx = hyp_level_integrator->getCurrentContext(); Pointer<VariableContext> scratch_ctx = hyp_level_integrator->getScratchContext(); VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase(); const int Q_current_idx = var_db->mapVariableAndContextToIndex(Q_var, current_ctx); const int Q_scratch_idx = var_db->mapVariableAndContextToIndex(Q_var, scratch_ctx); Pointer<CellVariable<NDIM, double> > E_var = new CellVariable<NDIM, double>("E"); const int E_idx = var_db->registerVariableAndContext(E_var, scratch_ctx); for (int ln = 0; ln <= patch_hierarchy->getFinestLevelNumber(); ++ln) { Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln); if (!level->checkAllocated(Q_scratch_idx)) level->allocatePatchData(Q_scratch_idx, time_integrator->getIntegratorTime()); if (!level->checkAllocated(E_idx)) level->allocatePatchData(E_idx, time_integrator->getIntegratorTime()); } const int coarsest_ln = 0; const int finest_ln = patch_hierarchy->getFinestLevelNumber(); Pointer<HierarchyMathOps> hier_math_ops = new HierarchyMathOps("HierarchyMathOps", patch_hierarchy, coarsest_ln, finest_ln); Pointer<RelaxationLSMethod> level_set_ops = new RelaxationLSMethod("RelaxationLSMethod", app_initializer->getComponentDatabase("LevelSet")); level_set_ops->registerInterfaceNeighborhoodLocatingFcn(&circular_interface_neighborhood, (void*)&circle); level_set_ops->initializeLSData(Q_scratch_idx, hier_math_ops, time_integrator->getIntegratorStep(), time_integrator->getIntegratorTime(), /*initial_time*/ true); // Compute L1 error from analytical solution for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln); for (PatchLevel<NDIM>::Iterator p(level); p; p++) { Pointer<Patch<NDIM> > patch = level->getPatch(p()); const Box<NDIM>& patch_box = patch->getBox(); Pointer<CellData<NDIM, double> > E_data = patch->getPatchData(E_idx); for (Box<NDIM>::Iterator it(patch_box); it; it++) { CellIndex<NDIM> ci(it()); // Get physical coordinates IBTK::Vector coord = IBTK::Vector::Zero(); Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry(); const double* patch_X_lower = patch_geom->getXLower(); const hier::Index<NDIM>& patch_lower_idx = patch_box.lower(); const double* const patch_dx = patch_geom->getDx(); for (int d = 0; d < NDIM; ++d) { coord[d] = patch_X_lower[d] + patch_dx[d] * (static_cast<double>(ci(d) - patch_lower_idx(d)) + 0.5); } const double distance = std::sqrt(std::pow((coord[0] - circle.X0(0)), 2.0) + std::pow((coord[1] - circle.X0(1)), 2.0) #if (NDIM == 3) + std::pow((coord[2] - circle.X0(2)), 2.0) #endif ); (*E_data)(ci) = distance - circle.R; } } } HierarchyCellDataOpsReal<NDIM, double> cc_data_ops(patch_hierarchy, coarsest_ln, finest_ln); cc_data_ops.subtract(E_idx, E_idx, Q_scratch_idx); const int wgt_cc_idx = hier_math_ops->getCellWeightPatchDescriptorIndex(); pout << "Error in Q after level set initialization:" << std::endl << "L1-norm: " << std::setprecision(10) << cc_data_ops.L1Norm(E_idx, wgt_cc_idx) << std::endl; double E_domain = 0.0; double E_interface = 0.0; int num_interface_pts = 0; // Compute L1 Norm for specific regions for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln); for (PatchLevel<NDIM>::Iterator p(level); p; p++) { Pointer<Patch<NDIM> > patch = level->getPatch(p()); const Box<NDIM>& patch_box = patch->getBox(); Pointer<CellData<NDIM, double> > D_data = patch->getPatchData(Q_scratch_idx); Pointer<CellData<NDIM, double> > E_data = patch->getPatchData(E_idx); Pointer<CellData<NDIM, double> > W_data = patch->getPatchData(wgt_cc_idx); for (Box<NDIM>::Iterator it(patch_box); it; it++) { CellIndex<NDIM> ci(it()); const double phi = (*D_data)(ci); const double err = (*E_data)(ci); const double dV = (*W_data)(ci); Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry(); const double* const patch_dx = patch_geom->getDx(); if (std::abs(phi) < 1.2 * patch_dx[0]) { E_interface += std::abs(err) * dV; num_interface_pts++; } if (phi > -0.8) E_domain += std::abs(err) * dV; } } } // Perform sum reduction num_interface_pts = SAMRAI_MPI::sumReduction(num_interface_pts); E_interface = SAMRAI_MPI::sumReduction(E_interface); E_domain = SAMRAI_MPI::sumReduction(E_domain); pout << "Error in Q near interface after level set initialization:" << std::endl << "L1-norm: " << std::setprecision(10) << E_interface << std::endl; pout << "Error in Q in entire domain (minus center) after level set initialization:" << std::endl << "L1-norm: " << std::setprecision(10) << E_domain << std::endl; pout << "Number of points within the interface (used to compute interface error):" << std::endl << num_interface_pts << std::endl; // Register for plotting visit_data_writer->registerPlotQuantity("Error", "SCALAR", E_idx); cc_data_ops.copyData(Q_current_idx, Q_scratch_idx); for (int ln = 0; ln <= patch_hierarchy->getFinestLevelNumber(); ++ln) { Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln); if (level->checkAllocated(Q_scratch_idx)) level->deallocatePatchData(Q_scratch_idx); } // Deallocate initialization objects. app_initializer.setNull(); // Print the input database contents to the log file. plog << "Input database:\n"; input_db->printClassData(plog); // Write out initial visualization data. int iteration_num = time_integrator->getIntegratorStep(); double loop_time = time_integrator->getIntegratorTime(); if (dump_viz_data && uses_visit) { pout << "\n\nWriting visualization files...\n\n"; visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } // Main time step loop. double loop_time_end = time_integrator->getEndTime(); while (!MathUtilities<double>::equalEps(loop_time, loop_time_end) && time_integrator->stepsRemaining()) { iteration_num = time_integrator->getIntegratorStep(); loop_time = time_integrator->getIntegratorTime(); pout << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "At beginning of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; double dt_new = time_integrator->advanceHierarchy(dt_now); loop_time += dt_now; dt_now = dt_new; pout << "\n"; pout << "At end of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "\n"; // At specified intervals, write visualization and restart files, // and print out timer data. iteration_num += 1; const bool last_step = !time_integrator->stepsRemaining(); if (dump_viz_data && uses_visit && (iteration_num % viz_dump_interval == 0 || last_step)) { pout << "\nWriting visualization files...\n\n"; visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } if (dump_restart_data && (iteration_num % restart_dump_interval == 0 || last_step)) { pout << "\nWriting restart files...\n\nn"; RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num); } if (dump_timer_data && (iteration_num % timer_dump_interval == 0 || last_step)) { pout << "\nWriting timer data...\n\n"; TimerManager::getManager()->print(plog); } } if (dump_viz_data && uses_visit) { visit_data_writer->writePlotData(patch_hierarchy, iteration_num + 1, loop_time); } } // cleanup dynamically allocated objects prior to shutdown SAMRAIManager::shutdown(); SAMRAI_MPI::finalize(); } // main
49.861538
117
0.58845
[ "vector" ]
2862a6aab0362e8ac1a0c58bd704713b6c15c61c
3,324
cpp
C++
Week 10-11/Cplus-fstream/fstreanIO.cpp
ToyVo/CSIIStout
c9b0f2adfa9eb60f078413c2a17f30b44d85059f
[ "MIT" ]
null
null
null
Week 10-11/Cplus-fstream/fstreanIO.cpp
ToyVo/CSIIStout
c9b0f2adfa9eb60f078413c2a17f30b44d85059f
[ "MIT" ]
null
null
null
Week 10-11/Cplus-fstream/fstreanIO.cpp
ToyVo/CSIIStout
c9b0f2adfa9eb60f078413c2a17f30b44d85059f
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string> #include <stdlib.h> using namespace std; int readWrite(); // this function demonstreates reading and writing a file through an fstream object int errorTest(); // This program demonstrates the return value of the stream object error testing member functions. void showState(fstream &file); int failTest(); // This program shows the behavior of the >> operator on files that contain spaces as part of the information. // The program reads the contents of the file and transfers those contents to standard output. int main() { // Test readWrite() function // Test errorTest() function // Test failTest() function system("pause"); return 0; } int readWrite() { fstream inOutFile; string word; // Used to read a word from the file // Open the file inOutFile.open("inout.txt"); if (!inOutFile) { cout << "The file was not found." << endl; return 1; } // Read and print every word already in the file while (inOutFile >> word) { cout << word << endl; } // Clear end of file flag to allow additional file operations inOutFile.clear(); // Write a word to the file and close the file inOutFile << "Hello3" << endl; inOutFile.close(); return 0; } int errorTest() { // Open a file, write a number, and show file status fstream testFile("stuff.dat", ios::out); if (testFile.fail()) { cout << "cannot open the file.\n"; return 1; } int num = 10; cout << "Writing to the file.\n"; testFile << num; showState(testFile); testFile.close(); // Open the same file, read the number, show status testFile.open("stuff.dat", ios::in); if (testFile.fail()) { cout << "cannot open the file.\n"; return 1; } cout << "Reading from the file.\n"; testFile >> num; showState(testFile); // Attempt an invalid read, and show status cout << "Forcing a bad read operation.\n"; testFile >> num; showState(testFile); // Close file and quit. testFile.close(); return 0; } //********************************************************* // Definition of function showState. This function uses * // an fstream reference as its parameter. The return * // values of the eof(), fail(), bad(), and good() member * // functions is displayed. The clear() function is called * // before the function returns. * //********************************************************* void showState(fstream &file) { cout << "File Status:\n"; cout << " eof bit: " << file.eof() << endl; cout << " fail bit: " << file.fail() << endl; cout << " bad bit: " << file.bad() << endl; cout << " good bit: " << file.good() << endl; file.clear(); // Clear any bad bits } int failTest() { // variables needed to read file fstream file; string input; // Open the file file.open("murphy.txt", ios::in); if (!file) { cout << "File open error!" << endl; return 1; } // Read the file and echo to screen file >> input; while (!file.fail()) { cout << input; file >> input; } cout << endl; // Close the file file.close(); return 0; }
23.244755
126
0.576414
[ "object" ]
286c605654d29918b3ac92e7d5514042b7118dce
8,090
cpp
C++
Data Structures/van Emde Boas Tree.cpp
vzsky/Algorithms
e57558a2a51588957d395196024e06359861450f
[ "MIT" ]
634
2015-02-25T15:30:26.000Z
2022-03-27T15:34:19.000Z
Data Structures/van Emde Boas Tree.cpp
vzsky/Algorithms
e57558a2a51588957d395196024e06359861450f
[ "MIT" ]
6
2016-10-18T13:58:18.000Z
2021-04-28T17:21:07.000Z
Data Structures/van Emde Boas Tree.cpp
vzsky/Algorithms
e57558a2a51588957d395196024e06359861450f
[ "MIT" ]
288
2015-04-21T07:01:00.000Z
2022-03-25T22:42:42.000Z
/* Petar 'PetarV' Velickovic Data Structure: van Emde Boas Tree (vEB) */ #include <stdio.h> #include <math.h> #include <string.h> #include <time.h> #include <iostream> #include <vector> #include <list> #include <string> #include <algorithm> #include <queue> #include <stack> #include <set> #include <map> #include <complex> using namespace std; typedef long long lld; typedef unsigned long long llu; /* van Emde Boas Tree structure for holding a set of integers in a given universe. Complexity: O(1) for min, max and first O(log log u) for member, insert, delete, pred, succ, extractMin and decreaseKey */ class vEB { llu u; llu *m, *M; vEB *summary; // used if u != 2 vEB **cluster; // used if u != 2 public: vEB(llu); bool member(llu); void insert(llu); void Delete(llu); llu min(); llu max(); llu* pred(llu); llu* succ(llu); llu extractMin(); llu first(); void decreaseKey(llu, llu); }; vEB::vEB(llu u) { this -> u = u; this -> m = NULL; this -> M = NULL; if (u == 2) { this -> summary = NULL; this -> cluster = NULL; } else { llu subSize = (llu)sqrt(u); this -> summary = new vEB(subSize); this -> cluster = new vEB*[subSize]; } } bool vEB::member(llu x) { if (u == 2) { if (m == NULL) return false; if (x == 0) return ((*m) == 0); else if (x == 1) return ((*M) == 1); return false; } else { if (m == NULL) return false; if (x < (*m) || x > (*M)) return false; else if (x == (*m) || (x == (*M))) return true; else { llu subSize = (llu)sqrt(u); llu hi = x / subSize, lo = x % subSize; if (cluster[hi] == NULL) return false; else return cluster[hi] -> member(lo); } } } void vEB::insert(llu x) { if (u == 2) { if (x == 0) { if (m == NULL) { m = new llu; M = new llu; (*m) = (*M) = x; } else (*m) = x; } else if (x == 1) { if (M == NULL) { m = new llu; M = new llu; (*m) = (*M) = x; } else (*M) = x; } } else { if (m == NULL) { m = new llu; M = new llu; (*m) = (*M) = x; } else { if (x < (*m)) { llu currMin = (*m); (*m) = x; this -> insert(currMin); } else { llu subSize = (llu)sqrt(u); llu hi = x / subSize, lo = x % subSize; if (cluster[hi] == NULL) { cluster[hi] = new vEB(subSize); cluster[hi] -> insert(lo); summary -> insert(hi); } else cluster[hi] -> insert(lo); if (x > (*M)) (*M) = x; } } } } void vEB::Delete(llu x) { if (u == 2) { if (x == 0) { if ((*M) == 0) { m = M = NULL; } else (*m) = 1; } else if (x == 1) { if ((*m) == 1) { m = M = NULL; } else (*M) = 0; } } else { llu subSize = (llu)sqrt(u); llu hi = x / subSize, lo = x % subSize; if (x == (*m)) { if (x == (*M)) { m = M = NULL; } else { llu nextMinHi = summary -> min(); llu nextMinLo = cluster[summary -> min()] -> min(); llu nextMin = nextMinHi * subSize + nextMinLo; this -> Delete(nextMin); (*m) = nextMin; } } else { cluster[hi] -> Delete(lo); if (cluster[hi] -> m == NULL) { summary -> Delete(hi); delete cluster[hi]; cluster[hi] = NULL; } if (x == (*M)) { if (summary -> m == NULL) (*M) = (*m); else { llu nextMaxHi = summary -> max(); llu nextMaxLo = cluster[summary -> max()] -> max(); (*M) = nextMaxHi * subSize + nextMaxLo; } } } } } llu vEB::min() { return (*m); } llu vEB::max() { return (*M); } llu* vEB::pred(llu x) { if (u == 2) { if (x == 0) return NULL; else if (x == 1) { if (m == NULL) return NULL; if ((*m) == 1) return NULL; return m; } else return NULL; } else { if (m == NULL) return NULL; if (x <= (*m)) return NULL; if (x > (*M)) return M; llu subSize = (llu)sqrt(u); llu hi = x / subSize; llu lo = x % subSize; if (cluster[hi] == NULL) { llu* prev = summary -> pred(hi); llu* ret = new llu; (*ret) = (*prev) * subSize + cluster[(*prev)] -> max(); return ret; } else { llu *newLo, *newHi; newHi = new llu; newLo = new llu; (*newHi) = hi; llu minInCluster = cluster[hi] -> min(); if (lo > minInCluster) newLo = cluster[hi] -> pred(lo); else { newHi = summary -> pred(hi); (*newLo) = cluster[(*newHi)] -> max(); } llu *ret = new llu; (*ret) = (*newHi) * subSize + (*newLo); return ret; } } } llu* vEB::succ(llu x) { if (u == 2) { if (x == 1) return NULL; else if (x == 0) { if (M == NULL) return NULL; if ((*M) == 0) return NULL; return M; } else return NULL; } else { if (m == NULL) return NULL; if (x >= (*M)) return NULL; if (x < (*m)) return m; llu subSize = (llu)sqrt(u); llu hi = x / subSize; llu lo = x % subSize; if (cluster[hi] == NULL) { llu* next = summary -> succ(hi); llu* ret = new llu; (*ret) = (*next) * subSize + cluster[(*next)] -> min(); return ret; } else { llu *newLo, *newHi; newHi = new llu; newLo = new llu; (*newHi) = hi; llu maxInCluster = cluster[hi] -> max(); if (lo < maxInCluster) newLo = cluster[hi] -> succ(lo); else { newHi = summary -> succ(hi); (*newLo) = cluster[(*newHi)] -> min(); } llu *ret = new llu; (*ret) = (*newHi) * subSize + (*newLo); return ret; } } } llu vEB::extractMin() { llu ret = this -> min(); this -> Delete(ret); return ret; } llu vEB::first() { return this -> min(); } void vEB::decreaseKey(llu x, llu y) { // Preconditions: y < x, x is in the tree, y is not in the tree this -> Delete(x); this -> insert(y); } int main() { vEB *vEB = new class vEB(16); vEB -> insert(2); vEB -> insert(3); vEB -> insert(4); vEB -> insert(5); vEB -> insert(7); vEB -> insert(14); vEB -> insert(15); printf("%llu\n", vEB -> min()); printf("%llu\n", vEB -> max()); printf("%llu\n", (*vEB -> pred(9))); printf("%llu\n", (*vEB -> succ(9))); vEB -> Delete(7); vEB -> Delete(14); printf("%llu\n", (*vEB -> pred(9))); printf("%llu\n", (*vEB -> succ(9))); return 0; }
21.689008
95
0.378739
[ "vector" ]
286dd713ce496ebc0d18032b86e57abd33da977e
47,879
cpp
C++
LayerManagerPlugins/Renderers/Graphic/src/WindowSystems/WaylandBaseWindowSystem.cpp
SanctuaryComponents/layer_management
d3927a6ae5e6c9230d55b6ba4195d434586521c1
[ "Apache-2.0" ]
1
2020-10-21T05:24:10.000Z
2020-10-21T05:24:10.000Z
LayerManagerPlugins/Renderers/Graphic/src/WindowSystems/WaylandBaseWindowSystem.cpp
SanctuaryComponents/layer_management
d3927a6ae5e6c9230d55b6ba4195d434586521c1
[ "Apache-2.0" ]
null
null
null
LayerManagerPlugins/Renderers/Graphic/src/WindowSystems/WaylandBaseWindowSystem.cpp
SanctuaryComponents/layer_management
d3927a6ae5e6c9230d55b6ba4195d434586521c1
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * * Copyright 2010, 2011 BMW Car IT GmbH * Copyright (C) 2011 DENSO CORPORATION and Robert Bosch Car Multimedia Gmbh * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * ****************************************************************************/ #include "WindowSystems/WaylandBaseWindowSystem.h" #include "Log.h" #include "Layer.h" #include <time.h> #include <sys/time.h> #include <sys/wait.h> #include <linux/fb.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <iomanip> #include "WindowSystems/WaylandServerinfoServerProtocol.h" #include "InputManager.h" extern "C" { struct serverinfo { struct wl_resource base; WaylandBaseWindowSystem* windowSystem; }; struct serverinfoClient { struct wl_client *client; uint connectionId; struct wl_list link; }; void WaylandBaseWindowSystem::serverinfoIFCreateConnection(struct wl_client *client, struct wl_resource *resource) { struct serverinfo* deliver = (struct serverinfo*)resource->data; // creates new connection id and store it in memory struct serverinfoClient* clientPair = (struct serverinfoClient*)malloc(sizeof *clientPair); clientPair->client = client; clientPair->connectionId = deliver->windowSystem->m_manageConnectionId; deliver->windowSystem->m_manageConnectionId++; wl_list_init(&clientPair->link); wl_list_insert(&deliver->windowSystem->m_connectionList, &clientPair->link); // send native client handle to this client. // by protocol default, this information is not needed. wl_resource_post_event(resource, SERVERINFO_CONNECTION_ID, clientPair->connectionId); LOG_DEBUG("WaylandBaseWindowSystem", "serverinfoIFCreateConnection() create connection id" << clientPair->connectionId << " for client " << clientPair->client); } struct serverinfo_interface g_serverinfoImplementation = { WaylandBaseWindowSystem::serverinfoIFCreateConnection, }; void WaylandBaseWindowSystem::bindServerinfo(struct wl_client *client, void *data, uint32_t version, uint32_t id) { LOG_DEBUG("WaylandBaseWindowSystem", "bindServerinfo client:" << client << ", data:" << data << ", version:" << version << ", id:" << id); wl_client_add_object(client, &serverinfo_interface, &g_serverinfoImplementation, id, data); } void WaylandBaseWindowSystem::createServerinfo(WaylandBaseWindowSystem* windowSystem) { struct serverinfo* serverInfo; serverInfo = (struct serverinfo*)malloc(sizeof *serverInfo); if (NULL == serverInfo) { LOG_ERROR("WaylandBaseWindowSystem", "failed to alloc serverinfo"); return; } serverInfo->base.object.interface = &serverinfo_interface; serverInfo->base.object.implementation = (void(**)(void)) &g_serverinfoImplementation; serverInfo->base.client = NULL; serverInfo->base.data = NULL; serverInfo->windowSystem = windowSystem; m_serverInfoGlobal = wl_display_add_global(windowSystem->m_wlDisplay, &serverinfo_interface, serverInfo, WaylandBaseWindowSystem::bindServerinfo); if (NULL == m_serverInfoGlobal) { LOG_ERROR("WaylandBaseWindowSystem", "failed wl_display_add_global"); free(serverInfo); return; } m_serverInfo = (void*)serverInfo; } int WaylandBaseWindowSystem::finishFrameHandler(void *data) { BaseWindowSystem* windowSystem = static_cast<BaseWindowSystem*>(data); if (windowSystem) { windowSystem->finishFrame(); } return 1; } } WaylandBaseWindowSystem::WaylandBaseWindowSystem(const char* displayname, int width, int height, Scene* pScene, InputManager* pInputManager) : BaseWindowSystem(pScene, pInputManager) , m_wlDisplay(NULL) , m_wlDisplayClient(NULL) , m_wlCompositorClient(NULL) , m_wlSurfaceClient(NULL) , renderThread(0) , run_lock() , graphicSystem(NULL) , m_wlShm(NULL) , m_serverInfoGlobal(NULL) , m_serverInfo(NULL) , m_wlCompositorGlobal(NULL) , m_initialized(false) , m_takeScreenshot(ScreenShotNone) , m_displayname(displayname) , m_success(false) , m_systemState(IDLE_STATE) , m_manageConnectionId(256) , m_screenShotFile() , m_screenShotScreenID(0) , m_screenShotSurfaceID(0) , m_screenShotLayerID(0) , m_debugMode(false) , m_error(false) , m_width(width) , m_height(height) , m_bRepaintNeeded(false) , m_bRepaintScheduled(false) , m_bUseFrameTimer(true) , m_finishFrameTimer(NULL) , m_listFrameCallback() , m_inputEvent(NULL) , m_connectionList() { LOG_DEBUG("WaylandBaseWindowSystem", "creating WaylandBaseWindowSystem width:" << width << " height:" << height); // init and take mutex, so windowsystem only does init phase until mutex is released again pthread_mutex_init(&run_lock, NULL); pthread_mutex_lock(&run_lock); } WaylandBaseWindowSystem::~WaylandBaseWindowSystem() { if (m_inputEvent) delete m_inputEvent; } void WaylandBaseWindowSystem::printDebug() { // print stuff about layerlist std::stringstream debugmessage; debugmessage << "Layer: ID | X | Y | W | H | Al. \n"; LayerList list = m_pScene->getCurrentRenderOrder(0); // loop the layers LayerListConstIterator iter = list.begin(); LayerListConstIterator iterEnd = list.end(); for (; iter != iterEnd; ++iter) { Rectangle dest = (*iter)->getDestinationRegion(); debugmessage << " " << std::setw(4) << (*iter)->getID() << " " << std::setw(3) << dest.x << " " << std::setw(3) << dest.y << " " << std::setw(3) << dest.width << " " << std::setw(3) << dest.height << " " << std::setw(3) << (*iter)->opacity << "\n"; debugmessage << " Surface: ID |Al.| SVP: X | Y | W | H DVP: X | Y | W | H \n"; // loop the surfaces of within each layer SurfaceList surfaceList = (*iter)->getAllSurfaces(); SurfaceListIterator surfaceIter = surfaceList.begin(); SurfaceListIterator surfaceIterEnd = surfaceList.end(); for (; surfaceIter != surfaceIterEnd; ++surfaceIter) { Rectangle src = (*surfaceIter)->getSourceRegion(); Rectangle dest = (*surfaceIter)->getDestinationRegion(); debugmessage << " " << std::setw(4) << (*surfaceIter)->getID() << " " << std::setprecision(3) << (*surfaceIter)->opacity << " " << std::setw(3) << src.x << " " << std::setw(3) << src.y << " " << std::setw(3) << src.width << " " << std::setw(3) << src.height << " " << std::setw(3) << dest.x << " " << std::setw(3) << dest.y << " " << std::setw(3) << dest.width << " " << std::setw(3) << dest.height << "\n"; } } LOG_DEBUG("WaylandBaseWindowSystem", debugmessage.str()); } Surface* WaylandBaseWindowSystem::getSurfaceFromNativeSurface(struct native_surface* nativeSurface) { // go though all surfaces const std::map<unsigned int, Surface*> surfaces = m_pScene->getAllSurfaces(); for (std::map<unsigned int, Surface*>::const_iterator currentS = surfaces.begin(); currentS != surfaces.end(); ++currentS) { Surface* currentSurface = (*currentS).second; if (!currentSurface) { continue; } WaylandPlatformSurface* nativePlatform = (WaylandPlatformSurface*)currentSurface->platform; if (!nativePlatform) { continue; } if (nativePlatform->connectionId != nativeSurface->connectionId) { continue; } if (nativePlatform->surfaceId != nativeSurface->surface.resource.object.id) { continue; } return currentSurface; } LOG_DEBUG("WaylandBaseWindowSystem", "could not find surface for surface " << nativeSurface); return NULL; } struct native_surface* WaylandBaseWindowSystem::getNativeSurfaceFromSurface(Surface* surface) { struct native_surface *nativeSurface = NULL; WaylandPlatformSurface* platformSurface = static_cast<WaylandPlatformSurface*>(surface->platform); if (!platformSurface) { return NULL; } wl_list_for_each(nativeSurface, &m_nativeSurfaceList, link) { if ((nativeSurface->connectionId == platformSurface->connectionId) && (nativeSurface->surface.resource.object.id == platformSurface->surfaceId)) { break; // FOUND } } return nativeSurface; } void WaylandBaseWindowSystem::checkForNewSurfaceNativeContent() { m_pScene->lockScene(); LayerList layers = m_pScene->getCurrentRenderOrder(0); for (LayerListConstIterator current = layers.begin(); current != layers.end(); current++) { SurfaceList surfaces = (*current)->getAllSurfaces(); for (SurfaceListConstIterator currentS = surfaces.begin(); currentS != surfaces.end(); currentS++) { if ((*currentS)->hasNativeContent()) { allocatePlatformSurface(*currentS); } else // While we are at it, also cleanup any stale native content { deallocatePlatformSurface(*currentS); } } } m_pScene->unlockScene(); } static struct timeval tv0; static struct timeval tv0_forRender; void WaylandBaseWindowSystem::calculateSurfaceFps(Surface *currentSurface, float time) { char floatStringBuffer[256]; float surfaceUpdateFps = ((float)(currentSurface->updateCounter)) / time; float surfaceDrawFps = ((float)(currentSurface->drawCounter)) / time; sprintf(floatStringBuffer, "0x%08x update fps: %3.2f", currentSurface->getID(), surfaceUpdateFps); currentSurface->updateCounter = 0; LOG_INFO("WaylandBaseWindowSystem", "Surface " << floatStringBuffer); sprintf(floatStringBuffer, "0x%08x draw fps: %3.2f", currentSurface->getID(), surfaceDrawFps); currentSurface->drawCounter = 0; LOG_INFO("WaylandBaseWindowSystem", "Surface " << floatStringBuffer); } void WaylandBaseWindowSystem::calculateFps() { struct timeval tv; float FPS = 0.0; int Frame = 0; float timeSinceLastCalc = 0.0; // we have rendered a frame Frame ++; std::list<Layer*> layers = m_pScene->getCurrentRenderOrder(0); // every 3 seconds, calculate & print fps gettimeofday(&tv, NULL); timeSinceLastCalc = (float)(tv.tv_sec-tv0.tv_sec) + 0.000001*((float)(tv.tv_usec-tv0.tv_usec)); // calculate every rendering because of event driven // if (timeSinceLastCalc > 10.0f) // { //LOG_INFO("WaylandBaseWindowSystem", "tv.tv_sec:" << tv.tv_sec << ", tv.tv_usec:" << tv.tv_usec); //LOG_INFO("WaylandBaseWindowSystem", "timeSinceLastCalc " << timeSinceLastCalc); FPS = ((float)(Frame)) / timeSinceLastCalc; char floatStringBuffer[256]; sprintf(floatStringBuffer, "Overall fps: %f", FPS); timeSinceLastCalc = (float)(tv.tv_sec-tv0_forRender.tv_sec) + 0.000001*((float)(tv.tv_usec-tv0_forRender.tv_usec)); for (std::list<Layer*>::const_iterator current = layers.begin(); current != layers.end(); ++current) { SurfaceList surfaceList = (*current)->getAllSurfaces(); SurfaceListIterator surfaceIter = surfaceList.begin(); SurfaceListIterator surfaceIterEnd = surfaceList.end(); for (; surfaceIter != surfaceIterEnd; ++surfaceIter) { calculateSurfaceFps((*surfaceIter), timeSinceLastCalc); } } LOG_INFO("WaylandBaseWindowSystem", floatStringBuffer); tv0 = tv; Frame = 0; // } } void WaylandBaseWindowSystem::RedrawAllLayers(bool clear, bool swap) { LayerList layers = m_pScene->getCurrentRenderOrder(0); LayerList swLayers; // TODO: bRedraw is overly conservative if layers includes a hardware layer bool bRedraw = m_forceComposition || graphicSystem->needsRedraw(layers) || (m_systemState == REDRAW_STATE); if (bRedraw) { graphicSystem->activateGraphicContext(); #ifndef WL_OMIT_CLEAR_GB if (clear) { graphicSystem->clearBackground(); } #endif /* WL_OMIT_CLEAR_GB */ } for (std::list<Layer*>::const_iterator current = layers.begin(); current != layers.end(); ++current) { if ((*current)->getLayerType() == Hardware) { if (m_forceComposition || graphicSystem->needsRedraw(*current)) { renderHWLayer(*current); } } else if (bRedraw) { swLayers.push_back(*current); } } if (bRedraw) { #ifdef WL_LOG_DETAIL_TIMER struct timeval tv_s; struct timeval tv_e; float timeSinceLastCalc = 0.0; //glFinish(); gettimeofday(&tv_s, NULL); graphicSystem->renderSWLayers(swLayers, false); // Already cleared if (swap) { graphicSystem->swapBuffers(); } //glFinish(); gettimeofday(&tv_e, NULL); timeSinceLastCalc = (float)(tv_e.tv_sec-tv_s.tv_sec) + 0.000001*((float)(tv_e.tv_usec-tv_s.tv_usec)); LOG_INFO("WaylandBaseWindowSystem", "swapBuffers" << timeSinceLastCalc); #else graphicSystem->renderSWLayers(swLayers, false); // Already cleared if (swap) { graphicSystem->swapBuffers(); } #endif graphicSystem->releaseGraphicContext(); if (m_debugMode) { printDebug(); } calculateFps(); m_systemState = IDLE_STATE; } // update the frame timer if (true == m_bUseFrameTimer) { wl_event_source_timer_update(m_finishFrameTimer, 10); } } void WaylandBaseWindowSystem::renderHWLayer(Layer *layer) { (void)layer; } void WaylandBaseWindowSystem::Redraw() { gettimeofday(&tv0_forRender, NULL); // draw all the layers //graphicSystem->clearBackground(); /*LOG_INFO("WaylandBaseWindowSystem","Locking List");*/ m_pScene->lockScene(); RedrawAllLayers(true, true); // Clear and Swap ClearDamage(); m_pScene->unlockScene(); m_forceComposition = false; } void WaylandBaseWindowSystem::Screenshot() { /*LOG_INFO("WaylandBaseWindowSystem","Locking List");*/ m_pScene->lockScene(); graphicSystem->activateGraphicContext(); if (m_takeScreenshot == ScreenshotOfDisplay) { LOG_DEBUG("WaylandBaseWindowSystem", "Taking screenshot"); graphicSystem->switchScreen(m_screenShotScreenID); RedrawAllLayers(true, false); // Do clear, Don't swap } else if (m_takeScreenshot == ScreenshotOfLayer) { LOG_DEBUG("WaylandBaseWindowSystem", "Taking screenshot of layer"); Layer* layer = m_pScene->getLayer(m_screenShotLayerID); graphicSystem->switchScreen(layer->getContainingScreenId()); graphicSystem->clearBackground(); if (layer != NULL) { graphicSystem->renderSWLayer(layer, true); // Do clear } } else if (m_takeScreenshot == ScreenshotOfSurface) { LOG_DEBUG("WaylandBaseWindowSystem", "Taking screenshot of surface"); Layer* layer = m_pScene->getLayer(m_screenShotLayerID); Surface* surface = m_pScene->getSurface(m_screenShotSurfaceID); graphicSystem->switchScreen(layer->getContainingScreenId()); graphicSystem->clearBackground(); if (layer != NULL && surface != NULL) { graphicSystem->beginLayer(layer); graphicSystem->renderSurface(surface); graphicSystem->endLayer(); } } graphicSystem->saveScreenShotOfFramebuffer(m_screenShotFile); m_takeScreenshot = ScreenShotNone; LOG_DEBUG("WaylandBaseWindowSystem", "Done taking screenshot"); graphicSystem->releaseGraphicContext(); m_pScene->unlockScene(); /*LOG_INFO("WaylandBaseWindowSystem","UnLocking List");*/ } void WaylandBaseWindowSystem::destroyListenerSurfaceBuffer(struct wl_listener* listener, void *data) { LOG_DEBUG("WaylandBaseWindowSystem", "destroyListenerSurfaceBuffer listener:" << listener << "data :" << data); struct native_surface *es = wl_container_of(listener, es, buffer_destroy_listener); es->buffer = NULL; } void WaylandBaseWindowSystem::destroyListenerSurfacePendingBuffer(struct wl_listener* listener, void *data) { LOG_DEBUG("WaylandBaseWindowSystem", "destroyListenerSurfacePendingBuffer listener:" << listener << "data :" << data); struct native_surface *es = wl_container_of(listener, es, pending.buffer_destroy_listener); es->pending.buffer = NULL; } struct native_surface* WaylandBaseWindowSystem::createNativeSurface() { LOG_DEBUG("WaylandBaseWindowSystem", "createNativeSurface IN"); struct native_surface* surface; surface = (struct native_surface*)calloc(1, sizeof *surface); if (NULL == surface) { LOG_ERROR("WaylandBaseWindowSystem", "failed to create native surface"); return NULL; } wl_signal_init(&surface->surface.resource.destroy_signal); wl_list_init(&surface->link); surface->surface.resource.client = NULL; surface->windowSystem = this; // TODO visual // surface->visual = NONE_VISUAL; surface->buffer = NULL; surface->buffer_destroy_listener.notify = destroyListenerSurfaceBuffer; surface->pending.buffer_destroy_listener.notify = destroyListenerSurfacePendingBuffer; wl_list_init(&surface->pending.frame_callback_list); LOG_DEBUG("WaylandBaseWindowSystem", "createNativeSurface OUT"); return surface; } uint32_t WaylandBaseWindowSystem::getTime(void) { #ifdef WL_OMIT_GETTIME return 0xF0F0F0F0; #else /* WL_OMIT_GETTIME */ struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; #endif /* WL_OMIT_GETTIME */ } void WaylandBaseWindowSystem::destroySurfaceCallback(struct wl_resource* resource) { struct native_surface* nativeSurface = wl_container_of(resource, nativeSurface, surface.resource); WaylandBaseWindowSystem* windowSystem = static_cast<WaylandBaseWindowSystem*>((WaylandBaseWindowSystem*)nativeSurface->windowSystem); Surface* ilmSurface = windowSystem->getSurfaceFromNativeSurface(nativeSurface); if (NULL != ilmSurface) { if (NULL != ilmSurface->platform) { delete ilmSurface->platform; ilmSurface->platform = NULL; } windowSystem->graphicSystem->activateGraphicContext(); windowSystem->graphicSystem->getTextureBinder()->destroyClientBuffer(ilmSurface); windowSystem->graphicSystem->releaseGraphicContext(); } wl_list_remove(&nativeSurface->link); if (nativeSurface->pending.buffer) { wl_list_remove(&nativeSurface->pending.buffer_destroy_listener.link); } if (nativeSurface->buffer) { wl_list_remove(&nativeSurface->buffer_destroy_listener.link); } free(nativeSurface); } extern "C" void WaylandBaseWindowSystem::surfaceIFDestroy(struct wl_client *client, struct wl_resource *resource) { LOG_DEBUG("WaylandBaseWindowSystem", "surfaceIFDestroy client:" << client << ", resource:" << resource); wl_resource_destroy(resource); } void WaylandBaseWindowSystem::postReleaseBuffer(struct wl_buffer *buffer) { LOG_DEBUG("WaylandBaseWindowSystem", "postReleaseBufferIN"); if (--buffer->busy_count > 0) { return; } if (NULL == buffer->resource.client) { LOG_ERROR("WaylandBaseWindowSystem", "Release client is NULL"); } wl_resource_queue_event(&buffer->resource, WL_BUFFER_RELEASE); LOG_DEBUG("WaylandBaseWindowSystem", "postReleaseBuffer OUT"); } void WaylandBaseWindowSystem::attachBufferToNativeSurface(struct wl_buffer* buffer, struct wl_surface* surface) { LOG_DEBUG("WaylandBaseWindowSystem", "attachBufferToNativeSurface IN"); struct native_surface* nativeSurface = (struct native_surface*)surface; WaylandBaseWindowSystem* windowSystem = static_cast<WaylandBaseWindowSystem*>((WaylandBaseWindowSystem*)nativeSurface->windowSystem); Surface* ilmSurface = windowSystem->getSurfaceFromNativeSurface(nativeSurface); if (NULL == ilmSurface) { LOG_ERROR("WaylandBaseWindowSystem", "failed to get surface for wl_surface"); return; } ilmSurface->updateCounter++; ilmSurface->removeNativeContent(); ilmSurface->setNativeContent((long int)buffer); WaylandPlatformSurface* nativePlatformSurface = (WaylandPlatformSurface*)ilmSurface->platform; if (0 != nativePlatformSurface) { windowSystem->graphicSystem->activateGraphicContext(); windowSystem->graphicSystem->getTextureBinder()->createClientBuffer(ilmSurface); windowSystem->graphicSystem->releaseGraphicContext(); LOG_DEBUG("WaylandBaseWindowSystem", "nativePlatformSurface->enable"); nativePlatformSurface->enableRendering(); } LOG_DEBUG("WaylandBaseWindowSystem", "attachBufferToNativeSurface OUT"); } extern "C" void WaylandBaseWindowSystem::surfaceIFAttach(struct wl_client* client, struct wl_resource* resource, struct wl_resource* buffer_resource, int32_t x, int32_t y) { LOG_DEBUG("WaylandBaseWindowSystem", "surfaceIFAttach client:" << client); LOG_DEBUG("WaylandBaseWindowSystem", "surfaceIFAttach IN"); struct native_surface* nativeSurface = (struct native_surface*)resource->data; struct wl_buffer* buffer = NULL; if (buffer_resource) { buffer = (struct wl_buffer*)buffer_resource->data; } if (nativeSurface->buffer) { wl_list_remove(&nativeSurface->pending.buffer_destroy_listener.link); } nativeSurface->pending.sx = x; nativeSurface->pending.sy = y; nativeSurface->pending.buffer = buffer; if (buffer) { wl_signal_add(&buffer->resource.destroy_signal, &nativeSurface->pending.buffer_destroy_listener); nativeSurface->pending.remove_contents = 0; } else { nativeSurface->pending.remove_contents = 1; } LOG_DEBUG("WaylandBaseWindowSystem", "surfaceIFAttach OUT"); } extern "C" void WaylandBaseWindowSystem::surfaceIFDamage(struct wl_client *client, struct wl_resource *resource, int32_t x, int32_t y, int32_t width, int32_t height) { LOG_DEBUG("WaylandBaseWindowSystem", "surfaceIFDamage client:" << client); LOG_DEBUG("WaylandBaseWindowSystem", "surfaceIFDamage IN"); struct native_surface* nativeSurface = (struct native_surface*)resource->data; if (NULL == nativeSurface) { LOG_ERROR("WaylandBaseWindowSystem", "invalid surface"); return; } nativeSurface->pending.damaged = true; nativeSurface->pending.damage.x = x; nativeSurface->pending.damage.y = y; nativeSurface->pending.damage.width = width; nativeSurface->pending.damage.height = height; LOG_DEBUG("WaylandBaseWindowSystem", "surfaceIFDamage OUT"); } extern "C" void WaylandBaseWindowSystem::destroyFrameCallback(struct wl_resource *resource) { struct native_frame_callback* cb = (struct native_frame_callback*)resource->data; wl_list_remove(&cb->link); free(cb); } extern "C" void WaylandBaseWindowSystem::surfaceIFFrame(struct wl_client *client, struct wl_resource *resource, uint32_t callback) { LOG_DEBUG("WaylandBaseWindowSystem", "surfaceIFFrame IN"); struct native_frame_callback* cb; struct native_surface* es = (struct native_surface*)resource->data; cb = (struct native_frame_callback*)malloc(sizeof *cb); if (NULL == cb) { wl_resource_post_no_memory(resource); return; } cb->resource.object.interface = &wl_callback_interface; cb->resource.object.id = callback; cb->resource.destroy = destroyFrameCallback; cb->resource.client = client; cb->resource.data = cb; wl_client_add_resource(client, &cb->resource); wl_list_insert(es->pending.frame_callback_list.prev, &cb->link); LOG_DEBUG("WaylandBaseWindowSystem", "surfaceIFFrame OUT"); } extern "C" void WaylandBaseWindowSystem::surfaceIFCommit(struct wl_client *client, struct wl_resource *resource) { LOG_DEBUG("WaylandBaseWindowSystem", "surfaceIFCommit IN clinet:" << client); struct native_surface* nativeSurface = (struct native_surface*)resource->data; WaylandBaseWindowSystem* windowSystem = static_cast<WaylandBaseWindowSystem*>((WaylandBaseWindowSystem*)nativeSurface->windowSystem); Surface* surface = windowSystem->getSurfaceFromNativeSurface(nativeSurface); struct wl_buffer* buffer = NULL; /* surface_frame process */ windowSystem->checkForNewSurfaceNativeContent(); /* wl_surface_attach process */ if (nativeSurface->pending.buffer || nativeSurface->pending.remove_contents) { buffer = nativeSurface->pending.buffer; if (nativeSurface->buffer) { windowSystem->postReleaseBuffer(nativeSurface->buffer); wl_list_remove(&nativeSurface->buffer_destroy_listener.link); } if (buffer) { buffer->busy_count++; wl_signal_add(&buffer->resource.destroy_signal, &nativeSurface->buffer_destroy_listener); } } windowSystem->attachBufferToNativeSurface(buffer, &nativeSurface->surface); nativeSurface->buffer = buffer; if (NULL != surface) { /* surface_damage process */ if (nativeSurface->pending.damaged == true) { surface->damaged = true; } else { surface->damaged = false; } LOG_WARNING("WaylandBaseWindowSystem", "invalid surface"); } wl_list_insert_list(windowSystem->m_listFrameCallback.prev, &nativeSurface->pending.frame_callback_list); wl_list_init(&nativeSurface->pending.frame_callback_list); windowSystem->scheduleRepaint(windowSystem); LOG_DEBUG("WaylandBaseWindowSystem", "surfaceIFCommit OUT"); } extern "C" const struct wl_surface_interface g_surfaceInterface = { WaylandBaseWindowSystem::surfaceIFDestroy, WaylandBaseWindowSystem::surfaceIFAttach, WaylandBaseWindowSystem::surfaceIFDamage, WaylandBaseWindowSystem::surfaceIFFrame, NULL, NULL, WaylandBaseWindowSystem::surfaceIFCommit }; extern "C" void WaylandBaseWindowSystem::compositorIFCreateSurface (struct wl_client *client, struct wl_resource* resource, uint32_t id) { LOG_DEBUG("WaylandBaseWindowSystem", "compositorIFCreateSurface IN"); WaylandBaseWindowSystem* windowSystem = static_cast<WaylandBaseWindowSystem*>((WaylandBaseWindowSystem*) resource->data); struct native_surface* surface; surface = windowSystem->createNativeSurface(); if (NULL == surface) { wl_resource_post_no_memory(resource); return; } surface->surface.resource.destroy = destroySurfaceCallback; surface->windowSystem = windowSystem; surface->surface.resource.object.id = id; surface->surface.resource.object.interface = &wl_surface_interface; surface->surface.resource.object.implementation = (void (**)(void))&g_surfaceInterface; surface->surface.resource.data = surface; struct serverinfoClient* serverinfoPairNode; wl_list_for_each(serverinfoPairNode, &windowSystem->m_connectionList, link) { if (serverinfoPairNode->client != client) { continue; } surface->connectionId = serverinfoPairNode->connectionId; break; } windowSystem->checkForNewSurfaceNativeContent(); wl_client_add_resource(client, &surface->surface.resource); wl_list_insert(windowSystem->m_nativeSurfaceList.prev, &surface->link); LOG_DEBUG("WaylandBaseWindowSystem", "compositorIFCreateSurface OUT"); } const static struct wl_compositor_interface g_compositorInterface = { WaylandBaseWindowSystem::compositorIFCreateSurface, NULL }; /** * Thread in charge of the CompositorWindow eventloop * Friend function of class WaylandBaseWindowSystem */ extern "C" void* WaylandBaseWindowSystem::eventLoopCallback(void *ptr) { WaylandBaseWindowSystem *windowsys = static_cast<WaylandBaseWindowSystem*>((WaylandBaseWindowSystem*) ptr); return windowsys->eventLoop(); } void WaylandBaseWindowSystem::bindCompositor(struct wl_client* client, void* data, uint32_t version, uint32_t id) { LOG_DEBUG("WaylandBaseWindowSystem", "bindCompositor client:" << client << ", data:" << data << ", version:" << version << ", id:" << id); wl_client_add_object(client, &wl_compositor_interface, &g_compositorInterface, id, data); } void WaylandBaseWindowSystem::repaint(int msecs) { LOG_DEBUG("WaylandBaseWindowSystem", "repaint IN"); struct native_frame_callback* cb; struct native_frame_callback* cnext; Redraw(); wl_list_for_each_safe(cb, cnext, &m_listFrameCallback, link) { wl_callback_send_done(&cb->resource, msecs); wl_resource_destroy(&cb->resource); } LOG_DEBUG("WaylandBaseWindowSystem", "repaint OUT"); } void WaylandBaseWindowSystem::finishFrame() { if (m_bRepaintNeeded) { repaint(getTime()); m_bRepaintNeeded = false; return; } m_bRepaintScheduled = false; } void WaylandBaseWindowSystem::idleEventRepaint(void *data) { LOG_DEBUG("WaylandBaseWindowSystem", "idleEventRepaint IN"); WaylandBaseWindowSystem* windowSystem = static_cast<WaylandBaseWindowSystem*>(data); if (windowSystem) { windowSystem->finishFrame(); } LOG_DEBUG("WaylandBaseWindowSystem", "idleEventRepaint OUT"); } void WaylandBaseWindowSystem::scheduleRepaint(void *data) { m_bRepaintNeeded = true; if (m_bRepaintScheduled) return; struct wl_event_loop *loop = wl_display_get_event_loop(m_wlDisplay); if (loop) { wl_event_loop_add_idle(loop, WaylandBaseWindowSystem::idleEventRepaint, data); m_bRepaintScheduled = true; } } bool WaylandBaseWindowSystem::initCompositor() { LOG_DEBUG("WaylandBaseWindowSystem", "initCompositor START"); m_wlCompositorGlobal = wl_display_add_global(m_wlDisplay, &wl_compositor_interface, this, bindCompositor); if (NULL == m_wlCompositorGlobal) { LOG_ERROR("WaylandBaseWindowSystem", "wl_display_add_global:failed to set wl_compositor_interface"); return false; } LOG_DEBUG("WaylandBaseWindowSystem", "wl_display_add_global:SUCCESS"); wl_display_init_shm(m_wlDisplay); wl_list_init(&m_listFrameCallback); wl_list_init(&m_connectionList); wl_list_init(&m_nativeSurfaceList); createServerinfo(this); LOG_DEBUG("WaylandBaseWindowSystem", "initCompositor END"); return true; } void WaylandBaseWindowSystem::shutdownCompositor() { if (NULL != m_serverInfoGlobal) { wl_display_remove_global(m_wlDisplay, m_serverInfoGlobal); m_serverInfoGlobal = NULL; } if (NULL != m_serverInfo) { free(m_serverInfo); m_serverInfo = NULL; } if (NULL != m_wlCompositorGlobal) { wl_display_remove_global(m_wlDisplay, m_wlCompositorGlobal); m_wlCompositorGlobal = NULL; } } void WaylandBaseWindowSystem::wakeUpRendererThread() { } int WaylandBaseWindowSystem::signalEventOnTerm(int signal_number, void *data) { WaylandBaseWindowSystem* windowSystem = static_cast<WaylandBaseWindowSystem*>((WaylandBaseWindowSystem*)data); LOG_INFO("WaylandBaseWindowSystem", "caught signal " << signal_number); windowSystem->cleanup(); return 1; } void* WaylandBaseWindowSystem::eventLoop() { // INITALIZATION LOG_DEBUG("WaylandBaseWindowSystem", "Enter thread"); bool status = true; struct wl_event_loop *loop; do { m_wlDisplay = wl_display_create(); if (NULL == m_wlDisplay) { LOG_ERROR("WaylandBaseWindowSystem", "failed to create wayland display"); break; } LOG_DEBUG("WaylandBaseWindowSystem", "create wayland display"); loop = wl_display_get_event_loop(m_wlDisplay); wl_event_loop_add_signal(loop, SIGTERM, signalEventOnTerm, this); wl_event_loop_add_signal(loop, SIGINT, signalEventOnTerm, this); wl_event_loop_add_signal(loop, SIGQUIT, signalEventOnTerm, this); wl_event_loop_add_signal(loop, SIGKILL, signalEventOnTerm, this); LOG_DEBUG("WaylandBaseWindowSystem", "wl_event_loop_add_signal"); status = this->initCompositor(); if (false == status) { LOG_ERROR("WaylandBaseWindowSystem", "failed to init compositor"); break; } LOG_DEBUG("WaylandBaseWindowSystem", "SUCCESS:initCompositor"); //. create Native Context status = createNativeContext(); if (false == status) { LOG_ERROR("WaylandBaseWindowSystem", "failed to create Native context"); break; } LOG_DEBUG("WaylandBaseWindowSystem", "SUCCESS:createNativeContext"); //. create egl context status = initGraphicSystem(); if (false == status) { LOG_ERROR("WaylandBaseWindowSystem", "failed to init graphicSystem"); break; } LOG_DEBUG("WaylandBaseWindowSystem", "SUCCESS:init GraphicSystem"); if (true == m_bUseFrameTimer) { struct wl_event_loop *loop = wl_display_get_event_loop(m_wlDisplay); m_finishFrameTimer = wl_event_loop_add_timer(loop, finishFrameHandler, this); } // create input event status = createInputEvent(); if (false == status) { LOG_WARNING("WaylandBaseWindowSystem", "WARNING: failed to create input event"); status = true; } else { LOG_DEBUG("WaylandBaseWindowSystem", "SUCCESS:create InputEvent"); } this->m_success = status; this->m_initialized = true; // Done with init, wait for lock to actually run (ie start/stop method called) pthread_mutex_lock(&this->run_lock); LOG_DEBUG("WaylandBaseWindowSystem", "Starting Event loop"); // run the main event loop while rendering gettimeofday(&tv0, NULL); LOG_DEBUG("WaylandBaseWindowSystem", "Enter render loop"); if (wl_display_add_socket(m_wlDisplay, NULL)) { LOG_ERROR("WaylandBaseWindowSystem", "failed to add socket"); this->m_success = false; this->m_initialized = false; break; } // clear screen to avoid garbage on startup this->graphicSystem->clearBackground(); this->graphicSystem->swapBuffers(); wl_display_run(m_wlDisplay); } while (0); this->cleanup(); LOG_DEBUG("WaylandBaseWindowSystem", "Renderer thread finished"); return NULL; } extern "C" void WaylandBaseWindowSystem::surfaceListenerFrame(void* data, struct wl_callback* callback, uint32_t time) { data = data; // TODO:to avoid warning time = time; // TODO:to avoid warining if (callback) { wl_callback_destroy(callback); } } extern "C" const struct wl_callback_listener g_frameListener = { WaylandBaseWindowSystem::surfaceListenerFrame }; void WaylandBaseWindowSystem::signalRedrawEvent() { LOG_DEBUG("WaylandBaseWindowSystem", "signalRedrawEvent"); // set flag that redraw is needed this->m_systemState = REDRAW_STATE; struct wl_callback* callback = wl_surface_frame(m_wlSurfaceClient); wl_callback_add_listener(callback, &g_frameListener, NULL); wl_surface_commit(m_wlSurfaceClient); } void WaylandBaseWindowSystem::cleanup() { LOG_DEBUG("WaylandBaseWindowSystem", "Cleanup"); shutdownCompositor(); if (NULL != m_wlDisplay) { wl_display_terminate(m_wlDisplay); m_wlDisplay = NULL; } } extern "C" void WaylandBaseWindowSystem::registryHandleGlobalClient(void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) { LOG_DEBUG("WaylandBaseWindowSystem", "version " << version); WaylandBaseWindowSystem* windowsys = static_cast<WaylandBaseWindowSystem*>((WaylandBaseWindowSystem*) data); int ans_strcmp = 0; do { ans_strcmp = strcmp(interface, "wl_compositor"); if (0 == ans_strcmp) { windowsys->m_wlCompositorClient = (wl_compositor*)wl_registry_bind(registry, name, &wl_compositor_interface, 1); break; } } while (0); } extern "C" const struct wl_registry_listener g_registryListener = { WaylandBaseWindowSystem::registryHandleGlobalClient, NULL }; bool WaylandBaseWindowSystem::createWaylandClient() { do { while (NULL == m_wlDisplayClient) { usleep(10000); LOG_DEBUG("WaylandBaseWindowSystem", "Waiting start wayland server"); m_wlDisplayClient = wl_display_connect(NULL); } LOG_DEBUG("WaylandBaseWindowSystem", "connect display"); m_wlRegistryClient = wl_display_get_registry(m_wlDisplayClient); if (NULL == m_wlRegistryClient) { LOG_ERROR("WaylandBaseWindowSystem", "Waiting start wayland server"); break; } wl_registry_add_listener(m_wlRegistryClient, &g_registryListener, this); wl_display_dispatch(m_wlDisplayClient); wl_display_roundtrip(m_wlDisplayClient); m_wlSurfaceClient = wl_compositor_create_surface(m_wlCompositorClient); if (NULL == m_wlSurfaceClient) { LOG_ERROR("WaylandBaseWindowSystem", "failed to create client surface"); break; } LOG_DEBUG("WaylandBaseWindowSystem", "create client surface"); return true; } while (0); releaseWaylandClient(); return false; } void WaylandBaseWindowSystem::releaseWaylandClient() { if (NULL != m_wlSurfaceClient) { wl_surface_destroy(m_wlSurfaceClient); m_wlSurfaceClient = NULL; } if (NULL != m_wlCompositorClient) { wl_compositor_destroy(m_wlCompositorClient); m_wlCompositorClient = NULL; } if (NULL != m_wlDisplayClient) { #if 0 // will add wayland version more than 0.85.0 wl_display_disconnect(m_wlDisplayClient); #endif m_wlDisplayClient = NULL; } } bool WaylandBaseWindowSystem::init(BaseGraphicSystem<void*, void*>* base) { LOG_DEBUG("WaylandBaseWindowSystem", "init base:" << base); graphicSystem = base; int status = pthread_create(&renderThread, NULL, eventLoopCallback, (void*)this); if (0 != status) { return false; } while (false == m_initialized) { usleep(10000); // TODO LOG_DEBUG("WaylandBaseWindowSystem", "Waiting start compositor complete " << m_initialized); } LOG_INFO("WaylandBaseWindowSystem", "Start complete [connect display]" << m_initialized << " success " << m_success); return m_success; } bool WaylandBaseWindowSystem::start(int maxIterationDurationInMS) { m_maxIterationDurationInMS = maxIterationDurationInMS; bool result = true; LOG_DEBUG("WaylandBaseWindowSystem", "Starting / Creating thread"); // let thread actually run if (m_error == false) { pthread_mutex_unlock(&run_lock); } else { pthread_mutex_unlock(&run_lock); result = false; } result = createWaylandClient(); if (false == result) { LOG_DEBUG("WaylandBaseWindowSystem", "Failed to create wayland client"); } return result; } void WaylandBaseWindowSystem::stop() { LOG_INFO("WaylandBaseWindowSystem", "Stopping.."); // needed if start was never called, we wake up thread, so it can immediatly finish // this->signalRedrawEvent(); releaseWaylandClient(); pthread_mutex_unlock(&run_lock); pthread_join(renderThread, NULL); } void WaylandBaseWindowSystem::allocatePlatformSurface(Surface* surface) { LOG_INFO("WaylandBaseWindowSystem", "allocatePlatformSurface begin"); WaylandPlatformSurface* nativeSurface = (WaylandPlatformSurface*)surface->platform; if (!nativeSurface) { LOG_DEBUG("WaylandBaseWindowSystem", "creating native surface for new window"); // this surface does not have a native platform surface attached yet! nativeSurface = (WaylandPlatformSurface*)graphicSystem->getTextureBinder()->createPlatformSurface(surface); if (0 != nativeSurface) { unsigned int surfaceId = surface->getNativeContent(); LOG_DEBUG("WaylandBaseWindowSystem", "surface->getNativeContent() : " << surfaceId); nativeSurface->connectionId = (unsigned short)((surfaceId >> 16) & 0xFFFF); nativeSurface->surfaceId = (unsigned short)(surfaceId & 0xFFFF); surface->platform = nativeSurface; } else { LOG_ERROR("WaylandBaseWindowSystem", "failed to allocate platformsurface"); } } LOG_INFO("WaylandBaseWindowSystem", "allocatePlatformSurface end"); } void WaylandBaseWindowSystem::deallocatePlatformSurface(Surface* surface) { LOG_DEBUG("WaylandBaseWindowSystem", "deallocatePlatformSurface begin"); WaylandPlatformSurface* nativeSurface = (WaylandPlatformSurface*)surface->platform; if (nativeSurface) { LOG_DEBUG("WaylandBaseWindowSystem", "destroyingnative surface"); #if 0 // TODO graphicSystem->activateGraphicContext(); graphicSystem->getTextureBinder()->destroyClientBuffer(surface); graphicSystem->releaseGraphicContext(); surface->renderPropertyChanged = true; delete surface->platform; surface->platform = NULL; #endif } LOG_DEBUG("WaylandBaseWindowSystem", "deallocatePlatformSurface end"); } void WaylandBaseWindowSystem::doScreenShot(std::string fileName, const uint screen_id) { m_takeScreenshot = ScreenshotOfDisplay; m_screenShotFile = fileName; m_screenShotScreenID = screen_id; } void WaylandBaseWindowSystem::doScreenShotOfLayer(std::string fileName, const uint id) { m_takeScreenshot = ScreenshotOfLayer; m_screenShotFile = fileName; m_screenShotLayerID = id; } void WaylandBaseWindowSystem::doScreenShotOfSurface(std::string fileName, const uint id, const uint layer_id) { m_takeScreenshot = ScreenshotOfSurface; m_screenShotFile = fileName; m_screenShotSurfaceID = id; m_screenShotLayerID = layer_id; } void WaylandBaseWindowSystem::manageWLInputEvent(const InputDevice type, const InputEventState state, const WLEvent *wlEvent) { if (!m_inputEvent) { LOG_WARNING("WaylandBaseWindowSystem", "InputEvent not available"); return; } Surface *surface = NULL; native_surface *nativeSurface = NULL; uint32_t time = getTime(); switch (type) { case INPUT_DEVICE_KEYBOARD: { LOG_DEBUG("WaylandBaseWindowSystem", "INPUT_DEVICE_KEYBOARD: state = " << state << ", keyCode = " << wlEvent->keyCode); surface = m_pInputManager->reportKeyboardEvent(state, wlEvent->keyCode); if (!surface) { m_inputEvent->inputDevice().setKeyboardFocus(NULL); break; } nativeSurface = getNativeSurfaceFromSurface(surface); if (!nativeSurface) break; switch (state) { case INPUT_STATE_PRESSED: m_inputEvent->inputDevice().sendKeyPressEvent( &nativeSurface->surface, time, wlEvent->keyCode); break; case INPUT_STATE_RELEASED: m_inputEvent->inputDevice().sendKeyReleaseEvent( &nativeSurface->surface, time, wlEvent->keyCode); break; case INPUT_STATE_OTHER: default: // nothing to do break; } } break; case INPUT_DEVICE_POINTER: { LOG_DEBUG("WaylandBaseWindowSystem", "INPUT_DEVICE_POINTER: state = " << state << ", x = " << wlEvent->x << ", y = " << wlEvent->y); Point globalPos = {state, wlEvent->x, wlEvent->y}; Point localPos = globalPos; surface = m_pInputManager->reportPointerEvent(localPos); if (!surface) { LOG_WARNING("WaylandBaseWindowSystem", "NO FOUND SURFACE!"); break; } LOG_DEBUG("WaylandBaseWindowSystem", "Local coordinates: x = " << localPos.x << ", y = " << localPos.y); nativeSurface = getNativeSurfaceFromSurface(surface); if (!nativeSurface) break; switch (state) { case INPUT_STATE_PRESSED: m_inputEvent->inputDevice().sendMousePressEvent( globalPos, localPos, wlEvent->button, time); break; case INPUT_STATE_RELEASED: m_inputEvent->inputDevice().sendMouseReleaseEvent( globalPos, localPos, wlEvent->button, time); break; case INPUT_STATE_MOTION: m_inputEvent->inputDevice().sendMouseMotionEvent( &nativeSurface->surface, globalPos, localPos, time); break; case INPUT_STATE_OTHER: default: break; } } break; case INPUT_DEVICE_TOUCH: { LOG_DEBUG("WaylandBaseWindowSystem", "INPUT_DEVICE_TOUCH: state = " << state << ", x = " << wlEvent->x << ", y = " << wlEvent->y); Point pt = {state, wlEvent->x, wlEvent->y}; PointVect ptVec(1, pt); surface = m_pInputManager->reportTouchEvent(ptVec); if (!surface) break; nativeSurface = getNativeSurfaceFromSurface(surface); if (!nativeSurface) break; switch (state) { case INPUT_STATE_PRESSED: case INPUT_STATE_MOTION: case INPUT_STATE_RELEASED: m_inputEvent->inputDevice().sendTouchPointEvent( &nativeSurface->surface, time, wlEvent->touchId, wlEvent->touchType, ptVec[0]); break; case INPUT_STATE_OTHER: default: break; } } break; case INPUT_DEVICE_ALL: default: break; } }
33.458421
442
0.666618
[ "render", "object" ]
287069f51104d1fb429b50680e6a5c9f3355c29e
11,506
cpp
C++
src/polyDeformerWeights.cpp
yantor3d/polySymmetry
b41e2dde43148dd504e0055ee7deb04067baaef8
[ "MIT" ]
51
2017-01-29T07:59:37.000Z
2022-03-12T06:52:28.000Z
src/polyDeformerWeights.cpp
sod462/polySymmetry
b41e2dde43148dd504e0055ee7deb04067baaef8
[ "MIT" ]
null
null
null
src/polyDeformerWeights.cpp
sod462/polySymmetry
b41e2dde43148dd504e0055ee7deb04067baaef8
[ "MIT" ]
17
2017-01-29T07:39:14.000Z
2022-03-28T15:38:50.000Z
/** Copyright (c) 2017 Ryan Porter You may use, distribute, or modify this code under the terms of the MIT license. */ #include <stdio.h> #include <vector> #include "parseArgs.h" #include "polyDeformerWeights.h" #include "polySymmetryNode.h" #include "sceneCache.h" #include "selection.h" #include <maya/MArgList.h> #include <maya/MArgDatabase.h> #include <maya/MDagPath.h> #include <maya/MFnMesh.h> #include <maya/MFnWeightGeometryFilter.h> #include <maya/MFloatArray.h> #include <maya/MGlobal.h> #include <maya/MItGeometry.h> #include <maya/MObject.h> #include <maya/MObjectArray.h> #include <maya/MPxCommand.h> #include <maya/MSelectionList.h> #include <maya/MString.h> #include <maya/MStatus.h> #include <maya/MSyntax.h> using namespace std; // Indicates the source deformer. #define SOURCE_DEFORMER_FLAG "-sd" #define SOURCE_DEFORMER_LONG_FLAG "-sourceDeformer" // Indicates the source deformed mesh. #define SOURCE_MESH_FLAG "-sm" #define SOURCE_MESH_LONG_FLAG "-sourceMesh" // Indicates the destination deformer. #define DESTINATION_DEFORMER_FLAG "-dd" #define DESTINATION_DEFORMER_LONG_FLAG "-destinationDeformer" // Indicates the destination deformed shape. #define DESTINATION_MESH_FLAG "-dm" #define DESTINATION_MESH_LONG_FLAG "-destinationMesh" // Indicates the direction of the mirror or flip action - 1 (left to right) or -1 (right to left) #define DIRECTION_FLAG "-d" #define DIRECTION_LONG_FLAG "-direction" // Indicates that the deformer weights should be mirrored. #define MIRROR_FLAG "-m" #define MIRROR_LONG_FLAG "-mirror" // Indicates that the deformer weights should be flipped. #define FLIP_FLAG "-f" #define FLIP_LONG_FLAG "-flip" #define RETURN_IF_ERROR(s) if (!s) { return s; } PolyDeformerWeightsCommand::PolyDeformerWeightsCommand() {} PolyDeformerWeightsCommand::~PolyDeformerWeightsCommand() {} void* PolyDeformerWeightsCommand::creator() { return new PolyDeformerWeightsCommand(); } MSyntax PolyDeformerWeightsCommand::getSyntax() { MSyntax syntax; syntax.addFlag(SOURCE_DEFORMER_FLAG, SOURCE_DEFORMER_LONG_FLAG, MSyntax::kSelectionItem); syntax.addFlag(SOURCE_MESH_FLAG, SOURCE_MESH_LONG_FLAG, MSyntax::kSelectionItem); syntax.addFlag(DESTINATION_DEFORMER_FLAG, DESTINATION_DEFORMER_LONG_FLAG, MSyntax::kSelectionItem); syntax.addFlag(DESTINATION_MESH_FLAG, DESTINATION_MESH_LONG_FLAG, MSyntax::kSelectionItem); syntax.addFlag(DIRECTION_FLAG, DIRECTION_LONG_FLAG, MSyntax::kLong); syntax.addFlag(MIRROR_FLAG, MIRROR_LONG_FLAG); syntax.addFlag(FLIP_FLAG, FLIP_LONG_FLAG); syntax.enableEdit(false); syntax.enableQuery(false); return syntax; } MStatus PolyDeformerWeightsCommand::parseArguments(MArgDatabase &argsData) { MStatus status; status = parseArgs::getNodeArgument(argsData, SOURCE_DEFORMER_FLAG, this->sourceDeformer, true); RETURN_IF_ERROR(status); status = parseArgs::getNodeArgument(argsData, DESTINATION_DEFORMER_FLAG, this->destinationDeformer, false); RETURN_IF_ERROR(status); status = parseArgs::getDagPathArgument(argsData, SOURCE_MESH_FLAG, this->sourceMesh, true); RETURN_IF_ERROR(status); status = parseArgs::getDagPathArgument(argsData, DESTINATION_MESH_FLAG, this->destinationMesh, false); RETURN_IF_ERROR(status); this->mirrorWeights = argsData.isFlagSet(MIRROR_FLAG); this->flipWeights = argsData.isFlagSet(FLIP_FLAG); status = argsData.getFlagArgument(DIRECTION_FLAG, 0, this->direction); return MStatus::kSuccess; } MStatus PolyDeformerWeightsCommand::validateArguments() { MStatus status; if (this->direction != 1 && this->direction != -1) { MString errorMsg("^1s/^2s flag should be 1 (left to right) or -1 (right to left)"); errorMsg.format(errorMsg, MString(DIRECTION_LONG_FLAG), MString(DIRECTION_FLAG)); MGlobal::displayError(errorMsg); return MStatus::kFailure; } if (!parseArgs::isNodeType(sourceDeformer, MFn::kWeightGeometryFilt)) { MString errorMsg("A deformer node should be specified with the ^1s/^2s flag."); errorMsg.format(errorMsg, MString(SOURCE_DEFORMER_LONG_FLAG), MString(SOURCE_DEFORMER_FLAG)); MGlobal::displayError(errorMsg); return MStatus::kFailure; } if (destinationDeformer.isNull()) { destinationDeformer = sourceDeformer; } else if (!destinationDeformer.hasFn(MFn::kWeightGeometryFilt)) { MString errorMsg("A deformer node should be specified with the ^1s/^2s flag."); errorMsg.format(errorMsg, MString(DESTINATION_DEFORMER_LONG_FLAG), MString(DESTINATION_DEFORMER_FLAG)); MGlobal::displayError(errorMsg); return MStatus::kFailure; } if (!parseArgs::isNodeType(this->sourceMesh, MFn::kMesh)) { MString errorMsg("A mesh node should be specified with the ^1s/^2s flag."); errorMsg.format(errorMsg, MString(SOURCE_MESH_LONG_FLAG), MString(SOURCE_MESH_FLAG)); MGlobal::displayError(errorMsg); return MStatus::kFailure; } if (destinationMesh.node().isNull()) { destinationMesh.set(sourceMesh); } else if (!destinationMesh.hasFn(MFn::kMesh)) { MString errorMsg("A mesh node should be specified with the ^1s/^2s flag."); errorMsg.format(errorMsg, MString(DESTINATION_MESH_LONG_FLAG), MString(DESTINATION_MESH_FLAG)); MGlobal::displayError(errorMsg); return MStatus::kFailure; } else { MFnMesh fnSourceMesh(this->sourceMesh); MFnMesh fnDestinationMesh(this->destinationMesh); if (fnSourceMesh.numVertices() != fnDestinationMesh.numVertices()) { MString errorMsg("Source mesh and destination mesh are not point compatible. Cannot continue."); MGlobal::displayError(errorMsg); return MStatus::kFailure; } } MSelectionList activeSelection; MSelectionList vertexSelection; MGlobal::getActiveSelectionList(activeSelection); if (destinationMesh.node().hasFn(MFn::kMesh)) { destinationMesh.pop(); } getSelectedComponents(destinationMesh, activeSelection, vertexSelection, MFn::Type::kMeshVertComponent); if (!vertexSelection.isEmpty()) { vertexSelection.getDagPath(0, destinationMesh, components); } if (!sourceMesh.node().hasFn(MFn::kMesh)) { sourceMesh.extendToShapeDirectlyBelow(0); } if (!destinationMesh.node().hasFn(MFn::kMesh)) { destinationMesh.extendToShapeDirectlyBelow(0); } if (mirrorWeights || flipWeights) { bool cacheHit = PolySymmetryCache::getNodeFromCache(this->sourceMesh, this->polySymmetryData); if (!cacheHit) { MString errorMsg("Mesh specified with the ^1s/^2s flag must have an associated ^3s node."); errorMsg.format(errorMsg, MString(SOURCE_MESH_LONG_FLAG), MString(SOURCE_MESH_FLAG), PolySymmetryNode::NODE_NAME); MGlobal::displayError(errorMsg); return MStatus::kFailure; } } return MStatus::kSuccess; } MStatus PolyDeformerWeightsCommand::doIt(const MArgList& argList) { MStatus status; MArgDatabase argsData(syntax(), argList, &status); RETURN_IF_ERROR(status); status = this->parseArguments(argsData); RETURN_IF_ERROR(status); status = this->validateArguments(); RETURN_IF_ERROR(status); return this->redoIt(); } MStatus PolyDeformerWeightsCommand::redoIt() { MStatus status; MFnWeightGeometryFilter fnSourceDeformer(this->sourceDeformer, &status); MFnWeightGeometryFilter fnDestinationDeformer(this->destinationDeformer, &status); MObjectArray sourceOutputGeometry; MObjectArray destinationOutputGeometry; int numberOfVertices = MFnMesh(this->sourceMesh).numVertices(); MObject sourceComponents; MObject destinationComponents; getAllVertices(numberOfVertices, sourceComponents); getAllVertices(numberOfVertices, destinationComponents); MFloatArray sourceWeights(numberOfVertices); MFloatArray destinationWeights(numberOfVertices); oldWeightValues.setLength(numberOfVertices); uint sourceGeometryIndex = fnSourceDeformer.indexForOutputShape(this->sourceMesh.node(), &status); if (!status) { MString errorMsg("Source mesh ^1s is not deformed by deformer ^2s."); errorMsg.format(errorMsg, this->sourceMesh.partialPathName(), MFnDependencyNode(this->sourceDeformer).name()); MGlobal::displayError(errorMsg); return MStatus::kFailure; } uint destinationGeometryIndex = fnDestinationDeformer.indexForOutputShape(this->destinationMesh.node(), &status); if (!status) { MString errorMsg("Destination mesh ^1s is not deformed by deformer ^2s."); errorMsg.format(errorMsg, this->destinationMesh.partialPathName(), MFnDependencyNode(this->destinationDeformer).name()); MGlobal::displayError(errorMsg); return MStatus::kFailure; } status = fnSourceDeformer.getWeights(sourceGeometryIndex, sourceComponents, sourceWeights); CHECK_MSTATUS_AND_RETURN_IT(status); status = fnDestinationDeformer.getWeights(destinationGeometryIndex, destinationComponents, oldWeightValues); CHECK_MSTATUS_AND_RETURN_IT(status); destinationWeights.copy(sourceWeights); if (mirrorWeights || flipWeights) { vector<int> vertexSymmetry; vector<int> vertexSides; MFnDependencyNode fnNode(polySymmetryData); PolySymmetryNode::getValues(fnNode, VERTEX_SYMMETRY, vertexSymmetry); PolySymmetryNode::getValues(fnNode, VERTEX_SIDES, vertexSides); MItGeometry itGeo(destinationMesh, components); bool useVertexSelection = !components.isNull(); while (!itGeo.isDone()) { int i = itGeo.index(); int o = vertexSymmetry[i]; float wti = this->getWeight(i, sourceWeights, vertexSymmetry, vertexSides); destinationWeights.set(wti, i); if (useVertexSelection) { float wto = this->getWeight(o, sourceWeights, vertexSymmetry, vertexSides); destinationWeights.set(wto, o); } itGeo.next(); } } status = fnDestinationDeformer.setWeight(this->destinationMesh, destinationGeometryIndex, destinationComponents, destinationWeights); CHECK_MSTATUS_AND_RETURN_IT(status); this->geometryIndex = destinationGeometryIndex; this->components = destinationComponents; return MStatus::kSuccess; } float PolyDeformerWeightsCommand::getWeight(int vertexIndex, MFloatArray &sourceWeights, vector<int> &vertexSymmetry, vector<int> vertexSides) { int i = vertexIndex; int o = vertexSymmetry[i]; float wt = sourceWeights[i]; if (flipWeights || (mirrorWeights && vertexSides[i] != direction)) { wt = sourceWeights[o]; } return wt; } MStatus PolyDeformerWeightsCommand::undoIt() { MStatus status; MFnWeightGeometryFilter fnDeformer(this->destinationDeformer, &status); status = fnDeformer.setWeight( this->destinationMesh, this->geometryIndex, this->components, this->oldWeightValues ); CHECK_MSTATUS_AND_RETURN_IT(status); return MStatus::kSuccess; }
31.961111
142
0.705284
[ "mesh", "shape", "vector" ]
2876eee15aee8045de9dca8a7db58e9baae364be
15,411
cpp
C++
kp2rig/src/KpMpii_27.cpp
mcengija/riggingtools
a9e725d3e4419da87f787ff6a0c67bfd28c8f1bb
[ "MIT" ]
30
2020-06-20T10:58:44.000Z
2022-03-07T16:41:35.000Z
kp2rig/src/KpMpii_27.cpp
mcengija/riggingtools
a9e725d3e4419da87f787ff6a0c67bfd28c8f1bb
[ "MIT" ]
11
2020-09-15T19:05:20.000Z
2021-09-14T16:46:37.000Z
kp2rig/src/KpMpii_27.cpp
mcengija/riggingtools
a9e725d3e4419da87f787ff6a0c67bfd28c8f1bb
[ "MIT" ]
7
2020-07-03T05:49:27.000Z
2021-09-07T18:33:36.000Z
#define _USE_MATH_DEFINES #include <cmath> #include <stdio.h> #include <stdlib.h> #include <string> #include "KpMpii_27.hpp" #include "KpToRigHelper.hpp" #include "RigToKpHelper.hpp" #include "KpHelper.hpp" // Helper functions Eigen::Vector3d GetTipOfFoot( const Eigen::Vector3d & bigToe, const Eigen::Vector3d & smallToe, const Eigen::Vector3d & heel ); KpMpii_27::KpMpii_27( std::string kpType, const std::map< KEYPOINT_TYPE, int > & kpLayout ) : Pose( kpType, kpLayout ) { } KpMpii_27::KpMpii_27( const KpMpii_27 & rhs ) : Pose( rhs ) { _keypoints = rhs._keypoints; _rigPose = rhs._rigPose; _rigCreated = rhs._rigCreated; _coordinateSystem = rhs._coordinateSystem; } RigPose & KpMpii_27::GenerateRig() { if ( _rigCreated ) return _rigPose; _rigPose.Timestamp( Timestamp() ); // Spine, including baseNeck and baseHead KpToRigHelper::HandleSpine( *this ); // Legs (not feet) KpToRigHelper::HandleLegs( *this ); // Arms (not hands) KpToRigHelper::HandleArms( *this ); // Deal with hands and feet HandleHands(); HandleFeet(); _rigPose.KpType( KpType() ); _rigCreated = true; return _rigPose; } void KpMpii_27::FromRigPose( const class RigPose & rigPose ) { _rigPose = rigPose; RigToKpHelper::HandleSpine( *this ); RigToKpHelper::HandleLegs( *this ); RigToKpHelper::HandleArms( *this ); // Handle supplimentary joints for ( auto jointPair : rigPose.SupplimentaryJoints ) { // Get the parent location // I'm using both the keypoint and the rig to avoid walking the entire hiearchy const Joint & parentJoint = rigPose.GetRig().GetJoint( jointPair.second.parentName ); auto parentLocation = Utility::RawToVector( Keypoint( StrToKpType( jointPair.second.parentName ) ) ); // If attaching to the parent's tail if ( 0 ) // TODO: our supplimentary joints attach to the head of the parent joint, but if this changes we will need a real condition here { // Move the parent's location to the tail, not the head parentLocation += Utility::RawToQuaternion( parentJoint.quaternionAbs )._transformVector( Eigen::Vector3d::UnitY() ) * parentJoint.length; } // Get the bone vector Eigen::Vector3d boneVector = Utility::RawToQuaternion( jointPair.second.quaternionAbs )._transformVector( Eigen::Vector3d::UnitY() ) * jointPair.second.length; // Add the keypoint Keypoint( Utility::VectorToRaw( parentLocation + boneVector ), StrToKpType( jointPair.second.name ) ); } _timestamp = rigPose.Timestamp(); _rigCreated = true; } void KpMpii_27::InputDataToArray( std::vector< double > & serializedList ) { for ( size_t i = 0; i < InputDataSize(); ++i ) serializedList.push_back( *((double *)&_keypoints + i) ); } bool KpMpii_27::ValidateRig() const { try { if ( !KpHelper::ValidateSpine( *this ) ) return false; if ( !KpHelper::ValidateLegs( *this ) ) return false; if ( !KpHelper::ValidateArms( *this ) ) return false; if ( !ValidateFeet() ) return false; } catch ( std::out_of_range & ) { return false; } return true; } void KpMpii_27::CoordinateSystem( std::array< double, 3 > value ) { _coordinateSystem = value; std::array< double, 3 > * keypointsByOffset = reinterpret_cast< std::array< double, 3 > * >( &_keypoints ); for ( size_t i = 0; i < InputDataSize() / 3; ++i ) { keypointsByOffset->at( 0 ) *= _coordinateSystem[ 0 ]; keypointsByOffset->at( 1 ) *= _coordinateSystem[ 1 ]; keypointsByOffset->at( 2 ) *= _coordinateSystem[ 2 ]; ++keypointsByOffset; } if ( _coordinateSystem[ 2 ] < 0 ) { KpHelper::KeypointsRhToLh( *this ); std::swap( _keypoints.rightBigToe, _keypoints.leftBigToe ); std::swap( _keypoints.rightSmallToe, _keypoints.leftSmallToe ); std::swap( _keypoints.rightHeel, _keypoints.leftHeel ); std::swap( _keypoints.rightEye, _keypoints.leftEye ); std::swap( _keypoints.rightEar, _keypoints.leftEar ); } } void KpMpii_27::HandleHands() { Rig & rig = _rigPose.GetRig(); Rig restPose = Rig::RestPoseHumanoid(); // Guess the hands, starting with the wrist rig.rWrist.length = (rig.rElbow.length / restPose.rElbow.length) * restPose.rWrist.length; rig.rWrist.quaternion = { 0, 0, 0, 1 }; rig.rWrist.quaternionAbs = rig.rElbow.quaternionAbs; rig.lWrist.length = (rig.lElbow.length / restPose.lElbow.length) * restPose.lWrist.length; rig.lWrist.quaternion = { 0, 0, 0, 1 }; rig.lWrist.quaternionAbs = rig.lElbow.quaternionAbs; } void KpMpii_27::HandleFeet() { Rig & rig = _rigPose.GetRig(); Rig restPose = Rig::RestPoseHumanoid(); Eigen::Vector3d forwardVector( 0, 0, 1 ); Eigen::Vector3d rAnkle( _keypoints.rightAnkle[0], _keypoints.rightAnkle[1], _keypoints.rightAnkle[2] ); Eigen::Vector3d lAnkle( _keypoints.leftAnkle[0], _keypoints.leftAnkle[1], _keypoints.leftAnkle[2] ); Eigen::Vector3d rBigToe( _keypoints.rightBigToe[0], _keypoints.rightBigToe[1], _keypoints.rightBigToe[2] ); Eigen::Vector3d rSmallToe( _keypoints.rightSmallToe[0], _keypoints.rightSmallToe[1], _keypoints.rightSmallToe[2] ); Eigen::Vector3d rHeel( _keypoints.rightHeel[0], _keypoints.rightHeel[1], _keypoints.rightHeel[2] ); Eigen::Vector3d lBigToe( _keypoints.leftBigToe[0], _keypoints.leftBigToe[1], _keypoints.leftBigToe[2] ); Eigen::Vector3d lSmallToe( _keypoints.leftSmallToe[0], _keypoints.leftSmallToe[1], _keypoints.leftSmallToe[2] ); Eigen::Vector3d lHeel( _keypoints.leftHeel[0], _keypoints.leftHeel[1], _keypoints.leftHeel[2] ); Eigen::Quaterniond rKneeRotationAbs = Utility::RawToQuaternion( rig.rKnee.quaternionAbs ); Eigen::Quaterniond lKneeRotationAbs = Utility::RawToQuaternion( rig.lKnee.quaternionAbs ); // Create a point at the tip of the foot somewhere between the big and small toe. // Note the vector between big and small toe is not naturally perpendicular to center line along length of foot. Eigen::Vector3d rToe = GetTipOfFoot( rBigToe, rSmallToe, rHeel ); Eigen::Vector3d lToe= GetTipOfFoot( lBigToe, lSmallToe, lHeel ); Eigen::Vector3d rAnkleToToe = rToe - rAnkle; Eigen::Vector3d lAnkleToToe = lToe - lAnkle; const double ankleToeRatio = restPose.rAnkle.length / (restPose.rAnkle.length + restPose.rToeBase.length); // Rest poses Eigen::Quaterniond rAnkleRestPoseAdjustment = rKneeRotationAbs * Utility::RawToQuaternion( restPose.rAnkle.quaternion ); Eigen::Quaterniond lAnkleRestPoseAdjustment = lKneeRotationAbs * Utility::RawToQuaternion( restPose.lAnkle.quaternion ); // Ankle Rotations Eigen::Quaterniond rAnkleRotation = Eigen::Quaterniond::FromTwoVectors( Eigen::Vector3d::UnitY(), rAnkleRestPoseAdjustment.inverse()._transformVector( rAnkleToToe.normalized() ) ); Eigen::Quaterniond lAnkleRotation = Eigen::Quaterniond::FromTwoVectors( Eigen::Vector3d::UnitY(), lAnkleRestPoseAdjustment.inverse()._transformVector( lAnkleToToe.normalized() ) ); // Ankle roll // We don't have enough information to know the difference between toe roll and ankle roll, // so the same roll will be applied to both; this is good enough when stiff shoes are worn, but not ideal // when soft shoes are worn or bare foot. // 1 calculate the toes unit vector, where the direction of the vector depends on the foot // 2 adjust this toes vector so that it's perpendcular to the ankle vector // 3 apply the inverse ankle rotation to get the toes vector perpendicular to the up vector. // The toes vector now lies along the xz plane // 4 determine the difference between the x vector (one positive, one negative) and the toes vector. // Final rotation should be small unless an injury occurs! // 1 Eigen::Vector3d rToesVector = (rBigToe - rSmallToe).normalized(); Eigen::Vector3d lToesVector = (lSmallToe - lBigToe).normalized(); // 2 rToesVector = rToesVector.cross( rAnkleToToe.normalized() ).normalized(); lToesVector = lAnkleToToe.cross( lToesVector.normalized() ).normalized(); // 3 rToesVector = (rAnkleRestPoseAdjustment * rAnkleRotation).inverse()._transformVector( rToesVector ); lToesVector = (lAnkleRestPoseAdjustment * lAnkleRotation).inverse()._transformVector( lToesVector ); // 4 // TODO: ROLL IS DISABLED: Swap commented sections once input toes vectors are more reliable. Eigen::Quaterniond rAnkleRoll = {1,0,0,0}; Eigen::Quaterniond lAnkleRoll = {1,0,0,0}; //Eigen::Quaterniond rAnkleRoll = Eigen::Quaterniond::FromTwoVectors( -Eigen::Vector3d::UnitZ(), rToesVector ); //Eigen::Quaterniond lAnkleRoll = Eigen::Quaterniond::FromTwoVectors( Eigen::Vector3d::UnitZ(), lToesVector ); // Finish the ankles rig.rAnkle.length = rAnkleToToe.norm() * ankleToeRatio; rig.rAnkle.quaternion = Utility::QuaternionToRaw( rAnkleRotation * rAnkleRoll ); rig.rAnkle.quaternionAbs = Utility::QuaternionToRaw( rAnkleRestPoseAdjustment * (rAnkleRotation * rAnkleRoll) ); rig.lAnkle.length = lAnkleToToe.norm() * ankleToeRatio; rig.lAnkle.quaternion = Utility::QuaternionToRaw( lAnkleRotation * lAnkleRoll ); rig.lAnkle.quaternionAbs = Utility::QuaternionToRaw( lAnkleRestPoseAdjustment * (lAnkleRotation * lAnkleRoll) ); // Toe base (ball of foot) rig.rToeBase.length = rAnkleToToe.norm() * (1-ankleToeRatio); rig.rToeBase.quaternion = {0,0,0,1}; rig.rToeBase.quaternionAbs = Utility::QuaternionToRaw( Utility::RawToQuaternion( rig.rAnkle.quaternionAbs ) * Utility::RawToQuaternion( restPose.rToeBase.quaternion ) ); rig.lToeBase.length = lAnkleToToe.norm() * (1-ankleToeRatio); rig.lToeBase.quaternion = {0,0,0,1}; rig.lToeBase.quaternionAbs = Utility::QuaternionToRaw( Utility::RawToQuaternion( rig.lAnkle.quaternionAbs ) * Utility::RawToQuaternion( restPose.lToeBase.quaternion ) ); // Heel, big toe, and small toe are supplimentary joints _rigPose.SupplimentaryJoints[ "rightHeel" ] = SupplimentaryJoint( "rightHeel", "rightAnkle", KpToRigHelper::CreateJoint( rig.rAnkle, rHeel - rAnkle ) ); _rigPose.SupplimentaryJoints[ "rightBigToe" ] = SupplimentaryJoint( "rightBigToe", "rightAnkle", KpToRigHelper::CreateJoint( rig.rAnkle, rBigToe - rAnkle ) ); _rigPose.SupplimentaryJoints[ "rightSmallToe"] = SupplimentaryJoint( "rightSmallToe", "rightAnkle", KpToRigHelper::CreateJoint( rig.rAnkle, rSmallToe - rAnkle ) ); _rigPose.SupplimentaryJoints[ "leftHeel" ] = SupplimentaryJoint( "leftHeel", "leftAnkle", KpToRigHelper::CreateJoint( rig.lAnkle, lHeel - lAnkle ) ); _rigPose.SupplimentaryJoints[ "leftBigToe" ] = SupplimentaryJoint( "leftBigToe", "leftAnkle", KpToRigHelper::CreateJoint( rig.lAnkle, lBigToe - lAnkle ) ); _rigPose.SupplimentaryJoints[ "leftSmallToe" ] = SupplimentaryJoint( "leftSmallToe", "leftAnkle", KpToRigHelper::CreateJoint( rig.lAnkle, lSmallToe - lAnkle ) ); } Eigen::Vector3d GetTipOfFoot( const Eigen::Vector3d & bigToe, const Eigen::Vector3d & smallToe, const Eigen::Vector3d & heel ) { // Estimate the tip of the foot // // LEFT FOOT example: // // * <--point t, estimated tip of foot // point p1, * <--point b, center of big toe (not the tip) // estimated --> * // point along * <--point s, center of small toe (not the tip) // center line of // foot // // // // // * <--point h, heel // // This represents the distance between the center of the big toe // (where the nail meets the skin) and the tip of the longest toe, // as a ratio of the entire length of the foot. constexpr double bigToeCenterToFootTipRatio = 0.05; // The longest portion of the foot isn't centered between the big toe // and small toe, it is usually biased towards the big toe. // This respresents the distance between the center of the big toe // and the line connecting the tip of the foot to the heel. constexpr double bigToeCenterToFootLongestLineRatio = 0.39; // Get vector bs that points from the big toe towards the small toe Eigen::Vector3d bs = smallToe - bigToe; // - Find point p1 along vector bs using fixed ratio bs *= bigToeCenterToFootLongestLineRatio; Eigen::Vector3d p1 = bigToe + bs; // Get vector hb Eigen::Vector3d hb = bigToe - heel; // Get vector hp1 Eigen::Vector3d hp1 = p1 - heel; // set ||hp1|| = ||hb||(1 + ratio) hp1 = hp1.normalized() * (hb.norm() * (1 + bigToeCenterToFootTipRatio)); // Return the tip of the foot return heel + hp1; } bool KpMpii_27::ValidateFeet() const { const Rig & rig = _rigPose.GetRig(); Rig restPose = Rig::RestPoseHumanoid(); constexpr double tolerance = 0.25; // Get the absolute location of the ankles auto rAnkleLocation = RigToKpHelper::WorldCoordinates( rig, Rig::RANKLE ); auto lAnkleLocation = RigToKpHelper::WorldCoordinates( rig, Rig::LANKLE ); // Heel auto joint = _rigPose.SupplimentaryJoints.at( "rightHeel" ); Eigen::Quaterniond q = Utility::RawToQuaternion( joint.quaternionAbs ); Eigen::Vector3d vec = q._transformVector( Eigen::Vector3d::UnitY() ) * joint.length; double distance = (Utility::RawToVector(rAnkleLocation) + vec - Utility::RawToVector(Keypoint(RIGHT_HEEL))).norm(); if ( distance > tolerance ) return false; joint = _rigPose.SupplimentaryJoints.at( "leftHeel" ); q = Utility::RawToQuaternion( joint.quaternionAbs ); vec = q._transformVector( Eigen::Vector3d::UnitY() ) * joint.length; distance = (Utility::RawToVector(lAnkleLocation) + vec - Utility::RawToVector(Keypoint(LEFT_HEEL))).norm(); if ( distance > tolerance ) return false; // Big toe joint = _rigPose.SupplimentaryJoints.at( "rightBigToe" ); q = Utility::RawToQuaternion( joint.quaternionAbs ); vec = q._transformVector( Eigen::Vector3d::UnitY() ) * joint.length; distance = (Utility::RawToVector(rAnkleLocation) + vec - Utility::RawToVector(Keypoint(RIGHT_BIG_TOE))).norm(); if ( distance > tolerance ) return false; joint = _rigPose.SupplimentaryJoints.at( "leftBigToe" ); q = Utility::RawToQuaternion( joint.quaternionAbs ); vec = q._transformVector( Eigen::Vector3d::UnitY() ) * joint.length; distance = (Utility::RawToVector(lAnkleLocation) + vec - Utility::RawToVector(Keypoint(LEFT_BIG_TOE))).norm(); if ( distance > tolerance ) return false; // Small toe joint = _rigPose.SupplimentaryJoints.at( "rightSmallToe" ); q = Utility::RawToQuaternion( joint.quaternionAbs ); vec = q._transformVector( Eigen::Vector3d::UnitY() ) * joint.length; distance = (Utility::RawToVector(rAnkleLocation) + vec - Utility::RawToVector(Keypoint(RIGHT_SMALL_TOE))).norm(); if ( distance > tolerance ) return false; joint = _rigPose.SupplimentaryJoints.at( "leftSmallToe" ); q = Utility::RawToQuaternion( joint.quaternionAbs ); vec = q._transformVector( Eigen::Vector3d::UnitY() ) * joint.length; distance = (Utility::RawToVector(lAnkleLocation) + vec - Utility::RawToVector(Keypoint(LEFT_SMALL_TOE))).norm(); if ( distance > tolerance ) return false; return true; }
45.193548
183
0.693336
[ "vector" ]
2879414dc42ffe633ac74b51e1bb116698c41162
3,973
hpp
C++
include/mesos/docker/spec.hpp
em-mcg/cse223b-mesos
e7d0867d5bf67dbc28117f52babc73dd43d0bb4c
[ "Apache-2.0" ]
2
2017-01-13T19:40:15.000Z
2018-05-16T21:37:13.000Z
include/mesos/docker/spec.hpp
em-mcg/cse223b-mesos
e7d0867d5bf67dbc28117f52babc73dd43d0bb4c
[ "Apache-2.0" ]
1
2022-01-17T12:25:46.000Z
2022-01-17T12:25:46.000Z
include/mesos/docker/spec.hpp
em-mcg/cse223b-mesos
e7d0867d5bf67dbc28117f52babc73dd43d0bb4c
[ "Apache-2.0" ]
1
2021-08-18T09:26:06.000Z
2021-08-18T09:26:06.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __MESOS_DOCKER_SPEC_HPP__ #define __MESOS_DOCKER_SPEC_HPP__ #include <iostream> #include <string> #include <stout/error.hpp> #include <stout/json.hpp> #include <stout/option.hpp> #include <stout/try.hpp> // ONLY USEFUL AFTER RUNNING PROTOC. #include <mesos/docker/spec.pb.h> #include <mesos/docker/v1.hpp> #include <mesos/docker/v2.hpp> namespace docker { namespace spec { // The prefix of whiteout files in a docker image. constexpr char WHITEOUT_PREFIX[] = ".wh."; // The prefix of opaque whiteout files in a docker image. constexpr char WHITEOUT_OPAQUE_PREFIX[] = ".wh..wh..opq"; // Parse the docker image reference. Docker expects the image // reference to be in the following format: // [REGISTRY_HOST[:REGISTRY_PORT]/]REPOSITORY[:TAG|@TYPE:DIGEST] // // This format is inherently ambiguous when dealing with repository // names that include forward slashes. To disambiguate, the docker // code looks for '.', or ':', or 'localhost' to decide if the first // component is a registry or a repository name. For more detail, // drill into the implementation of docker pull. // // See docker implementation: // https://github.com/docker/distribution/blob/master/reference/reference.go Try<ImageReference> parseImageReference(const std::string& s); std::ostream& operator<<(std::ostream& stream, const ImageReference& reference); // Returns the port of a docker registry. Result<int> getRegistryPort(const std::string& registry); // Returns the scheme of a docker registry. Try<std::string> getRegistryScheme(const std::string& registry); // Returns the host of a docker registry. std::string getRegistryHost(const std::string& registry); // Returns the hashmap<registry_URL, spec::DockerConfigAuth> by // parsing the docker config file from a JSON object. Try<hashmap<std::string, Config::Auth>> parseAuthConfig( const JSON::Object& _config); // Returns the hashmap<registry_URL, spec::DockerConfigAuth> by // parsing the docker config file from a string. Try<hashmap<std::string, Config::Auth>> parseAuthConfig(const std::string& s); // Find the host from a docker config auth url. std::string parseAuthUrl(const std::string& _url); namespace v1 { // Validates if the specified docker v1 image manifest conforms to the // Docker v1 spec. Returns the error if the validation fails. Option<Error> validate(const ImageManifest& manifest); // Returns the docker v1 image manifest from the given JSON object. Try<ImageManifest> parse(const JSON::Object& json); // Returns the docker v1 image manifest from the given string. Try<ImageManifest> parse(const std::string& s); } // namespace v1 { namespace v2 { // Validates if the specified v2 image manifest conforms to the Docker // v2 spec. Returns the error if the validation fails. Option<Error> validate(const ImageManifest& manifest); // Returns the docker v2 image manifest from the given JSON object. Try<ImageManifest> parse(const JSON::Object& json); // Returns the docker v2 image manifest from the given string. Try<ImageManifest> parse(const std::string& s); } // namespace v2 { } // namespace spec { } // namespace docker { #endif // __MESOS_DOCKER_SPEC_HPP__
31.531746
80
0.753083
[ "object" ]
287df24ec0b1256105e511a86e7125b289e069b8
3,688
cpp
C++
Computational Geometry/Sweep Line Algorithm/rectangle union.cpp
mniverthi/programming-templates
96f89554eef2b3375493ed84e26b78eeaab4aaef
[ "MIT" ]
null
null
null
Computational Geometry/Sweep Line Algorithm/rectangle union.cpp
mniverthi/programming-templates
96f89554eef2b3375493ed84e26b78eeaab4aaef
[ "MIT" ]
null
null
null
Computational Geometry/Sweep Line Algorithm/rectangle union.cpp
mniverthi/programming-templates
96f89554eef2b3375493ed84e26b78eeaab4aaef
[ "MIT" ]
1
2022-02-19T18:45:16.000Z
2022-02-19T18:45:16.000Z
// Given N rectangles on a plane (they are all parallel to the axis), find the union area of all the rectangles // Each rectangle is defined by two points (x1, y1) bottom left and (x2, y2) top right // Problem link: https://cses.fi/problemset/task/1741/ // Idea: Sweep Line Algorithm (apply to 2 events simultaneously) // At any instance, the set contains only the rectangles which intersect the sweep line // Reference: https://www.topcoder.com/community/competitive-programming/tutorials/line-sweep-algorithms/ // Time complexity: O(N^2) // It can be improved to O(NlogN) if we use a more efficient data structure (i.e segment tree) #include <bits/stdc++.h> using namespace std; const int INF = 1 << 30; const int MAX_N = 1e5 + 5; const int MAX_L = 20; // ~ Log N const long long MOD = 1e9 + 7; typedef long long ll; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<vi> vvi; #define LSOne(S) (S & (-S)) #define isBitSet(S, i) ((S >> i) & 1) struct event { int id; // Index of rectangle in rects int type; // Type of event: 0 = Lower-left ; 1 = Upper-right event() {}; event(int id, int type) : id(id), type(type) {}; }; struct point{ int x, y; }; int N, E = 0; // N = no. of rectangles, E = no. of events point rects[MAX_N][2]; // Each rectangle consists of 2 points: [0] = lower-left ; [1] = upper-right event events_v [2 * MAX_N]; // Events of horizontal sweep line event events_h [2 * MAX_N]; // Events of vertical sweep line bool in_set[MAX_N] = {0}; // Boolean array in place of balanced binary tree (set) long long area = 0; // The output: Area of the union bool compare_x(event a, event b) { return rects[a.id][a.type].x < rects[b.id][b.type].x; } bool compare_y(event a, event b) { return rects[a.id][a.type].y < rects[b.id][b.type].y; } int main() { /// x -> v; y -> h ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); cin >> N; for(int i = 0; i < N; i++){ cin >> rects[i][0].x >> rects[i][0].y; // Lower-left coordinate cin >> rects[i][1].x >> rects[i][1].y; // Upper-right coordinate events_v[E] = event(i, 0); events_h[E++] = event(i, 0); events_v[E] = event(i, 1); events_h[E++] = event(i, 1); } sort(events_v, events_v + E, compare_x); sort(events_h, events_h + E, compare_y); // Pre-sort set of horizontal edges in_set[events_v[0].id] = 1; // Vertical sweep line for(int i = 1; i < E; i++){ event cur = events_v[i], precur = events_v[i - 1]; int cnt = 0; // Counter to indicate how many rectangles are currently overlapping // Delta_x: Distance between current sweep line and previous sweep line ll delta_x = rects[cur.id][cur.type].x - rects[precur.id][precur.type].x; if (delta_x < 0) continue; int begin_y; // Horizontal sweep line for (int j = 0; j < E; j++){ if (in_set[events_h[j].id]){ if (events_h[j].type == 0) { if (cnt == 0) begin_y = rects[events_h[j].id][0].y; // Block starts cnt++; } else { cnt--; if (cnt == 0) { // Block ends ll delta_y = rects[events_h[j].id][1].y - begin_y; area += delta_x * delta_y; } } } } in_set[cur.id] = (cur.type == 0); } cout << area; }
34.792453
112
0.559653
[ "vector" ]
2886a9adcd0f06b1e921a21d59cc144d88e69e04
1,049
hpp
C++
Client/app/scenes/IntroScene.hpp
HadesD/Client-Server.CPP
c81cfb477f85563cc898693dc835fa2bf63b3f73
[ "MIT" ]
5
2017-09-15T01:38:13.000Z
2021-01-09T12:01:14.000Z
Client/app/scenes/IntroScene.hpp
HadesD/Client-Server.CPP
c81cfb477f85563cc898693dc835fa2bf63b3f73
[ "MIT" ]
11
2017-08-29T09:16:49.000Z
2021-09-22T16:46:45.000Z
Client/app/scenes/IntroScene.hpp
HadesD/Client-Server.CPP
c81cfb477f85563cc898693dc835fa2bf63b3f73
[ "MIT" ]
5
2017-09-01T12:40:46.000Z
2022-03-14T18:48:04.000Z
#ifndef APP_SCENES_INTRO_SCENE_HPP #define APP_SCENES_INTRO_SCENE_HPP #include <functional> #include <vector> #include <map> #include "app/Scene.hpp" #include "app/input/Kbhit.hpp" namespace app { namespace core { class Game; } } namespace app { namespace scenes { class IntroScene : public app::Scene { public: struct Selection { Selection(const std::string &n, const std::function<void()> &c) : name(n) , call(c) {} std::string name; std::function<void()> call; }; public: IntroScene(const std::shared_ptr<app::core::Game> &game); ~IntroScene(); public: void init(); void update(const float dt); void draw(); public: void waitKeyboardEvent(); void onKeyboardEvent(); private: void goToPlayOnline(); void goToPlayOffline(); void quit(); protected: std::vector<Selection> m_selection; std::size_t m_cursor; app::input::Kbhit m_kbhit; }; } } #endif
16.919355
73
0.594852
[ "vector" ]
28876ca0866a0ee38d8b43180e253d5f98b504a7
3,351
cpp
C++
luogu/codes/SP10707.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
1
2021-02-22T03:39:24.000Z
2021-02-22T03:39:24.000Z
luogu/codes/SP10707.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
luogu/codes/SP10707.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
/************************************************************* * > File Name : SP10707.cpp * > Author : Tony * > Created Time : 2020/04/30 13:52:29 * > Algorithm : **************************************************************/ #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 200020; int n, m, l, r, Ans, len, ocnt; int cnt[maxn], fst[maxn], lst[maxn], vis[maxn], ans[maxn]; int ord[maxn], val[maxn], dep[maxn], fa[maxn][25], old[maxn]; struct Query { int l, r, id, pos, lca; }q[maxn]; bool cmp(Query a, Query b) { if (a.pos != b.pos) return a.pos < b.pos; if (a.pos & 1) return a.r < b.r; return a.r > b.r; } struct Edge { int from, to; Edge(int f, int t): from(f), to(t) {} }; vector<Edge> edges; vector<int> G[maxn]; void add(int f, int t) { edges.push_back(Edge(f, t)); edges.push_back(Edge(t, f)); int mm = edges.size(); G[t].push_back(mm - 1); G[f].push_back(mm - 2); } void dfs(int u, int f) { ord[++ocnt] = u; fst[u] = ocnt; for (int i = 0; i < G[u].size(); ++i) { Edge& e = edges[G[u][i]]; if (e.to == f) continue; dep[e.to] = dep[u] + 1; fa[e.to][0] = u; for (int j = 1; j <= 20; ++j) { fa[e.to][j] = fa[fa[e.to][j - 1]][j - 1]; } dfs(e.to, u); } ord[++ocnt] = u; lst[u] = ocnt; } int lca(int x, int y) { if (dep[x] > dep[y]) swap(x, y); for (int i = 20; i >= 0; --i) { if (dep[fa[y][i]] >= dep[x]) y = fa[y][i]; } if (x == y) return x; for (int i = 20; i >= 0; --i) { if (fa[x][i] != fa[y][i]) { x = fa[x][i]; y = fa[y][i]; } } return fa[x][0]; } void add(int x) { cnt[val[x]]--; if (!cnt[val[x]]) Ans--; } void del(int x) { cnt[val[x]]++; if (cnt[val[x]] == 1) Ans++; } void chg(int x) { if (vis[x]) add(x); else del(x); vis[x] ^= 1; } int main() { n = read(); m = read(); len = sqrt(2 * n); for (int i = 1; i <= n; ++i) old[i] = val[i] = read(); sort(old + 1, old + 1 + n); int len_ = unique(old + 1, old + 1 + n) - old - 1; for (int i = 1; i <= n; ++i) val[i] = lower_bound(old + 1, old + 1 + len_, val[i]) - old; for (int i = 1; i < n; ++i) add(read(), read()); dep[1] = 1; dfs(1, 0); for (int i = 1; i <= m; ++i) { int il = read(), ir = read(); int LCA = lca(il, ir); if (fst[il] > fst[ir]) swap(il, ir); if (il == LCA) { q[i].l = fst[il]; q[i].r = fst[ir]; } else { q[i].l = lst[il]; q[i].r = fst[ir]; q[i].lca = LCA; } q[i].id = i; q[i].pos = (q[i].l - 1) / len + 1; } sort(q + 1, q + 1 + m, cmp); l = 1; for (int i = 1; i <= m; ++i) { while (l < q[i].l) chg(ord[l++]); while (r > q[i].r) chg(ord[r--]); while (l > q[i].l) chg(ord[--l]); while (r < q[i].r) chg(ord[++r]); if (q[i].lca) chg(q[i].lca); ans[q[i].id] = Ans; if (q[i].lca) chg(q[i].lca); } for (int i = 1; i <= m; ++i) { printf("%d\n", ans[i]); } return 0; }
27.243902
93
0.411519
[ "vector" ]
2888dec311c2a54cb3fdd1991323898c170d23f3
5,522
cpp
C++
Ubuntu/tests/VCLTests.cpp
rifraf/quick_unit
334a038b9c403c384564a5effe157d95a6a5d763
[ "MIT" ]
1
2015-07-14T15:45:42.000Z
2015-07-14T15:45:42.000Z
Ubuntu/tests/VCLTests.cpp
rifraf/quick_unit
334a038b9c403c384564a5effe157d95a6a5d763
[ "MIT" ]
null
null
null
Ubuntu/tests/VCLTests.cpp
rifraf/quick_unit
334a038b9c403c384564a5effe157d95a6a5d763
[ "MIT" ]
null
null
null
#include "../code_under_test/vcl.h" #include "../quick_unit.hpp" #include "../quick_unit_netbeans.hpp" //-------------------------------------------- DECLARE_SUITE(AnsiString Tests) TEST(AnsiStrings can be created) { assert(new AnsiString() != NULL, SHOULD(create empty AnsiString)); assert(new AnsiString("content") != NULL, SHOULD(create AnsiString with content)); assert(new AnsiString((unsigned)5) != NULL, SHOULD(create AnsiString with unsigned value)); assert(new AnsiString(-5) != NULL, SHOULD(create AnsiString with signed value)); } TEST(AnsiString content can be read) { assert_equal((new AnsiString())->c_str(), "", SHOULD(be empty)); assert_equal((new AnsiString("content"))->c_str(), "content", SHOULD(contain 'content')); assert_equal((new AnsiString((unsigned)5))->c_str(), "5", SHOULD(contain 5)); assert_equal((new AnsiString(-5))->c_str(), "-5", SHOULD(contain -5)); } TEST(AnsiString content can be assigned) { AnsiString x; assert_equal(x.c_str(), "", SHOULD(start empty)); x = "Hello"; assert_equal(x.c_str(), "Hello", SHOULD(be assignable from char *)); x = std::string("Bye"); assert_equal(x.c_str(), "Bye", SHOULD(be assignable from std::string)); } TEST(AnsiString content can be compared) { AnsiString x("Fi"); AnsiString y("Fo"); AnsiString z("Fi"); assert(x == z, SHOULD(match content)); assert(x != y, SHOULD(not match content)); assert(x == "Fi", SHOULD(match string content)); assert(x != "Blah", SHOULD(not match string content)); } TEST(AnsiStrings can be added) { AnsiString x("One"); AnsiString y("Two"); assert_equal((x + y).c_str(), "OneTwo", SHOULD(add 2 AnsiStrings)); assert_equal((x + "Three").c_str(), "OneThree", SHOULD(add an AnsiString and a string)); } TEST(AnsiStrings can be appended) { AnsiString x("One"); AnsiString y("Two"); x += y; assert_equal(x.c_str(), "OneTwo", SHOULD(append an AnsiString)); x += "Three"; assert_equal(x.c_str(), "OneTwoThree", SHOULD(append a string)); } TEST(AnsiStrings have size) { AnsiString x; assert(x.IsEmpty(), SHOULD(be empty after init)); assert(0 == x.Length(), SHOULD(be have zero length after init)); x = "1234567890"; assert(!x.IsEmpty(), SHOULD(not be empty after assign)); assert_equal(10,x.Length(), SHOULD(have length 10 chars)); } TEST(Can find position of a substring) { AnsiString x("The quick brown fox"); assert_equal( 5, x.Pos("quick"), SHOULD(find 'quick')); assert_equal( 1, x.Pos("The"), SHOULD(find 'The')); assert_equal( 0, x.Pos("fax"), SHOULD(not find 'fax')); } TEST(AnsiStrings can extract a sub string) { AnsiString x("The quick brown fox"); AnsiString y = x.SubString(11, 5); assert_equal("brown", y.c_str(), SHOULD(extract 'brown')); y = x.SubString(11, 500); assert_equal("brown fox", y.c_str(), SHOULD(extract 'brown fox')); y = x.SubString(1, 500); assert_equal("The quick brown fox", y.c_str(), SHOULD(extract everything)); } TEST(AnsiStrings can change case) { AnsiString x("Mamba #5"); assert_equal("MAMBA #5", x.UpperCase().c_str(), SHOULD(return upper case)); assert_equal("Mamba #5", x.c_str(), SHOULD(not be changed)); } TEST(AnsiStrings can parse for integers) { assert_equal( 3, ((AnsiString) "").ToIntDef(3)); assert_equal( 4, ((AnsiString)"!2").ToIntDef(4)); assert_equal( 5, ((AnsiString) "5").ToIntDef(99)); assert_equal( 6, ((AnsiString)"+6").ToIntDef(99)); assert_equal(-7, ((AnsiString)"-7").ToIntDef(99)); assert_equal( 8, ((AnsiString)" 8").ToIntDef(99)); } TEST(AnsiStrings support printf) { AnsiString x; x.printf("One %02d %3d", 2, 3); assert_equal("One 02 3", x.c_str(), SHOULD(contain printf result)); } //-------------------------------------------- DECLARE_SUITE(StringList Tests) TEST(StringLists can be created) { assert(new TStringList() != NULL, SHOULD(create empty TStringList)); } TEST(StringLists can contain text) { TStringList x; x.Text("Some content"); assert_equal("Some content", x.Text().c_str(), SHOULD(contain text)); } TEST(Adding to StringLists gives newline separators) { TStringList x; x.Add("One"); assert_equal("One", x.Text().c_str(), SHOULD(contain single element)); x.Add("Two"); assert_equal("One\nTwo", x.Text().c_str(), SHOULD(contain two elements)); x.Add("Three"); assert_equal("One\nTwo\nThree", x.Text().c_str(), SHOULD(contain Three elements)); } TEST(A StringList can be cleared) { TStringList x; x.Text("One\nTwo\nThree"); assert_equal("One\nTwo\nThree", x.Text().c_str(), SHOULD(contain nothing)); x.Clear(); assert_equal("", x.Text().c_str(), SHOULD(contain nothing)); } TEST(A StringList has countable elements) { TStringList x; assert_equal(0, x.Count(), SHOULD(contain nothing)); x.Text("One\nTwo\nThree"); assert_equal(3, x.Count(), SHOULD(contain three)); } TEST(The elements of a StringList can be accessed) { TStringList x; x.Text("One\nTwo\nThree"); x.Add("Four"); assert_equal("One", x.Strings(0).c_str(), SHOULD(contain One)); assert_equal("Two", x.Strings(1).c_str(), SHOULD(contain Two)); assert_equal("Three",x.Strings(2).c_str(), SHOULD(contain Three)); assert_equal("Four", x.Strings(3).c_str(), SHOULD(contain Four)); assert_equal("", x.Strings(4).c_str(), SHOULD(contain nothing)); } // ---------------------------- int main(int argc, char** argv) { return RUN_TESTS(); }
31.19774
93
0.644151
[ "3d" ]
2889e63eba1e4ecd9b50d04980e2ac286f2a066b
1,856
cpp
C++
Wangscape/noise/module/codecs/TranslatePointWrapperCodec.cpp
cheukyin699/Wangscape
b01cb310f97e33394c1c0fac23a7f40c34f632cf
[ "MIT" ]
60
2016-12-30T03:18:34.000Z
2022-02-15T21:43:59.000Z
Wangscape/noise/module/codecs/TranslatePointWrapperCodec.cpp
cheukyin699/Wangscape
b01cb310f97e33394c1c0fac23a7f40c34f632cf
[ "MIT" ]
149
2016-12-29T19:38:36.000Z
2017-10-29T18:19:51.000Z
Wangscape/noise/module/codecs/TranslatePointWrapperCodec.cpp
cheukyin699/Wangscape
b01cb310f97e33394c1c0fac23a7f40c34f632cf
[ "MIT" ]
16
2016-12-31T06:09:42.000Z
2021-09-10T05:34:51.000Z
#include "TranslatePointWrapperCodec.h" namespace spotify { namespace json { using TranslatePointWrapper = noise::module::Wrapper<noise::module::TranslatePoint>; codec::object_t<TranslatePointWrapper> default_codec_t<TranslatePointWrapper>::codec() { auto codec = codec::object<TranslatePointWrapper>(); codec.required("type", codec::eq<std::string>("TranslatePoint")); codec.required("SourceModule", codec::ignore_t<int>()); codec.optional("XTranslation", [](const TranslatePointWrapper& mw) {return mw.module->GetXTranslation(); }, [](TranslatePointWrapper& mw, double x_translation) {mw.module->SetXTranslation(x_translation); }); codec.optional("YTranslation", [](const TranslatePointWrapper& mw) {return mw.module->GetYTranslation(); }, [](TranslatePointWrapper& mw, double y_translation) {mw.module->SetYTranslation(y_translation); }); codec.optional("ZTranslation", [](const TranslatePointWrapper& mw) {return mw.module->GetZTranslation(); }, [](TranslatePointWrapper& mw, double z_translation) {mw.module->SetZTranslation(z_translation); }); codec.optional("Translation", [](const TranslatePointWrapper& mw) {return noise::module::UniformTriple( mw.module->GetXTranslation(), mw.module->GetYTranslation(), mw.module->GetZTranslation()); }, [](TranslatePointWrapper& mw, noise::module::UniformTriple translation) {mw.module->SetTranslation( translation.x, translation.y, translation.z); }, default_codec<noise::module::UniformTriple>()); return codec; } } }
50.162162
122
0.609375
[ "object" ]
288a5418028a866c818ff03f75f02de5020988e2
1,270
cpp
C++
ds3runtime/hooks/lua_capture.cpp
tremwil/DS3RuntimeScripting
50508bbf9295f87c459722ea3bea015c85a36de5
[ "MIT" ]
8
2021-06-05T21:59:53.000Z
2022-02-03T10:00:09.000Z
ds3runtime/hooks/lua_capture.cpp
tremwil/DS3RuntimeScripting
50508bbf9295f87c459722ea3bea015c85a36de5
[ "MIT" ]
null
null
null
ds3runtime/hooks/lua_capture.cpp
tremwil/DS3RuntimeScripting
50508bbf9295f87c459722ea3bea015c85a36de5
[ "MIT" ]
5
2021-05-17T19:49:29.000Z
2022-02-26T11:00:29.000Z
/* * DS3RuntimeScripting * Contributers: Amir */ #pragma once #include "pch.h" #include "lua_capture.h" #include "ds3runtime/ds3runtime.h" namespace ds3runtime { LuaCapture::LuaCapture() : Hook(0x14112fcd0, (uintptr_t)onLuaGetTop, {}), mut(), cond() { instance = this; this->luaStates = std::vector<lua_State*>(); } LuaCapture::~LuaCapture() { } int LuaCapture::onLuaGetTop(lua_State* luaState) { int(*originalFunction)(lua_State*); *(uintptr_t*)&originalFunction = *instance->original; int luaStateTop = originalFunction(luaState); bool alreadyCaptured = false; std::lock_guard<std::mutex> lock(instance->mut); for (lua_State* iLuaState : instance->luaStates) if (luaState == iLuaState) alreadyCaptured = true; if (!alreadyCaptured) { static int stateNumber = 1; static uint64_t startTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); instance->luaStates.push_back(luaState); stateNumber++; /* lua_getglobal(luaState, "hkbSelf"); const void* hkbSelf = lua_topointer(luaState, -1); lua_remove(luaState, -1); spdlog::debug("hkbSelf??: {}", hkbSelf); */ } instance->cond.notify_one(); return luaStateTop; } LuaCapture* LuaCapture::instance = nullptr; };
23.518519
145
0.715748
[ "vector" ]
288dc03aae826f486cc132b92eb600f2860adca0
1,180
cpp
C++
array/mergeSortedArrays.cpp
auniquesun/Data-Structure-and-Algorithms
10baee11e8e0ff84873d37e91a7b360e22a5d9a0
[ "Apache-2.0" ]
1
2018-05-09T03:12:06.000Z
2018-05-09T03:12:06.000Z
array/mergeSortedArrays.cpp
auniquesun/Data-Structure-and-Algorithms
10baee11e8e0ff84873d37e91a7b360e22a5d9a0
[ "Apache-2.0" ]
null
null
null
array/mergeSortedArrays.cpp
auniquesun/Data-Structure-and-Algorithms
10baee11e8e0ff84873d37e91a7b360e22a5d9a0
[ "Apache-2.0" ]
1
2021-04-23T13:37:41.000Z
2021-04-23T13:37:41.000Z
/* problem: 合并两个有序数组 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。 说明: 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。 示例: 输入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 输出: [1,2,2,3,5,6] idea: 这道题看似非常简单,但是也有几个坑 1. nums1是引用传递,而且函数返回值为void,所以最终的操作结果要体现在nums1上 2. nums1在插入或者删除的过程中,长度是动态变化的,循环条件要注意这种变化 */ class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { for(int j=0, i=0;j<n;){ // 有两种情况,需要把nums2[j]插入nums1 // 1. nums1[i]>nums2[j], 表明合并出现逆序,需要把nums2[j]插到nums1[i]之前 // 2. 当nums1已经扫描到末尾,nums2还有元素,把nums2剩余元素逐个插入nums1 if(nums1[i]>nums2[j] || i==m+j){ vector<int>::iterator it = nums1.begin();//it需要初始化 nums1.insert(it+i, nums2[j]); j++; i++; } else if(nums1[i]<=nums2[j]) i++; } //删掉多余的元素;要灵活,这种情况从后往前删 for(vector<int>::iterator it = nums1.end() - 1; nums1.size()>m+n; it--){ cout<< *it << endl; nums1.erase(it); } } };
26.222222
84
0.527119
[ "vector" ]
288df604eae6bbc5a729e0abbaabe17b483e84d6
244
cpp
C++
AtCoder/abc208/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
AtCoder/abc208/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
1
2021-10-19T08:47:23.000Z
2022-03-07T05:23:56.000Z
AtCoder/abc208/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { int p, ans = 0, q = 3628800; cin >> p; for (int i = 10; i >= 1; i--) ans += p / q, p %= q, q /= i; cout << ans << endl; }
22.181818
63
0.540984
[ "vector" ]
288eb3bdcfaefffb882d39a3be67f5414011209b
10,720
cpp
C++
src/UnfoldingEvaluator.cpp
BBrumback/Final_project_mesh_unfolder
4fbb1f9b4e34f6061c87ae08dc0c4e7ab256cddc
[ "MIT" ]
1
2021-04-23T09:11:23.000Z
2021-04-23T09:11:23.000Z
src/UnfoldingEvaluator.cpp
BBrumback/Final_project_mesh_unfolder
4fbb1f9b4e34f6061c87ae08dc0c4e7ab256cddc
[ "MIT" ]
null
null
null
src/UnfoldingEvaluator.cpp
BBrumback/Final_project_mesh_unfolder
4fbb1f9b4e34f6061c87ae08dc0c4e7ab256cddc
[ "MIT" ]
null
null
null
/* * UnfoldingEvaluator.cpp * * Created on: Feb 29, 2016 * Author: zxi */ #include "UnfoldingEvaluator.h" #include <numeric> #include "libga/Individual.h" #include "unfolder.h" #include "OverlappingChecker.h" #include "util/UnfolderHelper.h" #include "polygon/polygon.h" #include "CurveMatching/img2ply.h" #include "CurveMatching/opencvstd.h" #include "CurveMatching/curve_db_param.h" #include "CurveMatching/shadow.h" namespace masc { namespace unfolding { /////////////////////////////////////////////////////////////////////////////// // OverlappingEvaluator /////////////////////////////////////////////////////////////////////////////// double OverlappingEvaluator::evaluate(masc::ga::Individual* ind) { // Build from weights, check global overlaps const int global_overlaps = this->m_unfolder->buildFromWeights( ind->getGenome()); // Check local overlaps // local overlaps is not very useful when the net is large. const int local_overlaps = this->m_unfolder->checkLocalOverlaps(); // use default overlapping check double fitness = -(global_overlaps + local_overlaps * 100); return fitness; } /////////////////////////////////////////////////////////////////////////////// // AreaEvaluator /////////////////////////////////////////////////////////////////////////////// AreaEvaluator::AreaEvaluator(Unfolder* unfolder) : UnfoldingEvaluator(unfolder) { m_checker.reset(new PixelChecker(unfolder)); m_best_ratio = 1e3; } double AreaEvaluator::evaluate(masc::ga::Individual* ind) { // build the model, but do not check overlaps this->m_unfolder->buildFromWeights(ind->getGenome(), false); // check area ratio const double area_ratio = this->m_checker->checkOverlapping( m_unfolder->getUnfolded(), m_unfolder->getConfig()); // maximum overlaps int overlaps = (m_unfolder->getModel()->t_size) * (m_unfolder->getModel()->t_size); // only check when ratio is low if (area_ratio < m_best_ratio * 1.01) overlaps = m_unfolder->checkOverlaps(); if (area_ratio < m_best_ratio) m_best_ratio = area_ratio; return -overlaps; } /////////////////////////////////////////////////////////////////////////////// // Net Evaluators /////////////////////////////////////////////////////////////////////////////// double CutLengthEvaluator::evaluate(Unfolder* unfolder) { return unfolder->getTotalCutLength(); } double FoldAmountEvaluator::evaluate(Unfolder* unfolder) { return unfolder->getTotalFoldAmount(); } double HullAreaEvaluator::evaluate(Unfolder* unfolder) { return 1.0/unfolder->getHullArea(); } //----------------------------------------------------------------------------- // // parameters for PolygonFitEvaluator // //----------------------------------------------------------------------------- //a shape is said to be inside the target is the boundary and area differences are smaller than the values below const int matching_tolerable_max_diff = 3; //max boundary difference const float matching_tolerable_sum_diff = 200; //max area difference //smallest boundary that will be extracted from the image const int curveDB_resample_size=100; const int spot_target_smallest_curve_size = 70; // 5, 10, 25 const int spot_target_longest_curve_size = 99; const int spot_target_offset_size = 2; typedef CurveMatcher MATCHER; typedef cv::Point CVPT; typedef CURVE_DB_PARAM<MATCHER> MY_CURVE_DB_PARAM; PolygonFitEvaluator::PolygonFitEvaluator(const std::string& stencil_filename) :NetEvaluator(), m_poly_ptr(NULL), m_best_net_ptr(NULL), m_min_error(FLT_MAX) { auto * target = new CSShape<MATCHER, CVPT>(); assert(target); if(stencil_filename.empty()) { cerr<<"! Error: No stencil file is given for PolygonFitEvaluator"<<endl; exit(1); } cv::Mat img = cv::imread(stencil_filename, CV_LOAD_IMAGE_GRAYSCALE); //cout<<"image size="<<img.size[0]<<" "<<img.size[1]<<endl; // flip the image //cv::flip(img, img, 0); //cv::imshow("img",img); //waitKey(0); // c_polygon polygon; bool success = img2ply(img, polygon); if(!success) { cerr<<"! Error: Failed to create polygon from stencil file "<<stencil_filename<<" in PolygonFitEvaluator"<<endl; exit(1); } //cout<<polygon<<endl; target->contours.push_back(polygon); //from polygon create matching curves MY_CURVE_DB_PARAM::CurveResampleSize = curveDB_resample_size; MY_CURVE_DB_PARAM::SmallestCurveSegmentSize = spot_target_smallest_curve_size; MY_CURVE_DB_PARAM::LongestCurveSegmentSize = spot_target_longest_curve_size; MY_CURVE_DB_PARAM::OffsetStepSize = spot_target_offset_size; target->buildCurveSegmentDB(); //target->image = img;//cv::Mat(img.size[0], img.size[1], CV_8UC1, img); //m_target.build_domain(shadow_shader, depthVP, buffers); //target->builDistField(); m_poly_ptr=target; } PolygonFitEvaluator::~PolygonFitEvaluator() { auto * target = (CSShape<MATCHER, CVPT>*)m_poly_ptr; auto * source = (CSShape<MATCHER, CVPT>*)m_best_net_ptr; if(target!=NULL && source!=NULL) { auto& target_db = target->contourDBs[0]; //only consider the first contour auto& source_db = source->contourDBs[0]; //only consider the first contour #if 1 MATCHER matcher; MY_CURVE_DB_PARAM::initializeMatcher(matcher); matcher.setTarget(target_db.cv_contour); matcher.setSource(source_db.cv_contour); //save the best match to file //cout<<"min_error="<<min_error<<endl; //matcher.visualizeMatching(best_source_curve_segment.x,best_source_curve_segment.y, best_target_curve_segment.x, best_target_curve_segment.y); stringstream ss; ss<<"polygonfitevaluator_best_net_gen_err_"<<m_min_error<<".jpg"; matcher.renderMatching(ss.str(), best_src_off,best_src_len, best_target_off, best_src_len); cout<<"- PolygonFitEvaluator:: Saved best matching to "<<ss.str()<<endl; #endif } delete target; } //convert a flattened model into a CSShape inline void model2poly(const model* m, CSShape<MATCHER, CVPT>& net, const Config& config) { SVGWriter writer(m, config); vector<int> boundary; writer.FindBoundaryPolygon(&boundary); //create netshadow c_polygon polygon; c_ply ply(c_ply::POUT); ply.beginPoly(); for(auto& id : boundary) { Vector3d pos=writer.GetSVGCoord(id); ply.addVertex(pos[0],pos[2]); } ply.endPoly(); polygon.push_back(ply); net.contours.push_back(polygon); net.buildCurveSegmentDB(); } double PolygonFitEvaluator::evaluate(Unfolder* unfolder) { //cout<<"is flattended="<<unfolder->isFlattened()<<endl; CSShape<MATCHER, CVPT> net; auto * target = (CSShape<MATCHER, CVPT>*)m_poly_ptr; if(target==NULL) { cerr<<"! Error: Cannot convert from m_poly_ptr to CSShape"<<endl; exit(1); } //auto start_time = clock(); unfolder->rebuildModel(); model2poly(unfolder->getNet(), net, unfolder->getConfig()); //cout<<"model2poly takes "<<(clock()-start_time)*1.0/CLOCKS_PER_SEC<<" secs"<<endl; //compute transforms and check if we can put the net inside... auto& target_db = target->contourDBs[0]; //only consider the first contour auto& source_db = net.contourDBs[0]; //only consider the first contour int cs_size = target_db.curve_segments.size(); //initialize the matcher MATCHER matcher; MY_CURVE_DB_PARAM::initializeMatcher(matcher); matcher.setTarget(target_db.cv_contour); //initalize the matches //update the best match so far auto best_target_curve_segment = target_db.curve_segments[0]; auto best_source_curve_segment = source_db.curve_segments[0]; double min_error=FLT_MAX; //cout<<"target cs_size="<<cs_size<<" source cs_size="<<source_db.curve_segments.size()<<endl; //start_time = clock(); for (int j = 0; j < cs_size; j++) { //cout << "\t- Working on curve segetment=" << j << "/" << cs_size << " updated!!" << endl; auto& target_curve_segment = target_db.curve_segments[j]; vector<double>& target_curve_curvatures = target_db.curvatures[j]; matcher.setSource(source_db.cv_contour); cv::DMatch match; //match the shadow to the segment of the target... //the return is the best match //matcher.CompareCurvesUsingSignatureDB(source_db.curve_segments, target_curve_segment, source_db.curvatures, target_curve_curvatures, match); matcher.CompareCurvesUsingSignatureDB_curvature_only(source_db.curve_segments, target_curve_segment, source_db.curvatures, target_curve_curvatures, match); if (match.queryIdx < 0) continue; //there is not match to the curve_segment // //make sure that the entire contour can fit in.... // int shadow_len = source_db.curve_segments[match.queryIdx].x; // int shadow_off = source_db.curve_segments[match.queryIdx].y; // int target_len = target_curve_segment.x; // int target_off = target_curve_segment.y; //double rmse = matcher.ComputeWholeRMSE(shadow_len, shadow_off, target_len, target_off); //if (rmse >= min_error) continue; //the error is bigger if(match.distance>=min_error) continue; //the error is bigger //cv::Mat transform; //matcher.computeTransform(shadow_len, shadow_off, target_len, target_off, transform); //bool isinside = target->inside(source_db.cv_contour, transform, matching_tolerable_max_diff, matching_tolerable_sum_diff); //if (isinside == false) continue; //does not fit to the target... best_target_curve_segment = target_db.curve_segments[j]; best_source_curve_segment = source_db.curve_segments[match.queryIdx]; //min_error = rmse; min_error = match.distance; } //cout<<"find match takes "<<(clock()-start_time)*1.0/CLOCKS_PER_SEC<<" secs"<<endl; if(min_error<m_min_error) { m_min_error=min_error; best_src_off=best_source_curve_segment.x; best_src_len=best_source_curve_segment.y; best_target_off=best_target_curve_segment.x; best_target_len=best_target_curve_segment.y; if(m_best_net_ptr==NULL) m_best_net_ptr= new CSShape<MATCHER, CVPT>(); assert(m_best_net_ptr); //copy net to m_best_net_ptr *((CSShape<MATCHER, CVPT>*)m_best_net_ptr)=net; } #if 0 //save the best match to file //cout<<"min_error="<<min_error<<endl; //matcher.visualizeMatching(best_source_curve_segment.x,best_source_curve_segment.y, best_target_curve_segment.x, best_target_curve_segment.y); static int counter=0; stringstream ss; ss<<"gen_err_"<<min_error<<"_"<<counter++<<".jpg"; matcher.renderMatching(ss.str(), best_source_curve_segment.x,best_source_curve_segment.y, best_target_curve_segment.x, best_target_curve_segment.y); //cout<<"\t- Saved best matching to "<<ss.str()<<endl; #endif return 1.0/min_error; } } /* namespace unfoldings */ } /* namespace masc */
33.188854
159
0.684795
[ "shape", "vector", "model", "transform" ]
288f11cfd1ccc0224e585b3c8c53ef7d65eb850a
1,876
hh
C++
PacEnv/EdmlDetector.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
PacEnv/EdmlDetector.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
PacEnv/EdmlDetector.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
/* Class: EdmlDetector * * A top-level class representing an EDML detector */ #ifndef EdmlDetector_HH #define EdmlDetector_HH #include <string> #include <vector> class EdmlDetVolume; class EdmlDetElement; /// A top-level detector class of an EDML configuration /** * The class is a (potentially multi-layered) container for detector volumes. */ class EdmlDetector { friend class EdmlParser; private: /* These methods and are prohibited because of the instance-level cache * which can't be trivially cloned in its current implementation. */ EdmlDetector( ); EdmlDetector( const EdmlDetector& ); EdmlDetector& operator=( const EdmlDetector& ); /// Normal c-tor /** * It's available to the friends only. It will set up a context of * of an object. * * OWNERSHIP NOTE: the ownership IS transfered into the method (object) */ EdmlDetector( const std::string& theName, const std::vector<EdmlDetVolume* >& theVolumes ); void append(const std::vector<EdmlDetVolume* >& theVolumes ); public: /// The d-tor /** * NOTE: It will destroy all volumes owned by an object. */ virtual ~EdmlDetector( ); /// Get detector name inline std::string name( ) const { return _name; } /// Get volumes /** * OWNSHIP NOTE: the ownership is NOT returned with the result. */ void volumes( std::vector<const EdmlDetVolume* >& theVolumes ) const; /// Get all elements from all volumes /** * OWNSHIP NOTE: the ownership is NOT returned with the result. */ void elements( std::vector<const EdmlDetElement* >& theElements ) const; private: // The context of the class // std::string _name; std::vector<EdmlDetVolume* > _volumes; }; #endif // EdmlDetector_HH
24.363636
78
0.640192
[ "object", "vector" ]
288f4f129d61a243679457631b571d179db0a749
8,723
cc
C++
tensorflow/compiler/mlir/tensorflow/transforms/freeze_global_tensors.cc
zhupengyang/tensorflow
584cd92f6a2ff3ba63e653e2e3d0c6f78e3d15eb
[ "Apache-2.0" ]
2
2022-01-08T13:06:57.000Z
2022-02-16T01:08:00.000Z
tensorflow/compiler/mlir/tensorflow/transforms/freeze_global_tensors.cc
zhupengyang/tensorflow
584cd92f6a2ff3ba63e653e2e3d0c6f78e3d15eb
[ "Apache-2.0" ]
19
2021-12-28T12:44:55.000Z
2022-01-13T08:11:28.000Z
tensorflow/compiler/mlir/tensorflow/transforms/freeze_global_tensors.cc
zhupengyang/tensorflow
584cd92f6a2ff3ba63e653e2e3d0c6f78e3d15eb
[ "Apache-2.0" ]
1
2022-01-26T18:52:28.000Z
2022-01-26T18:52:28.000Z
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <algorithm> #include <vector> #include "llvm/ADT/BitVector.h" #include "llvm/Support/Casting.h" #include "mlir/Analysis/DataFlowAnalysis.h" // from @llvm-project #include "mlir/IR/Builders.h" // from @llvm-project #include "mlir/IR/BuiltinAttributes.h" // from @llvm-project #include "mlir/IR/BuiltinOps.h" // from @llvm-project #include "mlir/IR/SymbolTable.h" // from @llvm-project #include "mlir/IR/UseDefLists.h" // from @llvm-project #include "mlir/IR/Value.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Support/LLVM.h" // from @llvm-project #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/savedmodel_passes_detail.h" namespace mlir { namespace tf_saved_model { namespace { // The value of our lattice represents the GlobalTensorOp matching the value. struct ResourceLatticeValue { explicit ResourceLatticeValue(GlobalTensorOp op = nullptr) { if (op) ops.insert(op); } static ResourceLatticeValue getPessimisticValueState(MLIRContext *context) { return ResourceLatticeValue(); } static ResourceLatticeValue getPessimisticValueState(Value value) { if (auto barg = value.dyn_cast<BlockArgument>()) { if (FuncOp func = dyn_cast<FuncOp>(barg.getOwner()->getParentOp())) { SymbolTable symbol_table(func->getParentOfType<ModuleOp>()); auto global_tensor = LookupBoundInputOfType<GlobalTensorOp>( func, barg.getArgNumber(), symbol_table); return ResourceLatticeValue(global_tensor); } } return ResourceLatticeValue(); } bool operator==(const ResourceLatticeValue &rhs) const { return ops == rhs.ops; } static ResourceLatticeValue join(const ResourceLatticeValue &lhs, const ResourceLatticeValue &rhs) { // Take union of both sets of possible GlobalTensorOp values that can be // referenced here. ResourceLatticeValue ret; ret.ops.insert(lhs.ops.begin(), lhs.ops.end()); ret.ops.insert(rhs.ops.begin(), rhs.ops.end()); return ret; } // The location which originated the int value. DenseSet<GlobalTensorOp> ops; }; class ResourceAnalysis : public ForwardDataFlowAnalysis<ResourceLatticeValue> { public: using LatticeElementT = LatticeElement<ResourceLatticeValue>; using ForwardDataFlowAnalysis<ResourceLatticeValue>::ForwardDataFlowAnalysis; ~ResourceAnalysis() override = default; ChangeResult visitOperation(Operation *op, ArrayRef<LatticeElementT *> operands) override { return markAllPessimisticFixpoint(op->getResults()); } }; struct FreezeGlobalTensorsPass : public FreezeGlobalTensorsPassBase<FreezeGlobalTensorsPass> { explicit FreezeGlobalTensorsPass(bool allow_mutable_tensors) { this->allow_mutable_tensors = allow_mutable_tensors; } void runOnOperation() override; }; void FreezeGlobalTensorsPass::runOnOperation() { auto module = getOperation(); if (!tf_saved_model::HasTfSavedModelSemantics(module)) return; ResourceAnalysis analysis(&getContext()); analysis.run(module); DenseSet<GlobalTensorOp> remaining_global_tensor_ops; { auto ops = module.getOps<GlobalTensorOp>(); remaining_global_tensor_ops.insert(ops.begin(), ops.end()); } for (auto global_tensor : remaining_global_tensor_ops) { // This pass assumes that all global tensors as immutable (e.g. by a // previous optimize global tensors pass). If not, this pass has to fail // since it cannot perform one of its goals. if (global_tensor.is_mutable()) { if (allow_mutable_tensors) continue; global_tensor.emitError() << "is not immutable, try removing mutable variables in your model " "since mutable variables are currently not supported through " "this converter"; return signalPassFailure(); } } // Collect all those freezable. This is an extra scan but allows for the // partial behavior from `allow_mutable_tensor`. DenseMap<BlockArgument, bool> freezeable; for (auto func : module.getOps<FuncOp>()) { for (BlockArgument val : func.getArguments()) { if (!getElementTypeOrSelf(val.getType()).isa<TF::ResourceType>()) continue; // Check that there is only a single global tensor associated with arg. LatticeElement<ResourceLatticeValue> *latticeElement = analysis.lookupLatticeElement(val); if (!latticeElement || latticeElement->getValue().ops.size() != 1) continue; // Don't freeze mutable tensors. if (latticeElement->getValue().ops.begin()->is_mutable()) { freezeable[val] = false; continue; } freezeable[val] = true; // Verify users are supported kind. for (Operation *user : val.getUsers()) { if (!(isa<TF::ReadVariableOp>(user) || isa<CallOpInterface>(user))) { freezeable[val] = false; // Error out early if possible. if (!allow_mutable_tensors) { user->emitError() << "could not rewrite use of immutable bound input"; return signalPassFailure(); } } } } } DenseSet<GlobalTensorOp> frozen_global_tensors; for (auto func : module.getOps<FuncOp>()) { SmallVector<unsigned, 4> args_to_erase; DenseMap<Operation *, llvm::BitVector> remove_operands; OpBuilder builder(func.getBody()); for (BlockArgument val : func.getArguments()) { if (!freezeable[val]) continue; LatticeElement<ResourceLatticeValue> *latticeElement = analysis.lookupLatticeElement(val); GlobalTensorOp global_tensor = *latticeElement->getValue().ops.begin(); SmallVector<TF::ReadVariableOp, 4> read_variable_ops_to_erase; frozen_global_tensors.insert(global_tensor); for (Operation *user : val.getUsers()) { if (auto read_op = llvm::dyn_cast<TF::ReadVariableOp>(user)) { // Collect all read variable ops so that all its uses can be replaced // with the tf.constant corresponding to the global tensor op. read_variable_ops_to_erase.push_back(read_op); } else { llvm::BitVector &bvector = remove_operands[user]; bvector.resize(user->getNumOperands()); for (OpOperand &use : user->getOpOperands()) bvector.set(use.getOperandNumber()); } } // Replace the arg with a tf.Const op in the function body. builder.setInsertionPointToStart(&func.getBody().front()); auto const_op = builder.create<TF::ConstOp>(global_tensor.getLoc(), global_tensor.value()); args_to_erase.push_back(val.getArgNumber()); for (auto read_op : read_variable_ops_to_erase) { read_op.getResult().replaceAllUsesWith(const_op.getResult()); read_op.erase(); } } // As the other uses are call operations, we simply remove the arguments // as the function arguments will be removed below once that function is // processed. for (auto it : remove_operands) { it.first->eraseOperands(it.second); } func.eraseArguments(args_to_erase); } // Erase all global tensors that were frozen. for (auto global_tensor : frozen_global_tensors) { remaining_global_tensor_ops.erase(global_tensor); global_tensor->erase(); } // Verify that there are no remaining global tensors. if (!allow_mutable_tensors && !remaining_global_tensor_ops.empty()) { module.emitError() << "could not freeze all global tensors in the module"; return signalPassFailure(); } } } // namespace std::unique_ptr<OperationPass<ModuleOp>> CreateFreezeGlobalTensorsPass( bool allow_mutable_tensors) { return std::make_unique<FreezeGlobalTensorsPass>(allow_mutable_tensors); } } // namespace tf_saved_model } // namespace mlir
37.437768
84
0.692308
[ "vector", "model" ]
28930924d9077badbc788327de612a68c09968c3
3,945
cc
C++
mts/src/model/QueryMediaListByURLRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
mts/src/model/QueryMediaListByURLRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
mts/src/model/QueryMediaListByURLRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/mts/model/QueryMediaListByURLRequest.h> using AlibabaCloud::Mts::Model::QueryMediaListByURLRequest; QueryMediaListByURLRequest::QueryMediaListByURLRequest() : RpcServiceRequest("mts", "2014-06-18", "QueryMediaListByURL") { setMethod(HttpRequest::Method::Post); } QueryMediaListByURLRequest::~QueryMediaListByURLRequest() {} long QueryMediaListByURLRequest::getResourceOwnerId() const { return resourceOwnerId_; } void QueryMediaListByURLRequest::setResourceOwnerId(long resourceOwnerId) { resourceOwnerId_ = resourceOwnerId; setParameter(std::string("ResourceOwnerId"), std::to_string(resourceOwnerId)); } bool QueryMediaListByURLRequest::getIncludeSummaryList() const { return includeSummaryList_; } void QueryMediaListByURLRequest::setIncludeSummaryList(bool includeSummaryList) { includeSummaryList_ = includeSummaryList; setParameter(std::string("IncludeSummaryList"), includeSummaryList ? "true" : "false"); } std::string QueryMediaListByURLRequest::getAccessKeyId() const { return accessKeyId_; } void QueryMediaListByURLRequest::setAccessKeyId(const std::string &accessKeyId) { accessKeyId_ = accessKeyId; setParameter(std::string("AccessKeyId"), accessKeyId); } std::string QueryMediaListByURLRequest::getFileURLs() const { return fileURLs_; } void QueryMediaListByURLRequest::setFileURLs(const std::string &fileURLs) { fileURLs_ = fileURLs; setParameter(std::string("FileURLs"), fileURLs); } bool QueryMediaListByURLRequest::getIncludePlayList() const { return includePlayList_; } void QueryMediaListByURLRequest::setIncludePlayList(bool includePlayList) { includePlayList_ = includePlayList; setParameter(std::string("IncludePlayList"), includePlayList ? "true" : "false"); } std::string QueryMediaListByURLRequest::getResourceOwnerAccount() const { return resourceOwnerAccount_; } void QueryMediaListByURLRequest::setResourceOwnerAccount(const std::string &resourceOwnerAccount) { resourceOwnerAccount_ = resourceOwnerAccount; setParameter(std::string("ResourceOwnerAccount"), resourceOwnerAccount); } bool QueryMediaListByURLRequest::getIncludeSnapshotList() const { return includeSnapshotList_; } void QueryMediaListByURLRequest::setIncludeSnapshotList(bool includeSnapshotList) { includeSnapshotList_ = includeSnapshotList; setParameter(std::string("IncludeSnapshotList"), includeSnapshotList ? "true" : "false"); } std::string QueryMediaListByURLRequest::getOwnerAccount() const { return ownerAccount_; } void QueryMediaListByURLRequest::setOwnerAccount(const std::string &ownerAccount) { ownerAccount_ = ownerAccount; setParameter(std::string("OwnerAccount"), ownerAccount); } long QueryMediaListByURLRequest::getOwnerId() const { return ownerId_; } void QueryMediaListByURLRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter(std::string("OwnerId"), std::to_string(ownerId)); } bool QueryMediaListByURLRequest::getIncludeMediaInfo() const { return includeMediaInfo_; } void QueryMediaListByURLRequest::setIncludeMediaInfo(bool includeMediaInfo) { includeMediaInfo_ = includeMediaInfo; setParameter(std::string("IncludeMediaInfo"), includeMediaInfo ? "true" : "false"); }
33.432203
100
0.769582
[ "model" ]
80bfb072b853ffe9434e57f23d9be8714d2e244c
5,563
cpp
C++
3rdparty/openmm/platforms/cuda/tests/TestCudaSort.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
5
2020-07-31T17:33:03.000Z
2022-01-01T19:24:37.000Z
3rdparty/openmm/platforms/cuda/tests/TestCudaSort.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
11
2020-06-16T05:05:42.000Z
2022-03-30T09:59:14.000Z
3rdparty/openmm/platforms/cuda/tests/TestCudaSort.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
9
2020-01-24T12:02:37.000Z
2020-10-16T06:23:56.000Z
/* -------------------------------------------------------------------------- * * OpenMM * * -------------------------------------------------------------------------- * * This is part of the OpenMM molecular simulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2008-2016 Stanford University and the Authors. * * Authors: Peter Eastman * * Contributors: * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * * THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * * USE OR OTHER DEALINGS IN THE SOFTWARE. * * -------------------------------------------------------------------------- */ /** * This tests the CUDA implementation of sorting. */ #include "openmm/internal/AssertionUtilities.h" #include "CudaArray.h" #include "CudaContext.h" #include "CudaSort.h" #include "sfmt/SFMT.h" #include "openmm/System.h" #include <iostream> #include <cmath> #include <set> using namespace OpenMM; using namespace std; CudaPlatform platform; class SortTrait : public CudaSort::SortTrait { int getDataSize() const {return 4;} int getKeySize() const {return 4;} const char* getDataType() const {return "float";} const char* getKeyType() const {return "float";} const char* getMinKey() const {return "-3.40282e+38f";} const char* getMaxKey() const {return "3.40282e+38f";} const char* getMaxValue() const {return "3.40282e+38f";} const char* getSortKey() const {return "value";} }; void verifySorting(vector<float> array) { // Sort the array. System system; system.addParticle(0.0); CudaPlatform::PlatformData platformData(NULL, system, "", "true", platform.getPropertyDefaultValue("CudaPrecision"), "false", platform.getPropertyDefaultValue(CudaPlatform::CudaCompiler()), platform.getPropertyDefaultValue(CudaPlatform::CudaTempDirectory()), platform.getPropertyDefaultValue(CudaPlatform::CudaHostCompiler()), platform.getPropertyDefaultValue(CudaPlatform::CudaDisablePmeStream()), "false", 1, NULL); CudaContext& context = *platformData.contexts[0]; context.initialize(); CudaArray data(context, array.size(), 4, "sortData"); data.upload(array); CudaSort sort(context, new SortTrait(), array.size()); sort.sort(data); vector<float> sorted; data.download(sorted); // Verify that it is in sorted order. for (int i = 1; i < (int) sorted.size(); i++) ASSERT(sorted[i-1] <= sorted[i]); // Make sure the sorted array contains the same values as the original one. multiset<float> elements1(array.begin(), array.end()); multiset<float> elements2(sorted.begin(), sorted.end()); ASSERT(elements1 == elements2); } void testUniformValues() { OpenMM_SFMT::SFMT sfmt; init_gen_rand(0, sfmt); vector<float> array(10000); for (int i = 0; i < (int) array.size(); i++) array[i] = (float) genrand_real2(sfmt); verifySorting(array); } void testLogValues() { OpenMM_SFMT::SFMT sfmt; init_gen_rand(0, sfmt); vector<float> array(10000); for (int i = 0; i < (int) array.size(); i++) array[i] = (float) log(genrand_real2(sfmt)); verifySorting(array); } void testShortList() { OpenMM_SFMT::SFMT sfmt; init_gen_rand(0, sfmt); vector<float> array(500); for (int i = 0; i < (int) array.size(); i++) array[i] = (float) log(genrand_real2(sfmt)); verifySorting(array); } int main(int argc, char* argv[]) { try { if (argc > 1) platform.setPropertyDefaultValue("CudaPrecision", string(argv[1])); testUniformValues(); testLogValues(); testShortList(); } catch(const exception& e) { cout << "exception: " << e.what() << endl; return 1; } cout << "Done" << endl; return 0; }
40.904412
170
0.577926
[ "vector" ]
80c35d704374957008e893d4bcb709553478db20
8,465
cpp
C++
Testing/Operations/mafOpExporterVTKTest.cpp
breseight/MAF2
77b517b5450cc7fe82cb99c5bb23db89980e30e8
[ "Apache-2.0" ]
1
2021-05-10T19:01:10.000Z
2021-05-10T19:01:10.000Z
Testing/Operations/mafOpExporterVTKTest.cpp
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
null
null
null
Testing/Operations/mafOpExporterVTKTest.cpp
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Program: MAF2 Module: mafOpExporterVTKTest Authors: Matteo Giacomoni Copyright (c) B3C All rights reserved. See Copyright.txt or http://www.scsitaly.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "mafDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the MAF must include "mafDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include <cppunit/config/SourcePrefix.h> #include "mafOpExporterVTKTest.h" #include "mafOpExporterVTK.h" #include "mafVMERoot.h" #include "mafVMESurface.h" #include "mafVMEVolumeGray.h" #include "mafVMEMesh.h" #include "mafVMEPolyline.h" #include "vtkSphereSource.h" #include "vtkPolyDataReader.h" #include "vtkPolyData.h" #include "vtkRectilinearGridReader.h" #include "vtkUnstructuredGridReader.h" #define TEST_RESULT CPPUNIT_ASSERT(result); //---------------------------------------------------------------------------- class DummyVme : public mafVME //---------------------------------------------------------------------------- { public: DummyVme(){}; ~DummyVme(){}; mafTypeMacro(DummyVme,mafVME); /*virtual*/ void SetMatrix(const mafMatrix &mat){}; /*virtual*/ void GetLocalTimeStamps(std::vector<mafTimeStamp> &kframes){}; protected: private: }; mafCxxTypeMacro(DummyVme); //---------------------------------------------------------------------------- void mafOpExporterVTKTest::TestFixture() //---------------------------------------------------------------------------- { } //---------------------------------------------------------------------------- void mafOpExporterVTKTest::setUp() //---------------------------------------------------------------------------- { m_ExporterVTK = new mafOpExporterVTK("VTK"); } //---------------------------------------------------------------------------- void mafOpExporterVTKTest::tearDown() //---------------------------------------------------------------------------- { mafDEL(m_ExporterVTK); } //---------------------------------------------------------------------------- void mafOpExporterVTKTest::TestAccept() //---------------------------------------------------------------------------- { DummyVme *dummyVme = new DummyVme(); result = m_ExporterVTK->Accept((mafNode*)dummyVme); CPPUNIT_ASSERT(result); delete dummyVme; } //---------------------------------------------------------------------------- void mafOpExporterVTKTest::TestOpExportPolydata() //---------------------------------------------------------------------------- { vtkSphereSource *sphere; vtkNEW(sphere); sphere->Update(); mafVMESurface *surface; mafNEW(surface); result = surface->SetData((vtkPolyData*)sphere->GetOutput(),0.0) == MAF_OK; CPPUNIT_ASSERT(result); surface->Update(); m_ExporterVTK->SetInput(surface); mafString filename=MAF_DATA_ROOT; filename<<"/Test_ExporterVTK/PolydataToCheck.vtk"; m_ExporterVTK->SetFileName(filename); m_ExporterVTK->SaveVTKData(); vtkPolyDataReader *reader; vtkNEW(reader); reader->SetFileName(filename); reader->Update(); result = reader->GetOutput() != NULL; CPPUNIT_ASSERT(result); vtkDEL(reader); mafDEL(surface); vtkDEL(sphere); } //---------------------------------------------------------------------------- void mafOpExporterVTKTest::TestOpExportPolydataWithApplyABSMatrix() //---------------------------------------------------------------------------- { vtkSphereSource *sphere; vtkNEW(sphere); sphere->Update(); double start_bounds[6]; sphere->GetOutput()->GetBounds(start_bounds); // Create a mafVMESurface mafVMESurface *surface; mafNEW(surface); surface->SetData((vtkPolyData*)sphere->GetOutput(),0.0) == MAF_OK; surface->Update(); // Apply a transformation mafMatrix m; m.SetElement(0, 3, 2.1); m.SetElement(1, 3, 2.1); m.SetElement(2, 3, 2.1); surface->SetAbsMatrix(m); // set the ABSMatrix flat On m_ExporterVTK->ApplyABSMatrixOn(); m_ExporterVTK->SetInput(surface); mafString filename=MAF_DATA_ROOT; filename<<"/Test_ExporterVTK/PolydataToCheckTransformation.vtk"; m_ExporterVTK->SetFileName(filename); m_ExporterVTK->SaveVTKData(); vtkPolyDataReader *reader; vtkNEW(reader); reader->SetFileName(filename); reader->Update(); result = reader->GetOutput() != NULL; CPPUNIT_ASSERT(result); double end_bounds[6]; reader->GetOutput()->GetBounds(end_bounds); result = mafEquals(start_bounds[0], end_bounds[0]) && mafEquals(start_bounds[1], end_bounds[1]) && mafEquals(start_bounds[2], end_bounds[2]) && mafEquals(start_bounds[3], end_bounds[3]) && mafEquals(start_bounds[4], end_bounds[4]) && mafEquals(start_bounds[5], end_bounds[5]); // check that bounds are not equals. CPPUNIT_ASSERT(!result); vtkDEL(reader); mafDEL(surface); vtkDEL(sphere); } //---------------------------------------------------------------------------- void mafOpExporterVTKTest::TestOpExportMesh() //---------------------------------------------------------------------------- { vtkUnstructuredGridReader *reader; vtkNEW(reader); mafString filenameIn=MAF_DATA_ROOT; filenameIn<<"/Test_ExporterVTK/MeshInput.vtk"; reader->SetFileName(filenameIn); reader->Update(); mafVMEMesh *mesh; mafNEW(mesh); result = mesh->SetData(reader->GetOutput(),0.0) == MAF_OK; CPPUNIT_ASSERT(result); mesh->Update(); mafString filenameOut=MAF_DATA_ROOT; filenameOut<<"/Test_ExporterVTK/MeshToCheck.vtk"; m_ExporterVTK->SetInput(mesh); m_ExporterVTK->SetFileName(filenameOut); m_ExporterVTK->SaveVTKData(); reader->SetFileName(filenameOut); reader->Update(); result = reader->GetOutput() != NULL; CPPUNIT_ASSERT(result); mafDEL(mesh); vtkDEL(reader); } //---------------------------------------------------------------------------- void mafOpExporterVTKTest::TestOpExportVolume() //---------------------------------------------------------------------------- { vtkRectilinearGridReader *reader; vtkNEW(reader); mafString filenameIn=MAF_DATA_ROOT; filenameIn<<"/Test_ExporterVTK/VolumeInput.vtk"; reader->SetFileName(filenameIn); reader->Update(); mafVMEVolumeGray *volume; mafNEW(volume); result = volume->SetData(reader->GetOutput(),0.0) == MAF_OK; CPPUNIT_ASSERT(result); volume->Update(); mafString filenameOut=MAF_DATA_ROOT; filenameOut<<"/Test_ExporterVTK/VolumeToCheck.vtk"; m_ExporterVTK->SetInput(volume); m_ExporterVTK->SetFileName(filenameOut); m_ExporterVTK->SaveVTKData(); reader->SetFileName(filenameOut); reader->Update(); result = reader->GetOutput() != NULL; CPPUNIT_ASSERT(result); mafDEL(volume); vtkDEL(reader); } //---------------------------------------------------------------------------- void mafOpExporterVTKTest::TestOpExportPolyline() //---------------------------------------------------------------------------- { vtkPolyDataReader *reader; vtkNEW(reader); mafString filenameIn=MAF_DATA_ROOT; filenameIn<<"/Test_ExporterVTK/PolylineInput.vtk"; reader->SetFileName(filenameIn); reader->Update(); mafVMEPolyline *polyline; mafNEW(polyline); result = polyline->SetData(reader->GetOutput(),0.0) == MAF_OK; CPPUNIT_ASSERT(result); polyline->Update(); mafString filenameOut=MAF_DATA_ROOT; filenameOut<<"/Test_ExporterVTK/PolylineToCheck.vtk"; m_ExporterVTK->SetInput(polyline); m_ExporterVTK->SetFileName(filenameOut); m_ExporterVTK->SaveVTKData(); reader->SetFileName(filenameOut); reader->Update(); result = reader->GetOutput() != NULL; CPPUNIT_ASSERT(result); mafVMEPolyline *polylineToCheck; mafNEW(polylineToCheck); result = polylineToCheck->SetData(reader->GetOutput(),0.0) == MAF_OK; CPPUNIT_ASSERT(result); polylineToCheck->Update(); mafDEL(polylineToCheck); mafDEL(polyline); vtkDEL(reader); }
29.089347
78
0.570585
[ "mesh", "vector" ]
80c43963cd3f0b19c9b6124a6849435ac7ac4221
4,765
cc
C++
NS3-master/src/network/helper/simple-net-device-helper.cc
legendPerceptor/blockchain
615ba331ae5ec53c683dfe6a16992a5181be0fea
[ "Apache-2.0" ]
1
2021-09-20T07:05:25.000Z
2021-09-20T07:05:25.000Z
NS3-master/src/network/helper/simple-net-device-helper.cc
legendPerceptor/blockchain
615ba331ae5ec53c683dfe6a16992a5181be0fea
[ "Apache-2.0" ]
null
null
null
NS3-master/src/network/helper/simple-net-device-helper.cc
legendPerceptor/blockchain
615ba331ae5ec53c683dfe6a16992a5181be0fea
[ "Apache-2.0" ]
2
2021-09-02T08:25:16.000Z
2022-01-03T08:48:38.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2014 Universita' di Firenze * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Tommaso Pecorella <tommaso.pecorella@unifi.it> */ #include "ns3/abort.h" #include "ns3/log.h" #include "ns3/simulator.h" #include "ns3/object-factory.h" #include "ns3/queue.h" #include "ns3/net-device-queue-interface.h" #include "ns3/simple-net-device.h" #include "ns3/simple-channel.h" #include "ns3/config.h" #include "ns3/packet.h" #include "ns3/names.h" #include "ns3/boolean.h" #include "ns3/trace-helper.h" #include "simple-net-device-helper.h" #include <string> namespace ns3 { NS_LOG_COMPONENT_DEFINE ("SimpleNetDeviceHelper"); SimpleNetDeviceHelper::SimpleNetDeviceHelper () { m_queueFactory.SetTypeId ("ns3::DropTailQueue<Packet>"); m_deviceFactory.SetTypeId ("ns3::SimpleNetDevice"); m_channelFactory.SetTypeId ("ns3::SimpleChannel"); m_pointToPointMode = false; } void SimpleNetDeviceHelper::SetQueue (std::string type, std::string n1, const AttributeValue &v1, std::string n2, const AttributeValue &v2, std::string n3, const AttributeValue &v3, std::string n4, const AttributeValue &v4) { QueueBase::AppendItemTypeIfNotPresent (type, "Packet"); m_queueFactory.SetTypeId (type); m_queueFactory.Set (n1, v1); m_queueFactory.Set (n2, v2); m_queueFactory.Set (n3, v3); m_queueFactory.Set (n4, v4); } void SimpleNetDeviceHelper::SetChannel (std::string type, std::string n1, const AttributeValue &v1, std::string n2, const AttributeValue &v2, std::string n3, const AttributeValue &v3, std::string n4, const AttributeValue &v4) { m_channelFactory.SetTypeId (type); m_channelFactory.Set (n1, v1); m_channelFactory.Set (n2, v2); m_channelFactory.Set (n3, v3); m_channelFactory.Set (n4, v4); } void SimpleNetDeviceHelper::SetDeviceAttribute (std::string n1, const AttributeValue &v1) { m_deviceFactory.Set (n1, v1); } void SimpleNetDeviceHelper::SetChannelAttribute (std::string n1, const AttributeValue &v1) { m_channelFactory.Set (n1, v1); } void SimpleNetDeviceHelper::SetNetDevicePointToPointMode (bool pointToPointMode) { m_pointToPointMode = pointToPointMode; } NetDeviceContainer SimpleNetDeviceHelper::Install (Ptr<Node> node) const { Ptr<SimpleChannel> channel = m_channelFactory.Create<SimpleChannel> (); return Install (node, channel); } NetDeviceContainer SimpleNetDeviceHelper::Install (Ptr<Node> node, Ptr<SimpleChannel> channel) const { return NetDeviceContainer (InstallPriv (node, channel)); } NetDeviceContainer SimpleNetDeviceHelper::Install (const NodeContainer &c) const { Ptr<SimpleChannel> channel = m_channelFactory.Create<SimpleChannel> (); return Install (c, channel); } NetDeviceContainer SimpleNetDeviceHelper::Install (const NodeContainer &c, Ptr<SimpleChannel> channel) const { NetDeviceContainer devs; for (NodeContainer::Iterator i = c.Begin (); i != c.End (); i++) { devs.Add (InstallPriv (*i, channel)); } return devs; } Ptr<NetDevice> SimpleNetDeviceHelper::InstallPriv (Ptr<Node> node, Ptr<SimpleChannel> channel) const { Ptr<SimpleNetDevice> device = m_deviceFactory.Create<SimpleNetDevice> (); device->SetAttribute ("PointToPointMode", BooleanValue (m_pointToPointMode)); device->SetAddress (Mac48Address::Allocate ()); node->AddDevice (device); device->SetChannel (channel); Ptr<Queue<Packet> > queue = m_queueFactory.Create<Queue<Packet> > (); device->SetQueue (queue); NS_ASSERT_MSG (!m_pointToPointMode || (channel->GetNDevices () <= 2), "Device set to PointToPoint and more than 2 devices on the channel."); // Aggregate a NetDeviceQueueInterface object Ptr<NetDeviceQueueInterface> ndqi = CreateObject<NetDeviceQueueInterface> (); ndqi->GetTxQueue (0)->ConnectQueueTraces (queue); device->AggregateObject (ndqi); return device; } } // namespace ns3
31.348684
142
0.703043
[ "object" ]
80c63aeed7a09e4806fb07b64561acaf908c3c57
3,147
hpp
C++
solver/include/beam_searcher.hpp
kurokoji/procon30-kyogi
24fe6157772718d100e6658a94a78795853ce1b8
[ "MIT" ]
1
2019-10-29T23:34:40.000Z
2019-10-29T23:34:40.000Z
solver/include/beam_searcher.hpp
kurokoji/procon30-kyogi
24fe6157772718d100e6658a94a78795853ce1b8
[ "MIT" ]
null
null
null
solver/include/beam_searcher.hpp
kurokoji/procon30-kyogi
24fe6157772718d100e6658a94a78795853ce1b8
[ "MIT" ]
null
null
null
#ifndef INCLUDE_BEAM_SEARCHER_HPP #define INCLUDE_BEAM_SEARCHER_HPP #include <algorithm> #include <iostream> #include <memory> #include <vector> #include <color.hpp> #include <types.hpp> #include <util/state_visualize.hpp> namespace procon30 { template <typename state_type, size_t beam_width> class beam_searcher { private: struct node; using node_ptr = std::shared_ptr<node>; struct node { state_type _state; node_ptr _parent_node; node() {} node(const state_type& state, node_ptr parent_node = nullptr) : _state(state), _parent_node(parent_node) {} node(state_type&& state, node_ptr parent_node = nullptr) : _state(state), _parent_node(parent_node) {} score_type eval() const { return _state.tile_point(); } const state_type& state() const { return _state; } const node_ptr& parent_node() const { return _parent_node; } }; public: beam_searcher() {} state_type solve(const state_type& init_state) const { std::vector<node_ptr> bucket, next; bucket.reserve(beam_width * 1000); next.reserve(beam_width * 1000); auto best = std::make_shared<node>(init_state); bucket.emplace_back(best); size_t turn = 0; while (!bucket.empty()) { std::cerr << "\r\x1b[K" << "Turn: " << turn++; next.clear(); // 一番よい結果 best = bucket.front(); for (auto&& e : bucket) { auto&& next_states = e->state().next_states(); for (auto&& st : next_states) { next.emplace_back(std::make_shared<node>(st, e)); } } const size_t width = std::min(beam_width, next.size()); // タイルポイントでソート std::partial_sort(next.begin(), next.begin() + width, next.end(), [](const node_ptr& lhs, const node_ptr& rhs) { const score_type lhs_score = lhs->state().tile_point(color::ally) - lhs->state().tile_point(color::enemy), rhs_score = rhs->state().tile_point(color::ally) - rhs->state().tile_point(color::enemy); return lhs_score > rhs_score; }); next.erase(next.begin() + width, next.end()); bucket.swap(next); } std::cerr << std::endl; std::vector<state_type> res; for (auto node = best; node != nullptr; node = node->parent_node()) { res.emplace_back(node->state()); } std::reverse(res.begin(), res.end()); for (size_t i = 0; i < res.size(); ++i) { std::cerr << "Turn: " << i << std::endl; int32 ally_tile = res.at(i).tile_point(color::ally), ally_area = res.at(i).area_point(color::ally); int32 enemy_tile = res.at(i).tile_point(color::enemy), enemy_area = res.at(i).area_point(color::enemy); std::cerr << "Ally: " << ally_tile + ally_area << std::endl; std::cerr << "Ally_Tile: " << ally_tile << std::endl; std::cerr << "Ally_Area: " << ally_area << std::endl; std::cerr << "Enemy: " << enemy_tile + enemy_area << std::endl; std::cerr << "Enemy_Tile: " << enemy_tile << std::endl; std::cerr << "Enemy_Area: " << enemy_area << std::endl; util::state_visualize(res.at(i)); } return best->state(); } }; } // namespace procon30 #endif
31.47
118
0.618684
[ "vector" ]
80c82f660461e15425c158f735a2a541dfbbc6c9
19,092
hpp
C++
tools/framework/config.hpp
kinmantam/oopt-tai
34bb7026b5e15ee0b34ae6c1c1bd380a79c4bc01
[ "BSD-3-Clause" ]
null
null
null
tools/framework/config.hpp
kinmantam/oopt-tai
34bb7026b5e15ee0b34ae6c1c1bd380a79c4bc01
[ "BSD-3-Clause" ]
null
null
null
tools/framework/config.hpp
kinmantam/oopt-tai
34bb7026b5e15ee0b34ae6c1c1bd380a79c4bc01
[ "BSD-3-Clause" ]
null
null
null
#ifndef __TAI_FRAMEWORK_CONFIG_HPP__ #define __TAI_FRAMEWORK_CONFIG_HPP__ #include "tai.h" #include "taimetadata.h" #include <map> #include <set> #include <vector> #include <cstring> #include <algorithm> #include <functional> #include <mutex> #include "attribute.hpp" #include "fsm.hpp" #include "logger.hpp" namespace tai::framework { static tai_status_t convert_tai_error_to_list( _In_ tai_status_t err, _In_ uint32_t idx) { if (TAI_STATUS_IS_INVALID_ATTRIBUTE(err) || TAI_STATUS_IS_INVALID_ATTR_VALUE(err) || TAI_STATUS_IS_ATTR_NOT_IMPLEMENTED(err) || TAI_STATUS_IS_UNKNOWN_ATTRIBUTE(err) || TAI_STATUS_IS_ATTR_NOT_SUPPORTED(err)) { return err + idx; } return err; } using validator_f = std::function< tai_status_t(const tai_attribute_value_t* const value) >; // setter_f : the callback function which gets called when setting the attribute // attribute : the attribute to be set // fsm : the FSM state which we need to transit // user : context using setter_f = std::function< tai_status_t(const tai_attribute_t* const attribute, FSMState* fsm, void* const user) >; // getter_f : the callback function which gets called when setting the attribute // attribute : the attribute to be get // user : context using getter_f = std::function< tai_status_t(tai_attribute_t* const attribute, void* const user) >; class EnumValidator { public: EnumValidator(std::set<int32_t> enums) : m_enums(enums) {} tai_status_t operator()(const tai_attribute_value_t* const value) { if ( m_enums.find(value->s32) == m_enums.end() ) { return TAI_STATUS_ATTR_NOT_SUPPORTED_0; } return TAI_STATUS_SUCCESS; } private: std::set<int32_t> m_enums; }; template<tai_object_type_t T> struct AttributeInfo { AttributeInfo(int32_t id) : id(id), defaultvalue(nullptr), fsm(FSM_STATE_INIT), meta(tai_metadata_get_attr_metadata(T, id)), no_store(false), setter(nullptr), getter(nullptr), validator(nullptr) {} AttributeInfo(int32_t id, FSMState fsm, const tai_attribute_value_t* const value, validator_f validator, setter_f setter, getter_f getter, bool no_store) : id(id), defaultvalue(value), fsm(fsm), meta(tai_metadata_get_attr_metadata(T, id)), no_store(no_store), setter(setter), getter(getter), validator(validator) {} AttributeInfo set_fsm_state(FSMState v) { return AttributeInfo(id, v, defaultvalue, validator, setter, getter, no_store); } AttributeInfo set_default(const tai_attribute_value_t* const v) { return AttributeInfo(id, fsm, v, validator, setter, getter, no_store); } AttributeInfo set_validator(validator_f v) { return AttributeInfo(id, fsm, defaultvalue, v, setter, getter, no_store); } AttributeInfo set_setter(setter_f v) { return AttributeInfo(id, fsm, defaultvalue, validator, v, getter, no_store); } AttributeInfo set_getter(getter_f v) { return AttributeInfo(id, fsm, defaultvalue, validator, setter, v, no_store); } AttributeInfo set_no_store(bool v) { return AttributeInfo(id, fsm, defaultvalue, validator, setter, getter, v); } int id; const tai_attr_metadata_t* const meta; // the FSM state which we need to transit after changing the value FSMState fsm; // overrides the default value specified in TAI headers by @default const tai_attribute_value_t* const defaultvalue; validator_f validator; setter_f setter; getter_f getter; bool no_store; // only execute the set_hook and don't store the attribute to the config }; template<tai_object_type_t T> class AttributeInfoMap : public std::map<tai_attr_id_t, AttributeInfo<T>> { public: AttributeInfoMap(std::initializer_list<AttributeInfo<T>> list) { for (const auto& v : list ) { this->emplace(std::make_pair(v.id, v)); } } }; struct error_info { int index; // original index of the attribute tai_status_t status; // error status }; // default_setter_f : the fallback callback function which gets called when any error happens in set path // count : number of attributes // attrs : list of the attributes to be set // fsm : the FSM state which we need to transit // user : context // error_info : list of the error status in previous set path using default_setter_f = std::function< tai_status_t(uint32_t count, const tai_attribute_t* const attrs, FSMState* fsm, void* const user, const error_info* const) >; // default_getter_f : the fallback callback function which gets called when any error happens in get path // count : number of attributes // attrs : list of the attribute to be get // user : context // error_info : list of the error status in previous set path using default_getter_f = std::function< tai_status_t(uint32_t count, tai_attribute_t* const attrs, void* const user, const error_info* const) >; template<tai_object_type_t T> class Config { public: Config(uint32_t attr_count = 0, const tai_attribute_t* attr_list = nullptr, void* user = nullptr, default_setter_f setter = nullptr, default_getter_f getter = nullptr) : m_user(user), m_default_setter(setter), m_default_getter(getter) { FSMState tmp; auto ret = set_attributes(attr_count, attr_list, tmp, true); if ( ret != TAI_STATUS_SUCCESS ) { throw Exception(ret); } } std::vector<tai_attribute_t> list() const { std::unique_lock<std::mutex> lk(m_mtx); std::vector<tai_attribute_t> list; std::transform(m_config.begin(), m_config.end(), list.begin(), [](std::pair<const tai_attr_id_t, S_Attribute>& p) { return p.second->raw(); }); return list; } const tai_attribute_value_t* get(tai_attr_id_t id, bool no_default = false) const { std::unique_lock<std::mutex> lk(m_mtx); return _get(id, no_default); } tai_status_t get(tai_attribute_t* const attr, bool no_default = false) { auto info = m_info.find(attr->id); if ( info == m_info.end() ) { return TAI_STATUS_ATTR_NOT_SUPPORTED_0; } std::unique_lock<std::mutex> lk(m_mtx); auto v = _get(attr->id, no_default); if ( v == nullptr ) { return TAI_STATUS_UNINITIALIZED; } tai_attribute_t src{attr->id, *v}; return tai_metadata_deepcopy_attr_value(info->second.meta, &src, attr); } tai_status_t set(S_Attribute src, bool without_hook = false) { return _set(src, false, without_hook); } tai_status_t set_readonly(S_Attribute src, bool without_hook = false) { return _set(src, true, without_hook); } tai_status_t set(const tai_attribute_t& src, bool without_hook = false) { return _set(src, false, without_hook); } tai_status_t set_readonly(const tai_attribute_t& src, bool without_hook = false) { return _set(src, true, without_hook); } tai_status_t get_attributes(uint32_t attr_count, tai_attribute_t * const attr_list) { std::vector<std::pair<tai_attribute_t*const, error_info>> failed_attributes; for ( auto i = 0; i < attr_count; i++ ) { auto attr = &attr_list[i]; auto info = m_info.find(attr->id); if ( info == m_info.end() ) { auto ret = convert_tai_error_to_list(TAI_STATUS_ATTR_NOT_SUPPORTED_0, i); if ( m_default_getter == nullptr ) { return ret; } failed_attributes.emplace_back(std::make_pair(attr, error_info{i, ret})); continue; } if ( info->second.getter != nullptr ) { auto ret = info->second.getter(attr, m_user); if ( ret != TAI_STATUS_SUCCESS ) { return convert_tai_error_to_list(ret, i); } } else { std::unique_lock<std::mutex> lk(m_mtx); auto v = _get(attr->id); if ( v == nullptr ) { auto ret = convert_tai_error_to_list(TAI_STATUS_UNINITIALIZED, i); if ( m_default_getter == nullptr ) { return ret; } failed_attributes.emplace_back(std::make_pair(attr, error_info{i, ret})); continue; } tai_attribute_t src{attr->id, *v}; // when this failed, don't fallback to default_getter and return immediately auto ret = tai_metadata_deepcopy_attr_value(info->second.meta, &src, attr); if ( ret != TAI_STATUS_SUCCESS ) { attr_list[i] = *attr; return convert_tai_error_to_list(ret, i); } } } if ( m_default_getter != nullptr && failed_attributes.size() > 0 ) { std::vector<tai_attribute_t> list; std::vector<error_info> err_list; for ( auto& a : failed_attributes ) { list.emplace_back(*a.first); err_list.emplace_back(a.second); } auto ret = m_default_getter(list.size(), list.data(), m_user, err_list.data()); for ( auto i = 0; i < list.size(); i++ ) { const auto& a = failed_attributes[i]; attr_list[a.second.index] = list[i]; } if ( ret != TAI_STATUS_SUCCESS ) { return ret; } } return TAI_STATUS_SUCCESS; } tai_status_t set_attributes(uint32_t attr_count, const tai_attribute_t * const attr_list, FSMState& next_state, bool readonly = false) { std::vector<const tai_attribute_t*> diff; { std::unique_lock<std::mutex> lk(m_mtx); for ( auto i = 0; i < attr_count; i++ ) { const auto& attr = attr_list[i]; auto info = m_info.find(attr.id); if ( m_default_setter == nullptr && info == m_info.end() ) { return convert_tai_error_to_list(TAI_STATUS_ATTR_NOT_SUPPORTED_0, i); } if ( info != m_info.end() && info->second.validator != nullptr ) { auto ret = info->second.validator(&attr.value); if ( ret != TAI_STATUS_SUCCESS ) { return convert_tai_error_to_list(ret, i); } } auto v = _get(attr.id, true); bool equal = false; if ( v != nullptr ) { const tai_attribute_t& rhs{attr.id, *v}; tai_metadata_deepequal_attr_value(info->second.meta, &attr, &rhs, &equal); } if ( !equal ) { diff.emplace_back(&attr); } } } if ( diff.size() == 0 ) { TAI_DEBUG("already configured with the same configuration"); return TAI_STATUS_SUCCESS; } const auto current = next_state; std::vector<std::pair<const tai_attribute_t*const, error_info>> failed_attributes; std::vector<FSMState> states; for ( auto i = 0; i < diff.size(); i++ ) { auto state = current; auto ret = _set(*diff[i], readonly, false, &state); if ( ret != TAI_STATUS_SUCCESS ) { if ( m_default_setter == nullptr ) { return convert_tai_error_to_list(ret, i); } failed_attributes.emplace_back(std::make_pair(diff[i], error_info{i, ret})); } states.emplace_back(state); } if ( m_default_setter != nullptr && failed_attributes.size() > 0 ) { auto state = current; std::vector<tai_attribute_t> list; std::vector<error_info> err_list; for ( auto& a : failed_attributes ) { list.emplace_back(*a.first); err_list.emplace_back(a.second); } auto ret = m_default_setter(list.size(), list.data(), &state, m_user, err_list.data()); if ( ret != TAI_STATUS_SUCCESS ) { return ret; } states.emplace_back(state); } // determine which state to transit // choose the lowest state if we have multiple choice // the state can't go upper from the current state for ( const auto& state : states ) { if ( state != current && state < next_state) { next_state = state; } } return TAI_STATUS_SUCCESS; } tai_status_t clear_attributes(uint32_t attr_count, const tai_attr_id_t* const attr_list, FSMState& next_state, bool force = false) { std::unique_lock<std::mutex> lk(m_mtx); for ( auto i = 0; i < attr_count; i++ ) { auto id = attr_list[i]; auto info = m_info.find(id); if ( info == m_info.end() ) { return convert_tai_error_to_list(TAI_STATUS_ATTR_NOT_SUPPORTED_0, i); } if ( !force && !info->second.meta->isclearable ) { TAI_WARN("can't clear non-clearable attribute: 0x%x", id); return convert_tai_error_to_list(TAI_STATUS_INVALID_ATTR_VALUE_0, i); } m_config.erase(id); } return TAI_STATUS_SUCCESS; } int clear(tai_attr_id_t id) { auto dummy = FSM_STATE_INIT; return (clear_attributes(1, &id, dummy, true) == TAI_STATUS_SUCCESS) ? 0 : -1; } int clear_all() { std::unique_lock<std::mutex> lk(m_mtx); m_config.clear(); return 0; } size_t size() const { return m_config.size(); } tai_status_t direct_set(S_Attribute src) { return _set(src, false, false, nullptr, true); } const tai_attribute_value_t* direct_get(tai_attr_id_t id) { return _get(id, false, true); } private: const tai_attribute_value_t* _get(tai_attr_id_t id, bool no_default = false, bool direct = false) const { auto info = m_info.find(id); if ( !direct && info == m_info.end() ) { return nullptr; } auto it = m_config.find(id); if ( it == m_config.end() ) { if ( no_default || direct ) { return nullptr; } if ( info->second.defaultvalue != nullptr ) { return info->second.defaultvalue; } if ( info->second.meta->defaultvalue != nullptr ) { return info->second.meta->defaultvalue; } return nullptr; } return &it->second->raw()->value; } // readonly : if true, allow readonly attribute to be set tai_status_t _set(S_Attribute src, bool readonly, bool without_hook, FSMState* fsm = nullptr, bool direct = false) { auto info = m_info.find(src->id()); if ( !direct && info == m_info.end() ) { TAI_DEBUG("no meta: 0x%x", src->id()); return TAI_STATUS_ATTR_NOT_SUPPORTED_0; } if ( !direct && !readonly && info->second.meta->isreadonly) { TAI_WARN("read only: 0x%x", src->id()); return TAI_STATUS_INVALID_ATTR_VALUE_0; } if ( !direct && fsm != nullptr && info->second.fsm != FSM_STATE_INIT ) { *fsm = info->second.fsm; } if ( !direct && !without_hook && info->second.setter != nullptr ) { auto ret = info->second.setter(src->raw(), fsm, m_user); if ( ret != TAI_STATUS_SUCCESS || info->second.no_store ) { return ret; } } std::unique_lock<std::mutex> lk(m_mtx); m_config[src->id()] = src; return TAI_STATUS_SUCCESS; } tai_status_t _set(const tai_attribute_t& src, bool readonly, bool without_hook, FSMState* fsm = nullptr) { auto info = m_info.find(src.id); if ( info == m_info.end() ) { TAI_DEBUG("no meta: 0x%x", src.id); return TAI_STATUS_ATTR_NOT_SUPPORTED_0; } auto attr = std::make_shared<Attribute>(info->second.meta, src); return _set(attr, readonly, without_hook, fsm); } static const AttributeInfoMap<T> m_info; std::map<tai_attr_id_t, S_Attribute> m_config; const default_setter_f m_default_setter; const default_getter_f m_default_getter; mutable std::mutex m_mtx; void* const m_user; }; } #endif // __TAI_FRAMEWORK_CONFIG_HPP__
46.227603
323
0.522523
[ "vector", "transform" ]
80ca0c8a72c7a3509467b685d053a6d6cd669dde
1,112
cpp
C++
src/Data.cpp
It4innovations/PTDR
facb1ee43a68028379c41c231776e87f82eabc27
[ "BSD-3-Clause" ]
1
2019-03-13T13:52:46.000Z
2019-03-13T13:52:46.000Z
src/Data.cpp
It4innovations/PTDR
facb1ee43a68028379c41c231776e87f82eabc27
[ "BSD-3-Clause" ]
null
null
null
src/Data.cpp
It4innovations/PTDR
facb1ee43a68028379c41c231776e87f82eabc27
[ "BSD-3-Clause" ]
null
null
null
#include <map> #include <regex> #include "Data.h" #include "CSVReader.h" #define PROFILE_FILE_NAME_SEP "_" void Routing::Data::WriteResultAll(std::vector<float> &result, const std::string &file, int samples, float secondInterval) { std::ofstream rfile(file); int intervalsPerDay = 86400 / secondInterval; // Header rfile << "day;interval;1"; for (int j = 2; j <= samples; ++j) { rfile << ";" << j; } rfile << std::endl; // Data for (int d = 0; d < 7; ++d) { for (int i = 0; i < intervalsPerDay; ++i) { rfile << d << ";" << i << ";"; for (int s = 0; s < samples; ++s) { if (s != 0) rfile << ";"; rfile << result[(d * intervalsPerDay * samples) + (i * samples) + s]; } rfile << std::endl; } } rfile.close(); } void Routing::Data::WriteResultSingle(std::vector<float> &result, const std::string &file) { std::ofstream rfile(file); for (const auto &r : result) { rfile << r << "\n"; } rfile.flush(); rfile.close(); }
27.121951
119
0.507194
[ "vector" ]