blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
dfa00ce8d7d3c72fe310bcfd2e41366ef04beffc
d9234c208ac831aea11a2b46b7a4860a879e6e27
/src/envoy/tcp/sni_verifier/config.h
5ef1baf5aa96e7a3cb1608b606f1ae3e976bdca9
[ "Apache-2.0" ]
permissive
liuerfire/proxy
b45a8197ead7d97e076ad6a905e1aa71837a2906
39d6b756016b8f56a6fa589807dbb94e781e5ac6
refs/heads/master
2020-06-28T07:57:33.475763
2019-08-01T19:45:03
2019-08-01T19:45:03
200,182,614
1
0
Apache-2.0
2019-08-02T06:57:19
2019-08-02T06:57:19
null
UTF-8
C++
false
false
1,579
h
/* Copyright 2018 Istio 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 "envoy/server/filter_config.h" namespace Envoy { namespace Tcp { namespace SniVerifier { /** * Config registration for the SNI verifier filter. @see * NamedNetworkFilterConfigFactory. */ class SniVerifierConfigFactory : public Server::Configuration::NamedNetworkFilterConfigFactory { public: // NamedNetworkFilterConfigFactory Network::FilterFactoryCb createFilterFactory( const Json::Object&, Server::Configuration::FactoryContext& context) override; Network::FilterFactoryCb createFilterFactoryFromProto( const Protobuf::Message&, Server::Configuration::FactoryContext& context) override; ProtobufTypes::MessagePtr createEmptyConfigProto() override; std::string name() override { return "sni_verifier"; } private: Network::FilterFactoryCb createFilterFactoryFromContext( Server::Configuration::FactoryContext& context); }; } // namespace SniVerifier } // namespace Tcp } // namespace Envoy
[ "istio.testing@gmail.com" ]
istio.testing@gmail.com
eaa3828428f292b20e64bd3c9b2e1890f3892c2e
c38f2746e0fc168759f6147c5fc1d286ee08e94c
/Shared/Messages/Messages/Manager/ExecuteManager.hpp
23198abb4dd66ce12451e6ba7924941863990270
[]
no_license
cameronfrandsenjenkins/R-Pi-Cluster
0777dee77487f9ec8ba5b63d29c38eb6487e6b74
85b2cbc211747cfd1301517d17309a8a0d360ddb
refs/heads/master
2020-05-18T22:06:35.807521
2018-05-03T23:00:34
2018-05-03T23:00:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,356
hpp
#ifndef EXECUTE_MANAGER_H #define EXECUTE_MANAGER_H #include "Job.hpp" #include <map> #include <mutex> #include <string> #include "Results.hpp" #include "ProtoFiles/TaskMsg.pb.h" #include <atomic> #include <qthreadpool.h> #include <qtimer.h> #include <QObject> Q_DECLARE_METATYPE(std::vector<manager::Result>) namespace manager { class ExecuteManager : public QObject { Q_OBJECT signals: void sendResults(std::vector<manager::Result>); private slots: void endTask(int id); public: ExecuteManager(std::string m_database); ~ExecuteManager(); void addJob(int, int, int, int, std::string, std::string); void addTasks(std::vector<manager::Task> tasks); void removeJob(int id); void modifyJob(int id, std::string field, std::string value); void addResults(int id, std::vector<Result>); void addResults(int id, int pageid, std::string result); private: void addTasksToQueue(manager::Task task); std::map<int, std::shared_ptr<Job>> m_jobs; std::map<int, std::vector<manager::Task>> m_waitingJobs; std::string m_database; std::atomic<int> m_size; std::shared_ptr<std::mutex> m_pResultsMutex; std::shared_ptr<std::map<int, std::vector<manager::Result>>> m_pResults; std::shared_ptr<QThreadPool> m_pThreadPool; QTimer* m_pTimer; }; } // namespace manager #endif
[ "cameron.frandsen1@gmail.com" ]
cameron.frandsen1@gmail.com
ea59b5462c6884fa12b79f11b66f2a97deaf3cd6
67792dd74f487b85af202fe3eb2142f35b96f84f
/2531.cpp
e863cf6b78ac2f849a45a8b2914c04e0d371328e
[]
no_license
trickpsv/URI
ed8eade864ae673a718fe2de59914faccde6d5be
952d6e0b37ca5f06ec6d9ff403763bc42775324b
refs/heads/master
2020-12-02T23:55:18.973805
2017-07-01T12:48:33
2017-07-01T12:48:33
95,962,510
1
0
null
null
null
null
UTF-8
C++
false
false
1,757
cpp
#include <cstdio> #include <algorithm> #include <vector> #define INF 9999999 #define INFNEG -9999999 using namespace std; int tree[300010][2]; int vet[100010]; int folhas[100010]; typedef vector<int> vi ; void build(int no , int a , int b ) { if (a > b) return ; if (a == b){ tree[no][0] = vet[a]; tree[no][1] = vet[a]; folhas[a] = no ; return ; } build( no << 1 , a , (a+b)>>1); build( (no << 1) + 1 , ((a + b)>>1) +1 , b); tree[no][0] = min(tree[no<<1][0],tree[(no<<1) +1][0]); tree[no][1] = max(tree[no<<1][1],tree[(no<<1) +1][1]); } void att(int no) { if (no == 0) return ; tree[no][0] = min(tree[no<<1][0],tree[(no<<1)+1][0]); tree[no][1] = max(tree[no<<1][1],tree[(no<<1)+1][1]); if (no != 1) att(no>>1); } pair<int,int> query(int no , int a , int b , int i , int j) { if (a > b || a > j || b < i) return make_pair(INF,INFNEG); if (i <= a && b <= j) return make_pair(tree[no][0],tree[no][1]); pair<int,int> p1 = query((no << 1) , a , (a+b)>>1, i , j ); pair<int,int> p2 = query((no << 1) + 1, ((a+b)>>1) + 1 , b , i , j); return make_pair(min(p1.first,p2.first),max(p1.second,p2.second)); } int main() { int n; int x , y , aux , q; pair<int , int> par ; int cont = 0; while(scanf("%d",&n) == 1) { //if (cont != 0) printf("\n"); //cont ++; for (int i = 0; i < n; i++) { scanf("%d",&vet[i]); } build(1, 0, n-1 ); scanf("%d",&q); for(int i = 0 ; i < q ; i ++) { scanf("%d %d %d", &aux , &x , &y); if (aux == 1) { tree[folhas[x-1]][0] = y; tree[folhas[x-1]][1] = y; att(folhas[x-1]>>1); } else { par = query(1,0,n-1,x-1,y-1); printf("%d\n",par.second-par.first); } } } }
[ "trickpsv@gmail.com" ]
trickpsv@gmail.com
1e0e58abbc9ba86aa9457e1268d1b61c7148d8e1
7fb0b8593cdf2a6304d2d2483d23f90aa46aed13
/IMClient/view/IMDiscussionMemberListWidget.cpp
3683a32e82f42f7d42714e7193789325fc55d128
[ "MIT" ]
permissive
WenbinLiworks/desktopInstantMessagingTools
42751348e969453e1b440d3a08917e6a55653b26
85d85b9bde027c1cc88d38a3b1ceab8a411a5e40
refs/heads/master
2020-12-11T00:03:07.629566
2020-01-20T14:21:11
2020-01-20T14:21:11
233,748,050
1
0
MIT
2020-01-14T04:38:14
2020-01-14T03:26:51
C++
UTF-8
C++
false
false
1,384
cpp
#include "IMDiscussionMemberListWidget.h" #include <QVBoxLayout> #include <QScrollArea> IMDiscussionMemberListWidget::IMDiscussionMemberListWidget(QWidget *parent) : QWidget(parent), m_layout(new QVBoxLayout) { QVBoxLayout *mainLayout=new QVBoxLayout(); mainLayout->setContentsMargins(0,0,0,0); mainLayout->setSpacing(0); m_contentsWidget = new QWidget; m_layout->setContentsMargins(0,0,0,0); m_layout->setSpacing(0); m_contentsWidget->setLayout(m_layout); m_contentsWidget->setStyleSheet("QWidget{border: 0;}"); m_flocksScrollArea = new QScrollArea(this); m_flocksScrollArea->setWidgetResizable(true); m_flocksScrollArea->setAlignment(Qt::AlignLeft); m_flocksScrollArea->setWidget(m_contentsWidget); mainLayout->addWidget(m_flocksScrollArea); setLayout(mainLayout); setStyleSheet("QWidget{border: 0;}"); } /************************************************* Function Name: addItem() Description: 添加 *************************************************/ void IMDiscussionMemberListWidget::addItem(QWidget *item) { // Remove last spacer item if present. int count = m_layout->count(); if (count > 1) { m_layout->removeItem(m_layout->itemAt(count - 1)); } // Add item and make sure it stretches the remaining space. m_layout->addWidget(item); m_layout->addStretch(); }
[ "1120173001@bit.edu.cn" ]
1120173001@bit.edu.cn
ed2cb50c8c26ee6d867512d9f1e21eb1daad7055
e32fae35484e23dcb6e8c196bb9ee27ad6857b5d
/employee.cpp
a160c7daba4fe5768c4b8af70102606c496b8a1e
[]
no_license
SruthiVNair/B.Tech-Codes-Repo
5f17d0e8d333a8693a8e88cd1b78857271c65449
22de53f404709af7eb597441a23f4ba38d665e05
refs/heads/master
2021-04-09T10:24:39.297671
2018-05-06T03:56:26
2018-05-06T03:56:26
125,472,973
0
0
null
null
null
null
UTF-8
C++
false
false
504
cpp
#include<iostream> using namespace std; class employee { private: int p,d,s,n,i; int emp_id; char name[40]; public: void input() { cout<<"enter name"; cin>>name; cout<<"emp_id"; cin>>emp_id; cout<<"basic pay:"; cin>>p; } void display() {int g; d=(52*p)/100; g=d+p; i=(30*g)/100; n=p+d-i; cout<<"\n...EMPLOYEE DETAILS\n"<<"emp_id:"<<emp_id<<"\n"<<"pay"<<p<<"\nda:"<< d<<"\nincome tax" <<i<<"\nnet salary:" <<n; } }; int main() { employee anu; anu.input(); anu.display(); }
[ "nairsruthiv@gmail.com" ]
nairsruthiv@gmail.com
651458f78e9fc0958bfc91c8e9a9bb31cd20143b
03dc61f77c8f338983c5111d25a01b8a42372bb3
/cpp/13.roman-to-integer.cpp
225853ca520b39056ab25b87ab79110624c8b6cb
[ "MIT" ]
permissive
Rholais/leet-code
f28c54a4fbcabfd9a9fd2e1fa3cb124a63ae4e88
a0ae2788a2934d737f2a7581f1754a15f44c050a
refs/heads/master
2020-04-22T21:41:54.122499
2020-04-12T05:06:39
2020-04-12T05:06:39
170,681,483
1
0
null
null
null
null
UTF-8
C++
false
false
4,070
cpp
/* * @lc app=leetcode id=13 lang=cpp * * [13] Roman to Integer * * https://leetcode.com/problems/roman-to-integer/description/ * * algorithms * Easy (53.75%) * Likes: 1557 * Dislikes: 2997 * Total Accepted: 528.6K * Total Submissions: 983.4K * Testcase Example: '"III"' * * Roman numerals are represented by seven different symbols: I, V, X, L, C, D * and M. * * * Symbol Value * I 1 * V 5 * X 10 * L 50 * C 100 * D 500 * M 1000 * * For example, two is written as II in Roman numeral, just two one's added * together. Twelve is written as, XII, which is simply X + II. The number * twenty seven is written as XXVII, which is XX + V + II. * * Roman numerals are usually written largest to smallest from left to right. * However, the numeral for four is not IIII. Instead, the number four is * written as IV. Because the one is before the five we subtract it making * four. The same principle applies to the number nine, which is written as IX. * There are six instances where subtraction is used: * * * I can be placed before V (5) and X (10) to make 4 and 9.  * X can be placed before L (50) and C (100) to make 40 and 90.  * C can be placed before D (500) and M (1000) to make 400 and 900. * * * Given a roman numeral, convert it to an integer. Input is guaranteed to be * within the range from 1 to 3999. * * Example 1: * * * Input: "III" * Output: 3 * * Example 2: * * * Input: "IV" * Output: 4 * * Example 3: * * * Input: "IX" * Output: 9 * * Example 4: * * * Input: "LVIII" * Output: 58 * Explanation: L = 50, V= 5, III = 3. * * * Example 5: * * * Input: "MCMXCIV" * Output: 1994 * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. * */ // @lc code=start class Solution { public: int romanToInt(string s) { unsigned ret = 0; for (unsigned i = 0; i != s.size(); ++i) { switch (s[i]) { case 'M': ret += 1000; break; case 'D': ret += 500; break; case 'C': if (i + 1 == s.size()) { ret += 100; break; } switch (s[i + 1]) { case 'M': ret += 900; ++i; break; case 'D': ret += 400; ++i; break; default: ret += 100; break; } break; case 'L': ret += 50; break; case 'X': if (i + 1 == s.size()) { ret += 10; break; } switch (s[i + 1]) { case 'C': ret += 90; ++i; break; case 'L': ret += 40; ++i; break; default: ret += 10; break; } break; case 'V': ret += 5; break; case 'I': if (i + 1 == s.size()) { ret += 1; break; } switch (s[i + 1]) { case 'X': ret += 9; ++i; break; case 'V': ret += 4; ++i; break; default: ret += 1; break; } break; } } return ret; } }; // @lc code=end
[ "rholais@gmail.com" ]
rholais@gmail.com
38b3e01c4e44a5a862a72fd9b421e0e577e1712f
9dee5e0636406de13eaab805d9267f034f265de2
/binaryStrOp.cpp
abf35cb111e09a96aa0090baa66658142f1e07bf
[]
no_license
ssshrihari/MissionRnd-Strings
141f7b520259484bdd968dbdf732efe092e2bbbc
142125e84873ba87b66401df9bac0c42c75386e8
refs/heads/master
2021-01-19T15:24:14.020204
2017-08-21T15:30:28
2017-08-21T15:30:28
100,966,437
0
0
null
null
null
null
UTF-8
C++
false
false
2,923
cpp
/* ProblemCODE : BINARYSTROP Difficulty : Medium Marks : 15 Given two binary numbers in form of strings and a string representing "AND", "OR", "NOR" or "XOR". Return the output string which forms by doing the specified operation on those 2 strings . Ex: Input: "101", "111", op = "OR" Output: "111" Ex: Input: "10101", "1111", op = "AND" Output: "00101" Ex: Input: "0111", "1010", op = "XOR" Output: "0010" Ex: Input: "0011", "1010", op = "NOR" Output: "0100" Note : In the above representations ,Write those strings on a paper ,you will understand them better . [Align them to the Right] If 1 string length is less than other ,you need to consider missing letters as 0's ie "1111" AND "1" is same as "1111" AND "0001". Ie if a String is "" ,you should consider it as All 0's .This dosent not apply if String is NULL. Reference : http://www.bristolwatch.com/pport/pics/logic_table.gif [For AND,OR,XOR] For NOR : http://www.circuitstoday.com/wp-content/uploads/2010/04/2-Input-NOR-Gate-Truth-Table.jpg Contraints : String length < 50. For 50% of TestCases ,only AND/OR operations will be given . Difficulty : Medium */ #include <stdio.h> #include <stdlib.h> char *performOperation(char *str1, char *str2, char *operation) { int i = 0, j = 0,x=0; char *output = (char*)calloc(100, sizeof(char)); while (str1[i] != '\0') i++; while (str2[j] != '\0') j++; //printf("%d,%d",i,j); if (i > j) { x = i - j; for (j=j-1; j>=0; j--) { str2[j + x] = str2[j]; } for (i = 0; i < x; i++) { str2[i] = '0'; } //printf("\n%s\n", str2); } if (j>i) { x = j - i; for (i=i-1; i >= 0; i--) { str1[i + x] = str1[i]; } for (i = 0; i < x; i++) { str1[i] = '0'; } //printf("\n%s\n", str1); } i = 0; if (operation[1] == 'R') { while (str1[i] != '\0') { if (str1[i] == '1' || str2[i] == '1') { output[i] ='1'; } else { output[i] = '0'; } i++; } output[i] = '\0'; printf("%s", output); } if (operation[2] == 'D') { while (str1[i] != '\0') { if (str1[i] == '1' && str2[i] == '1') { output[i] = '1'; } else { output[i] = '0'; } i++; } output[i] = '\0'; printf("%s", output); } if (operation[0] == 'N') { while (str1[i] != '\0') { if (str1[i] == '1' || str2[i] == '1') { output[i] = '0'; } else { output[i] = '1'; } i++; } output[i] = '\0'; printf("%s", output); } if (operation[0] == 'X') { while (str1[i] != '\0') { if ((str1[i] == '1' && str2[i] == '1') || (str1[i] == '0' && str2[i] == '0')) { output[i] = '0'; } else { output[i] = '1'; } i++; } output[i] = '\0'; printf("%s", output); } return output; }
[ "noreply@github.com" ]
noreply@github.com
5420ed7ae0661ceed8d6dff6118b96664db44048
4c5645477261073c0d01aaea4c2cf62ddc89b311
/Algorithms/Sorting/Quicksort 2 - Sorting.cpp
f92ec45002dfc16fe23683fe8150f9a801ee3e12
[]
no_license
flere114/hackerrank
978fac8c18e24ee3175ba45327cbf37be248e39d
45024b00230746e5f8b904a26d03b273f184c039
refs/heads/master
2020-05-16T22:13:46.026384
2018-05-07T12:32:25
2018-05-07T12:32:25
41,917,922
0
0
null
null
null
null
UTF-8
C++
false
false
798
cpp
#include <bits/stdc++.h> using namespace std; void quickSort(vector <int> &arr) { // Complete this function vector <int> a,b; if(arr.size()<=1) return; int p = arr[0]; for(int i=1;i<arr.size();i++) if(arr[i] < p) a.push_back(arr[i]); else b.push_back(arr[i]); quickSort(a); quickSort(b); for(int i=0;i<a.size();i++) arr[i] = a[i]; arr[a.size()] = p; for(int i=0;i<b.size();i++) arr[i+a.size()+1] = b[i]; for(int i=0;i<arr.size();i++) if(i==0) printf("%d",arr[i]); else printf(" %d",arr[i]); printf("\n"); } int main() { int n; cin >> n; vector <int> arr(n); for(int i = 0; i < (int)n; ++i) { cin >> arr[i]; } quickSort(arr); return 0; }
[ "forst.and.flame11235@gmail.com" ]
forst.and.flame11235@gmail.com
d9e3d73d3b84aeca08fe9ffa80f0df25f6ec7ed9
d1e491d0f0e6acf05827dcc326313c0c989814c6
/Rogue/GameObjectFactory.cpp
c7119e7e395d145da8e457c6dacdc172f8d0ceee
[]
no_license
krovma/Rogue
9bf9b856414ca58ac176b0ad73d63c64b765cde8
0e555e36ae358ee447fdab37f6059c65bfb349a0
refs/heads/master
2021-06-17T02:25:56.815103
2017-06-03T20:20:08
2017-06-03T20:20:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
607
cpp
#include "GameObjectFactory.h" #include <iostream> bool GameObjectFactory::registerType(std::string typeID, BaseCreator *creator) { if (_creators.find(typeID) != _creators.end()) { delete creator; return false; } _creators[typeID] = creator; return true; } GameObject *GameObjectFactory::create(std::string typeID) { auto it = _creators.find(typeID); if (it == _creators.end()) { #ifdef _DEBUG std::cerr << '[' << __FUNCTION__ << ']' << "Unregisted type " << typeID << std::endl; #endif return nullptr; } else { auto creator = _creators[typeID]; return creator->createGameObject(); } }
[ "cs_suncc@outlook.com" ]
cs_suncc@outlook.com
badf8842b782b6b3fd5a69df7a3e6d0c33cd1eed
ef25402a233fe78e114afdbe7bed46c8fed41c5d
/june14/june19_Heaps2/selfheap.cpp
433e5a00e65d2707398425fc2154e4c92239d710
[]
no_license
manojmalik35/Code
966ae31351067a24713538a1fcbb659f57271eee
59a60f528aa83e1a0359041c46ed26b3af85ba3e
refs/heads/master
2023-01-13T03:12:43.795871
2020-11-09T07:15:19
2020-11-09T07:15:19
281,858,891
0
0
null
null
null
null
UTF-8
C++
false
false
1,886
cpp
#include<iostream> #include<vector> using namespace std; class heap{ private: vector<int> list; bool type;//true for min void swap(int i,int j) { int ith=list[i]; int jth=list[j]; list[i]=jth; list[j]=ith; } bool ishp(int i,int j) { if(this->type==true) return list[i]<list[j]; else return list[i]>list[j]; } void upheapify(int i) { if(i==0) return; int pi=(i-1)/2; if(ishp(i,pi)){ swap(i,pi); upheapify(pi); } } void downheapify(int i) { int li=2*i+1; int ri=2*i+2; int hpi=i; if(li<list.size() && ishp(li,hpi)) hpi=li; if(ri<list.size() && ishp(ri,hpi)) hpi=ri; if(hpi!=i) { swap(i,hpi); downheapify(hpi); } } public: heap(bool type) { this->type=type; } void push(int val) { list.push_back(val); upheapify(list.size()-1); } void pop() { swap(0,list.size()-1); list.pop_back(); downheapify(0); } int top() { return list[0]; } int size() { return list.size(); } }; int main(int argc,char** argv) { heap hp(false); hp.push(10); hp.push(2); hp.push(50); hp.push(15); hp.push(70); while(hp.size()>0) { int val=hp.top(); hp.pop(); cout<< val<<" "; } }
[ "malik.manoj35@gmail.com" ]
malik.manoj35@gmail.com
4afd4421c43c39fd3b3546f70788653a8f3ba010
6b40e9cba1dd06cd31a289adff90e9ea622387ac
/Develop/Server/GameServerOck/main/GDBTaskGuildDelete.h
05a602f5864ec378de781e22ae9758f6b06b2fb5
[]
no_license
AmesianX/SHZPublicDev
c70a84f9170438256bc9b2a4d397d22c9c0e1fb9
0f53e3b94a34cef1bc32a06c80730b0d8afaef7d
refs/heads/master
2022-02-09T07:34:44.339038
2014-06-09T09:20:04
2014-06-09T09:20:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
722
h
#ifndef _GDBTASK_GUILD_DELETE_H #define _GDBTASK_GUILD_DELETE_H #include "GDBAsyncTask.h" #include "GDBTaskDataGuild.h" #include "MMemPool.h" class GDBTaskGuildDelete : public GDBAsyncTask, public MMemPool<GDBTaskGuildDelete> { public : GDBTaskGuildDelete(const MUID& uidReqPlayer); ~GDBTaskGuildDelete(); enum { GUILD_DELETE, }; void Input(GDBT_GUILD& data); protected : void OnExecute(mdb::MDatabase& rfDB) override; mdb::MDB_THRTASK_RESULT _OnCompleted() override; protected : class Completer { public : Completer(GDBT_GUILD& data) : m_Data(data) {} void Do(); private : GDBT_GUILD& m_Data; }; protected : GDBT_GUILD m_Data; }; #endif
[ "shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4" ]
shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4
3071ea296af898d23fd0d5339fd8e80d775592fb
1d730206206c2c874c31554f0a1cea59f16fbbdd
/Car_Number/input.h
d56ff0a58fd4a64a4957b26001d8b846c5e34a68
[]
no_license
VasinPavlo/CarNumber
5347a937c27c859e99f40aa1294736df249fa401
911652d25a48acb8f59f1b0f85022610e7d3c2f6
refs/heads/master
2021-01-19T13:06:52.136845
2016-01-27T16:07:14
2016-01-27T16:07:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
276
h
#ifndef INPUT_H #define INPUT_H #include <vector> #include <string> #include "World_of_Struct.h" #include Direction_of_ImageH using namespace std; class Input { public: Input(); vector<Image> input; private: void Load(string name_of_image); }; #endif // INPUT_H
[ "bot-1@i.ua" ]
bot-1@i.ua
578d8a29c9953bc2c638175c6d3cde89c031ab75
89fc5b243d34612ba90e1d1649387907e29d90ac
/Closest Common Ancestors.cpp
d2c9c36a23f9523c72e89b6adad4b0a287abd65f
[]
no_license
Misaka233/exciting
8a074bf0924476c067a1965c6ea9a6dc1ad77d75
069455bb92560ceee47add71e1743f0d36c8cd10
refs/heads/master
2020-04-12T09:01:27.313535
2017-02-03T08:28:37
2017-02-03T08:28:37
55,968,227
0
0
null
null
null
null
GB18030
C++
false
false
2,094
cpp
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> using namespace std; const int MAXN = 1010; const int MAXQ = 500010;//查询数的最大值 //并查集部分 int F[MAXN];//需要初始化为-1 int find(int x) { if(F[x] == -1)return x; return F[x] = find(F[x]); } void bing(int u,int v) { int t1 = find(u); int t2 = find(v); if(t1 != t2) F[t1] = t2; } //************************ bool vis[MAXN];//访问标记 int ancestor[MAXN];//祖先 struct Edge { int to,next; }edge[MAXN*2]; int head[MAXN],tot; void addedge(int u,int v) { edge[tot].to = v; edge[tot].next = head[u]; head[u] = tot++; } struct Query { int q,next; int index;//查询编号 }query[MAXQ*2]; int answer[MAXQ];//存储最后的查询结果,下标0~Q-1 int h[MAXQ]; int tt; int Q; void add_query(int u,int v,int index) { query[tt].q = v; query[tt].next = h[u]; query[tt].index = index; h[u] = tt++; query[tt].q = u; query[tt].next = h[v]; query[tt].index = index; h[v] = tt++; } void init() { tot = 0; memset(head,-1,sizeof(head)); tt = 0; memset(h,-1,sizeof(h)); memset(vis,false,sizeof(vis)); memset(F,-1,sizeof(F)); memset(ancestor,0,sizeof(ancestor)); } void LCA(int u) { ancestor[u] = u; vis[u] = true; for(int i = head[u];i != -1;i = edge[i].next) { int v = edge[i].to; if(vis[v])continue; LCA(v); bing(u,v); ancestor[find(u)] = u; } for(int i = h[u];i != -1;i = query[i].next) { int v = query[i].q; if(vis[v]) { answer[query[i].index] = ancestor[find(v)]; } } } bool flag[MAXN]; int Count_num[MAXN]; int main() { int n; int u,v,k; while(scanf("%d",&n) == 1) { init(); memset(flag,false,sizeof(flag)); for(int i = 1;i <= n;i++) { scanf("%d:(%d)",&u,&k); while(k--) { scanf("%d",&v); flag[v] = true; addedge(u,v); addedge(v,u); } } scanf("%d",&Q); for(int i = 0;i < Q;i++) { char ch; cin>>ch; scanf("%d %d)",&u,&v); add_query(u,v,i); } int root; for(int i = 1;i <= n;i++) if(!flag[i]) { root = i; break; } LCA(root); memset(Count_num,0,sizeof(Count_num)); for(int i = 0;i < Q;i++) Count_num[answer[i]]++; for(int i = 1;i <= n;i++) if(Count_num[i] > 0) printf("%d:%d\n",i,Count_num[i]); } return 0; }
[ "1224936828@qq.com" ]
1224936828@qq.com
d2155d78791b3bb66415f252b2500fbe75bfd8a4
cecf385c6bab5bc17ed93b05cc60d44a2e3c8aec
/Line Segment Intersection/a.cpp
8026279d020ced85b9afab97bd9cd0b4879d1a18
[]
no_license
meysamaghighi/Kattis
d2970366846a8af74a99df3f099c99dca7635618
7467513c2927e6ad92573c5fdc5927f629cf6681
refs/heads/master
2020-05-22T01:27:41.519329
2019-10-05T12:46:05
2019-10-05T12:46:05
55,591,374
9
17
null
null
null
null
UTF-8
C++
false
false
3,366
cpp
// Meysam Aghighi #include <iostream> #include <cmath> #include <algorithm> #include <cassert> #include <cstdio> using namespace std; // Geometry part double INF = 1e100; double EPS = 1e-12; struct point { double x, y; point() {} point(double x, double y) : x(x), y(y) {} point(const point &p) : x(p.x), y(p.y) {} point operator + (const point &p) const { return point(x+p.x, y+p.y); } point operator - (const point &p) const { return point(x-p.x, y-p.y); } point operator * (double c) const { return point(x*c, y*c); } point operator / (double c) const { return point(x/c, y/c); } bool operator < (const point &p) const { if (x != p.x) return x < p.x; return y < p.y; } }; double dot(point p, point q) { return p.x*q.x + p.y*q.y; } // proportional to cos(x) double dist(point p, point q) { return sqrt(dot(p-q , p-q)); } double cross(point p, point q) { return p.x*q.y - p.y*q.x; } // proportional to sin(x) - p to q counterclockwise bool segments_parallel(point a, point b, point c, point d){ // if (a,b) || (c,d) return abs(cross(a-b,c-d)) < EPS; // sin(x) = 0 } bool point_on_segment(point p, point a, point b){ // p belongs to (a,b) or not - gives false for a and b if (segments_parallel(p,a,p,b) && dot(p-a,p-b) < 0) return true; // to check return false; } bool segments_intersect(point a, point b, point c, point d){ if (dist(a,c) < EPS || dist(a,d) < EPS || dist(b,c) < EPS || dist(b,d) < EPS) return true; if (dist(a,b) < EPS && dist(c,d) < EPS) return false; if (dist(a,b) < EPS) return point_on_segment(a,c,d); if (dist(c,d) < EPS) return point_on_segment(c,a,b); if (segments_parallel(a,b,c,d) && segments_parallel(a,c,b,d) && segments_parallel(a,d,b,c)){ if (point_on_segment(a,c,d) || point_on_segment(b,c,d) || point_on_segment(c,a,b) || point_on_segment(d,a,b)) return true; return false; } if (cross(a-b,a-c) * cross(a-b,a-d) > 0) return false; // c and d are one side of (a,b) if (cross(c-d,c-a) * cross(c-d,c-b) > 0) return false; // a and b are one side of (c,d) return true; } point lines_intersection(point a, point b, point c, point d) { b=b-a; d=c-d; c=c-a; assert(dot(b, b) > EPS && dot(d, d) > EPS); return a + b*cross(c, d)/cross(b, d); } void print(point a, point b, point c, point d){ point x[4]; x[0] = a , x[1] = b, x[2] = c, x[3] = d; sort(x,x+4); if (dist(x[1],x[2]) < EPS) printf("%.2f %.2f",x[1].x,x[1].y); else for (int i=1;i<3;i++) printf("%.2f %.2f ",x[i].x,x[i].y); printf("\n"); } void solve_intersection(point a, point b, point c, point d){ if (!segments_intersect(a,b,c,d)) cout << "none" << endl; // no intersection else if (segments_parallel(a,b,c,d)){ // intersection, includes a=b cases... if (dist(a,b) < EPS) printf("%.2f %.2f\n",a.x,a.y); else if (dist(c,d) < EPS) printf("%.2f %.2f\n",c.x,c.y); else print(a,b,c,d); // prints the two middle points (could be equal) } else { point ans = lines_intersection(a,b,c,d); // normal intersection, when there is one printf("%.2f %.2f\n",ans.x,ans.y); } } int main(){ int n; point a,b,c,d; cin >> n; while (n--){ cin >> a.x >> a.y >> b.x >> b.y >> c.x >> c.y >> d.x >> d.y; solve_intersection(a,b,c,d); } return 0; }
[ "meysam.aghighi@gmail.com" ]
meysam.aghighi@gmail.com
e886440010f13dfeaee636820dbb67f88657cae0
76dae4dfe18379dd11cd6d28d8d5bfcf30ff9dd9
/sources/opn2/adl/measurer/chips/opn_chip_base.h
9c2bc7be148c23e90226a36b468972948b64f6e0
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jpcima/ADLplug
a28122e6250ac1611fd7cc4a1e8acbad7e8c64ca
a488abedf1783c61cb4f0caa689f1b01bf9aa17d
refs/heads/master
2023-09-02T21:55:06.136735
2021-12-16T23:05:39
2021-12-16T23:05:39
129,364,699
388
27
BSL-1.0
2023-05-12T13:28:41
2018-04-13T07:21:41
C++
UTF-8
C++
false
false
4,880
h
/* * Interfaces over Yamaha OPN2 (YM2612) chip emulators * * Copyright (C) 2017-2018 Vitaly Novichkov (Wohlstand) * * 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 ONP_CHIP_BASE_H #define ONP_CHIP_BASE_H #include <stdint.h> #include <stddef.h> #if !defined(_MSC_VER) && (__cplusplus <= 199711L) #define final #define override #endif #if defined(OPNMIDI_ENABLE_HQ_RESAMPLER) class VResampler; #endif namespace OPN { #if defined(OPNMIDI_AUDIO_TICK_HANDLER) extern void opn2_audioTickHandler(void *instance, uint32_t chipId, uint32_t rate); #endif class OPNChipBase { public: enum { nativeRate = 53267 }; protected: uint32_t m_id; uint32_t m_rate; uint32_t m_clock; public: OPNChipBase(); virtual ~OPNChipBase(); uint32_t chipId() const { return m_id; } void setChipId(uint32_t id) { m_id = id; } virtual bool canRunAtPcmRate() const = 0; virtual bool isRunningAtPcmRate() const = 0; virtual bool setRunningAtPcmRate(bool r) = 0; #if defined(OPNMIDI_AUDIO_TICK_HANDLER) virtual void setAudioTickHandlerInstance(void *instance) = 0; #endif virtual void setRate(uint32_t rate, uint32_t clock) = 0; virtual uint32_t effectiveRate() const = 0; virtual void reset() = 0; virtual void writeReg(uint32_t port, uint16_t addr, uint8_t data) = 0; virtual void nativePreGenerate() = 0; virtual void nativePostGenerate() = 0; virtual void nativeGenerate(int16_t *frame) = 0; virtual void generate(int16_t *output, size_t frames) = 0; virtual void generateAndMix(int16_t *output, size_t frames) = 0; virtual void generate32(int32_t *output, size_t frames) = 0; virtual void generateAndMix32(int32_t *output, size_t frames) = 0; virtual const char* emulatorName() = 0; private: OPNChipBase(const OPNChipBase &c); OPNChipBase &operator=(const OPNChipBase &c); }; // A base class providing F-bounded generic and efficient implementations, // supporting resampling of chip outputs template <class T> class OPNChipBaseT : public OPNChipBase { public: OPNChipBaseT(); virtual ~OPNChipBaseT(); bool isRunningAtPcmRate() const override; bool setRunningAtPcmRate(bool r) override; #if defined(OPNMIDI_AUDIO_TICK_HANDLER) void setAudioTickHandlerInstance(void *instance); #endif virtual void setRate(uint32_t rate, uint32_t clock) override; uint32_t effectiveRate() const override; virtual void reset() override; void generate(int16_t *output, size_t frames) override; void generateAndMix(int16_t *output, size_t frames) override; void generate32(int32_t *output, size_t frames) override; void generateAndMix32(int32_t *output, size_t frames) override; private: bool m_runningAtPcmRate; #if defined(OPNMIDI_AUDIO_TICK_HANDLER) void *m_audioTickHandlerInstance; #endif void nativeTick(int16_t *frame); void setupResampler(uint32_t rate); void resetResampler(); void resampledGenerate(int32_t *output); #if defined(OPNMIDI_ENABLE_HQ_RESAMPLER) VResampler *m_resampler; #else int32_t m_oldsamples[2]; int32_t m_samples[2]; int32_t m_samplecnt; int32_t m_rateratio; enum { rsm_frac = 10 }; #endif // amplitude scale factors in and out of resampler, varying for chips; // values are OK to "redefine", the static polymorphism will accept it. enum { resamplerPreAmplify = 1, resamplerPostAttenuate = 1 }; }; // A base class which provides frame-by-frame interfaces on emulations which // don't have a routine for it. It produces outputs in fixed size buffers. // Fast register updates will suffer some latency because of buffering. template <class T, unsigned Buffer = 256> class OPNChipBaseBufferedT : public OPNChipBaseT<T> { public: OPNChipBaseBufferedT() : OPNChipBaseT<T>(), m_bufferIndex(0) {} virtual ~OPNChipBaseBufferedT() {} public: void reset() override; void nativeGenerate(int16_t *frame) override; protected: virtual void nativeGenerateN(int16_t *output, size_t frames) = 0; private: unsigned m_bufferIndex; int16_t m_buffer[2 * Buffer]; }; } // namespace OPN #include "opn_chip_base.tcc" #endif // ONP_CHIP_BASE_H
[ "jpcima@users.noreply.github.com" ]
jpcima@users.noreply.github.com
59ffdeb45acbd4e529ca9d47ac7576e5a0664196
43523509ac3324883943b52c7d3e0e92cc46ef70
/renderer/modules/peerconnection/rtc_stats_response.h
2fe975877fa340146b5abdd27e5855ab2f8dccab
[]
no_license
JDenghui/blink
d935ab9a906c9f95c890549b254b4dec80d93765
6732fc88d110451aebda75b8822ba5d9b4f9de04
refs/heads/master
2020-03-23T15:55:33.238563
2018-07-21T05:26:31
2018-07-21T05:26:31
141,783,126
1
1
null
null
null
null
UTF-8
C++
false
false
2,651
h
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_STATS_RESPONSE_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_STATS_RESPONSE_H_ #include "third_party/blink/renderer/modules/peerconnection/rtc_legacy_stats_report.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_stats_response_base.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { class RTCStatsResponse final : public RTCStatsResponseBase { DEFINE_WRAPPERTYPEINFO(); public: static RTCStatsResponse* Create(); const HeapVector<Member<RTCLegacyStatsReport>>& result() const { return result_; } RTCLegacyStatsReport* namedItem(const AtomicString& name); void AddStats(const WebRTCLegacyStats&) override; virtual void Trace(blink::Visitor*); private: RTCStatsResponse(); HeapVector<Member<RTCLegacyStatsReport>> result_; HashMap<String, int> idmap_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_STATS_RESPONSE_H_
[ "Denghui_Jia@Dell.com" ]
Denghui_Jia@Dell.com
be969a2003af669f99f7c3eb0c519740a645f5ef
99b52b5283d24f8dc92dee1bf7714f9dc0c930da
/src/pbrt/util/mesh.cpp
c90d69e0d7f246275c4018e866523aed2bd6abb4
[ "Apache-2.0" ]
permissive
xzllxls/pbrt-v4
15d9a7cf61a7eecca08cd1d7bb3b058dc274ec39
d430b0bc227054cff76b0c5c5e9d52a570e9f288
refs/heads/master
2023-06-04T22:05:58.452482
2021-06-28T18:18:05
2021-06-28T18:18:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,536
cpp
// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. // The pbrt source code is licensed under the Apache License, Version 2.0. // SPDX: Apache-2.0 #include <pbrt/util/mesh.h> #include <pbrt/util/buffercache.h> #include <pbrt/util/check.h> #include <pbrt/util/error.h> #include <pbrt/util/log.h> #include <pbrt/util/print.h> #include <pbrt/util/stats.h> #include <pbrt/util/transform.h> #include <rply/rply.h> namespace pbrt { STAT_RATIO("Geometry/Triangles per mesh", nTris, nTriMeshes); STAT_MEMORY_COUNTER("Memory/Triangles", triangleBytes); // TriangleMesh Method Definitions TriangleMesh::TriangleMesh(const Transform &renderFromObject, bool reverseOrientation, std::vector<int> indices, std::vector<Point3f> p, std::vector<Vector3f> s, std::vector<Normal3f> n, std::vector<Point2f> uv, std::vector<int> faceIndices) : nTriangles(indices.size() / 3), nVertices(p.size()) { CHECK_EQ((indices.size() % 3), 0); ++nTriMeshes; nTris += nTriangles; triangleBytes += sizeof(*this); // Initialize mesh _vertexIndices_ vertexIndices = intBufferCache->LookupOrAdd(indices); // Transform mesh vertices to rendering space and initialize mesh _p_ for (Point3f &pt : p) pt = renderFromObject(pt); this->p = point3BufferCache->LookupOrAdd(p); // Remainder of _TriangleMesh_ constructor this->reverseOrientation = reverseOrientation; this->transformSwapsHandedness = renderFromObject.SwapsHandedness(); if (!uv.empty()) { CHECK_EQ(nVertices, uv.size()); this->uv = point2BufferCache->LookupOrAdd(uv); } if (!n.empty()) { CHECK_EQ(nVertices, n.size()); for (Normal3f &nn : n) { nn = renderFromObject(nn); if (reverseOrientation) nn = -nn; } this->n = normal3BufferCache->LookupOrAdd(n); } if (!s.empty()) { CHECK_EQ(nVertices, s.size()); for (Vector3f &ss : s) ss = renderFromObject(ss); this->s = vector3BufferCache->LookupOrAdd(s); } if (!faceIndices.empty()) { CHECK_EQ(nTriangles, faceIndices.size()); this->faceIndices = intBufferCache->LookupOrAdd(faceIndices); } // Make sure that we don't have too much stuff to be using integers to // index into things. CHECK_LE(p.size(), std::numeric_limits<int>::max()); // We could be clever and check indices.size() / 3 if we were careful // to promote to a 64-bit int before multiplying by 3 when we look up // in the indices array... CHECK_LE(indices.size(), std::numeric_limits<int>::max()); } std::string TriangleMesh::ToString() const { std::string np = "(nullptr)"; return StringPrintf( "[ TriangleMesh reverseOrientation: %s transformSwapsHandedness: %s " "nTriangles: %d nVertices: %d vertexIndices: %s p: %s n: %s " "s: %s uv: %s faceIndices: %s ]", reverseOrientation, transformSwapsHandedness, nTriangles, nVertices, vertexIndices ? StringPrintf("%s", pstd::MakeSpan(vertexIndices, 3 * nTriangles)) : np, p ? StringPrintf("%s", pstd::MakeSpan(p, nVertices)) : nullptr, n ? StringPrintf("%s", pstd::MakeSpan(n, nVertices)) : nullptr, s ? StringPrintf("%s", pstd::MakeSpan(s, nVertices)) : nullptr, uv ? StringPrintf("%s", pstd::MakeSpan(uv, nVertices)) : nullptr, faceIndices ? StringPrintf("%s", pstd::MakeSpan(faceIndices, nTriangles)) : nullptr); } static void PlyErrorCallback(p_ply, const char *message) { Error("PLY writing error: %s", message); } bool TriangleMesh::WritePLY(const std::string &filename) const { p_ply plyFile = ply_create(filename.c_str(), PLY_DEFAULT, PlyErrorCallback, 0, nullptr); if (plyFile == nullptr) return false; ply_add_element(plyFile, "vertex", nVertices); ply_add_scalar_property(plyFile, "x", PLY_FLOAT); ply_add_scalar_property(plyFile, "y", PLY_FLOAT); ply_add_scalar_property(plyFile, "z", PLY_FLOAT); if (n) { ply_add_scalar_property(plyFile, "nx", PLY_FLOAT); ply_add_scalar_property(plyFile, "ny", PLY_FLOAT); ply_add_scalar_property(plyFile, "nz", PLY_FLOAT); } if (uv) { ply_add_scalar_property(plyFile, "u", PLY_FLOAT); ply_add_scalar_property(plyFile, "v", PLY_FLOAT); } if (s) Warning(R"(%s: PLY mesh will be missing tangent vectors "S".)", filename); ply_add_element(plyFile, "face", nTriangles); ply_add_list_property(plyFile, "vertex_indices", PLY_UINT8, PLY_INT); if (faceIndices) ply_add_scalar_property(plyFile, "face_indices", PLY_INT); ply_write_header(plyFile); for (int i = 0; i < nVertices; ++i) { ply_write(plyFile, p[i].x); ply_write(plyFile, p[i].y); ply_write(plyFile, p[i].z); if (n) { ply_write(plyFile, n[i].x); ply_write(plyFile, n[i].y); ply_write(plyFile, n[i].z); } if (uv) { ply_write(plyFile, uv[i].x); ply_write(plyFile, uv[i].y); } } for (int i = 0; i < nTriangles; ++i) { ply_write(plyFile, 3); ply_write(plyFile, vertexIndices[3 * i]); ply_write(plyFile, vertexIndices[3 * i + 1]); ply_write(plyFile, vertexIndices[3 * i + 2]); if (faceIndices) ply_write(plyFile, faceIndices[i]); } ply_close(plyFile); return true; } STAT_RATIO("Geometry/Bilinear patches per mesh", nBlps, nBilinearMeshes); STAT_MEMORY_COUNTER("Memory/Bilinear patches", blpBytes); BilinearPatchMesh::BilinearPatchMesh(const Transform &renderFromObject, bool reverseOrientation, std::vector<int> indices, std::vector<Point3f> P, std::vector<Normal3f> N, std::vector<Point2f> UV, std::vector<int> fIndices, PiecewiseConstant2D *imageDist) : reverseOrientation(reverseOrientation), transformSwapsHandedness(renderFromObject.SwapsHandedness()), nPatches(indices.size() / 4), nVertices(P.size()), imageDistribution(imageDist) { CHECK_EQ((indices.size() % 4), 0); ++nBilinearMeshes; nBlps += nPatches; // Make sure that we don't have too much stuff to be using integers to // index into things. CHECK_LE(P.size(), std::numeric_limits<int>::max()); CHECK_LE(indices.size(), std::numeric_limits<int>::max()); vertexIndices = intBufferCache->LookupOrAdd(indices); blpBytes += sizeof(*this); // Transform mesh vertices to world space for (Point3f &p : P) p = renderFromObject(p); p = point3BufferCache->LookupOrAdd(P); // Copy _UV_ and _N_ vertex data, if present if (!UV.empty()) { CHECK_EQ(nVertices, UV.size()); uv = point2BufferCache->LookupOrAdd(UV); } if (!N.empty()) { CHECK_EQ(nVertices, N.size()); for (Normal3f &n : N) { n = renderFromObject(n); if (reverseOrientation) n = -n; } n = normal3BufferCache->LookupOrAdd(N); } if (!fIndices.empty()) { CHECK_EQ(nPatches, fIndices.size()); faceIndices = intBufferCache->LookupOrAdd(fIndices); } } std::string BilinearPatchMesh::ToString() const { std::string np = "(nullptr)"; return StringPrintf( "[ BilinearMatchMesh reverseOrientation: %s transformSwapsHandedness: " "%s " "nPatches: %d nVertices: %d vertexIndices: %s p: %s n: %s " "uv: %s faceIndices: %s ]", reverseOrientation, transformSwapsHandedness, nPatches, nVertices, vertexIndices ? StringPrintf("%s", pstd::MakeSpan(vertexIndices, 4 * nPatches)) : np, p ? StringPrintf("%s", pstd::MakeSpan(p, nVertices)) : nullptr, n ? StringPrintf("%s", pstd::MakeSpan(n, nVertices)) : nullptr, uv ? StringPrintf("%s", pstd::MakeSpan(uv, nVertices)) : nullptr, faceIndices ? StringPrintf("%s", pstd::MakeSpan(faceIndices, nPatches)) : nullptr); } struct FaceCallbackContext { int face[4]; std::vector<int> triIndices, quadIndices; }; void rply_message_callback(p_ply ply, const char *message) { Warning("rply: %s", message); } /* Callback to handle vertex data from RPly */ int rply_vertex_callback(p_ply_argument argument) { Float *buffer; long index, flags; ply_get_argument_user_data(argument, (void **)&buffer, &flags); ply_get_argument_element(argument, nullptr, &index); int stride = (flags & 0x0F0) >> 4; int offset = flags & 0x00F; buffer[index * stride + offset] = (float)ply_get_argument_value(argument); return 1; } /* Callback to handle face data from RPly */ int rply_face_callback(p_ply_argument argument) { FaceCallbackContext *context; long flags; ply_get_argument_user_data(argument, (void **)&context, &flags); long length, value_index; ply_get_argument_property(argument, nullptr, &length, &value_index); if (length != 3 && length != 4) { Warning("plymesh: Ignoring face with %i vertices (only triangles and quads " "are supported!)", (int)length); return 1; } else if (value_index < 0) { return 1; } if (value_index >= 0) context->face[value_index] = (int)ply_get_argument_value(argument); if (value_index == length - 1) { if (length == 3) for (int i = 0; i < 3; ++i) context->triIndices.push_back(context->face[i]); else { CHECK_EQ(length, 4); // Note: modify order since we're specifying it as a blp... context->quadIndices.push_back(context->face[0]); context->quadIndices.push_back(context->face[1]); context->quadIndices.push_back(context->face[3]); context->quadIndices.push_back(context->face[2]); } } return 1; } int rply_faceindex_callback(p_ply_argument argument) { std::vector<int> *faceIndices; long flags; ply_get_argument_user_data(argument, (void **)&faceIndices, &flags); faceIndices->push_back((int)ply_get_argument_value(argument)); return 1; } TriQuadMesh TriQuadMesh::ReadPLY(const std::string &filename) { TriQuadMesh mesh; p_ply ply = ply_open(filename.c_str(), rply_message_callback, 0, nullptr); if (ply == nullptr) ErrorExit("Couldn't open PLY file \"%s\"", filename); if (ply_read_header(ply) == 0) ErrorExit("Unable to read the header of PLY file \"%s\"", filename); p_ply_element element = nullptr; size_t vertexCount = 0, faceCount = 0; /* Inspect the structure of the PLY file */ while ((element = ply_get_next_element(ply, element)) != nullptr) { const char *name; long nInstances; ply_get_element_info(element, &name, &nInstances); if (strcmp(name, "vertex") == 0) vertexCount = nInstances; else if (strcmp(name, "face") == 0) faceCount = nInstances; } if (vertexCount == 0 || faceCount == 0) ErrorExit("%s: PLY file is invalid! No face/vertex elements found!", filename); mesh.p.resize(vertexCount); if (ply_set_read_cb(ply, "vertex", "x", rply_vertex_callback, mesh.p.data(), 0x30) == 0 || ply_set_read_cb(ply, "vertex", "y", rply_vertex_callback, mesh.p.data(), 0x31) == 0 || ply_set_read_cb(ply, "vertex", "z", rply_vertex_callback, mesh.p.data(), 0x32) == 0) { ErrorExit("%s: Vertex coordinate property not found!", filename); } mesh.n.resize(vertexCount); if (ply_set_read_cb(ply, "vertex", "nx", rply_vertex_callback, mesh.n.data(), 0x30) == 0 || ply_set_read_cb(ply, "vertex", "ny", rply_vertex_callback, mesh.n.data(), 0x31) == 0 || ply_set_read_cb(ply, "vertex", "nz", rply_vertex_callback, mesh.n.data(), 0x32) == 0) mesh.n.resize(0); /* There seem to be lots of different conventions regarding UV coordinate * names */ mesh.uv.resize(vertexCount); if (((ply_set_read_cb(ply, "vertex", "u", rply_vertex_callback, mesh.uv.data(), 0x20) != 0) && (ply_set_read_cb(ply, "vertex", "v", rply_vertex_callback, mesh.uv.data(), 0x21) != 0)) || ((ply_set_read_cb(ply, "vertex", "s", rply_vertex_callback, mesh.uv.data(), 0x20) != 0) && (ply_set_read_cb(ply, "vertex", "t", rply_vertex_callback, mesh.uv.data(), 0x21) != 0)) || ((ply_set_read_cb(ply, "vertex", "texture_u", rply_vertex_callback, mesh.uv.data(), 0x20) != 0) && (ply_set_read_cb(ply, "vertex", "texture_v", rply_vertex_callback, mesh.uv.data(), 0x21) != 0)) || ((ply_set_read_cb(ply, "vertex", "texture_s", rply_vertex_callback, mesh.uv.data(), 0x20) != 0) && (ply_set_read_cb(ply, "vertex", "texture_t", rply_vertex_callback, mesh.uv.data(), 0x21) != 0))) ; else mesh.uv.resize(0); FaceCallbackContext context; context.triIndices.reserve(faceCount * 3); context.quadIndices.reserve(faceCount * 4); if (ply_set_read_cb(ply, "face", "vertex_indices", rply_face_callback, &context, 0) == 0) ErrorExit("%s: vertex indices not found in PLY file", filename); if (ply_set_read_cb(ply, "face", "face_indices", rply_faceindex_callback, &mesh.faceIndices, 0) != 0) mesh.faceIndices.reserve(faceCount); if (ply_read(ply) == 0) ErrorExit("%s: unable to read the contents of PLY file", filename); mesh.triIndices = std::move(context.triIndices); mesh.quadIndices = std::move(context.quadIndices); ply_close(ply); for (int idx : mesh.triIndices) if (idx < 0 || idx >= mesh.p.size()) ErrorExit("plymesh: Vertex index %i is out of bounds! " "Valid range is [0..%i)", idx, int(mesh.p.size())); for (int idx : mesh.quadIndices) if (idx < 0 || idx >= mesh.p.size()) ErrorExit("plymesh: Vertex index %i is out of bounds! " "Valid range is [0..%i)", idx, int(mesh.p.size())); return mesh; } void TriQuadMesh::ConvertToOnlyTriangles() { if (quadIndices.empty()) return; triIndices.reserve(triIndices.size() + 3 * quadIndices.size() / 2); for (size_t i = 0; i < quadIndices.size(); i += 4) { triIndices.push_back(quadIndices[i]); // 0, 1, 2 of original triIndices.push_back(quadIndices[i + 1]); triIndices.push_back(quadIndices[i + 3]); triIndices.push_back(quadIndices[i]); // 0, 2, 3 of original triIndices.push_back(quadIndices[i + 3]); triIndices.push_back(quadIndices[i + 2]); } quadIndices.clear(); } std::string TriQuadMesh::ToString() const { return StringPrintf("[ TriQuadMesh p: %s n: %s uv: %s faceIndices: %s triIndices: %s " "quadIndices: %s ]", p, n, uv, faceIndices, triIndices, quadIndices); } } // namespace pbrt
[ "matt@pharr.org" ]
matt@pharr.org
0587cd08c4b9b51495d16a390638738d1a41f8fa
d1933be4f7c06fe4290c368630a4cecab512ba76
/src/include/infotrope/server/master.hh
4292327f698d0f11c735dd88ae13d73e223c9a25
[ "MIT" ]
permissive
dwd/acapd
1159625ba4123ec2534a190a571a38e1263e41c6
e396962d6c7c19beb236b2a08097a6bb08a7bb9c
refs/heads/master
2020-05-19T12:20:58.644077
2017-02-24T11:48:08
2017-02-24T11:48:08
15,703,044
3
0
null
null
null
null
UTF-8
C++
false
false
4,149
hh
/* * 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 Library 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. */ #ifndef INFOTROPE_SERVER_MASTER_HH #define INFOTROPE_SERVER_MASTER_HH #include <map> #include <deque> #include <infotrope/threading/lock.hh> #include <infotrope/utils/magic-ptr.hh> #include <infotrope/config.h> #include <sasl/sasl.h> namespace Infotrope { namespace Data { class Datastore; } namespace Server { /* Master is responsible for handling incoming connections, and passing them onto Workers, and reaping Workers when they complete. The Master communicates with a Driver process, which actually handles listening to ports. Master also handles SASL setup and logging. */ class Worker; #ifdef INFOTROPE_ENABLE_XPERSIST class Session; #endif class Master { public: Master( int ctrlfd, std::string const & datadir ); ~Master(); int run(); // Send 'L' message, with priority 1-9. void log( int pri, std::string const & ) const; // Send 'E' message - server will not restart after this. void log_except( std::string const & ) const; // Access worker threads. bool exists( int ) const; Infotrope::Utils::magic_ptr<Worker> get( int ) const; static Master * master(); // dead is sent when a Worker has been told to shutdown, and has completed running all pending commands. void dead( int ); // We do this if we generate an exception. // All workers are rapidly shutdown, and * BYE is unilaterally sent. void shutdown_fast(); // Backgrounded dump request. void full_dump(); // Cyrus SASL support functions. std::string sasl_getopt( std::string const & path, std::string const & option ); std::string sasl_log( int level, std::string const & msg ); std::string sasl_getpath(); int sasl_verifyfile( std::string const & file, sasl_verify_type_t type ); int sasl_authorize( std::string const & user, std::string const & auth, std::string const & realm, struct propctx * propctx ); #ifdef INFOTROPE_ENABLE_XPERSIST Utils::magic_ptr<Session> const & session( std::string const & ); void session( Utils::magic_ptr<Session> const & ); #endif public: static Master * instance; private: void log_real( int prio, std::string const & ) const; void send_control( char, std::string const & ) const; int listen( std::string const & ); void close( std::string const & ); void setup_datastore(); void setup_sasl(); void setup_addresses(); bool load_dump( std::string const &, bool ); bool load_ts( std::string const & ); public: std::string const & datadir() const { return m_datadir; } private: int m_ctrlfd; typedef std::map< int, Infotrope::Utils::magic_ptr<Worker> > t_workers; t_workers m_workers; std::string m_datadir; std::deque<int> m_dead; Infotrope::Threading::Mutex m_lock; Infotrope::Threading::Mutex m_listen_lock; Infotrope::Utils::magic_ptr<Infotrope::Data::Datastore> m_ds; bool m_full_dump_rq; #ifdef INFOTROPE_ENABLE_XPERSIST typedef std::map< std::string, Infotrope::Utils::magic_ptr<Infotrope::Server::Session> > t_sessions; t_sessions m_sessions; Infotrope::Threading::Mutex m_session_lock; #endif pthread_t m_self; }; } } #endif
[ "dcridland@arcode.com" ]
dcridland@arcode.com
7470de152c2b810c468e7ef903b05a8d7953b5f6
2c62385f15b1f8e6072138d5175d7a70dd236b98
/blazetest/src/mathtest/dmatdmatmult/SDbHDb.cpp
1cf98eb925035c2afa9711f5179a84de9c78510c
[ "BSD-3-Clause" ]
permissive
lyxm/blaze
665e4c6f6e1a717973d2d98e148c720030843266
10dbaa368790316b5e044cfe9b92f5534f60a2dc
refs/heads/master
2021-01-12T20:31:45.197297
2015-10-15T21:39:17
2015-10-15T21:39:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,288
cpp
//================================================================================================= /*! // \file src/mathtest/dmatdmatmult/SDbHDb.cpp // \brief Source file for the SDbHDb dense matrix/dense matrix multiplication math test // // Copyright (C) 2013 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/HermitianMatrix.h> #include <blaze/math/SymmetricMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatdmatmult/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'SDbHDb'..." << std::endl; using blazetest::mathtest::TypeB; try { // Matrix type definitions typedef blaze::SymmetricMatrix< blaze::DynamicMatrix<TypeB> > SDb; typedef blaze::HermitianMatrix< blaze::DynamicMatrix<TypeB> > HDb; // Creator type definitions typedef blazetest::Creator<SDb> CSDb; typedef blazetest::Creator<HDb> CHDb; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { RUN_DMATDMATMULT_OPERATION_TEST( CSDb( i ), CHDb( i ) ); } // Running tests with large matrices RUN_DMATDMATMULT_OPERATION_TEST( CSDb( 15UL ), CHDb( 15UL ) ); RUN_DMATDMATMULT_OPERATION_TEST( CSDb( 37UL ), CHDb( 37UL ) ); RUN_DMATDMATMULT_OPERATION_TEST( CSDb( 63UL ), CHDb( 63UL ) ); RUN_DMATDMATMULT_OPERATION_TEST( CSDb( 16UL ), CHDb( 16UL ) ); RUN_DMATDMATMULT_OPERATION_TEST( CSDb( 32UL ), CHDb( 32UL ) ); RUN_DMATDMATMULT_OPERATION_TEST( CSDb( 64UL ), CHDb( 64UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
4a07f7d353054a8f8aaf406b39aa27483da3b494
cbfb8553a5c990c79e184149e236e1fa3e8ba943
/Leetcode/Tree/543_DiameterofBinaryTree.cpp
8574b63b55000dfc6190afe75f01d71958955eaa
[]
no_license
DancingOnAir/LeetCode
09c0b8c428216302be02447b257e7b9ca44c741b
62d5a81f9a774599368a91050bcf83e4ffab8f50
refs/heads/master
2023-05-09T01:59:58.943716
2023-05-04T01:10:42
2023-05-04T01:10:42
93,221,941
2
1
null
null
null
null
UTF-8
C++
false
false
2,894
cpp
//#include <iostream> //#include <vector> //#include <string> //#include <queue> // //using namespace std; // //struct TreeNode //{ // int val; // TreeNode* left; // TreeNode* right; // TreeNode(int x) : val(x), left(nullptr), right(nullptr) // { // // } //}; // //int depthOfBinaryTree2(TreeNode* root) //{ // if (!root) // return 0; // // return max(depthOfBinaryTree2(root->left), depthOfBinaryTree2(root->right)) + 1; //} // //void preorderTraversal(TreeNode* root, int& maxVal) //{ // if (!root) // return; // // maxVal = max(maxVal, depthOfBinaryTree2(root->left) + depthOfBinaryTree2(root->right)); // preorderTraversal(root->left, maxVal); // preorderTraversal(root->right, maxVal); //} // //int diameterOfBinaryTree2(TreeNode* root) //{ // if (!root) // return 0; // // int maxVal = INT_MIN; // preorderTraversal(root, maxVal); // // return maxVal; //} // //int maxVal = INT_MIN; // //int depthOfBinaryTree(TreeNode* root) //{ // if (!root) // return 0; // // maxVal = max(maxVal, depthOfBinaryTree(root->left) + depthOfBinaryTree(root->right)); // return max(depthOfBinaryTree(root->left), depthOfBinaryTree(root->right)) + 1; //} // //int diameterOfBinaryTree(TreeNode* root) //{ // if (!root) // return 0; // // depthOfBinaryTree(root); // // return maxVal; //} // //TreeNode* createBinaryTree(const vector<string>& nums) //{ // if (nums.empty()) // return nullptr; // // TreeNode* root = new TreeNode(stoi(nums[0])); // queue<TreeNode*> q; // q.emplace(root); // TreeNode* pCurrent = nullptr; // // int startIndex = 1; // int nextLevelIndex = 2; // int restIndex = nums.size() - 1; // // while (restIndex > 0) // { // for (int i = startIndex; i < startIndex + nextLevelIndex; i += 2) // { // if (i >= nums.size()) // return root; // // pCurrent = q.front(); // q.pop(); // // if (nums[i] != "null") // { // pCurrent->left = new TreeNode(stoi(nums[i])); // q.emplace(pCurrent->left); // } // // if (i + 1 >= nums.size()) // return root; // // if (nums[i + 1] != "null") // { // pCurrent->right = new TreeNode(stoi(nums[i + 1])); // q.emplace(pCurrent->right); // } // } // // startIndex += nextLevelIndex; // restIndex -= nextLevelIndex; // nextLevelIndex = q.size() * 2; // } // // return root; //} // //void testDiameterOfBinaryTree() //{ // vector<string> nums1 = { "1", "2", "3", "4", "5" }; // TreeNode* root1 = createBinaryTree(nums1); // cout << diameterOfBinaryTree(root1) << endl; //} // //int main() //{ // testDiameterOfBinaryTree(); // // getchar(); // return 0; //}
[ "taotong1984@hotmail.com" ]
taotong1984@hotmail.com
ba66839a6918cbc6ef54821982379bde90124e9b
ccfcbf1112b0ff36665bd24ebd2ff2367ca69086
/UI/JKAbout.h
a6704e7fe913ddc87d0312d5650f11d3cad928a4
[ "Apache-2.0" ]
permissive
kenylerich/StockTool
4733e8d8d5e56fb57443eb55dc7f205dcbb4d0ec
04da77d9be6633a66bef2d4f15c2b23f9ef522da
refs/heads/master
2020-03-18T10:24:52.085621
2018-03-26T10:44:11
2018-03-26T10:44:11
134,610,330
0
1
null
null
null
null
UTF-8
C++
false
false
228
h
#ifndef JKABOUT_H #define JKABOUT_H #include <QDialog> #include "ui_JKAbout.h" class JKAbout : public QDialog { Q_OBJECT public: JKAbout(QWidget *parent = 0); ~JKAbout(); private: Ui::JKAbout ui; }; #endif // JKABOUT_H
[ "WANGJL-F@glodon.com" ]
WANGJL-F@glodon.com
83a7b68c5b149e3cb259cfea4acda54d28cf9830
2a0fee7a6f566843c6d533bc1f7b621c7e3b3400
/chrome/browser/media/unified_autoplay_config_unittest.cc
9b950e4d8093793e4e155b43077ec91cecf1556a
[ "BSD-3-Clause" ]
permissive
amitsadaphule/chromium
f53b022c12d196281c55e41e44d46ff9eadf0e56
074114ff0d3f24fc078684526b2682f03aba0b93
refs/heads/master
2022-11-22T22:10:09.177669
2019-06-16T12:14:29
2019-06-16T12:14:29
282,966,085
0
0
BSD-3-Clause
2020-07-27T17:19:52
2020-07-27T17:19:51
null
UTF-8
C++
false
false
6,154
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/media/unified_autoplay_config.h" #include "base/test/scoped_command_line.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/content_settings/sound_content_setting_observer.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/prefs/pref_service.h" #include "content/public/common/web_preferences.h" #include "content/public/test/test_service_manager_context.h" #include "content/public/test/web_contents_tester.h" #include "media/base/media_switches.h" // Unit tests for the unified autoplay policy with the unified sound settings // UI enabled. class UnifiedAutoplaySoundSettingsTest : public ChromeRenderViewHostTestHarness { public: ~UnifiedAutoplaySoundSettingsTest() override = default; void SetUp() override { scoped_feature_list_.InitWithFeatures( {media::kAutoplayDisableSettings, media::kAutoplayWhitelistSettings}, {}); ChromeRenderViewHostTestHarness::SetUp(); test_service_manager_context_ = std::make_unique<content::TestServiceManagerContext>(); SoundContentSettingObserver::CreateForWebContents(web_contents()); } void TearDown() override { // Must be reset before browser thread teardown. test_service_manager_context_.reset(); ChromeRenderViewHostTestHarness::TearDown(); } void SetSoundContentSettingDefault(ContentSetting value) { HostContentSettingsMap* content_settings = HostContentSettingsMapFactory::GetForProfile(profile()); content_settings->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_SOUND, value); } void SetAutoplayPrefValue(bool value) { GetPrefs()->SetBoolean(prefs::kBlockAutoplayEnabled, value); EXPECT_EQ(value, GetPrefs()->GetBoolean(prefs::kBlockAutoplayEnabled)); } bool ShouldBlockAutoplay() { return UnifiedAutoplayConfig::ShouldBlockAutoplay(profile()); } content::AutoplayPolicy GetAppliedAutoplayPolicy() { return web_contents() ->GetRenderViewHost() ->GetWebkitPreferences() .autoplay_policy; } void NavigateToTestPage() { content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL("https://first.example.com")); } private: PrefService* GetPrefs() { return profile()->GetPrefs(); } base::test::ScopedFeatureList scoped_feature_list_; // WebContentsImpl accesses // content::ServiceManagerConnection::GetForProcess(), so // we must make sure it is instantiated. std::unique_ptr<content::TestServiceManagerContext> test_service_manager_context_; }; TEST_F(UnifiedAutoplaySoundSettingsTest, ContentSetting_Allow) { SetSoundContentSettingDefault(CONTENT_SETTING_ALLOW); SetAutoplayPrefValue(false); EXPECT_FALSE(ShouldBlockAutoplay()); NavigateToTestPage(); EXPECT_EQ(content::AutoplayPolicy::kNoUserGestureRequired, GetAppliedAutoplayPolicy()); } TEST_F(UnifiedAutoplaySoundSettingsTest, ContentSetting_Block) { SetSoundContentSettingDefault(CONTENT_SETTING_BLOCK); SetAutoplayPrefValue(false); EXPECT_TRUE(ShouldBlockAutoplay()); NavigateToTestPage(); EXPECT_EQ(content::AutoplayPolicy::kDocumentUserActivationRequired, GetAppliedAutoplayPolicy()); // Set back to ALLOW to ensure that the policy is updated on the next // navigation. SetSoundContentSettingDefault(CONTENT_SETTING_ALLOW); EXPECT_FALSE(ShouldBlockAutoplay()); NavigateToTestPage(); EXPECT_EQ(content::AutoplayPolicy::kNoUserGestureRequired, GetAppliedAutoplayPolicy()); } TEST_F(UnifiedAutoplaySoundSettingsTest, Feature_DisabledNoop) { // Explicitly disable the feature. base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures( {}, {media::kAutoplayDisableSettings, media::kAutoplayWhitelistSettings}); SetAutoplayPrefValue(false); EXPECT_FALSE(ShouldBlockAutoplay()); NavigateToTestPage(); EXPECT_EQ(content::AutoplayPolicy::kDocumentUserActivationRequired, GetAppliedAutoplayPolicy()); } TEST_F(UnifiedAutoplaySoundSettingsTest, Pref_DefaultEnabled) { EXPECT_TRUE(ShouldBlockAutoplay()); NavigateToTestPage(); EXPECT_EQ(content::AutoplayPolicy::kDocumentUserActivationRequired, GetAppliedAutoplayPolicy()); } TEST_F(UnifiedAutoplaySoundSettingsTest, Pref_Disabled) { SetAutoplayPrefValue(false); EXPECT_FALSE(ShouldBlockAutoplay()); NavigateToTestPage(); EXPECT_EQ(content::AutoplayPolicy::kNoUserGestureRequired, GetAppliedAutoplayPolicy()); // Now update the pref and make sure we apply it on the next navigation. SetAutoplayPrefValue(true); EXPECT_TRUE(ShouldBlockAutoplay()); NavigateToTestPage(); EXPECT_EQ(content::AutoplayPolicy::kDocumentUserActivationRequired, GetAppliedAutoplayPolicy()); } // Unit tests for the unified autoplay policy with the unified sound settings // UI enabled and a custom autoplay policy command line switch. class UnifiedAutoplaySoundSettingsOverrideTest : public UnifiedAutoplaySoundSettingsTest { public: ~UnifiedAutoplaySoundSettingsOverrideTest() override = default; void SetUp() override { scoped_command_line_.GetProcessCommandLine()->AppendSwitchASCII( switches::kAutoplayPolicy, switches::autoplay::kUserGestureRequiredPolicy); UnifiedAutoplaySoundSettingsTest::SetUp(); } private: base::test::ScopedCommandLine scoped_command_line_; }; TEST_F(UnifiedAutoplaySoundSettingsOverrideTest, CommandLineOverride) { EXPECT_TRUE(ShouldBlockAutoplay()); NavigateToTestPage(); EXPECT_EQ(content::AutoplayPolicy::kUserGestureRequired, GetAppliedAutoplayPolicy()); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f383ade0c3f2660eee6b23eba0998b20c653ac1d
9ffc3deb77c4e98e009e49324458179a59f8b2d5
/lib/soloud/src/core/soloud_file.cpp
93f018320387965d697f9cc26df7978647017a74
[ "MIT", "Zlib" ]
permissive
sina-/oni
befe59437628811a6b62c4c425138fd4f9d23b75
95b873bc545cd4925b5cea8c632a82f2d815be6e
refs/heads/master
2021-06-04T23:50:25.188350
2020-10-05T13:32:08
2020-10-05T13:32:08
112,530,006
2
1
MIT
2019-11-24T12:55:15
2017-11-29T21:30:02
C++
UTF-8
C++
false
false
5,761
cpp
/* SoLoud audio engine Copyright (c) 2013-2015 Jari Komppa This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #undef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include "soloud.h" #include "soloud_file.h" namespace SoLoud { unsigned int File::read8() { unsigned char d = 0; read((unsigned char*)&d, 1); return d; } unsigned int File::read16() { unsigned short d = 0; read((unsigned char*)&d, 2); return d; } unsigned int File::read32() { unsigned int d = 0; read((unsigned char*)&d, 4); return d; } DiskFile::DiskFile(FILE *fp): mFileHandle(fp) { } unsigned int DiskFile::read(unsigned char *aDst, unsigned int aBytes) { return (unsigned int)fread(aDst, 1, aBytes, mFileHandle); } unsigned int DiskFile::length() { if (!mFileHandle) return 0; int pos = ftell(mFileHandle); fseek(mFileHandle, 0, SEEK_END); int len = ftell(mFileHandle); fseek(mFileHandle, pos, SEEK_SET); return len; } void DiskFile::seek(int aOffset) { fseek(mFileHandle, aOffset, SEEK_SET); } unsigned int DiskFile::pos() { return ftell(mFileHandle); } FILE *DiskFile::getFilePtr() { return mFileHandle; } DiskFile::~DiskFile() { if (mFileHandle) fclose(mFileHandle); } DiskFile::DiskFile() { mFileHandle = 0; } result DiskFile::open(const char *aFilename) { if (!aFilename) return INVALID_PARAMETER; mFileHandle = fopen(aFilename, "rb"); if (!mFileHandle) return FILE_NOT_FOUND; return SO_NO_ERROR; } int DiskFile::eof() { return feof(mFileHandle); } unsigned int MemoryFile::read(unsigned char *aDst, unsigned int aBytes) { if (mOffset + aBytes >= mDataLength) aBytes = mDataLength - mOffset; memcpy(aDst, mDataPtr + mOffset, aBytes); mOffset += aBytes; return aBytes; } unsigned int MemoryFile::length() { return mDataLength; } void MemoryFile::seek(int aOffset) { if (aOffset >= 0) mOffset = aOffset; else mOffset = mDataLength + aOffset; if (mOffset > mDataLength-1) mOffset = mDataLength-1; } unsigned int MemoryFile::pos() { return mOffset; } unsigned char * MemoryFile::getMemPtr() { return mDataPtr; } MemoryFile::~MemoryFile() { if (mDataOwned) delete[] mDataPtr; } MemoryFile::MemoryFile() { mDataPtr = 0; mDataLength = 0; mOffset = 0; mDataOwned = false; } result MemoryFile::openMem(unsigned char *aData, unsigned int aDataLength, bool aCopy, bool aTakeOwnership) { if (aData == NULL || aDataLength == 0) return INVALID_PARAMETER; if (mDataOwned) delete[] mDataPtr; mDataPtr = 0; mOffset = 0; mDataLength = aDataLength; if (aCopy) { mDataOwned = true; mDataPtr = new unsigned char[aDataLength]; if (mDataPtr == NULL) return OUT_OF_MEMORY; memcpy(mDataPtr, aData, aDataLength); return SO_NO_ERROR; } mDataPtr = aData; mDataOwned = aTakeOwnership; return SO_NO_ERROR; } result MemoryFile::openToMem(const char *aFile) { if (!aFile) return INVALID_PARAMETER; if (mDataOwned) delete[] mDataPtr; mDataPtr = 0; mOffset = 0; DiskFile df; int res = df.open(aFile); if (res != SO_NO_ERROR) return res; mDataLength = df.length(); mDataPtr = new unsigned char[mDataLength]; if (mDataPtr == NULL) return OUT_OF_MEMORY; df.read(mDataPtr, mDataLength); mDataOwned = true; return SO_NO_ERROR; } result MemoryFile::openFileToMem(File *aFile) { if (!aFile) return INVALID_PARAMETER; if (mDataOwned) delete[] mDataPtr; mDataPtr = 0; mOffset = 0; mDataLength = aFile->length(); mDataPtr = new unsigned char[mDataLength]; if (mDataPtr == NULL) return OUT_OF_MEMORY; aFile->read(mDataPtr, mDataLength); mDataOwned = true; return SO_NO_ERROR; } int MemoryFile::eof() { if (mOffset >= mDataLength) return 1; return 0; } } extern "C" { int Soloud_Filehack_fgetc(Soloud_Filehack *f) { SoLoud::File *fp = (SoLoud::File *)f; if (fp->eof()) return EOF; return fp->read8(); } int Soloud_Filehack_fread(void *dst, int s, int c, Soloud_Filehack *f) { SoLoud::File *fp = (SoLoud::File *)f; return fp->read((unsigned char*)dst, s*c) / s; } int Soloud_Filehack_fseek(Soloud_Filehack *f, int idx, int base) { SoLoud::File *fp = (SoLoud::File *)f; switch (base) { case SEEK_CUR: fp->seek(fp->pos() + idx); break; case SEEK_END: fp->seek(fp->length() + idx); break; default: fp->seek(idx); } return 0; } int Soloud_Filehack_ftell(Soloud_Filehack *f) { SoLoud::File *fp = (SoLoud::File *)f; return fp->pos(); } int Soloud_Filehack_fclose(Soloud_Filehack *f) { SoLoud::File *fp = (SoLoud::File *)f; delete fp; return 0; } Soloud_Filehack * Soloud_Filehack_fopen(const char *aFilename, char *aMode) { SoLoud::DiskFile *df = new SoLoud::DiskFile(); int res = df->open(aFilename); if (res != SoLoud::SO_NO_ERROR) { delete df; df = 0; } return (Soloud_Filehack*)df; } }
[ "sina.tamanna@gmail.com" ]
sina.tamanna@gmail.com
ba92fe184d5f93bebbc1e2f8a859422f4060e47c
6bb4da71a780d5833756e555cc41584e1a136bbd
/workspace/assignments/03-mapping-and-matching/src/lidar_localization/src/matching/matching_flow.cpp
4a1bbd1b68405f1ebed7730f89efa6f3dff92fe0
[]
no_license
Xie-ai-catch/SensorFusionWork
f2eab05417cdb2d85bfc7ba80c2a3de8b123a5eb
f0dd736573ef6c346294d6c42cbf9631e4c0deb9
refs/heads/main
2023-06-21T16:51:45.801419
2021-07-08T08:28:04
2021-07-08T08:28:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,718
cpp
/* * @Description: 地图匹配任务管理, 放在类里使代码更清晰 * @Author: Ren Qian * @Date: 2020-02-10 08:38:42 */ #include "lidar_localization/matching/matching_flow.hpp" #include "glog/logging.h" #include "lidar_localization/global_defination/global_defination.h" namespace lidar_localization { MatchingFlow::MatchingFlow(ros::NodeHandle& nh) { // subscriber: // a. undistorted Velodyne measurement: cloud_sub_ptr_ = std::make_shared<CloudSubscriber>(nh, "/synced_cloud", 100000); // b. lidar pose in map frame: gnss_sub_ptr_ = std::make_shared<OdometrySubscriber>(nh, "/synced_gnss", 100000); // publisher: // a. global point cloud map: global_map_pub_ptr_ = std::make_shared<CloudPublisher>(nh, "/global_map", "/map", 100); // b. local point cloud map: local_map_pub_ptr_ = std::make_shared<CloudPublisher>(nh, "/local_map", "/map", 100); // c. current scan: current_scan_pub_ptr_ = std::make_shared<CloudPublisher>(nh, "/current_scan", "/map", 100); // d. estimated lidar pose in map frame: laser_odom_pub_ptr_ = std::make_shared<OdometryPublisher>(nh, "/laser_localization", "/map", "/lidar", 100); laser_tf_pub_ptr_ = std::make_shared<TFBroadCaster>("/map", "/vehicle_link"); matching_ptr_ = std::make_shared<Matching>(); } bool MatchingFlow::Run() { if (matching_ptr_->HasNewGlobalMap() && global_map_pub_ptr_->HasSubscribers()) { CloudData::CLOUD_PTR global_map_ptr(new CloudData::CLOUD()); matching_ptr_->GetGlobalMap(global_map_ptr); global_map_pub_ptr_->Publish(global_map_ptr); } if (matching_ptr_->HasNewLocalMap() && local_map_pub_ptr_->HasSubscribers()) local_map_pub_ptr_->Publish(matching_ptr_->GetLocalMap()); ReadData(); while(HasData()) { if (!ValidData()) { LOG(INFO) << "Invalid data. Skip matching" << std::endl; continue; } if (UpdateMatching()) { PublishData(); } } return true; } bool MatchingFlow::ReadData() { // pipe lidar measurements and pose into buffer: cloud_sub_ptr_->ParseData(cloud_data_buff_); gnss_sub_ptr_->ParseData(gnss_data_buff_); return true; } bool MatchingFlow::HasData() { if (cloud_data_buff_.size() == 0) return false; if (matching_ptr_->HasInited()) return true; if (gnss_data_buff_.size() == 0) return false; return true; } bool MatchingFlow::ValidData() { current_cloud_data_ = cloud_data_buff_.front(); if (matching_ptr_->HasInited()) { cloud_data_buff_.pop_front(); gnss_data_buff_.clear(); return true; } current_gnss_data_ = gnss_data_buff_.front(); double diff_time = current_cloud_data_.time - current_gnss_data_.time; if (diff_time < -0.05) { cloud_data_buff_.pop_front(); return false; } if (diff_time > 0.05) { gnss_data_buff_.pop_front(); return false; } cloud_data_buff_.pop_front(); gnss_data_buff_.pop_front(); return true; } bool MatchingFlow::UpdateMatching() { if (!matching_ptr_->HasInited()) { // // TODO: implement global initialization here // // Hints: You can use SetGNSSPose & SetScanContextPose from matching.hpp // // naive implementation: // Eigen::Matrix4f init_pose = Eigen::Matrix4f::Identity(); // matching_ptr_->SetInitPose(init_pose); // matching_ptr_->SetInited(); //! GNSS matrix4 matching_ptr_->SetGNSSPose(current_gnss_data_.pose); //! GNSS position + ScanContexy // if(!matching_ptr_->SetScanContextPose(current_cloud_data_)) // return false; // Eigen::Matrix4f init_pose_sc = matching_ptr_->GetInitPose(); // Eigen::Matrix4f init_pose = Eigen::Matrix4f::Identity(); // // position // init_pose.block<3,1>(0,3) = current_gnss_data_.pose.block<3,1>(0,3); // // rotation // init_pose.block<3,3>(0,0) = init_pose_sc.block<3,3>(0,0); // matching_ptr_->SetInitPose(init_pose); // matching_ptr_->SetInited(); //! ScanContext matrix4 // if(!matching_ptr_->SetScanContextPose(current_cloud_data_)) // return false; } return matching_ptr_->Update(current_cloud_data_, laser_odometry_); } bool MatchingFlow::PublishData() { laser_tf_pub_ptr_->SendTransform(laser_odometry_, current_cloud_data_.time); laser_odom_pub_ptr_->Publish(laser_odometry_, current_cloud_data_.time); current_scan_pub_ptr_->Publish(matching_ptr_->GetCurrentScan()); return true; } }
[ "gongyiqun51237@163.com" ]
gongyiqun51237@163.com
717d2c6efa730f0e596184e800f82a0e59bd3fad
b9031e843ff2639d590f5294ff7f598999096da3
/HardLight/include/Menu/MenuOption.h
ee859f4168c42c50565b48f2dd1a7cfc81ad58fb
[]
no_license
albchu/hardlight
d62fa67b5b1afdaa2e5a25a0eb7fe6fd042f882f
02d52288303e31ff51cb46de667a996a76bb9949
refs/heads/master
2021-01-01T03:37:31.952071
2015-04-17T23:21:26
2015-04-17T23:21:26
57,224,002
0
0
null
null
null
null
UTF-8
C++
false
false
1,997
h
#ifndef _MENU_OPTION_H_ #define _MENU_OPTION_H_ #include <iostream> #include "Menu/SDL_Texture_Wrapper.h" using namespace std; enum OptionType { REDIRECT, FLAG, RANGE }; // An option for the menu class MenuOption { public: MenuOption(SDL_Renderer* new_renderer, const char* init_id, const char* new_text="", int new_font_size=20, const char* font_path="../data/Fonts/Queen of Camelot Regular.ttf"); //MenuOption(SDL_Renderer* new_renderer, const char* new_text); //void init(SDL_Renderer* new_renderer, const char* new_text, const char* font_path); MenuOption(); ~MenuOption(); virtual void render(int x, int y); void setSelected(bool selected); virtual SDL_Rect* getButtonRect(); SDL_Texture_Wrapper* get_text_texture(); void set_button_texture(const char* texture_path); void set_button_selected_texture(const char* texture_path); const char* get_id(); // Option Data accessor/mutators void set_option_data(const char* menu_name); void set_option_data(bool& new_flag); OptionType get_type(); const char* get_redirect_menu(); bool get_flag(); void toggle_flag(); const char* get_text(); void set_text(const char* new_text); void set_selectable(bool new_selectable); bool is_selectable(); protected: const char * id; // different from text incase text changes, this wont be lost const char* text; SDL_Texture_Wrapper* buttonTexture; SDL_Texture_Wrapper* buttonTextureSelected; SDL_Texture_Wrapper* textTexture; TTF_Font *font; SDL_Renderer* renderer; int font_size; int padding_w_scalar; int padding_h_scalar; bool is_selected; bool selectable; // Option Data. These fields can vary in which ones are filled at any time OptionType type; const char* redirect_menu; // Name of the menu to redirect to: cant directly refer to menu due to circular dependancy issue bool* flag; // Needs to record a pointer to the reference of the original boolean so that we will change that original boolean when we need to. SDL_Rect* buttonRenderQuad; }; #endif
[ "achu@coverity.com" ]
achu@coverity.com
bcac64cf52985925a9a7bc1577be91a829c60253
ccfc53b7b7214a42f28de2420367f98d7bf93bf0
/camera.cpp
5bdfa7d67c6861c803ee4d821b0e42d3017b368e
[]
no_license
rubcuadra/solarsystem
28bef6789d2e23a98a6b249c1ca55dfe67fb7944
e9c80328a4dd557f14fc8e20676a3d8a2d675943
refs/heads/master
2021-01-22T04:53:28.783813
2017-05-15T16:30:05
2017-05-15T16:30:05
81,592,323
0
1
null
2017-05-15T01:09:45
2017-02-10T18:08:24
C
UTF-8
C++
false
false
8,531
cpp
#include <cmath> #include "camera.h" #ifdef __APPLE__ #include <OpenGL/gl.h> #include <GLUT/glut.h> #else #include <GL/gl.h> #include <GL/glut.h> #endif // my camera system i envisioned to be controlled kinda like a spaceship // so the keyboard would manipulate roll and direction and move around // so im representing it with 4 vectors // an up, forward, and right vector to represent orientation on all axes // and a position vector to represent the translation // these are some vector funcs i made to help me use the vectors easily // sets vec to (x,y,z) void vectorSet(float* vec, float x, float y, float z) { vec[0] = x; vec[1] = y; vec[2] = z; } // adds v2 to v1 void vectorAdd(float* v1, float* v2) { v1[0] += v2[0]; v1[1] += v2[1]; v1[2] += v2[2]; } // copies v2 into v1 void vectorCopy(float* v1, float* v2) { v1[0] = v2[0]; v1[1] = v2[1]; v1[2] = v2[2]; } // multiplies vec by the scalar void vectorMul(float* vec, float scalar) { vec[0] *= scalar; vec[1] *= scalar; vec[2] *= scalar; } // finds the magnitude of a vec using pythag float lengthOfVec(float* vec) { return sqrtf(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]); } // normalises a vector to magnitude 1 void normaliseVec(float* vec) { vectorMul(vec, 1 / lengthOfVec(vec)); } // makes a 3x3 rotation matrix from the given angle and axis and pointer to a 3x3 matrix void rotationMatrix(float* matrix, float* axis, float angle) { // using http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle float cos1 = cos(angle); float cos2 = 1 - cos1; float sin1 = sin(angle); matrix[0] = cos1 + axis[0]*axis[0]*cos2; matrix[1] = axis[0] * axis[1] * cos2 - axis[2]*sin1; matrix[2] = axis[0] * axis[2] * cos2 + axis[1]*sin1; matrix[3] = axis[1] * axis[0] * cos2 + axis[2]*sin1; matrix[4] = cos1 + axis[1] * axis[1] * cos2; matrix[5] = axis[1] * axis[2] * cos2 - axis[0] * sin1; matrix[6] = axis[2] * axis[0] * cos2 - axis[1] * sin1; matrix[7] = axis[2] * axis[1] * cos2 + axis[0] * sin1; matrix[8] = cos1 + axis[2] * axis[2] * cos2; } // multiplies a vector v1 by a matrix and puts the results into vector v2 void mulVecBy(float* v1, float* matrix, float* v2) { v2[0] = v1[0] * matrix[0] + v1[1] * matrix[1] + v1[2] * matrix[2]; v2[1] = v1[0] * matrix[3] + v1[1] * matrix[4] + v1[2] * matrix[5]; v2[2] = v1[0] * matrix[6] + v1[1] * matrix[7] + v1[2] * matrix[8]; } // rotate a vector v1 around the axis v2 by angle and put the result into v3 void rotateAroundVec(float* v1, float* v2, float angle, float* v3) { //. make a rotation matrix for it float matrix[16]; rotationMatrix(matrix, v2, angle); // multiply by the matrix mulVecBy(v1, matrix, v3); } Camera::Camera(void) { cameraSpeed = 0.005f; cameraTurnSpeed = 0.01f; // set default vector values - obtained a nice viewing angle of the planets, got values using the debugger /* forwardVec 0x00ab354c {-0.398769796, 0.763009906, -0.508720219} float[3] + upVec 0x00ab3564 {-0.235630989, 0.450859368, 0.860931039} float[3] + rightVec 0x00ab3558 {0.886262059, 0.463184059, 0.000000000} float[3] + position 0x00ab3570 {0.764331460, -1.66760659, 0.642456770} float[3] */ vectorSet(position, 0.764331460f, -1.66760659f, 0.642456770); vectorSet(forwardVec,-0.398769796f, 0.763009906f, -0.508720219f); vectorSet(rightVec, 0.886262059f, 0.463184059f, 0.000000000f); vectorSet(upVec, -0.235630989f, 0.450859368f, 0.860931039f); } // transform the opengl view matrix for the camera void Camera::transformOrientation(void) { // look in the direction of the orientation vectors gluLookAt(0, 0, 0, forwardVec[0], forwardVec[1], forwardVec[2], upVec[0], upVec[1], upVec[2]); } // transform the opoengl view matrix for the translation void Camera::transformTranslation(void) { // translate to emulate camera position glTranslatef(-position[0], -position[1], -position[2]); } // points the camera at the given point in 3d space void Camera::pointAt(float* targetVec) { float tempVec[3]; float up[3] = { 0.0f, 0.0f, 1.0f }; // first work out the new forward vector by subtracting the target position from the camera position forwardVec[0] = targetVec[0] - position[0]; forwardVec[1] = targetVec[1] - position[1]; forwardVec[2] = targetVec[2] - position[2]; // then normalise it to 1 length normaliseVec(forwardVec); // now to find the right vector we rotate the forward vector -pi/2 around the z axis rotateAroundVec(forwardVec, up, -1.57079632679f, tempVec); // and remove the y component to make it flat tempVec[2] = 0; // then normalise it normaliseVec(tempVec); // and assign it to rightVec vectorCopy(rightVec, tempVec); // now work out the upvector by rotating the forward vector pi/2 around the rightvector rotateAroundVec(forwardVec, rightVec, 1.57079632679f, tempVec); vectorCopy(upVec, tempVec); } // speed up the camera speed void Camera::speedUp(void) { if (cameraSpeed < 5.0f) cameraSpeed *= 2; } // slow down the camera speed void Camera::slowDown(void) { if (cameraSpeed > 0.000001f) cameraSpeed /= 2; } // move the camera forward void Camera::forward(void) { // make a movement vector the right speed facing the forward direction float vec[3]; vectorCopy(vec, forwardVec); vectorMul(vec, cameraSpeed); // add the movement vec to the position vec vectorAdd(position, vec); } // move the camera backward void Camera::backward(void) { // make a movement vector the right speed facing the backward direction float vec[3]; vectorCopy(vec, forwardVec); vectorMul(vec, -cameraSpeed); // -cameraSpeed for backwards // add the movement vec to the position vec vectorAdd(position, vec); } // strafe left void Camera::left(void) { // make a movement vector the right speed facing the left direction float vec[3]; vectorCopy(vec, rightVec); vectorMul(vec, -cameraSpeed); // -cameraSpeed for left // add the movement vec to the position vec vectorAdd(position, vec); } // strafe right void Camera::right(void) { // make a movement vector the right speed facing the right direction float vec[3]; vectorCopy(vec, rightVec); vectorMul(vec, cameraSpeed); // add the movement vec to the position vec vectorAdd(position, vec); } // roll the camera to the right void Camera::rollRight(void) { float tempVec[3]; // rotate the up and right vectors around the forward vector axis for roll rotateAroundVec(upVec, forwardVec, cameraTurnSpeed, tempVec); vectorCopy(upVec, tempVec); rotateAroundVec(rightVec, forwardVec, cameraTurnSpeed, tempVec); vectorCopy(rightVec, tempVec); } // roll the camera to the left void Camera::rollLeft(void) { float tempVec[3]; // rotate the up and right vectors around the forward vector axis for roll rotateAroundVec(upVec, forwardVec, -cameraTurnSpeed, tempVec); vectorCopy(upVec, tempVec); rotateAroundVec(rightVec, forwardVec, -cameraTurnSpeed, tempVec); vectorCopy(rightVec, tempVec); } // pitch the camera up void Camera::pitchUp(void) { float tempVec[3]; // rotate the forward and up vectors around the right vector axis for pitch rotateAroundVec(forwardVec, rightVec, cameraTurnSpeed, tempVec); vectorCopy(forwardVec, tempVec); rotateAroundVec(upVec, rightVec, cameraTurnSpeed, tempVec); vectorCopy(upVec, tempVec); } // pitch the camera down void Camera::pitchDown(void) { float tempVec[3]; // rotate the forward and up vectors around the right vector axis for pitch rotateAroundVec(forwardVec, rightVec, -cameraTurnSpeed, tempVec); vectorCopy(forwardVec, tempVec); rotateAroundVec(upVec, rightVec, -cameraTurnSpeed, tempVec); vectorCopy(upVec, tempVec); } // yaw left void Camera::yawLeft(void) { float tempVec[3]; // rotate the forward and right vectors around the up vector axis for yaw rotateAroundVec(forwardVec, upVec, cameraTurnSpeed, tempVec); vectorCopy(forwardVec, tempVec); rotateAroundVec(rightVec, upVec, cameraTurnSpeed, tempVec); vectorCopy(rightVec, tempVec); } // yaw right void Camera::yawRight(void) { float tempVec[3]; // rotate the forward and right vectors around the up vector axis for yaw rotateAroundVec(forwardVec, upVec, -cameraTurnSpeed, tempVec); vectorCopy(forwardVec, tempVec); rotateAroundVec(rightVec, upVec, -cameraTurnSpeed, tempVec); vectorCopy(rightVec, tempVec); } float Camera::getSpeed() { return cameraSpeed; } float Camera::getTurnSpeed() { return cameraTurnSpeed; } float Camera::getPositionX(){return position[0];} float Camera::getPositionY(){return position[1];} float Camera::getPositionZ(){return position[2];}
[ "rubcuadra@gmail.com" ]
rubcuadra@gmail.com
3c272c5ec0da6c292c5f470e2d19ce6028c8de82
4d9f3325764c08cc546b514d53796d7cef684747
/Code/Tools/FBuild/FBuildTest/Tests/TestUnity.cpp
e19f3ac313feec9405e41af418bf6a278b4ef385
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
inequation/fastbuild
926fb0a321214810069cbba6d705e1161c92c4ed
2122d227f09d022c7bf00db0e9c36e5d0b9a04a8
refs/heads/master
2021-01-16T23:04:26.443564
2015-05-31T03:22:34
2015-05-31T03:22:34
37,087,852
0
0
null
2015-06-08T19:27:21
2015-06-08T19:27:20
null
UTF-8
C++
false
false
7,368
cpp
// TestUnity.cpp //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "FBuildTest.h" #include "Tools/FBuild/FBuildCore/FBuild.h" #include "Tools/FBuild/FBuildCore/BFF/BFFParser.h" #include "Core/Containers/AutoPtr.h" #include "Core/FileIO/FileIO.h" #include "Core/FileIO/FileStream.h" #include "Core/Process/Thread.h" #include "Core/Strings/AStackString.h" // TestUnity //------------------------------------------------------------------------------ class TestUnity : public FBuildTest { private: DECLARE_TESTS // Helpers FBuildStats BuildGenerate( FBuildOptions options = FBuildOptions(), bool useDB = true ) const; const char * GetTestGenerateDBFileName() const { return "../../../../ftmp/Test/Unity/generate.fdb"; } FBuildStats BuildCompile( FBuildOptions options = FBuildOptions(), bool useDB = true ) const; const char * GetTestCompileDBFileName() const { return "../../../../ftmp/Test/Unity/compile.fdb"; } // Tests void TestGenerate() const; void TestGenerate_NoRebuild() const; void TestCompile() const; void TestCompile_NoRebuild() const; void TestGenerateFromExplicitList() const; }; // Register Tests //------------------------------------------------------------------------------ REGISTER_TESTS_BEGIN( TestUnity ) REGISTER_TEST( TestGenerate ) // clean build of unity files REGISTER_TEST( TestGenerate_NoRebuild ) // check nothing rebuilds REGISTER_TEST( TestCompile ) // compile a library using unity inputs REGISTER_TEST( TestCompile_NoRebuild ) // check nothing rebuilds REGISTER_TEST( TestGenerateFromExplicitList ) // create a unity with manually provided files REGISTER_TESTS_END // BuildGenerate //------------------------------------------------------------------------------ FBuildStats TestUnity::BuildGenerate( FBuildOptions options, bool useDB ) const { options.m_ConfigFile = "Data/TestUnity/unity.bff"; options.m_ShowSummary = true; // required to generate stats for node count checks FBuild fBuild( options ); TEST_ASSERT( fBuild.Initialize( useDB ? GetTestGenerateDBFileName() : nullptr ) ); // Implement Unity and activate this test TEST_ASSERT( fBuild.Build( AStackString<>( "Unity-Test" ) ) ); TEST_ASSERT( fBuild.SaveDependencyGraph( GetTestGenerateDBFileName() ) ); return fBuild.GetStats(); } // TestGenerate //------------------------------------------------------------------------------ void TestUnity::TestGenerate() const { FBuildOptions options; options.m_ShowSummary = true; // required to generate stats for node count checks options.m_ForceCleanBuild = true; EnsureFileDoesNotExist( "../../../../ftmp/Test/Unity/Unity1.cpp" ); EnsureFileDoesNotExist( "../../../../ftmp/Test/Unity/Unity2.cpp" ); FBuildStats stats = BuildGenerate( options, false ); // don't use DB EnsureFileExists( "../../../../ftmp/Test/Unity/Unity1.cpp" ); EnsureFileExists( "../../../../ftmp/Test/Unity/Unity2.cpp" ); // Check stats // Seen, Built, Type CheckStatsNode ( stats, 1, 1, Node::DIRECTORY_LIST_NODE ); CheckStatsNode ( stats, 1, 1, Node::UNITY_NODE ); CheckStatsTotal( stats, 2, 2 ); } // TestGenerate_NoRebuild //------------------------------------------------------------------------------ void TestUnity::TestGenerate_NoRebuild() const { AStackString<> unity1( "../../../../ftmp/Test/Unity/Unity1.cpp" ); AStackString<> unity2( "../../../../ftmp/Test/Unity/Unity2.cpp" ); EnsureFileExists( unity1 ); EnsureFileExists( unity2 ); // Unity must be "built" every time, but it only writes files when they change // so record the time before and after uint64_t dateTime1 = FileIO::GetFileLastWriteTime( unity1 ); uint64_t dateTime2 = FileIO::GetFileLastWriteTime( unity2 ); // NTFS file resolution is 100ns, so sleep long enough to ensure // an invalid write would modify the time Thread::Sleep( 1 ); // 1ms FBuildStats stats = BuildGenerate(); // Make sure files have not been changed TEST_ASSERT( dateTime1 == FileIO::GetFileLastWriteTime( unity1 ) ); TEST_ASSERT( dateTime2 == FileIO::GetFileLastWriteTime( unity2 ) ); // Check stats // Seen, Built, Type CheckStatsNode ( stats, 1, 1, Node::DIRECTORY_LIST_NODE ); CheckStatsNode ( stats, 1, 1, Node::UNITY_NODE ); CheckStatsTotal( stats, 2, 2 ); } // BuildCompile //------------------------------------------------------------------------------ FBuildStats TestUnity::BuildCompile( FBuildOptions options, bool useDB ) const { options.m_ConfigFile = "Data/TestUnity/unity.bff"; options.m_ShowSummary = true; // required to generate stats for node count checks FBuild fBuild( options ); TEST_ASSERT( fBuild.Initialize( useDB ? GetTestCompileDBFileName() : nullptr ) ); // Implement Unity and activate this test TEST_ASSERT( fBuild.Build( AStackString<>( "Unity-Compiled" ) ) ); TEST_ASSERT( fBuild.SaveDependencyGraph( GetTestCompileDBFileName() ) ); return fBuild.GetStats(); } // TestCompile //------------------------------------------------------------------------------ void TestUnity::TestCompile() const { FBuildOptions options; options.m_ForceCleanBuild = true; options.m_ShowSummary = true; // required to generate stats for node count checks EnsureFileDoesNotExist( "../../../../ftmp/Test/Unity/Unity.lib" ); FBuildStats stats = BuildCompile( options, false ); // don't use DB EnsureFileExists( "../../../../ftmp/Test/Unity/Unity.lib" ); // Check stats // Seen, Built, Type CheckStatsNode ( stats, 1, 1, Node::DIRECTORY_LIST_NODE ); CheckStatsNode ( stats, 1, 1, Node::UNITY_NODE ); CheckStatsNode ( stats, 10, 3, Node::FILE_NODE ); // pch + 2x generated unity files CheckStatsNode ( stats, 1, 1, Node::COMPILER_NODE ); CheckStatsNode ( stats, 3, 3, Node::OBJECT_NODE ); CheckStatsNode ( stats, 1, 1, Node::LIBRARY_NODE ); CheckStatsNode ( stats, 1, 1, Node::ALIAS_NODE ); CheckStatsTotal( stats, 18, 11 ); } // TestCompile_NoRebuild //------------------------------------------------------------------------------ void TestUnity::TestCompile_NoRebuild() const { FBuildStats stats = BuildCompile(); // Check stats // Seen, Built, Type CheckStatsNode ( stats, 1, 1, Node::DIRECTORY_LIST_NODE ); CheckStatsNode ( stats, 1, 1, Node::UNITY_NODE ); CheckStatsNode ( stats, 10, 10, Node::FILE_NODE ); // pch + 2x generated unity files + 6 source cpp files CheckStatsNode ( stats, 1, 0, Node::COMPILER_NODE ); CheckStatsNode ( stats, 3, 0, Node::OBJECT_NODE ); CheckStatsNode ( stats, 1, 0, Node::LIBRARY_NODE ); CheckStatsNode ( stats, 1, 1, Node::ALIAS_NODE ); CheckStatsTotal( stats, 18, 13 ); } // TestGenerateFromExplicitList //------------------------------------------------------------------------------ void TestUnity::TestGenerateFromExplicitList() const { FBuildOptions options; options.m_ConfigFile = "Data/TestUnity/unity.bff"; options.m_ShowSummary = true; // required to generate stats for node count checks FBuild fBuild( options ); TEST_ASSERT( fBuild.Initialize() ); TEST_ASSERT( fBuild.Build( AStackString<>( "Unity-Explicit-Files" ) ) ); // Check stats // Seen, Built, Type CheckStatsNode ( 1, 1, Node::UNITY_NODE ); CheckStatsTotal( 1, 1 ); } //------------------------------------------------------------------------------
[ "franta.fulin@gmail.com" ]
franta.fulin@gmail.com
37425d3dfce4d12f1ffbcb9df3024ec17d335fcf
23b297c816d8bfcee608684f798f1137258b5cbf
/MultiBallPowerUpSprite.h
25c8912325006d63ea5ec8947edf72df4089ece7
[]
no_license
AndreOliver/Brickout-Game
e1e16b38e874c3e14d1462329d7e347dcbc9abb5
4949e212c98457e63c5ad96b4dc993044ae505da
refs/heads/master
2020-12-24T14:26:35.937688
2015-02-10T01:16:16
2015-02-10T01:16:16
30,569,012
0
0
null
null
null
null
UTF-8
C++
false
false
1,095
h
#pragma once #include "powerupsprite.h" #include "BallSprite.h" #include "TPlayers.h" class MultiBallPowerUpSprite : public PowerUpSprite { public: MultiBallPowerUpSprite(string textureFileName="multiBall.png") { setup(textureFileName); setColor(TGlobal::randomizeColor(sf::Color(200,200,200,255))); setScale(0.2f); //setRotation(0.0f); setRotationSpeed(TGlobal::randomF(-2000.0f,2000.0f)); setSpecialness(5); } virtual void applyPowerup() { int ballCount=(rand()%5)+1; if(TGlobal::randomF()>0.9)ballCount+=100; for(int i=0;i<ballCount;i++) { BallSprite * pNewBall = (BallSprite *)(TPlayers::pBallList->getPointerToNextInactive()); if(pNewBall) { pNewBall->setPosition(TGlobal::randomF(0,(float)(TGlobal::pMainWindow->getSize().x)),-100.0f); pNewBall->setSpeed(TGlobal::randomF(-400.0f,400.0f),TGlobal::randomF(100.0f,200.0f)); pNewBall->isActive=true; pNewBall->changeState(BALLSTATE_INPLAY); } } } virtual void update(sf::Time elapsed) { PowerUpSprite::update(elapsed); } virtual ~MultiBallPowerUpSprite(void) { } };
[ "andreoliverswe@gmail.com" ]
andreoliverswe@gmail.com
7aa156c3b3b42513198115711b40f3c425d7ba99
1d4d57400a78731b3537e3a2fcc1b60a789027a5
/GeocoderRequest.cpp
9363235a3ef13bd6f774c12023237bda6d222828
[]
no_license
ksmadhu/GoogleMaps-1
e3c891a4d3320a356ca8cb064cbbc3ec94feb9cf
e85be57e8e6ea7de4d9ec2a4b740f95fb166a1bd
refs/heads/master
2021-01-09T13:45:58.310197
2017-04-06T03:49:56
2017-04-06T03:49:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,327
cpp
#include <exception> using namespace std; #include "GeocoderRequest.h" #include "LatLngBounds.h" #include "LatLng.h" googleMaps::GeocoderRequest::GeocoderRequest(QObject *parent) { setParent(parent); } googleMaps::GeocoderRequest::~GeocoderRequest() { } googleMaps::GeocoderRequest::GeocoderRequest(const GeocoderRequest& rhs) { m_address = rhs.getAddress(); m_bounds = rhs.getBounds(); m_region = rhs.getRegion(); m_placeId = rhs.getPlaceId(); m_location = rhs.getLocation(); m_componentRestrictions = rhs.getComponentRestrictions(); } googleMaps::GeocoderRequest googleMaps::GeocoderRequest::operator =(const GeocoderRequest& rhs) { if(this == &rhs) { return *this; } m_address = rhs.getAddress(); m_bounds = rhs.getBounds(); m_region = rhs.getRegion(); m_placeId = rhs.getPlaceId(); m_location = rhs.getLocation(); m_componentRestrictions = rhs.getComponentRestrictions(); return *this; } void googleMaps::GeocoderRequest::setAddress(const QString aAddress) { this->m_address = aAddress; } QString googleMaps::GeocoderRequest::getAddress() const { return this->m_address; } void googleMaps::GeocoderRequest::setBounds(const googleMaps::LatLngBounds aBounds) { this->m_bounds = aBounds; } googleMaps::LatLngBounds googleMaps::GeocoderRequest::getBounds() const { return this->m_bounds; } void googleMaps::GeocoderRequest::setRegion(QString aRegion) { this->m_region = aRegion; } QString googleMaps::GeocoderRequest::getRegion() const { return this->m_region; } void googleMaps::GeocoderRequest::setPlaceId(QString aPlaceId) { this->m_placeId = aPlaceId; } QString googleMaps::GeocoderRequest::getPlaceId() const { return this->m_placeId; } void googleMaps::GeocoderRequest::setLocation(const googleMaps::LatLng aLocation) { this->m_location = aLocation; } googleMaps::LatLng googleMaps::GeocoderRequest::getLocation() const { return this->m_location; } void googleMaps::GeocoderRequest::setComponentRestrictions(const GeocoderComponentRestrictions aComponentRestrictions) { this->m_componentRestrictions = aComponentRestrictions; } googleMaps::GeocoderComponentRestrictions googleMaps::GeocoderRequest::getComponentRestrictions() const { return this->m_componentRestrictions; }
[ "cwinston@technotainment.com" ]
cwinston@technotainment.com
5c47e981b9d5f38274a2f8673c96e1a7d25b13cd
1070f5ab8344627ae983bae9fefd09d49757c87e
/math_lib/math_tmp_2.h
0bd138fe8a22623b425008f515af0e83c6c2abe1
[]
no_license
BorisK09/math_lib
b5c77adcb9e4a3fa6439d41fdf2a5577dadfbbb5
bb854f7541aebe1a2b8ab884d95938880f034741
refs/heads/master
2016-09-06T02:46:53.136954
2013-09-05T15:04:10
2013-09-05T15:04:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,124
h
/* #include <cmath> enum MATRIX_PACK { ROW_MAJOR = 0, COLUMN_MAJOR = 1, }; */ /* template <class BaseType, unsigned int _nRows, unsigned int _nColumns> class Matrix { public: const unsigned int nRows, nColumns; BaseType* m; union { struct { }; }; Matrix() : nRows(_nRows), nColumns(_nColumns) { m = new BaseType[nRows*nColumns]; memset(m, 0, sizeof(BaseType)*nRows*nColumns); } ~Matrix() {delete[] m;} //overloaded operators //to do: 'out of bounds' check and row/column major order BaseType& operator () (unsigned int i, unsigned int j) {return m[nColumns*i + j];} BaseType operator () (unsigned int i, unsigned int j) const {return m[nColumns*i + j];} //BaseType& operator = (const baseType& matrix) {} //methods }; */ //typedef Matrix<float, 2, 2> Matrix2x2f; //typedef Matrix<float, 3, 3> Matrix3x3f; //typedef Matrix<float, 4, 4> Matrix4x4f; /* class Vector { public: unsigned int nRows, nColumns; Vector(); }; class Vector2f : public Vector { union { struct { float x, y; }; float v[2]; }; Vector2f() { Vector() } }; */ //functions
[ "boris132k@gmail.com" ]
boris132k@gmail.com
c53cfafe7b1ea7d989a09247a91e284a1f6272f7
5cf1fc743b87470543002508ea596afcfd008026
/Comm/glbdefs.h
6429438a8d9e45aa7f201d5537aa782cb775a390
[]
no_license
atelsy/dwm156_20141010
71ce531dc92965d485ee3ae7147657f0f2d2e6f6
68056917319586a815b053b152e37907bf181035
refs/heads/master
2021-01-23T14:56:29.777691
2014-11-12T07:23:49
2014-11-12T07:23:49
26,523,423
1
0
null
null
null
null
UTF-8
C++
false
false
4,902
h
/***************************************************************************** * Copyright Statement: * -------------------- * This software is protected by Copyright and the information contained * herein is confidential. The software may not be copied and the information * contained herein may not be used or disclosed except with the written * permission of MediaTek Inc. (C) 2007 * * BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO * NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S * SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * * BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE * LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE * WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF * LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND * RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER * THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC). * *****************************************************************************/ /******************************************************************************* * Filename: * --------- * glbdefs.h * * Project: * -------- * DCT * * Description: * ------------ * Global definitions * * Author: * ------- * Fengping Yu * *============================================================================== * HISTORY * Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!! *------------------------------------------------------------------------------ * $Revision:$ * $Modtime:$ * $Log:$ * * 10 09 2012 fengping.yu * [STP100004315] check in code * . * *------------------------------------------------------------------------------ * Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!! *============================================================================== *******************************************************************************/ // global definitions #ifndef _GLB_DEFS_H_ #define _GLB_DEFS_H_ #ifndef WIN32 #include "Win2Mac.h" #define __min(a, b) ((a) < (b) ? (a) : (b)) #define __max(a, b) ((a) > (b) ? (a) : (b)) #endif enum facility_lock_t { FL_SC = 0, // PIN FL_P2, // PIN2 FL_AO, FL_OI, FL_OX, FL_AI, FL_IR, FL_AB, FL_AG, FL_AC, FL_PN, FL_PU, FL_PP, FL_PC, FL_MAX }; ////////////////////////////////////////////////////////////////////////// class CALL { public: short idx; short dir; short status; short mode; short mpty; CString number; short type; mutable CString alpha; }; enum cf_reason_t { CF_UNCONDICTIONAL = 0, CF_MOBILEBUSY = 1, CF_NOREPLY = 2, CF_NOTREACHABLE = 3, CF_ALLFORWARDING = 4, CF_ALLCONDICTIONAL = 5 }; enum service_class_t { CLS_VOICE = 1, CLS_DATA = 2, CLS_FAX = 4, CLS_SMS = 8, CLS_DCS = 16, CLS_DCAS = 32, CLS_PACKET = 64, CLS_PAD = 128 }; ////////////////////////////////////////////////////////////////////////// // error code (16 bit) enum err_code_t { // +cme error: ER_OK = 0, ER_NOALLOW = 3, ER_NOSUPPORT = 4, ER_NOSIM = 10, ER_PINREQ = 11, ER_PUKREQ = 12, ER_SIMFAIL = 13, ER_SIMBUSY = 14, ER_SIMWRONG = 15, ER_WRONGPWD = 16, ER_PIN2REQ = 17, ER_PUK2REQ = 18, ER_BADINDEX = 21, ER_LONGTEXT = 24, ER_BADTEXT = 25, ER_LONGNUM = 26, ER_BADNUM = 27, ER_NOSERVICE = 30, ER_EMCALLONLY = 32, ER_UNKNOWN = 100, ER_TRYLATER = 256, ER_CALLBARRED = 257, ER_SSNOTEXE = 261, ER_SIMBLOCK = 262, // todo: +cms error: ER_TIMEOUT = 0x7f00, ER_NOCONNECTION, ER_USERABORT, ER_CMEERROR }; // error code ////////////////////////////////////////////////////////////////////////// #endif
[ "sy_aaaa@126.com" ]
sy_aaaa@126.com
34d575773b68ca3233f5c038a449cfcb8426c9ed
2c36841c1c3bef06fe4a82bd87cacc64425d08c7
/Source/rclUE/Private/Msgs/ROS2PoseWithCovarianceStampedMsg.cpp
d0116737c698c3330d3baebd76f4475f43c2586b
[]
no_license
saratrajput/rclUE
29edba1a9b5b218264880b60844e9da2a1474602
4521c29ac66caba6eb5aa91483e75751652f91bf
refs/heads/master
2023-08-12T07:28:01.881375
2021-10-04T22:06:57
2021-10-04T22:06:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,233
cpp
// Copyright 2021 Rapyuta Robotics Co., Ltd. // This code has been autogenerated from geometry_msgs/PoseWithCovarianceStamped.msg - do not modify #include "Msgs/ROS2PoseWithCovarianceStampedMsg.h" #include "Kismet/GameplayStatics.h" void UROS2PoseWithCovarianceStampedMsg::Init() { geometry_msgs__msg__PoseWithCovarianceStamped__init(&pose_with_covariance_stamped_msg); } void UROS2PoseWithCovarianceStampedMsg::Fini() { geometry_msgs__msg__PoseWithCovarianceStamped__fini(&pose_with_covariance_stamped_msg); } const rosidl_message_type_support_t* UROS2PoseWithCovarianceStampedMsg::GetTypeSupport() const { return ROSIDL_GET_MSG_TYPE_SUPPORT(geometry_msgs, msg, PoseWithCovarianceStamped); } void UROS2PoseWithCovarianceStampedMsg::SetMsg(const FROSPoseWithCovarianceStamped& Inputs) { Inputs.SetROS2(pose_with_covariance_stamped_msg); } void UROS2PoseWithCovarianceStampedMsg::GetMsg(FROSPoseWithCovarianceStamped& Outputs) const { Outputs.SetFromROS2(pose_with_covariance_stamped_msg); } void* UROS2PoseWithCovarianceStampedMsg::Get() { return &pose_with_covariance_stamped_msg; } FString UROS2PoseWithCovarianceStampedMsg::MsgToString() const { /* TODO: Fill here */ checkNoEntry(); return FString(); }
[ "christian.conti@rapyuta-robotics.com" ]
christian.conti@rapyuta-robotics.com
890a604ecc698eb3f830a3623b89d07195423cc8
c45ed46065d8b78dac0dd7df1c95b944f34d1033
/TC-SRM-575-div1-250/qj.cpp
a32d248557185040f964a74f0d496a7debfd1cde
[]
no_license
yzq986/cntt2016-hw1
ed65a6b7ad3dfe86a4ff01df05b8fc4b7329685e
12e799467888a0b3c99ae117cce84e8842d92337
refs/heads/master
2021-01-17T11:27:32.270012
2017-01-26T03:23:22
2017-01-26T03:23:22
84,036,200
0
0
null
2017-03-06T06:04:12
2017-03-06T06:04:12
null
UTF-8
C++
false
false
279
cpp
#include <bits/stdc++.h> using namespace std; typedef long long i64; class TheNumberGameDivOne { public: string find(i64 n) { if (n & 1) return "Brus"; return (__builtin_popcountll(n) == 1 && !(__builtin_clzll(n) & 1)) ? "Brus" : "John"; // find the pattern } };
[ "guru@live.hk" ]
guru@live.hk
27ba47e1197a0d2c24e9425facb48d6d154a54b2
c062e57abd677cc7c1fa4ca864a1eb75cce55388
/알고리즘/프로그래머스/Level2/[1차]프렌즈4블록/[1차]프렌즈4블록.cpp
04b540d7c8b1f74799b8c379f7cd60dfa78ace2f
[]
no_license
Soogyung1106/Algorithm
3a732471a69ac760ecece0c6125edbf9788743e8
a1376e46550d6e335e12a50d772f0241880f2a07
refs/heads/master
2023-08-20T14:11:00.464294
2021-10-21T13:45:34
2021-10-21T13:45:34
257,540,169
1
0
null
null
null
null
UTF-8
C++
false
false
2,528
cpp
#include <string> #include <vector> #include <iostream> #include <utility> #include <algorithm> using namespace std; vector<vector <char>> v; vector<pair <int, int>> p; //삭제할 좌표 <행, 열> void check(char c, int i, int j){ if(v[i][j+1]==c && v[i+1][j] == c && v[i+1][j+1] == c){ if(find(p.begin(), p.end(), make_pair(i, j)) == p.end()) p.push_back(make_pair(i, j)); if(find(p.begin(), p.end(), make_pair(i, j+1)) == p.end()) p.push_back(make_pair(i, j+1)); if(find(p.begin(), p.end(), make_pair(i+1, j)) == p.end()) p.push_back(make_pair(i+1, j)); if(find(p.begin(), p.end(), make_pair(i+1, j+1)) == p.end()) p.push_back(make_pair(i+1, j+1)); } } int solution(int m, int n, vector<string> board) { //재구성(지우기 쉽게) vector<char> tmp; for(int i=0;i<n;i++){ //열 for(int j=m-1;j>=0;j--){ //행 tmp.push_back(board[j][i]); } v.push_back(tmp); tmp.clear(); } int answer = 0; while(1){ for(int i=0;i<v.size()-1;i++){ for(int j=0;j<v[i].size()-1;j++){ if(v[i][j] == '0') continue; check(v[i][j], i, j); //2x2체크 } } //리스트에 담긴 원소 수 -> 0이면 break //아니면 answer에 누적 if(p.size() == 0) return answer; else answer += p.size(); //그 후 표시한 좌표 부분 제외하고 삽입 vector<vector <char>> tmp_v; vector<char> t; for(int i =0;i<v.size();i++){ int count = 0; for(int j=0;j<v[0].size();j++){ bool flag = false; for(int k =0;k<p.size();k++){ if(i == p[k].first && j == p[k].second){ count++; flag = true; p.erase(p.begin()+k); k--; break; } } if(flag == false) t.push_back(v[i][j]); } for(int u=0;u<count;u++) t.push_back('0'); tmp_v.push_back(t); t.clear(); } v = tmp_v; //복사 //좌표 리스트 비워주기 p.clear(); tmp_v.clear(); } }
[ "sally1106@naver.com" ]
sally1106@naver.com
992440583280ceec74381b430b200c616ae78770
6ac12e5fe30b8bfa22713e9afdc21ae1e17cd20f
/form/form_overallClu.cpp
118c5d880fac27aae3416b2385c2e960e54ce647
[]
no_license
jingzhesiye/9-0-2
004bae153309ad881214af6912fede60f0616327
79618563cc18ef13b8711180bf209bbdb0180af1
refs/heads/master
2020-04-15T18:05:17.834785
2016-06-15T07:57:19
2016-06-15T07:57:19
52,349,024
1
0
null
null
null
null
UTF-8
C++
false
false
896
cpp
#include "mainwidget.h" void MainWidget::fill_form_overallClu( QString str, replaceDocTypeList *replaceDocTypeList_Data) { if(overAll_conc.time.startsWith(QString::fromUtf8("不"))||overAll_conc.operating.startsWith(QString::fromUtf8("不")) ||overAll_conc.time.startsWith(QString::fromUtf8("不"))) { fillReplaceDocStructList(replaceDocTypeList_Data, "{overallClu}" ,QString::fromUtf8("不合格")); ui->intuit_CkBox->setText(QString::fromUtf8("不合格")); } else { fillReplaceDocStructList(replaceDocTypeList_Data, "{overallClu}" ,QString::fromUtf8("合格")); ui->intuit_CkBox->setText(QString::fromUtf8("合格")); } } void MainWidget::on_overallClu_CkBox_clicked(bool checked) { if(checked) ui->intuit_CkBox->setText(QString::fromUtf8("不合格")); else ui->intuit_CkBox->setText(QString::fromUtf8("合格")); }
[ "jingzhesiye@163.com" ]
jingzhesiye@163.com
8f1bfd12f10ac4dea4398b46f2c9ae8ab1908bb6
fbdf23adb78bac6f1fc451c84bee4a31de4cd283
/MultiSource/Applications/kimwitu++/testrk.h
f0b168a419309149e1103dd8ddb37f3842d09369
[]
no_license
edmcman/llvm-test-suite-mcsema
aa18aeee1b44b4b103c886282d1a9a40206746e6
92bb50a303a17085997e93190c8031225be6a593
refs/heads/master
2021-01-10T12:29:52.549157
2016-10-30T20:48:39
2016-10-30T20:48:39
48,399,018
2
1
null
null
null
null
UTF-8
C++
false
false
1,540
h
/* translation of file(s) "/home/ed/mcsema-testing/llvm-test-suite/MultiSource/Applications/kimwitu++/inputs/f3.k" "/home/ed/mcsema-testing/llvm-test-suite/MultiSource/Applications/kimwitu++/inputs/f2.k" "/home/ed/mcsema-testing/llvm-test-suite/MultiSource/Applications/kimwitu++/inputs/f1.k" */ /* generated by: * @(#)$Author: criswell $ */ #ifndef KC_REWRITE_HEADER #define KC_REWRITE_HEADER namespace kc { typedef enum { base_rview_enum, canon_enum, calculate_enum, last_rview } rview_enum; struct impl_rviews { const char *name; rview_class *view; }; extern struct impl_rviews rviews[]; class rview_class { protected: // only used in derivations rview_class(rview_enum v): m_view(v) { } rview_class(const rview_class&): m_view(base_rview_enum) { /* do not copy m_view */ } public: const char* name() const { return rviews[m_view].name; } operator rview_enum() const { return m_view; } bool operator==(const rview_class& other) const { return m_view == other.m_view; } private: rview_enum m_view; }; /* Use rviews instead extern char *kc_rview_names[]; */ struct base_rview_class: rview_class { base_rview_class():rview_class(base_rview_enum){} }; extern base_rview_class base_rview; struct canon_class: rview_class { canon_class():rview_class(canon_enum){} }; extern canon_class canon; struct calculate_class: rview_class { calculate_class():rview_class(calculate_enum){} }; extern calculate_class calculate; } // namespace kc #endif // KC_REWRITE_HEADER
[ "eschwartz@cert.org" ]
eschwartz@cert.org
2625bbe72f849b884df50987a31a4fb4c583b072
0d5715d6729c7cf95ef6bace081054547b3d7553
/agendatablecontextmenu.h
13910ee159a5531b99810bba5f13e51bad5fc340
[]
no_license
ealkenbrecher/ETVManager_old
098ddf9809fe4fa632d1ee0f8ef2c23adc1c3b84
cc5ceeab293f85d56f860e664191b4edc7b6d2df
refs/heads/master
2021-01-02T09:36:09.682869
2015-03-18T15:13:33
2015-03-18T15:13:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
207
h
#ifndef AGENDATABLECONTEXTMENU_H #define AGENDATABLECONTEXTMENU_H #include <QMenu> class AgendaTableContextMenu : public QMenu { public: AgendaTableContextMenu(); }; #endif // AGENDATABLECONTEXTMENU_H
[ "e.alkenbrecher@gmx.de" ]
e.alkenbrecher@gmx.de
3d8a8922c99c59480ebb491bbacaf98207dd7edd
c04b36f0270adbcd0a9d50482496cc9d37f6549e
/ArduinoEEPROM/ArduinoEEPROM.ino
8c614aa29a49287400ddd90aacf5196be5a5b91c
[ "MIT" ]
permissive
scemtan/Duino-hacks
262a24a3c997c72925bd30d367515b619a8b3bbb
7e316e29fece13b9c10360f431463653eaea9d22
refs/heads/master
2022-12-30T11:49:58.832525
2020-10-22T07:37:13
2020-10-22T07:37:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,123
ino
// ArduinoEEPROM // // Copyright 2020 by Bill Westfield // This is stripped version of ArduinoISP designed to allow access to the EEPROM of // AVR that is actually running the sketch, using the STK500v1 or Arduino Protocols. // This is needed because the normal Arduino Bootloader does not support accesss to // the EEPROM. The usual methods involve using a programmer, or specialized software // customized to the particular sketch that will use the EEPROM. // This sketch will allow the EEPROM to be programmed using standard methods, and then // the sketch that uses it can be uploaded. // Also note avrdude's "interactive" mode ("-t") // // There is code in here that doesn't do anything useful. // You can read flash memory (why would you want to?) // Attempts to write to flash memory are ignored. // // Based on ArduinoISP, which is: // Copyright (c) 2008-2011 Randall Bohn // If you require a license, see // http://www.opensource.org/licenses/bsd-license.php // // // Put an LED (with resistor) on the following pins: // 9: Heartbeat - shows the programmer is running // 8: Error - Lights up if something goes wrong (use red if that makes sense) // 7: Programming - In communication with the slave // #include "Arduino.h" #include <avr/boot.h> #undef SERIAL #define PROG_FLICKER true // Configure which pins to use: // The standard pin configuration. #define LED_HB 7 #define LED_ERR 13 #define LED_PMODE 5 // Configure the serial port to use. // // Prefer the USB virtual serial port (aka. native USB port), if the Arduino has one: // - it does not autoreset (except for the magic baud rate of 1200). // - it is more reliable because of USB handshaking. // // Leonardo and similar have an USB virtual serial port: 'Serial'. // Due and Zero have an USB virtual serial port: 'SerialUSB'. // // On the Due and Zero, 'Serial' can be used too, provided you disable autoreset. // To use 'Serial': #define SERIAL Serial #ifdef SERIAL_PORT_USBVIRTUAL #define SERIAL SERIAL_PORT_USBVIRTUAL #else #define SERIAL Serial #endif // Configure the baud rate: #define BAUDRATE 19200 // #define BAUDRATE 115200 // #define BAUDRATE 1000000 #define HWVER 2 #define SWMAJ 1 #define SWMIN 18 // STK Definitions #define STK_OK 0x10 #define STK_FAILED 0x11 #define STK_UNKNOWN 0x12 #define STK_INSYNC 0x14 #define STK_NOSYNC 0x15 #define CRC_EOP 0x20 //ok it is a space... void pulse(int pin, int times); void flush() { Serial.flush(); delay(200); while (Serial.read() > 0 ) ; delay(100); } void setup() { SERIAL.begin(BAUDRATE); pinMode(LED_PMODE, OUTPUT); pulse(LED_PMODE, 2); pinMode(LED_ERR, OUTPUT); pulse(LED_ERR, 2); pinMode(LED_HB, OUTPUT); pulse(LED_HB, 2); flush(); } int error = 0; int pmode = 0; // address for reading and writing, set by 'U' command unsigned int here; uint8_t buff[256]; // global block storage uint8_t sigbytes[3] = { SIGNATURE_0, SIGNATURE_1, SIGNATURE_2 }; #define beget16(addr) (*addr * 256 + *(addr+1) ) typedef struct param { uint8_t devicecode; uint8_t revision; uint8_t progtype; uint8_t parmode; uint8_t polling; uint8_t selftimed; uint8_t lockbytes; uint8_t fusebytes; uint8_t flashpoll; uint16_t eeprompoll; uint16_t pagesize; uint16_t eepromsize; uint32_t flashsize; } parameter; parameter param; // this provides a heartbeat on pin 9, so you can tell the software is running. uint8_t hbval = 128; int8_t hbdelta = 8; void heartbeat() { static unsigned long last_time = 0; unsigned long now = millis(); if ((now - last_time) < 40) return; last_time = now; if (hbval > 192) hbdelta = -hbdelta; if (hbval < 32) hbdelta = -hbdelta; hbval += hbdelta; analogWrite(LED_HB, hbval); } static bool rst_active_high; void loop(void) { // is pmode active? if (pmode) { digitalWrite(LED_PMODE, HIGH); } else { digitalWrite(LED_PMODE, LOW); } // is there an error? if (error) { digitalWrite(LED_ERR, HIGH); } else { digitalWrite(LED_ERR, LOW); } // light the heartbeat LED heartbeat(); if (SERIAL.available()) { avrisp(); } } uint8_t getch() { while (!SERIAL.available()); return SERIAL.read(); } void fill(int n) { for (int x = 0; x < n; x++) { buff[x] = getch(); } } #define PTIME 30 void pulse(int pin, int times) { do { digitalWrite(pin, HIGH); delay(PTIME); digitalWrite(pin, LOW); delay(PTIME); } while (times--); } void prog_lamp(int state) { if (PROG_FLICKER) { digitalWrite(LED_PMODE, state); } } void empty_reply() { if (CRC_EOP == getch()) { SERIAL.print((char)STK_INSYNC); SERIAL.print((char)STK_OK); } else { error++; SERIAL.print((char)STK_NOSYNC); } } void breply(uint8_t b) { if (CRC_EOP == getch()) { SERIAL.print((char)STK_INSYNC); SERIAL.print((char)b); SERIAL.print((char)STK_OK); } else { error++; SERIAL.print((char)STK_NOSYNC); } } void get_version(uint8_t c) { switch (c) { case 0x80: breply(HWVER); break; case 0x81: breply(SWMAJ); break; case 0x82: breply(SWMIN); break; case 0x93: breply('S'); // serial programmer break; default: breply(0); } } void set_parameters() { // call this after reading parameter packet into buff[] param.devicecode = buff[0]; param.revision = buff[1]; param.progtype = buff[2]; param.parmode = buff[3]; param.polling = buff[4]; param.selftimed = buff[5]; param.lockbytes = buff[6]; param.fusebytes = buff[7]; param.flashpoll = buff[8]; // ignore buff[9] (= buff[8]) // following are 16 bits (big endian) param.eeprompoll = beget16(&buff[10]); param.pagesize = beget16(&buff[12]); param.eepromsize = beget16(&buff[14]); // 32 bits flashsize (big endian) param.flashsize = buff[16] * 0x01000000 + buff[17] * 0x00010000 + buff[18] * 0x00000100 + buff[19]; // AVR devices have active low reset, AT89Sx are active high rst_active_high = (param.devicecode >= 0xe0); } void start_pmode() { pmode = 1; } void end_pmode() { pmode = 0; } void universal() { uint16_t a; uint8_t ch; fill(4); switch (buff[0]) { case 0x30: // signature byte N breply(sigbytes[buff[2]]); return; case 0x50: // fuses if (buff[1] == 0 && buff[2] == 0) { breply(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS)); return; } else if (buff[1] == 8) { breply(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS)); return; } break; case 0x58: // other fuses if (buff[1] == 8) { breply(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS)); return; } break; case 0xA0: // read eeprom a = (buff[1] << 8) + buff[2]; breply(eeprom_read_byte(a)); return; case 0xC0: // read eeprom a = (buff[1] << 8) + buff[2]; eeprom_write_byte(a, buff[3]); breply(buff[3]); return; } breply(0); } void commit(unsigned int addr) { if (PROG_FLICKER) { prog_lamp(LOW); } if (PROG_FLICKER) { delay(PTIME); prog_lamp(HIGH); } } unsigned int current_page() { if (param.pagesize == 32) { return here & 0xFFFFFFF0; } if (param.pagesize == 64) { return here & 0xFFFFFFE0; } if (param.pagesize == 128) { return here & 0xFFFFFFC0; } if (param.pagesize == 256) { return here & 0xFFFFFF80; } return here; } void halt(uint32_t d) { while (1) { digitalWrite(LED_ERR, 0); delay(d); digitalWrite(LED_ERR, 1); delay(d); } } #define EECHUNK (32) uint8_t write_eeprom(unsigned int length) { // here is a word address, get the byte address unsigned int start = here * 2; unsigned int remaining = length; if (length > param.eepromsize) { error++; return STK_FAILED; } while (remaining > EECHUNK) { write_eeprom_chunk(start, EECHUNK); start += EECHUNK; remaining -= EECHUNK; } write_eeprom_chunk(start, remaining); return STK_OK; } // write (length) bytes, (start) is a byte address uint8_t write_eeprom_chunk(unsigned int start, unsigned int length) { // this writes byte-by-byte, page writing may be faster (4 bytes at a time) fill(length); prog_lamp(LOW); for (unsigned int x = 0; x < length; x++) { unsigned int addr = start + x; eeprom_write_byte((uint8_t *)addr, buff[x]); delay(45); } prog_lamp(HIGH); return STK_OK; } void program_page() { char result = (char) STK_FAILED; unsigned int length = 256 * getch(); length += getch(); char memtype = getch(); // flash memory @here, (length) bytes if (memtype == 'F') { halt(200); return; } if (memtype == 'E') { result = (char)write_eeprom(length); if (CRC_EOP == getch()) { SERIAL.print((char) STK_INSYNC); SERIAL.print(result); } else { error++; SERIAL.print((char) STK_NOSYNC); } return; } SERIAL.print((char)STK_FAILED); return; } char eeprom_read_page(int length) { // here again we have a word address int start = here * 2; for (int x = 0; x < length; x++) { int addr = start + x; uint8_t ee = eeprom_read_byte((const uint8_t *)addr); SERIAL.print((char) ee); } return STK_OK; } char flash_read_page(int length) { for (int x = 0; x < length; x ++) { uint8_t b = pgm_read_byte(here); SERIAL.print((char) b); here++; } return STK_OK; } void read_page() { char result = (char)STK_FAILED; int length = 256 * getch(); length += getch(); char memtype = getch(); if (CRC_EOP != getch()) { error++; SERIAL.print((char) STK_NOSYNC); return; } SERIAL.print((char) STK_INSYNC); if (memtype == 'F') result = flash_read_page(length); if (memtype == 'E') result = eeprom_read_page(length); SERIAL.print(result); } void read_signature() { if (CRC_EOP != getch()) { error++; SERIAL.print((char) STK_NOSYNC); return; } SERIAL.print((char) STK_INSYNC); SERIAL.print((char) SIGNATURE_0); SERIAL.print((char) SIGNATURE_1); SERIAL.print((char) SIGNATURE_2); SERIAL.print((char) STK_OK); } ////////////////////////////////////////// ////////////////////////////////////////// //////////////////////////////////// //////////////////////////////////// void avrisp() { uint8_t ch = getch(); switch (ch) { case '0': // signon error = 0; empty_reply(); break; case '1': if (getch() == CRC_EOP) { SERIAL.print((char) STK_INSYNC); SERIAL.print("AVR ISP"); SERIAL.print((char) STK_OK); } else { error++; SERIAL.print((char) STK_NOSYNC); } break; case 'A': get_version(getch()); break; case 'B': fill(20); set_parameters(); empty_reply(); break; case 'E': // extended parameters - ignore for now fill(5); empty_reply(); break; case 'P': if (!pmode) start_pmode(); empty_reply(); break; case 'U': // set address (word) here = getch(); here += 256 * getch(); empty_reply(); break; case 0x60: //STK_PROG_FLASH getch(); // low addr getch(); // high addr empty_reply(); break; case 0x61: //STK_PROG_DATA getch(); // data empty_reply(); break; case 0x64: //STK_PROG_PAGE program_page(); break; case 0x74: //STK_READ_PAGE 't' read_page(); break; case 'V': //0x56 universal(); break; case 'Q': //0x51 error = 0; end_pmode(); empty_reply(); break; case 0x75: //STK_READ_SIGN 'u' read_signature(); break; // expecting a command, not CRC_EOP // this is how we can get back in sync case CRC_EOP: error++; SERIAL.print((char) STK_NOSYNC); break; // anything else we will return STK_UNKNOWN default: error++; if (CRC_EOP == getch()) SERIAL.print((char)STK_UNKNOWN); else SERIAL.print((char)STK_NOSYNC); } }
[ "westfw@gmail.com" ]
westfw@gmail.com
cb46e39c2778ea34330caafd25f7cfa6a448f9ae
208f1c8cca79c55c0df98c7aec920ee5b22e7e13
/src/game.h
efb6ed7c846bf223ebb84693d88289d845f576a7
[]
no_license
BenTarman/PhysicsPlatformerGameEngine
2dad9126f81b3233d6f72e953182601606ead0c4
083bf413abde84717ede9336657e1bd2d7820d80
refs/heads/master
2021-04-18T19:41:54.546540
2017-06-16T23:30:38
2017-06-16T23:30:38
94,588,242
1
0
null
null
null
null
UTF-8
C++
false
false
953
h
#ifndef GAME_HPP #define GAME_HPP #include <stack> #include <vector> #include <SFML/Graphics.hpp> #include "TextureManager.h" #include "FontManager.h" #include <memory> class GameState; class Game { public: bool isSpriteClicked(sf::Text sprite); sf::RenderWindow window; TextureManager texmgr; //main menu text FontManager playGame; FontManager options; FontManager quitGame; //options text FontManager resizeWindow; FontManager fullScreen; FontManager windowedScreen; sf::Sprite homuraSheet; sf::Sprite background; sf::Sprite dude; int counter; void pushState(std::shared_ptr<GameState> states); std::shared_ptr<GameState> currentState(); //void changeState(GameState* state); void gameLoop(); Game(); private: std::vector<std::shared_ptr<GameState>> states; void loadTextures(); void loadFonts(); }; #endif /* GAME_HPP */
[ "btarman@mymail.mines.edu" ]
btarman@mymail.mines.edu
3c5acd8893f0c99197bca6b08cd332e7a682d782
53ce2379978c3042519ad038c68f98e57b362b07
/meshutil.cpp
2016a1c86a9c397a6826b62e5bc3e2b126d5bde7
[ "MIT" ]
permissive
elementbound/glwrap
c65a8229662fd423211e4f3f52a4ab80a737fc65
834fbeacfd2fb4bf56ed9feb06fc58069a08ee49
refs/heads/master
2021-01-20T12:05:14.867793
2015-05-22T02:43:17
2015-05-22T02:43:17
32,824,458
0
0
null
null
null
null
UTF-8
C++
false
false
4,330
cpp
#include "meshutil.h" #include "util.h" #include <sstream> #include <string> //strtod because std::stod is broken on my compiler ( mingw 4.8.1 ) #include <cstdlib> #include <fstream> #include <vector> #include <set> #include <array> #include <glm/glm.hpp> namespace meshutil { void read_vec2(std::istream& is, glm::vec2& v) { std::string component[2]; is >> component[0] >> component[1]; v.x = (float)atof(component[0].c_str()); v.y = (float)atof(component[1].c_str()); } void read_vec3(std::istream& is, glm::vec3& v) { std::string component[3]; is >> component[0] >> component[1] >> component[2]; v.x = (float)atof(component[0].c_str()); v.y = (float)atof(component[1].c_str()); v.z = (float)atof(component[2].c_str()); } void load_obj(std::istream& is, separated_mesh& result_mesh) { typedef unsigned int index_t; result_mesh.clear_streams(); std::string line; std::stringstream parser; std::string token; std::vector<glm::vec3> obj_positions; std::vector<glm::vec3> obj_normals; std::vector<glm::vec2> obj_texcoords; std::vector<std::array<index_t, 3>> obj_vertices; std::set<std::array<index_t, 3>> vertex_combinations; // obj_positions.reserve(8192); obj_normals.reserve(8192); obj_texcoords.reserve(8192); // result_mesh.draw_mode = GL_TRIANGLES; result_mesh.storage_policy = GL_STATIC_DRAW; unsigned pos = result_mesh.add_stream(); unsigned nor = result_mesh.add_stream(); unsigned tex = result_mesh.add_stream(); //unsigned ind = result_mesh.add_stream(); result_mesh[pos].type = GL_FLOAT; result_mesh[pos].buffer_type = GL_ARRAY_BUFFER; result_mesh[pos].components = 3; result_mesh[pos].normalized = 0; result_mesh[pos].name = "vertexPosition"; result_mesh[nor].type = GL_FLOAT; result_mesh[nor].buffer_type = GL_ARRAY_BUFFER; result_mesh[nor].components = 3; result_mesh[nor].normalized = 0; result_mesh[nor].name = "vertexNormal"; result_mesh[tex].type = GL_FLOAT; result_mesh[tex].buffer_type = GL_ARRAY_BUFFER; result_mesh[tex].components = 2; result_mesh[tex].normalized = 0; result_mesh[tex].name = "vertexTexcoord"; /*result_mesh[ind].type = GL_UNSIGNED_INT; result_mesh[ind].buffer_type = GL_ELEMENT_ARRAY_BUFFER; result_mesh[ind].components = 1; result_mesh[ind].normalized = 0; result_mesh[ind].name = "";*/ // while(is.good()) { std::getline(is, line); //Ignore empty lines if(line.size() == 0) continue; //Ignore comments if(line[0] == '#') continue; parser.str(line); parser.seekg(0); parser >> token; if(token == "v") { glm::vec3 v; read_vec3(parser, v); obj_positions.push_back(v); } else if(token == "vn") { glm::vec3 n; read_vec3(parser, n); obj_normals.push_back(n); } else if(token == "vt") { glm::vec2 uv; read_vec2(parser, uv); obj_texcoords.push_back(uv); } else if(token == "f") { std::array<index_t, 3> f; for(unsigned j=0; j<3; j++) { for(unsigned i=0; i<3; i++) { parser >> f[i]; if(i!=2) parser.ignore(std::numeric_limits<std::streamsize>::max(), '/'); } obj_vertices.push_back(f); //vertex_combinations.insert(f); } } } /*for(const auto& f: vertex_combinations) { const index_t pos_index = f[0] - 1; const index_t uv_index = f[1] - 1; const index_t normal_index = f[2] - 1; result_mesh[pos].data << obj_positions[pos_index]; result_mesh[tex].data << obj_texcoords[uv_index]; result_mesh[nor].data << obj_normals[normal_index]; }*/ for(const auto& f: obj_vertices) { /*index_t index = std::distance(vertex_combinations.begin(), vertex_combinations.find(f)); result_mesh[ind].data << (unsigned int)index;*/ const index_t pos_index = f[0] - 1; const index_t uv_index = f[1] - 1; const index_t normal_index = f[2] - 1; result_mesh[pos].data << obj_positions[pos_index]; result_mesh[tex].data << obj_texcoords[uv_index]; result_mesh[nor].data << obj_normals[normal_index]; } result_mesh.upload(); } void load_obj(const char* file, separated_mesh& result_mesh) { std::ifstream fis(file); load_obj(fis, result_mesh); } };
[ "ezittgtx@gmail.com" ]
ezittgtx@gmail.com
4e673096b777663f79551a0f731b414fc23c6239
9280fea108f5b3912629de7851f6bbbde561c9a4
/src/common/state_estimation/test/test_kalman_filter.cpp
650efd7cd663d6a59c222b6fd8a54f9f52f89d0d
[ "MIT", "Apache-2.0" ]
permissive
bytetok/vde
93071992618b7c539cd618eaae24d65f1099295b
ff8950abbb72366ed3072de790c405de8875ecc3
refs/heads/main
2023-08-23T15:08:14.644017
2021-10-09T03:59:09
2021-10-09T03:59:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,222
cpp
// Copyright 2021 Apex.AI, 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. // // Co-developed by Tier IV, Inc. and Apex.AI, Inc. #include <common/types.hpp> #include <motion_model/linear_motion_model.hpp> #include <motion_model/stationary_motion_model.hpp> #include <state_estimation/kalman_filter/kalman_filter.hpp> #include <state_estimation/measurement/linear_measurement.hpp> #include <state_estimation/noise_model/wiener_noise.hpp> #include <gtest/gtest.h> #include <Eigen/Dense> #include <tuple> using autoware::common::state_vector::variable::X; using autoware::common::state_vector::variable::Y; using autoware::common::state_vector::variable::YAW; using autoware::common::state_vector::variable::X_VELOCITY; using autoware::common::state_vector::variable::Y_VELOCITY; using autoware::common::state_vector::variable::YAW_CHANGE_RATE; using autoware::common::state_vector::variable::X_ACCELERATION; using autoware::common::state_vector::variable::Y_ACCELERATION; using autoware::common::state_vector::variable::YAW_CHANGE_ACCELERATION; using autoware::common::state_vector::Variable; using autoware::common::state_vector::FloatState; using autoware::common::state_estimation::LinearMeasurement; using autoware::common::state_estimation::KalmanFilter; using autoware::common::state_estimation::NoiseInterface; using autoware::common::state_estimation::WienerNoise; using autoware::common::state_estimation::make_kalman_filter; using autoware::common::state_estimation::make_correction_only_kalman_filter; using autoware::common::motion_model::LinearMotionModel; using autoware::common::motion_model::StationaryMotionModel; using autoware::common::state_vector::ConstAccelerationXY32; using autoware::common::state_vector::ConstAccelerationXYYaw32; using autoware::common::types::float32_t; /// @test Test that a filter can be created and reset and is in a valid state throughout this. TEST(TestKalmanFilter, CreateAndReset) { using State = LinearMotionModel<ConstAccelerationXY32>::State; using Matrix = State::Matrix; LinearMotionModel<ConstAccelerationXY32> motion_model{}; WienerNoise<ConstAccelerationXY32> noise_model{{1.0F, 1.0F}}; auto kf = make_kalman_filter( motion_model, noise_model, State{}, {{1.0F, 1.0F, 1.0F, 1.0F, 1.0F, 1.0F}}); EXPECT_TRUE(kf.state().vector().isApproxToConstant(0.0F)); EXPECT_TRUE(kf.covariance().isApprox(Matrix::Identity())); kf.reset(State{State::Vector::Ones()}, Matrix::Ones()); EXPECT_TRUE(kf.state().vector().isApproxToConstant(1.0F)); EXPECT_TRUE(kf.covariance().isApproxToConstant(1.0F)); } /// @test Test that predictions without measurements always increase uncertainty. TEST(TestKalmanFilter, PredictionsIncreaseUncertainty) { using State = LinearMotionModel<ConstAccelerationXY32>::State; using Matrix = State::Matrix; LinearMotionModel<ConstAccelerationXY32> motion_model{}; WienerNoise<ConstAccelerationXY32> noise_model{{1.0F, 1.0F}}; auto kf = make_kalman_filter(motion_model, noise_model, State{}, Matrix::Identity()); EXPECT_TRUE(kf.state().vector().isApproxToConstant(0.0F)); auto covariance = kf.covariance(); for (int i = 0; i < 20; ++i) { kf.predict(std::chrono::milliseconds{100LL}); const auto diff = kf.covariance() - covariance; EXPECT_TRUE((diff.diagonal().array() > 0.0F).all()) << "New covariance: \n" << kf.covariance() << "\nis not bigger than old one:\n" << covariance; covariance = kf.covariance(); } } /// @test Test that we can track a static object measuring its full state. TEST(TestKalmanFilter, TrackStaticObjectWithDirectMeasurements) { using State = LinearMotionModel<ConstAccelerationXY32>::State; using Matrix = State::Matrix; using MeasurementState = FloatState< X, X_VELOCITY, X_ACCELERATION, Y, Y_VELOCITY, Y_ACCELERATION>; LinearMotionModel<ConstAccelerationXY32> motion_model{}; WienerNoise<ConstAccelerationXY32> noise_model{{1.0F, 1.0F}}; auto kf = make_kalman_filter(motion_model, noise_model, State{}, Matrix::Identity()); EXPECT_TRUE(kf.state().vector().isApproxToConstant(0.0F)); auto covariance = kf.covariance(); const MeasurementState::Vector stddev = MeasurementState::Vector::Constant(0.1F); for (int i = 0; i < 10; ++i) { kf.predict(std::chrono::milliseconds{100LL}); kf.correct( LinearMeasurement<MeasurementState>::create_with_stddev( MeasurementState::Vector::Zero(), stddev)); EXPECT_TRUE(kf.state().vector().isApproxToConstant(0.0F)) << "Vector " << kf.state().vector().transpose() << " is not a zero vector."; const auto covariance_difference = kf.covariance() - covariance; EXPECT_TRUE((covariance_difference.diagonal().array() < 0.0F).all()) << "New covariance: \n" << kf.covariance() << "\nis not smaller than old one:\n" << covariance; } } /// @test Test that we can track a static object measuring only its partial state. TEST(TestKalmanFilter, TrackStaticObjectHiddenState) { using State = LinearMotionModel<ConstAccelerationXY32>::State; using Matrix = State::Matrix; using MeasurementState = FloatState<X, Y>; LinearMotionModel<ConstAccelerationXY32> motion_model{}; WienerNoise<ConstAccelerationXY32> noise_model{{1.0F, 1.0F}}; auto kf = make_kalman_filter(motion_model, noise_model, State{}, 10.0F * Matrix::Identity()); EXPECT_TRUE(kf.state().vector().isApproxToConstant(0.0F)); auto covariance = kf.covariance(); const MeasurementState::Vector stddev = MeasurementState::Vector::Constant(0.1F); for (int i = 0; i < 10; ++i) { kf.predict(std::chrono::milliseconds{100LL}); kf.correct( LinearMeasurement<MeasurementState>::create_with_stddev( MeasurementState::Vector::Zero(), stddev)); EXPECT_TRUE(kf.state().vector().isApproxToConstant(0.0F)) << "Vector " << kf.state().vector().transpose() << " is not a zero vector."; } // Perform this check only in the end as the covariance of the unobserved variables _can_ grow // initially but will eventually fall below the original values. const auto covariance_difference = kf.covariance() - covariance; EXPECT_TRUE((covariance_difference.diagonal().array() < 0.0F).all()) << "New covariance: \n" << kf.covariance() << "\nis not smaller than old one:\n" << covariance; } /// @test Test that we can track a moving object measuring part of its state. /// /// @details The object is assumed to move at a straight line, changing its orientation with /// constant angular velocity. All the variables, X, Y, YAW are changing independently. TEST(TestKalmanFilter, TrackMovingObject) { using State = LinearMotionModel<ConstAccelerationXYYaw32>::State; using Matrix = State::Matrix; using MeasurementState = FloatState<X, Y, YAW>; LinearMotionModel<ConstAccelerationXYYaw32> motion_model{}; WienerNoise<ConstAccelerationXYYaw32> noise_model{{1.0F, 1.0F, 1.0F}}; const auto initial_covariance = Matrix::Identity(); auto kf = make_kalman_filter(motion_model, noise_model, State{}, initial_covariance); EXPECT_TRUE(kf.state().vector().isApproxToConstant(0.0F)); const auto speed = 10.0F; // m/s const std::chrono::milliseconds dt{100LL}; const std::chrono::seconds total_time{5}; const MeasurementState::Vector stddev = MeasurementState::Vector::Constant(0.1F); for (auto t = dt; t <= total_time; t += dt) { const auto float_seconds = std::chrono::duration<float32_t>{t}.count(); const auto travelled_distance = float_seconds * speed; const auto observation = travelled_distance * MeasurementState::Vector::Ones(); kf.predict(std::chrono::milliseconds{100LL}); kf.correct( LinearMeasurement<MeasurementState>::create_with_stddev(observation, stddev)); } const auto total_float_seconds = std::chrono::duration<float32_t>{total_time}.count(); const float32_t eps = 0.001F; EXPECT_NEAR(kf.state().at<X>(), total_float_seconds * speed, eps); EXPECT_NEAR(kf.state().at<Y>(), total_float_seconds * speed, eps); EXPECT_NEAR( kf.state().at<YAW>(), autoware::common::helper_functions::wrap_angle(total_float_seconds * speed), eps); EXPECT_NEAR(kf.state().at<X_VELOCITY>(), speed, eps); EXPECT_NEAR(kf.state().at<Y_VELOCITY>(), speed, eps); EXPECT_NEAR(kf.state().at<YAW_CHANGE_RATE>(), speed, eps); EXPECT_NEAR(kf.state().at<X_ACCELERATION>(), 0.0F, eps); EXPECT_NEAR(kf.state().at<Y_ACCELERATION>(), 0.0F, eps); EXPECT_NEAR(kf.state().at<YAW_CHANGE_ACCELERATION>(), 0.0F, eps); } /// \test Track a ball thrown at 45 deg angle. We perfectly observe positions of the ball. /// /// The ball moves at a parabola starting at (0, 0): /// ^ ___ /// | _/ \_ /// | _/ \_ /// |/ \_ /// └--------------> /// start end /// TEST(TestKalmanFilter, TrackThrownBall) { using namespace std::chrono_literals; using FloatSeconds = std::chrono::duration<float32_t>; using State = LinearMotionModel<ConstAccelerationXY32>::State; using Matrix = State::Matrix; using MeasurementState = FloatState<X, Y>; LinearMotionModel<ConstAccelerationXY32> motion_model{}; WienerNoise<ConstAccelerationXY32> noise_model{{1.0F, 1.0F}}; const float32_t g = -9.80665F; // m/s^2. const float32_t initial_speed = 9.80665F; // m/s State initial_state{}; initial_state.at<X_VELOCITY>() = initial_speed; initial_state.at<Y_VELOCITY>() = initial_speed; initial_state.at<Y_ACCELERATION>() = g; const auto initial_covariance = Matrix::Identity(); auto kf = make_kalman_filter( motion_model, noise_model, initial_state, initial_covariance); // In the way we model the ball it is going to reach the ground at this time. const std::chrono::system_clock::time_point start_time{std::chrono::system_clock::now()}; const auto duration = 2000ms; const auto expected_end_time = start_time + duration; const auto increment = 10ms; const float32_t seconds_increment{FloatSeconds{increment}.count()}; State expected_state{initial_state}; const MeasurementState::Vector stddev = MeasurementState::Vector::Constant(0.1F); for (auto timestamp = start_time; timestamp <= expected_end_time; timestamp += increment) { expected_state.at<X>() += seconds_increment * expected_state.at<X_VELOCITY>(); expected_state.at<Y>() += seconds_increment * expected_state.at<Y_VELOCITY>(); expected_state.at<X_VELOCITY>() += seconds_increment * expected_state.at<X_ACCELERATION>(); expected_state.at<Y_VELOCITY>() += seconds_increment * expected_state.at<Y_ACCELERATION>(); kf.predict(increment); kf.correct( LinearMeasurement<MeasurementState>::create_with_stddev( MeasurementState::Vector{expected_state.at<X>(), expected_state.at<Y>()}, stddev)); } // Quickly check our "simulation" of the ball. const auto duration_seconds = std::chrono::duration<float32_t>{duration}.count(); const auto kRelaxedEpsilon = 0.2F; // Allow up to 20 cm error. EXPECT_NEAR(expected_state.at<X>(), initial_speed * duration_seconds, kRelaxedEpsilon); EXPECT_NEAR(expected_state.at<Y>(), 0.0F, kRelaxedEpsilon); EXPECT_NEAR(expected_state.at<X>(), kf.state().at<X>(), 0.001F); EXPECT_NEAR(expected_state.at<Y>(), kf.state().at<Y>(), 0.001F); EXPECT_NEAR(expected_state.at<X_VELOCITY>(), kf.state().at<X_VELOCITY>(), kRelaxedEpsilon); EXPECT_NEAR(expected_state.at<Y_VELOCITY>(), kf.state().at<Y_VELOCITY>(), kRelaxedEpsilon); EXPECT_NEAR(expected_state.at<X_ACCELERATION>(), 0.0F, kRelaxedEpsilon); EXPECT_NEAR(expected_state.at<Y_ACCELERATION>(), g, kRelaxedEpsilon); } /// \test Check that Kalman Filter can be used for classification. In this example of a traffic /// light state. TEST(KalmanFilterWrapperTest, TrafficLightState) { struct RED : public Variable {}; struct GREEN : public Variable {}; struct ORANGE : public Variable {}; using TrafficLightState = FloatState<RED, GREEN, ORANGE>; const auto uniform_probability = 1.0F / TrafficLightState::size(); const auto uniform_vector = TrafficLightState::Vector::Constant(uniform_probability); TrafficLightState traffic_light_state{uniform_vector}; EXPECT_FLOAT_EQ(traffic_light_state.at<RED>(), uniform_probability); EXPECT_FLOAT_EQ(traffic_light_state.at<GREEN>(), uniform_probability); EXPECT_FLOAT_EQ(traffic_light_state.at<ORANGE>(), uniform_probability); auto filter = make_correction_only_kalman_filter( traffic_light_state, TrafficLightState::Matrix::Identity()); // Observe a red light. const auto red_light_measurement = LinearMeasurement<TrafficLightState>::create_with_stddev( {1.0F, 0.0F, 0.0F}, {0.1F, 0.1F, 0.1F}); EXPECT_FLOAT_EQ(filter.state().at<RED>(), uniform_probability); EXPECT_FLOAT_EQ(filter.state().at<GREEN>(), uniform_probability); EXPECT_FLOAT_EQ(filter.state().at<ORANGE>(), uniform_probability); filter.correct(red_light_measurement); const auto epsilon = 0.1F; // An epsilon chosen to match the observation covariance. EXPECT_GT(filter.state().at<RED>(), uniform_probability + epsilon); EXPECT_LT(filter.state().at<GREEN>(), uniform_probability - epsilon); EXPECT_LT(filter.state().at<ORANGE>(), uniform_probability - epsilon); // Observe a green light. const auto green_light_measurement = LinearMeasurement<TrafficLightState>::create_with_stddev( {0.0F, 1.0F, 0.0F}, {0.1F, 0.1F, 0.1F}); filter.correct(green_light_measurement); // We have now seen both green and red once, so it should be roughly 50/50 probability for either // of these states of the traffic light, but definitely not orange. EXPECT_NEAR(filter.state().at<RED>(), 0.5F, epsilon); EXPECT_NEAR(filter.state().at<GREEN>(), 0.5F, epsilon); EXPECT_NEAR(filter.state().at<ORANGE>(), 0.0F, epsilon); }
[ "Will.Heitman@utdallas.edu" ]
Will.Heitman@utdallas.edu
9597be6bb01e38a7f60dab3a366d874bf4189ef9
da9bcb04a400492d226466264b9b6b9efea24059
/CECS 282/Lectures/Classes/SimpleClasses/strings.cpp
3085dd18cf93420512afee204f3356ddad93a6c8
[ "MIT" ]
permissive
hidtran/CECS-Projects
bcb4ea6a1fcddf2d1c45582b903fd6952d3151c8
d74f30632bf1f7d6e60440e2d2e188dd4363b5dc
refs/heads/master
2021-01-10T10:02:26.659870
2015-10-15T03:35:40
2015-10-15T03:35:40
44,233,294
0
0
null
null
null
null
UTF-8
C++
false
false
2,571
cpp
#include <iostream> #include <string> // note this using namespace std; /* Explore objects and classes through the Standard Library string class. */ int maint(int argc, char* argv[]) { // string is a class. It represents a sequence of characters. // We can create a string variable with assignment. string s = "Hello"; // We can output a string variable with cout. cout << s << endl; /* *s is an "object", and string is a "class"*. What is the difference between a "class" and an "object"? */ /* We will briefly explore C++ objects through the string class. *A class defines a set of operations called "methods" that can be used with the "instances of the class (object)".* To access a method of an object, use the period . operator. This "calls" the method and does something to or with the object. */ // Example: print the length of a string. cout << s.length() << endl; // .length() gives the # of characters in s // Declare another object of type string string other = "Other string"; // Unlike Java, *C++ strings are mutable (can be changed)*. s.append(", world!");// By calling this method, the object's state is changed s.insert(0, "Yay! ");// This lets us insert at an index instead of the end. // append and insert are methods of the class, and define operations that can // be applied to the state of an object. Operations on one object do not // change the state of a different object. // Now that the state of s has changed, its output will change. cout << s << endl; // But has "other" changed? cout << other << endl; // Some simple functions of the string class: cout << s.at(0) << endl; // *retrieve character at index 0* cout << s[0] << endl; // *can also do s[0]* cout << s.find(',') /* gets first index of the character ',' */ << endl; // < 0 indicates a character doesn't found. // Can also use s.find(',', starting position to look for) // extract a substring. first parameter: start index. second: length. string sub = s.substr(5, s.size() - 5); // s.substring(starting index, length of the string(size of string - starting index)) cout << sub << endl; // What will this output? /* SUMMARY: With the string class, we can declare variables of the string type. Each "instance" of this class stores a state and provides methods that can operate on that state. Changing one object's state does not affect other objects of the same class. */ return 0; }
[ "hidtran@gmail.com" ]
hidtran@gmail.com
73ee09bd317f91b34cf37d405904ce043a4e9d26
a9817b707768160e37105c7a71eeea8c4db05b6b
/BinaryTree/lowestCommonAncessotorNaive.cpp
2e8d568cca38864e00126c6b714738bb6d9feac2
[]
no_license
faisals345/ProblemSolvingShorts
228e651c0c245c691c64305018efd85d1d590ca5
a4a7ee28626fc80c6fbf5c903e513cc6f22e16a9
refs/heads/master
2023-07-16T01:56:13.740371
2021-08-31T11:53:47
2021-08-31T11:53:47
374,855,919
0
0
null
null
null
null
UTF-8
C++
false
false
1,638
cpp
#include <bits/stdc++.h> using namespace std; struct node { int data; node *left; node *right; node(int d) { data = d; left = NULL; right = NULL; } }; //1 2 4 -1 -1 5 7 -1 -1 -1 3 -1 6 -1 -1 node *buildTree() { int d; cin >> d; if (d == -1) { return NULL; } node *n = new node(d); n->left = buildTree(); n->right = buildTree(); return n; } vector<int> vec1,vec2; int findPath1(node *root,int n){ if(root==NULL){ return 0; } vec1.push_back(root->data); if(root->data==n){ return -1; } int t1=findPath1(root->left,n); if(t1==-1){ return -1; } int t2=findPath1(root->right,n); if(t2==-1){ return -1; } vec1.pop_back(); return 0; } int findPath2(node *root,int n2){ if(root==NULL){ return 0; } vec2.push_back(root->data); if(root->data==n2){ return -1; } int t3=findPath2(root->left,n2); if(t3==-1){ return -1; } int t4=findPath2(root->right,n2); if(t4==-1){ return -1; } vec2.pop_back(); return 0; } int main() { node *root = buildTree(); //1 2 4 -1 -1 5 7 -1 -1 -1 3 -1 6 -1 -1 int d1= findPath1(root,5); int d2= findPath2(root,4); int ans=0; for(int i=0;i<vec1.size() && i<vec2.size();i++){ if(vec1[i]==vec2[i]){ ans=vec1[i]; } else{ break; } } cout<<d1<<" "<<d2<<endl; cout<<ans<<endl; return 0; }
[ "2019ugcs015@nitjsr.ac.in" ]
2019ugcs015@nitjsr.ac.in
88f91e76c708d007d9d2652c6eb6c4bd58c25c7a
f1ac5501fd36e4e420dfbc912890b4c848e4acc3
/src/ui_interface.h
59ead211bb6010c4886c817f2d8c8ffdc6fe71f2
[]
no_license
whojan/KomodoOcean
20ca84ea11ed791c407bed17b155134b640796e8
f604a95d848222af07db0005c33dc4852b5203a3
refs/heads/master
2022-08-07T13:10:15.341628
2019-06-14T17:27:57
2019-06-14T17:27:57
274,690,003
1
0
null
2020-06-24T14:28:50
2020-06-24T14:28:49
null
UTF-8
C++
false
false
4,644
h
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2012 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef KOMODO_UI_INTERFACE_H #define KOMODO_UI_INTERFACE_H #include <stdint.h> #include <string> #include "chain.h" #include <boost/signals2/last_value.hpp> #include <boost/signals2/signal.hpp> class CBasicKeyStore; class CWallet; class uint256; /** General change type (added, updated, removed). */ enum ChangeType { CT_NEW, CT_UPDATED, CT_DELETED }; /** Signals for UI communication. */ class CClientUIInterface { public: /** Flags for CClientUIInterface::ThreadSafeMessageBox */ enum MessageBoxFlags { ICON_INFORMATION = 0, ICON_WARNING = (1U << 0), ICON_ERROR = (1U << 1), /** * Mask of all available icons in CClientUIInterface::MessageBoxFlags * This needs to be updated, when icons are changed there! */ ICON_MASK = (ICON_INFORMATION | ICON_WARNING | ICON_ERROR), /** These values are taken from qmessagebox.h "enum StandardButton" to be directly usable */ BTN_OK = 0x00000400U, // QMessageBox::Ok BTN_YES = 0x00004000U, // QMessageBox::Yes BTN_NO = 0x00010000U, // QMessageBox::No BTN_ABORT = 0x00040000U, // QMessageBox::Abort BTN_RETRY = 0x00080000U, // QMessageBox::Retry BTN_IGNORE = 0x00100000U, // QMessageBox::Ignore BTN_CLOSE = 0x00200000U, // QMessageBox::Close BTN_CANCEL = 0x00400000U, // QMessageBox::Cancel BTN_DISCARD = 0x00800000U, // QMessageBox::Discard BTN_HELP = 0x01000000U, // QMessageBox::Help BTN_APPLY = 0x02000000U, // QMessageBox::Apply BTN_RESET = 0x04000000U, // QMessageBox::Reset /** * Mask of all available buttons in CClientUIInterface::MessageBoxFlags * This needs to be updated, when buttons are changed there! */ BTN_MASK = (BTN_OK | BTN_YES | BTN_NO | BTN_ABORT | BTN_RETRY | BTN_IGNORE | BTN_CLOSE | BTN_CANCEL | BTN_DISCARD | BTN_HELP | BTN_APPLY | BTN_RESET), /** Force blocking, modal message box dialog (not just OS notification) */ MODAL = 0x10000000U, /** Do not print contents of message to debug log */ SECURE = 0x40000000U, /** Predefined combinations for certain default usage cases */ MSG_INFORMATION = ICON_INFORMATION, MSG_WARNING = (ICON_WARNING | BTN_OK | MODAL), MSG_ERROR = (ICON_ERROR | BTN_OK | MODAL) }; /** Show message box. */ boost::signals2::signal<bool (const std::string& message, const std::string& caption, unsigned int style), boost::signals2::last_value<bool> > ThreadSafeMessageBox; /** If possible, ask the user a question. If not, falls back to ThreadSafeMessageBox(noninteractive_message, caption, style) and returns false. */ boost::signals2::signal<bool (const std::string& message, const std::string& noninteractive_message, const std::string& caption, unsigned int style), boost::signals2::last_value<bool> > ThreadSafeQuestion; /** Progress message during initialization. */ boost::signals2::signal<void (const std::string &message)> InitMessage; /** Number of network connections changed. */ boost::signals2::signal<void (int newNumConnections)> NotifyNumConnectionsChanged; /** Network activity state changed. */ boost::signals2::signal<void (bool networkActive)> NotifyNetworkActiveChanged; /** * New, updated or cancelled alert. * @note called with lock cs_mapAlerts held. */ boost::signals2::signal<void (const uint256 &hash, ChangeType status)> NotifyAlertChanged; /** A wallet has been loaded. */ boost::signals2::signal<void (CWallet* wallet)> LoadWallet; /** Show progress e.g. for verifychain */ boost::signals2::signal<void (const std::string &title, int nProgress, bool resume_possible)> ShowProgress; // /** New block has been accepted */ // boost::signals2::signal<void (const uint256& hash)> NotifyBlockTip; /** New block has been accepted */ boost::signals2::signal<void (bool, const CBlockIndex *)> NotifyBlockTip; // /** Best header has changed */ boost::signals2::signal<void (bool, const CBlockIndex *)> NotifyHeaderTip; /** Banlist did change. */ boost::signals2::signal<void (void)> BannedListChanged; }; extern CClientUIInterface uiInterface; #endif // KOMODO_UI_INTERFACE_H
[ "ip_gpu@mail.ru" ]
ip_gpu@mail.ru
4d2d8ec6ad04c3fa9e46eb7e6ae96b9dd5679f38
0f3cd546c1f60b1a47d045c9cbc6ab005d039aa9
/mfcddraw/mfcddrawDlg.cpp
31d1243f620a26ce2cfb4acff0b6da5c152a8f3e
[]
no_license
isliulin/legacy-vc6
62ea49025c519227af6cf73e5a4d1cc451568eb0
5d16f6e0bd71e3dff474cc2394263482c014ae56
refs/heads/master
2023-07-07T20:55:51.067797
2015-12-17T21:30:53
2015-12-17T21:30:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,407
cpp
// mfcddrawDlg.cpp : Implementierungsdatei // #include "stdafx.h" #include "mfcddraw.h" #include "mfcddrawDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialogfelddaten //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL // Implementierung protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // Keine Nachrichten-Handler //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMfcddrawDlg Dialogfeld CMfcddrawDlg::CMfcddrawDlg(CWnd* pParent /*=NULL*/) : CDialog(CMfcddrawDlg::IDD, pParent) { //{{AFX_DATA_INIT(CMfcddrawDlg) m_reflect = -1; m_amp = 0; m_speed = 0; m_hz = 0.0f; //}}AFX_DATA_INIT m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMfcddrawDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMfcddrawDlg) DDX_Radio(pDX, IDC_NOREF, m_reflect); DDX_Text(pDX, IDC_AMP, m_amp); DDV_MinMaxInt(pDX, m_amp, 1, 1000); DDX_Text(pDX, IDC_SPEED, m_speed); DDV_MinMaxInt(pDX, m_speed, 10, 10000); DDX_Text(pDX, IDC_HZ, m_hz); DDV_MinMaxFloat(pDX, m_hz, 1.e-004f, 100.f); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMfcddrawDlg, CDialog) //{{AFX_MSG_MAP(CMfcddrawDlg) ON_WM_SYSCOMMAND() ON_WM_DESTROY() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_TIMER() ON_BN_CLICKED(IDC_NOREF, OnChange) ON_BN_CLICKED(IDC_OPENEND, OnChange) ON_BN_CLICKED(IDC_FIXEDEND, OnChange) //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CMfcddrawDlg::OnInitDialog() { CDialog::OnInitDialog(); ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } SetIcon(m_hIcon, TRUE); SetIcon(m_hIcon, FALSE); ddraw.Create(140,10,640,480,this); SetTimer(1,25,NULL); m_reflect=0; m_hz=1; m_amp=100; m_speed=100; UpdateData(FALSE); CString str; str.Format("%f",m_hz); GetDlgItem(IDC_HZ)->SetWindowText(str); OnOK(); return TRUE; } void CMfcddrawDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } void CMfcddrawDlg::OnDestroy() { KillTimer(1); WinHelp(0L, HELP_QUIT); CDialog::OnDestroy(); } void CMfcddrawDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Symbol in Client-Rechteck zentrieren int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Symbol zeichnen dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } HCURSOR CMfcddrawDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } VOID CMfcddrawDlg::Update() { DWORD time=timeGetTime(); static DWORD lasttime=timeGetTime(); DWORD dTime=time-lasttime; ddraw.Update((float)dTime/1000); lasttime=time; } void CMfcddrawDlg::OnTimer(UINT nIDEvent) { CDialog::OnTimer(nIDEvent); Update(); } void CMfcddrawDlg::OnOK() { UpdateData(); m_hz=fabs(m_hz); if(m_hz==0)m_hz=1; if(m_hz>100)m_hz=100; m_speed=fabs(m_speed); ((CWaveGenerator*)ddraw.lpGenerator)->fFrequence=(float)m_hz; ((CWaveGenerator*)ddraw.lpGenerator)->fAmp=(float)m_amp; ddraw.fSpeed=(float)m_speed; UpdateData(FALSE); } void CMfcddrawDlg::OnChange() { UpdateData(); switch(m_reflect) { case 0: ddraw.bReflect=FALSE; break; case 1: ddraw.bReflect=TRUE; ddraw.bFixedEnd=FALSE; break; case 2: ddraw.bReflect=TRUE; ddraw.bFixedEnd=TRUE; break; } }
[ "sebastian.kotulla@gmx.de" ]
sebastian.kotulla@gmx.de
d33fa25526d0ef059024155630d2fc41dc9b151c
107dd749c9886d781894e5238d9c2419f7952649
/src/qt/transactionfilterproxy.cpp
58a316defb61a2eadda264cd037f9c17c8108144
[ "MIT" ]
permissive
Coin4Trade/Coin4Trade
ae58e76e09ed5a0cb62def5b91efd848cd77a284
fb5c4b7580212cd7e3daacd93fabf1be4d20ff7c
refs/heads/master
2023-08-23T22:42:33.681882
2021-10-02T20:58:21
2021-10-02T20:58:21
281,785,399
1
0
null
null
null
null
UTF-8
C++
false
false
3,991
cpp
// Copyright (c) 2011-2013 The Bitcoin developers // Copyright (c) 2017 The PIVX developers // Copyright (c) 2020 The C4T developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactionfilterproxy.h" #include "transactionrecord.h" #include "transactiontablemodel.h" #include <cstdlib> #include <QDateTime> // Earliest date that can be represented (far in the past) const QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0); // Last date that can be represented (far in the future) const QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF); TransactionFilterProxy::TransactionFilterProxy(QObject* parent) : QSortFilterProxyModel(parent), dateFrom(MIN_DATE), dateTo(MAX_DATE), addrPrefix(), typeFilter(COMMON_TYPES), watchOnlyFilter(WatchOnlyFilter_All), minAmount(0), limitRows(-1), showInactive(true) { } bool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); int type = index.data(TransactionTableModel::TypeRole).toInt(); QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime(); bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool(); QString address = index.data(TransactionTableModel::AddressRole).toString(); QString label = index.data(TransactionTableModel::LabelRole).toString(); qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong()); int status = index.data(TransactionTableModel::StatusRole).toInt(); if (!showInactive && status == TransactionStatus::Conflicted) return false; if (!(TYPE(type) & typeFilter)) return false; if (involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_No) return false; if (!involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_Yes) return false; if (datetime < dateFrom || datetime > dateTo) return false; if (!address.contains(addrPrefix, Qt::CaseInsensitive) && !label.contains(addrPrefix, Qt::CaseInsensitive)) return false; if (amount < minAmount) return false; return true; } void TransactionFilterProxy::setDateRange(const QDateTime& from, const QDateTime& to) { this->dateFrom = from; this->dateTo = to; invalidateFilter(); } void TransactionFilterProxy::setAddressPrefix(const QString& addrPrefix) { this->addrPrefix = addrPrefix; invalidateFilter(); } void TransactionFilterProxy::setTypeFilter(quint32 modes) { this->typeFilter = modes; invalidateFilter(); } void TransactionFilterProxy::setMinAmount(const CAmount& minimum) { this->minAmount = minimum; invalidateFilter(); } void TransactionFilterProxy::setWatchOnlyFilter(WatchOnlyFilter filter) { this->watchOnlyFilter = filter; invalidateFilter(); } void TransactionFilterProxy::setLimit(int limit) { this->limitRows = limit; } void TransactionFilterProxy::setShowInactive(bool showInactive) { this->showInactive = showInactive; invalidateFilter(); } int TransactionFilterProxy::rowCount(const QModelIndex& parent) const { if (limitRows != -1) { return std::min(QSortFilterProxyModel::rowCount(parent), limitRows); } else { return QSortFilterProxyModel::rowCount(parent); } }
[ "68502813+Coin4Trade@users.noreply.github.com" ]
68502813+Coin4Trade@users.noreply.github.com
5867e7c05c8c3a5051e2f495b762267d22ce7ba8
085bd798c39346feb10c6bc06fc4456c5bfd9cad
/include/kernel/assembly.hpp
d37ca11f81514911d8fbbbb98562e46c2711edd2
[ "MIT" ]
permissive
GenuineAster/Asterix
a718dd856783bf99178c7e34a3a3aa3cba5ac5e0
31935b321a82963a61d23afba1bbb70e226373f1
refs/heads/master
2021-10-11T08:05:09.506136
2014-05-17T21:56:29
2014-05-17T21:56:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
299
hpp
#pragma once extern "C" { void set_cr0(uint32_t cr0); uint32_t get_cr0(); void set_cr1(uint32_t cr1); uint32_t get_cr1(); void set_cr2(uint32_t cr2); uint32_t get_cr2(); void set_cr3(uint32_t cr3); uint32_t get_cr3(); void set_cr4(uint32_t cr4); uint32_t get_cr4(); uint64_t get_rsi(); }
[ "mischa@destrock.com" ]
mischa@destrock.com
4bdd0ecbdc4cac35417c4450c2e3c43f39cda3d4
f834a91fd9fa445a3c7f3c26a7b09cc0e348b552
/src/HKNetworkMessage.cpp
df536156f994db4a57024bd1fa40d2bd7e9cbe9a
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
DanielO/Particle-HAP
90fdd33a1e79f207b820aef736f8b66935972a65
3c62f214660cf2383c8fdf5533171f7286a63bde
refs/heads/master
2020-08-14T15:48:32.956847
2019-10-18T05:35:57
2019-10-18T05:35:57
215,193,671
0
0
MIT
2019-10-15T03:03:16
2019-10-15T03:03:16
null
UTF-8
C++
false
false
1,745
cpp
#include "HKNetworkMessage.h" #include "HKStringUtils.h" HKNetworkMessage::HKNetworkMessage(const char *rawData) { strcpy(method, "POST"); const char *ptr = rawData; for (int i = 0; (*ptr)!=0 && (*ptr)!=' '; ptr++, i++) { method[i] = (*ptr); method[i+1] = 0; } ptr+=2; //Copy message directory for (int i = 0; (*ptr)!=0 && (*ptr)!=' '; ptr++, i++) { directory[i] = (*ptr); directory[i+1] = 0; } ptr = skipTillChar(ptr, '\n'); char buffer[1024]; const char *dptr = ptr; for (int i = 0; i < 19; i++) { bzero(buffer, 1024); dptr = copyLine(dptr, buffer); } //Reject host if (strncmp(ptr, "Host", 4) == 0) { ptr = skipTillChar(ptr, '\n'); } //Get the length of content //Skip to the content-type ptr = skipTillChar(ptr, ':'); ptr++; unsigned int dataSize = (unsigned int)strtol(ptr, (char **)&ptr, 10); //Get the type of content //Skip to the content-length ptr = skipTillChar(ptr, ':'); ptr+=2; for (int i = 0; (*ptr)!=0 && (*ptr)!='\r'; ptr++, i++) { type[i] = (*ptr); type[i+1] = 0; } ptr+=4; //Data data = HKNetworkMessageData(ptr, dataSize); } void HKNetworkMessage::getBinaryPtr(char **buffer, int *contentLength) { const char *_data; unsigned short dataSize; data.rawData(&_data, &dataSize); (*buffer) = new char[1024]; (*contentLength) = snprintf((*buffer), 1024, "%s /%s HTTP/1.1\r\nContent-Length: %hu\r\n\Content-Type: %s\r\n\r\n", method, directory, dataSize, type); for (int i = 0; i < dataSize; i++) { (*buffer)[*contentLength+i] = _data[i]; } (*contentLength)+=dataSize; (*buffer)[*contentLength] = 0; }
[ "ljezny@gmail.com" ]
ljezny@gmail.com
b4bcc96df8f41ad176e1a88195b2529d011175c0
828390fe5c5c5ac723eaa7c5854f94ad3328ee7a
/PlatformIO/lib/myPowerMonitor/EmonLibPro.h
67e5de2fd008f77e48154348e9efde4320430e71
[]
no_license
Ulli2k/HomeControl
64f58a1cd1978a0c5e1b51d0d58b13785a7c0759
767b1e6700ed48bb8bafac450952f7b2e018053b
refs/heads/master
2021-06-22T01:50:15.473632
2019-07-07T19:16:30
2019-07-07T19:16:30
110,287,523
0
0
null
null
null
null
UTF-8
C++
false
false
14,337
h
/* Energy monitor Library Pro Based on emonTx hardware from OpenEnergyMonitor http://openenergymonitor.org/emon/ This is a generic library for any voltage and current sensors. Interrupt based, implements a zero cross detector and phase-locked loop for better precision. Reports Voltage, Frequency, Current, Active Power, Aparent Power and Power Factor. Completely line frequency independent. This library idea cames from ATMEL AVR465: Single-Phase Power/Energy Meter. Get latest version at https://github.com/chaveiro/EmonLibPro Copyright (C) 2013-2015 Nuno Chaveiro nchaveiro[at]gmail.com Lisbon, Portugal This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. History: 1.0 - 25-05-2013 - First public release. 1.1 - 02-06-2013 - Added suport for ADC pin MAP and revised freq calculations an timer1 fix. 1.2 - 07-06-2013 - Speed up ISR routine a little. (Now 120 adc samples/sec for 3 sensors.) 1.3 - 10-06-2013 - Speed up ISR by offloading freq calculation from ISR to user code. 1.4 - 14-06-2013 - Speed up ISR by doing HPF calculation in integer math. 1.5 - 20-06-2013 - Added CycleWaveVisualizer.html, a graph viewer in realtime on browser via ethernet. 2.0 - 21-02-2015 - Changed ADC Triger from Timer1 A comparator to Timer1 B comparator with ADC auto trigger activated. Less gitter. Improved line frequency calculation. Added auto sample rate detection. Works for any line frequency at max attainable sample rate. */ #ifndef boolean #define boolean uint8_t #endif #ifndef byte #define byte uint8_t #endif #ifndef absolute #define absolute(x) ((x)>0?(x):-(x)) #endif #ifndef EmonLibPro_H #define EmonLibPro_H #define EMONLIBPROVERSION "2.0Pro" //-------------------------------------------------------------------------------------------------- // User configurable Section //-------------------------------------------------------------------------------------------------- #if defined(HAS_POWER_MONITOR_CT) //Ulli #include "EmonLibPro_config.h" #else #define VOLTSCOUNT 0 // Number of V sensors installed, can be 0 or 1, multiple voltage sensors are not supported this time #define CURRENTCOUNT 3 // Number of CT sensors installed can be 1 to 3. #define CONSTVOLTAGE 220 // Only used if VOLTSCOUNT = 0 - Voltage RMS fixed value #define CONSTFREQ 50 // Only used if VOLTSCOUNT = 0 - Line frequency fixed value //#define V1CAL 245.23 // Gain for Voltage1 calculated value is 243:10.9 (for transformer) x 11:1 (for resistor divider) = 122.61 #define V1CAL 267.53 // Gain for Voltage1 calculated value is 243:10.9 (for transformer) x 12:1 (for resistor divider) = 122.61 #define I1CAL 13.333 // Gain for CT1 calculated value is 20A:0.02A (for CT spirals) / 100 Ohms (for burden resistor) = 10 #define I2CAL 13.333 // Gain for CT2 100:0.05 / 150 Ohm = 13,333 #define I3CAL 13.333 // Gain for CT3 //#define AUTOSAMPLERATE // ADC sample rate is auto tracked for max sample rate. Requires a voltage sensor. //#define USEPLL // PLL is active to track zero crosses as close to 0vac as possible. (not recommended as induces gitter on Hz calculation when pll is unlocked) #define DIAG // Will populate CycleArray with one cycle data for diagnostics // Only used if not using AUTOSAMPLERATE // Samples per second (one sample unit includes all sensors) //#define SAMPLESPSEC 1250 // Samples per second (50Hz ok) //#define SAMPLESPSEC 1600 // Samples per second (50Hz ok) #define SAMPLESPSEC 2000 // Samples per second (50Hz ok) (for 3 CT, 1 volt sensors) //#define SAMPLESPSEC 2500 // Samples per second (50Hz ok) //#define SAMPLESPSEC 3200 // Samples per second (50Hz ok) (for 2 CT, 0 Voltage sensors) //#define SAMPLESPSEC 4000 // Samples per second (50Hz ok) (for 1 CT, 1 Voltage sensors) //#define SAMPLESPSEC 5000 // 250khz adc Samples per second (for 2 CT, 0 Voltage sensors) //#define SAMPLESPSEC 6400 // Samples per second (50Hz ok) (for 1 CT, 0 Voltage sensors) #define CALCULATECYCLES 50 * 5 // Number of line cycles to activate FlagCALC_READY (50cycles x 5 = 5 secs) #define SUPPLY_VOLTS 3.306 //4.95 // used here because it's more accurate than the internal band-gap reference //-------------------------------------------------------------------------------------------------- // Hardware Configuration Variables //-------------------------------------------------------------------------------------------------- //ADC sampling pin order map. First values must be Voltage, last Current. If no voltage sensors are used, don't put any pin number. //const byte adc_pin_order[] = {4,1,2,3,0,5}; const byte adc_pin_order[] = {0,1,2,3,4,5}; #endif //-------------------------------------------------------------------------------------------------- // Macro checks - Don't change //-------------------------------------------------------------------------------------------------- #if (VOLTSCOUNT == 0) #warning VOLTSCOUNT is 0, using only CT sensors #define VOLTSCOUNTVARS 1 #ifdef AUTOSAMPLERATE #error "AUTOSAMPLERATE cant be used with VOLTSCOUNT set to 0, must use a Voltage sensor for this." #endif #else #define VOLTSCOUNTVARS VOLTSCOUNT #endif //-------------------------------------------------------------------------------------------------- // Sensor Calibration Data Structure, change IRATIO/VRATIO if sensors count is changed. //-------------------------------------------------------------------------------------------------- const struct CalDataStructure { unsigned int PCC[VOLTSCOUNTVARS + CURRENTCOUNT]; float IRATIO[CURRENTCOUNT]; float VRATIO[VOLTSCOUNTVARS]; unsigned int MC, DPC; } static CalCoeff = { { 0 // 1st sensor Phase calibration angle offset - Range is 0 to 65535 #if VOLTSCOUNTVARS + CURRENTCOUNT >= 2 // {0,23576,47152,73728} ,20076 // 2st sensor - must set for each sensor (voltage and CTs) adc pin is the same as index order of adc_pin_order #endif #if VOLTSCOUNTVARS + CURRENTCOUNT >= 3 ,40152 // 3nd sensor #endif #if VOLTSCOUNTVARS + CURRENTCOUNT >= 4 ,60228 // 4rd sensor #endif }, { (I1CAL * SUPPLY_VOLTS)/1024 // 1st CT - current gain - must set a line for each I sensor same order as adc_pin_order #if CURRENTCOUNT >= 2 ,(I2CAL * SUPPLY_VOLTS)/1024 // 2nd CT #endif #if CURRENTCOUNT >= 3 ,(I3CAL * SUPPLY_VOLTS)/1024 // 3rd CT #endif }, { #if VOLTSCOUNT == 1 (V1CAL * SUPPLY_VOLTS)/1024 // voltage gain - must set a line for each V sensor #endif }, 10000, 100 // TBD }; //-------------------------------------------------------------------------------------------------- // Macro checks at compile time - Don't change //-------------------------------------------------------------------------------------------------- #ifndef F_CPU #error "F_CPU not defined" //# define F_CPU 16000000UL // 16 Mhz #endif #ifndef AUTOSAMPLERATE #if (!((SAMPLESPSEC % 50 == 0) && (F_CPU % SAMPLESPSEC == 0)) && (CONSTFREQ != 60)) #warning For 50Hz line, SAMPLESPSEC defined value must be divisible by 50 and multiple of F_CPU for better performance of PLL. #endif #if (!((SAMPLESPSEC % 60 == 0) && (F_CPU % SAMPLESPSEC == 0)) && (CONSTFREQ != 50)) #warning For 60Hz line, SAMPLESPSEC defined value must be divisible by 60 and multiple of F_CPU for better performance of PLL. #endif #endif //-------------------------------------------------------------------------------------------------- // Internal constants - No need to change //-------------------------------------------------------------------------------------------------- #define TIMERTOP F_CPU/SAMPLESPSEC // Sampling timer #define PLLTIMERDELAYCOEF TIMERTOP/V1CAL // PLL delay coefficient #ifdef AUTOSAMPLERATE #define CYCLEARRSIZE 192/(VOLTSCOUNT + CURRENTCOUNT) // Size of CycleArray for saving sample data if one cycle for debug #define TIMERSAFE 10000 // A value for timer increment that is know to be in close range #else #define CYCLEARRSIZE (SAMPLESPSEC/CONSTFREQ) // Size of CycleArray for saving sample data if one cycle for debug #endif //################################################################################################## // Don't modify below this line //################################################################################################## // Does not work, first adc read after sleep is garbage. //#define USE_ANALOG_COMP // Specifies the usage of analog comparator for zero cross check. Requires ADC0 voltage connected to analog comp. // If a lower resolution than 10 bits is needed, the input clock frequency to the ADC can be higher than 200kHz to get a higher sample rate. const byte adc_sra = (1UL<<ADEN) | // ADC Enable (1UL<<ADATE) | // ADC Auto Trigger Enable (1UL<<ADIF) | // ADC Interrupt Flag (1UL<<ADIE) | // ADC Interrupt Enable (1UL<<ADPS2) | // --- ADC Prescaler Select Bits /128 = 125kHz clock (1UL<<ADPS1) | // | (1UL<<ADPS0); // -- comment this line to change ADC prescaler to /64 = 250kHz clock (less precision) const byte adc_srb = //(1UL<<ACME) | // Analog Comparator Multiplexer Enable (1UL<<ADTS2) | // ADC Auto Trigger Source | Timer/Counter1 Compare Match B (1UL<<ADTS0); // | struct AccVoltageDataStructure { unsigned long U2; unsigned long PeriodDiff; }; struct AccPowerDataStructure { signed long P; unsigned long I2; }; struct TotVoltageDataStructure { unsigned long U2; unsigned long PeriodDiff; }; struct TotPowerDataStructure { signed long P; unsigned long I2; }; struct ResultVoltageDataStructure { float U,HZ; }; struct ResultPowerDataStructure { float I,P,S,F; }; struct SampleStructure { boolean FlagZeroDetec, WaitNextCross; unsigned int PreviousADC; signed long Filtered , PreviousFiltered; signed int Calibrated , PreviousCalibrated; unsigned int TimerVal , PreviousTimerVal; #ifdef DIAG signed int CycleArr[CYCLEARRSIZE]; #endif }; class EmonLibPro { public: EmonLibPro(void); //Constructor void begin(); void printStatus(); void calculateResult(); #ifdef DIAG static boolean FlagCYCLE_DIAG; // Flags cycle diagnostics data it to be gathered on next cycle #endif static boolean FlagCYCLE_FULL; // Flags a new cycle. static boolean FlagCALC_READY; // Flags new data to calculate static boolean FlagINVALID_DATA; // Flags Invalid data static boolean FlagOutOfTime; // Warn ISR routing did not complete before next timer #ifdef USEPLL static uint8_t pllUnlocked; // If = 0 pll is locked #endif #ifdef AUTOSAMPLERATE static unsigned int timeNextSample; // Used for AUTOSAMPLERATE mode to auto adjust sample interval #endif static uint8_t SamplesPerCycle; // --- Gives number of samples that got summed in summed Cycle Data Structure (ajusted/detected by soft pll for each AC cycle) static unsigned long SamplesPerCycleTotal; // --- Number of cycles added for all sums of Total Var. static unsigned int CyclesPerTotal; // --- Number of sums on Total var. static TotVoltageDataStructure TotalV[VOLTSCOUNTVARS]; // |- Total Vars (Sum of cycles until calculation) static TotPowerDataStructure TotalP[CURRENTCOUNT]; // -/ static ResultVoltageDataStructure ResultV[VOLTSCOUNTVARS]; // -\_ Result is here! static ResultPowerDataStructure ResultP[CURRENTCOUNT]; // -/ // ISR vars static uint8_t AdcId; // ADC PIN number of sensor measured static SampleStructure Sample[VOLTSCOUNT + CURRENTCOUNT]; //Data for last sample static AccVoltageDataStructure AccumulatorV[VOLTSCOUNTVARS]; // |- Sum of all samples (copyed to cycle var at end of cycle) static AccPowerDataStructure AccumulatorP[CURRENTCOUNT]; // -/ static signed int Temp[VOLTSCOUNT + CURRENTCOUNT]; // Internal Aux var private: }; #endif /* emonLibPro_H */
[ "14141949+Ulli2k@users.noreply.github.com" ]
14141949+Ulli2k@users.noreply.github.com
41f45cb43611b21ee0dc867d653e22d6c057206d
29f2549998b45a046930f3b1c5e3024791b1be16
/include/llvm/CompilerDriver/Plugin.h
9f9eee3c0db99b566b5ec5225a1d5aa830de8d91
[ "NCSA" ]
permissive
fanfuqiang/iec-61131_new
eda210bd30a6a32e3d14c3d3e87f51b179124c72
fde56fdefd60e33facaa07661e388ed6c916c763
refs/heads/master
2016-09-05T14:59:12.678870
2015-02-06T23:55:09
2015-02-06T23:55:09
30,048,552
2
0
null
null
null
null
UTF-8
C++
false
false
2,474
h
//===--- Plugin.h - The LLVM Compiler Driver --------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open // Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Plugin support for llvmc. // //===----------------------------------------------------------------------===// #ifndef LLVM_INCLUDE_COMPILER_DRIVER_PLUGIN_H #define LLVM_INCLUDE_COMPILER_DRIVER_PLUGIN_H #include "llvm/Support/Registry.h" namespace llvmc { class LanguageMap; class CompilationGraph; /// BasePlugin - An abstract base class for all LLVMC plugins. struct BasePlugin { /// Priority - Plugin priority, useful for handling dependencies /// between plugins. Plugins with lower priorities are loaded /// first. virtual int Priority() const { return 0; } /// PopulateLanguageMap - The auto-generated function that fills in /// the language map (map from file extensions to language names). virtual void PopulateLanguageMap(LanguageMap&) const = 0; /// PopulateCompilationGraph - The auto-generated function that /// populates the compilation graph with nodes and edges. virtual void PopulateCompilationGraph(CompilationGraph&) const = 0; /// Needed to avoid a compiler warning. virtual ~BasePlugin() {} }; typedef llvm::Registry<BasePlugin> PluginRegistry; template <class P> struct RegisterPlugin : public PluginRegistry::Add<P> { typedef PluginRegistry::Add<P> Base; RegisterPlugin(const char* Name = "Nameless", const char* Desc = "Auto-generated plugin") : Base(Name, Desc) {} }; /// PluginLoader - Helper class used by the main program for /// lifetime management. struct PluginLoader { PluginLoader(); ~PluginLoader(); /// PopulateLanguageMap - Fills in the language map by calling /// PopulateLanguageMap methods of all plugins. void PopulateLanguageMap(LanguageMap& langMap); /// PopulateCompilationGraph - Populates the compilation graph by /// calling PopulateCompilationGraph methods of all plugins. void PopulateCompilationGraph(CompilationGraph& tools); private: // noncopyable PluginLoader(const PluginLoader& other); const PluginLoader& operator=(const PluginLoader& other); }; } #endif // LLVM_INCLUDE_COMPILER_DRIVER_PLUGIN_H
[ "feqin1023@gmail.com" ]
feqin1023@gmail.com
5c39eba5989b87b36d11eda146907696d7841154
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/tlrmvnmvt/src/svd.cpp
08d2e089055ab3c64eb26123e219adb51cf0fba7
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
C++
false
false
1,720
cpp
#include <RcppEigen.h> #include <R_ext/Lapack.h> #include <R_ext/Print.h> #include "svd.h" using namespace std; using namespace Eigen; /* svd decomposition Decomposition is performed to a leading block of A of size ARowNum X AColNum work should be of dimension larger than 5 X min(ARowNum,AColNum) lwork is the dimension of work */ int svd(Eigen::MatrixXd &A , int ARowNum , int AColNum , Eigen::MatrixXd &U , Eigen::MatrixXd &VT , Eigen::VectorXd &S , double *work , int lwork) { int ldA = A.rows(); int rk = min(ARowNum , AColNum); if(U.rows() < ARowNum || U.cols() < rk) { Rprintf("Warning: the U factor in svd decomposition is resized. " "Increasing the allocation for U will improve performance\n"); U.resize(ARowNum , rk); } if(VT.rows() < rk || VT.cols() < AColNum) { Rprintf("Warning: the VT factor in svd decomposition is resized. " "Increasing the allocation for VT will improve " "performance\n"); VT.resize(rk , AColNum); } if(S.size() < rk) { Rprintf("Warning: the S factor in svd decomposition is resized. " "Increasing the allocation for S will improve performance\n"); S.resize(rk); } int ldU = U.rows(); int ldVT = VT.rows(); int fail; F77_CALL(dgesvd)("S" , "S" , &ARowNum , &AColNum , A.data() , &ldA , S.data() , U.data() , &ldU , VT.data() , &ldVT , work , &lwork , &fail); return fail; }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
4696032f14c2dba9b761d3861cfb7b28a5fc1022
fb2d77dbb104dcf1406319c8a310904d03b24204
/Practice/Level8/Exercises/5.1/Exercise 1/Exercise 1/Array.cpp
91985ef86e4b319921ac82080e2e90419a96a1a6
[]
no_license
mandeepsaikia/CPP-Programming-for-Financial-Engineering
536a45f86c6263527651e3b5272f5d8e97315a85
9338166b3bebf10775f65e5c272e68278eb3ad34
refs/heads/master
2022-10-27T07:13:23.092005
2022-09-27T19:52:07
2022-09-27T19:52:07
175,872,048
0
0
null
2019-03-15T18:26:58
2019-03-15T18:26:58
null
UTF-8
C++
false
false
3,606
cpp
// // Array.cpp // Exercise 1 // // Created by Changheng Chen on 2/9/17. // Copyright © 2017 Changheng Chen. All rights reserved. // #ifndef Array_CPP #define Array_CPP #include "SizeMismatchException.hpp" #include "OutOfBoundsException.hpp" #include "Array.hpp" #include <iostream> namespace chako { namespace Containers { // ================================================================= // Static default size of array template <typename T> int Array<T>::d_size = 12; // ================================================================= // Constructors, destructor, and assignment operator template <typename T> Array<T>::Array() : m_size(Array<T>::d_size), m_data(new T[Array<T>::d_size]) { // Default constructor //cout << "Array default constructor..." << endl; } template <typename T> Array<T>::Array(int size) : m_size(size), m_data(new T[size]) { // Constructor with size //cout << "Array constructor with size..." << endl; } template <typename T> Array<T>::Array(const Array<T>& source) : m_size(source.m_size), m_data(new T[source.m_size]) { // Copy constructor for (int i = 0; i < m_size; i++) m_data[i] = source.m_data[i]; //cout << "Array copy constructor..." << endl; } template <typename T> Array<T>::~Array() { // Destructor delete [] m_data; cout << "By my array..." << endl; } template <typename T> Array<T>& Array<T>::operator = (const Array<T>& source) { // Assignment operator if (this == &source) return *this; delete [] m_data; m_size = source.m_size; m_data = new T[m_size]; for (int i = 0; i < m_size; i++) m_data[i] = source.m_data[i]; return *this; } // ================================================================= // Getter functions template <typename T> int Array<T>::Size() const { return m_size; } template <typename T> int Array<T>::DefaultSize() const { return d_size; } template <typename T> T& Array<T>::GetElement(int index) const { if (index >= m_size || index < 0) throw OutOfBoundsException(index); return m_data[index]; } // Setter function template <typename T> void Array<T>::DefaultSize(int size) { d_size = size; } template <typename T> void Array<T>::SetElement(int index, const T& p) { if (index >= m_size || index < 0) throw OutOfBoundsException(index); m_data[index] = p; } // Operator overloading template <typename T> T& Array<T>::operator [] (int index) { if (index >= m_size || index < 0) throw OutOfBoundsException(index); return m_data[index]; } template <typename T> const T& Array<T>::operator [] (int index) const { if (index >= m_size || index < 0) throw OutOfBoundsException(index); return m_data[index]; } } } #endif
[ "chiongheng.chen@gmail.com" ]
chiongheng.chen@gmail.com
9b30fba793f2a44cb80abf7689949ab73a64d44c
6b9cab39e61c5e2ec156a7312b62ce60bf301396
/Trees and Graphs/binaryTree.cpp
bbd9b3316f2854c4514dc8cac672a70c8c7f1579
[]
no_license
HItzz07/VsCode-CP
4ed21ff4a25f99a3af0573fdf8676dac5e21d9b1
e75eab0fd4994ee1aac3e9eec7fad6a25e6a91ad
refs/heads/master
2023-02-16T19:33:13.744202
2020-06-13T01:59:49
2020-06-13T01:59:49
271,918,831
0
0
null
null
null
null
UTF-8
C++
false
false
1,576
cpp
#include<bits/stdc++.h> using namespace std; #define COUNT 10 class Node{ public: int data; Node *left,*right; }; Node* newNode(int d){ Node *node = new Node; node->data=d; node->left=NULL; node->right=NULL; return (node); }; void displayPreorder(Node *root){ if(root==NULL) return; cout<<root->data<<" "; displayPreorder(root->left); displayPreorder(root->right); } void displayInorder(Node *root){ if(root==NULL) return; displayInorder(root->left); cout<<root->data<<" "; displayInorder(root->right); } void displayPostorder(Node *root){ if(root==NULL) return; displayPostorder(root->left); displayPostorder(root->right); cout<<root->data<<" "; } //Main Working Function to display tree in 2D; void printTree(Node *root , int space){ if(root==NULL) return; space+=COUNT; printTree(root->right,space); cout<<endl; for(int i=0;i<space;i++){ cout<<" "; } cout<<root->data<<endl; printTree(root->left,space); } //Function to display tree in 2D void display(Node *root){ printTree(root,0); } int main(){ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); display(root); cout<<endl; displayPreorder(root); cout<<endl; displayInorder(root); cout<<endl; displayPostorder(root); return 0; }
[ "noreply@github.com" ]
noreply@github.com
ded27c1741c223f079092bad0e22553519a1fb36
60e284d357878ec65ca4527c182d95defac18d13
/io/OutputStream.cpp
ff02698c7bd24e9f0885f26ed7f5dabd56fcb4a7
[]
no_license
keyguansz/Obotcha
ee2198bc403e6d7ae76dbb5f0c758f35f0a4d0ad
c0cc39294d90abc9d7b92f79970bf4de573f70c8
refs/heads/master
2020-05-13T03:28:25.797363
2019-04-09T14:25:30
2019-04-09T14:25:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
355
cpp
#include "OutputStream.hpp" namespace obotcha { bool _OutputStream::write(char c) { //TODO return false; } bool _OutputStream::write(char *buffer,int size) { //TODO return false; } bool _OutputStream::open() { //TODO return false; } void _OutputStream::close() { //TODO } void _OutputStream::flush() { //TODO } }
[ "wang_sun_1983@yahoo.co.jp" ]
wang_sun_1983@yahoo.co.jp
320df62c90ada4687d4bbf888aa371e76d11c838
18de2e600c01c29bb83d0714923a4d8583e36bed
/flashlight/app/asr/augmentation/AdditiveNoise.h
fef039adf5e6bb4c08f5e063676942e7ee90783d
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mega-cqz/flashlight
5f5350ebf0f2596120405a902f08ded1e85c65c8
3d7bff540722b3a2e60ff89763134be579ef0b94
refs/heads/master
2023-02-17T02:06:49.003993
2021-01-16T19:58:57
2021-01-16T20:00:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,238
h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include "flashlight/app/asr/augmentation/SoundEffect.h" #include <random> #include <string> #include <vector> #include "flashlight/app/asr/augmentation/SoundEffectUtil.h" namespace fl { namespace app { namespace asr { namespace sfx { /** * The additive noise sound effect loads noise files and augments them to the * signal with hyper parameters that are chosen randomly within a configured * range, including: * - number of noise clips that are augmented on the input. * - noise shift. The noise clip is shifted with a random value. This means that * we choose a random index of the noise and start there when adding it to * input. We tile the noise to cover the augmentation interval if it is too * short to do so. * - augmentation interval location. When ratio < 1, an interval of that ratio * of the input is augmented. * - SNR: the noise is added with random SNR. In order to minimize change to the * input we use the following formula. output = input + noise * * rms(signal)/rms(noise) / snrDB. rms(signal) is calculated only on the * augmented interval. rms(noise) is calculated on the sum of all noise clipse * over the augmented interval. */ class AdditiveNoise : public SoundEffect { public: struct Config { /** * probability of aapplying reverb. */ float proba_ = 1.0; double ratio_ = 1.0; double minSnr_ = 0; double maxSnr_ = 30; int nClipsMin_ = 1; int nClipsMax_ = 3; std::string listFilePath_; unsigned int randomSeed_ = std::mt19937::default_seed; RandomPolicy dsetRndPolicy_; std::string prettyString() const; }; explicit AdditiveNoise(const AdditiveNoise::Config& config); ~AdditiveNoise() override = default; void apply(std::vector<float>& signal) override; std::string prettyString() const override; private: const AdditiveNoise::Config conf_; RandomNumberGenerator rng_; std::unique_ptr<ListRandomizer<std::string>> ListRandomizer_; }; } // namespace sfx } // namespace asr } // namespace app } // namespace fl
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
1ebb5100726e2b5ec45640b48811884c62ba5ba1
efa458412aa27e4f7c37eb4ad24bc04376f5e3e9
/Lib/MPM/Force/MpmForceBase.cpp
0e6cd410f2a2c5595fd1e50677b9ae4abef46df7
[ "MIT" ]
permissive
Remotion/HOT
27e28f020bc6977f562e714ad6e469e143bd6f23
d8d57be410ed343c3fb37af6020cf5e14a0d1bec
refs/heads/master
2022-04-25T06:39:06.228059
2020-04-25T19:24:21
2020-04-25T19:24:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,800
cpp
#include "MpmForceBase.h" #include <Ziran/CS/Util/AttributeNamesForward.h> #include <Ziran/CS/Util/Timer.h> #include <Ziran/Math/Geometry/Elements.h> #include <Ziran/Math/Geometry/Particles.h> #include <Ziran/Physics/LagrangianForce/LagrangianForce.h> #include <Ziran/Sim/Scene.h> namespace ZIRAN { template <class T, int dim> MpmForceBase<T, dim>::MpmForceBase(const bool& mls_mpm, const T& dx, const T& dt, Particles<T, dim>& particles, Scene<T, dim>& scene, StdVector<TV>& scratch_xp, TVStack& scratch_vp, TVStack& scratch_fp, StdVector<TM>& scratch_gradV, StdVector<TM>& scratch_stress, const TVStack& dv, const TVStack& vn, MpmGrid<T, dim>& grid, StdVector<uint64_t>& particle_base_offset, StdVector<int>& particle_order, std::vector<std::pair<int, int>>& particle_group, std::vector<uint64_t>& block_offset, int& num_nodes, StdVector<std::unique_ptr<PlasticityApplierBase>>& plasticity_appliers, bool& full_implicit) : mls_mpm(mls_mpm) , D_inverse(0) , dx(dx) , dt(dt) , dv(dv) , vn(vn) , particles(particles) , scene(scene) , scratch_xp(scratch_xp) , scratch_vp(scratch_vp) , scratch_fp(scratch_fp) , scratch_gradV(scratch_gradV) , scratch_stress(scratch_stress) , grid(grid) , particle_base_offset(particle_base_offset) , particle_order(particle_order) , particle_group(particle_group) , block_offset(block_offset) , num_nodes(num_nodes) , plasticity_appliers(plasticity_appliers) , full_implicit(full_implicit) { } template <class T, int dim> MpmForceBase<T, dim>::~MpmForceBase() { } template <class T, int dim> void MpmForceBase<T, dim>::reinitialize() { if (mls_mpm && D_inverse == 0) { T dx2 = dx * dx; if (interpolation_degree == 2) D_inverse = 4 / dx2; else if (interpolation_degree == 3) D_inverse = 3 / dx2; else ZIRAN_ASSERT(false); } for (auto& h : helpers) h->reinitialize(); } template <class T, int dim> void MpmForceBase<T, dim>::backupStrain() { ZIRAN_QUIET_TIMER(); for (auto& h : helpers) h->backupStrain(); } template <class T, int dim> void MpmForceBase<T, dim>::restoreStrain() { ZIRAN_QUIET_TIMER(); for (auto& h : helpers) h->restoreStrain(); } template <class T, int dim> void MpmForceBase<T, dim>::computeVAndGradV() { ZIRAN_QUIET_TIMER(); evalInterpolantAndGradient([&](int node_id) -> TV { return vn.col(node_id) + dv.col(node_id); }, scratch_vp, scratch_gradV); } template <class T, int dim> void MpmForceBase<T, dim>::computeDvAndGradDv(const TVStack& dv) const { ZIRAN_QUIET_TIMER(); evalInterpolantAndGradient([&](int node_id) -> TV { return dv.col(node_id); }, scratch_vp, scratch_gradV); } template <class T, int dim> template <bool USE_MLS_MPM> void MpmForceBase<T, dim>::rasterizeForceToTVStack(const T scale, TVStack& force) const { ZIRAN_QUIET_TIMER(); grid.iterateGrid([&](IV node, GridState<T, dim>& g) { g.new_v = TV::Zero(); }); auto& Xarray = particles.X.array; { for (uint64_t color = 0; color < (1 << dim); ++color) { tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) { if ((block_offset[group_idx] & ((1 << dim) - 1)) != color) return; for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) { int i = particle_order[idx]; TV& Xp = Xarray[i]; TM4 stress_density = TM4::Zero(); TM& stress = scratch_stress[i]; stress_density.template topLeftCorner<dim, dim>() = stress; // stress density const TV& fp = scratch_fp.col(i); stress_density.template topRightCorner<dim, 1>() = -fp; // fp (for meshed forces). BSplineWeights<T, dim> spline(Xp, dx); grid.iterateKernel(spline, particle_base_offset[i], [&](const IV& node, T w, const TV& dw, GridState<T, dim>& g) { TV4 weight = TV4::Zero(); weight.template topLeftCorner<dim, 1>() = dw; weight(3) = w; if constexpr (USE_MLS_MPM) { TV4 xi_minus_xp = TV4::Zero(); xi_minus_xp.template topLeftCorner<dim, 1>() = node.template cast<T>() * dx - Xp; // top dim entries non-zero xi_minus_xp(3) = 1; TV4 delta = ((stress_density * xi_minus_xp) * (w * D_inverse)); g.new_v -= scale * delta.template topLeftCorner<dim, 1>(); // fi -= \sum_p (Ap (xi-xp) - fp )w_ip Dp_inv } else { TV4 delta = (stress_density * weight); g.new_v -= scale * delta.template topLeftCorner<dim, 1>(); } }); } }); } } grid.iterateGrid([&](IV node, GridState<T, dim>& g) { force.col(g.idx) += g.new_v; }); } template <class T, int dim> void MpmForceBase<T, dim>::updateParticleState() { ZIRAN_QUIET_TIMER(); // zero out scratch_fp and scratch_stress, prepare for adding lagrangian force tbb::parallel_for(tbb::blocked_range<size_t>(0, particles.count), [&](const tbb::blocked_range<size_t>& range) { for (size_t b = range.begin(), b_end = range.end(); b < b_end; ++b) { scratch_fp.col(b) = TV::Zero(); scratch_stress[b] = TM::Zero(); } }); // Lagrangian for (auto& lf : scene.forces) lf->updatePositionBasedState(); auto& vtau = scratch_stress; auto& fp = scratch_fp; auto ranges = particles.X.ranges; tbb::parallel_for(ranges, [&](DisjointRanges& subrange) { for (auto& h : helpers) h->updateState(subrange, vtau, fp); // this adds to vtau and fp }); // Lagrangian scene.addScaledForces(1, fp); // add forces to fp } template <class T, int dim> void MpmForceBase<T, dim>::updateParticleImplicitState() { ZIRAN_QUIET_TIMER(); // zero out scratch_fp and scratch_stress, prepare for adding lagrangian force tbb::parallel_for(tbb::blocked_range<size_t>(0, particles.count), [&](const tbb::blocked_range<size_t>& range) { for (size_t b = range.begin(), b_end = range.end(); b < b_end; ++b) { scratch_fp.col(b) = TV::Zero(); scratch_stress[b] = TM::Zero(); } }); // Lagrangian for (auto& lf : scene.forces) lf->updatePositionBasedState(scratch_xp); auto& vPFnT = scratch_stress; auto& fp = scratch_fp; auto ranges = particles.X.ranges; tbb::parallel_for(ranges, [&](DisjointRanges& subrange) { for (auto& h : helpers) h->updateImplicitState(subrange, vPFnT, fp); // this adds to vPFnT and fp }); // Lagrangian scene.addScaledForces(1, fp); // add forces to fp } /** Compute for a vector function f defined on active grid nodes, compute f and grad f on particles */ template <class T, int dim> template <class Func> void MpmForceBase<T, dim>::evalInterpolantAndGradient(Func&& f, TVStack& f_eval, StdVector<TM>& grad_f) const { grid.iterateTouchedGrid([&](IV node, GridState<T, dim>& g) { g.new_v = TV::Zero(); }); grid.iterateGrid([&](IV node, GridState<T, dim>& g) { g.new_v = f((int)g.idx); }); { for (uint64_t color = 0; color < (1 << dim); ++color) { tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) { if ((block_offset[group_idx] & ((1 << dim) - 1)) != color) return; for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) { int i = particle_order[idx]; TM& grad_fp = grad_f[i]; // if (grad_fp != grad_fp) // continue; TV& Xp = particles.X[i]; BSplineWeights<T, dim> spline(Xp, dx); grad_fp = TM::Zero(); f_eval.col(i) = TV::Zero(); grid.iterateKernel(spline, particle_base_offset[i], [&](const IV& node, T w, const TV& dw, GridState<T, dim>& g) { grad_fp.noalias() += g.new_v * dw.transpose(); f_eval.col(i) += g.new_v * w; }); } }); } } } template <class T, int dim> void MpmForceBase<T, dim>::addScaledForces(const T scale, TVStack& forces) const { ZIRAN_QUIET_TIMER(); if (mls_mpm) { rasterizeForceToTVStack<true>(scale, forces); } else { rasterizeForceToTVStack<false>(scale, forces); } } template <class T, int dim> void MpmForceBase<T, dim>::addScaledForceDifferential(const T scale, const TVStack& dv, TVStack& df) const { ZIRAN_QUIET_TIMER(); computeDvAndGradDv(dv); // Compute per element dF for (auto& lf : scene.forces) lf->updatePositionDifferentialBasedState(scratch_vp); // scratch_gradV is now temporaraly used for storing gradDV (evaluated at particles) // scratch_vp is now temporaraly used for storing DV (evaluated at particles) // zero out scratch_fp and scratch_stress, prepare for adding lagrangian force differentials tbb::parallel_for(tbb::blocked_range<size_t>(0, particles.count), [&](const tbb::blocked_range<size_t>& range) { for (size_t b = range.begin(), b_end = range.end(); b < b_end; ++b) { scratch_fp.col(b) = TV::Zero(); scratch_stress[b] = TM::Zero(); } }); auto ranges = particles.X.ranges; tbb::parallel_for(ranges, [&](DisjointRanges& subrange) { for (auto& h : helpers) { if (full_implicit) { ZIRAN_ASSERT(false, "full implicit stress differential with plasticity not implemented"); } else { h->computeStressDifferential(subrange, scratch_gradV, scratch_stress, scratch_vp, scratch_fp); } } // scratch_stress is now V_p^0 dP (F_p^n)^T (dP is Ap in snow paper) }); // Lagrangian scene.addScaledForceDifferentials(1, scratch_vp, scratch_fp); if (mls_mpm) { rasterizeForceToTVStack<true>(scale, df); } else { rasterizeForceToTVStack<false>(scale, df); } } // This is only called when implicit. template <class T, int dim> void MpmForceBase<T, dim>::updatePositionBasedState() { ZIRAN_QUIET_TIMER(); computeVAndGradV(); restoreStrain(); evolveStrain(dt); if (full_implicit) { } // xp = xn + dt * vp tbb::parallel_for(tbb::blocked_range<size_t>(0, particles.count), [&](const tbb::blocked_range<size_t>& range) { for (size_t b = range.begin(), b_end = range.end(); b < b_end; ++b) { scratch_xp[b] = particles.X.array[b] + dt * scratch_vp.col(b); } }); updateParticleImplicitState(); } template <class T, int dim> void MpmForceBase<T, dim>::updatePositionBasedState(const StdVector<TV>& x) { ZIRAN_ASSERT(false, "UpdatePositionBasedState(const StdVector<TV>& x) is not supported by mpm"); } template <class T, int dim> void MpmForceBase<T, dim>::evolveStrain(T dt) { // TODO: combinme evolve strain and update state? ZIRAN_QUIET_TIMER(); auto ranges = particles.X.ranges; tbb::parallel_for(ranges, [&](DisjointRanges& subrange) { for (auto& h : helpers) h->evolveStrain(subrange, dt, scratch_gradV); }); } template <class T, int dim> T MpmForceBase<T, dim>::totalEnergy() const { ZIRAN_QUIET_TIMER(); auto ranges = particles.X.ranges; T result = tbb::parallel_reduce(ranges, 0.0, [&](const DisjointRanges& subset, const double& e) -> double { double psi = e; for (auto& h : helpers) psi += h->totalEnergy(subset); return psi; }, [&](const double& x, const double& y) -> double { return x + y; }); // Lagrangian result += scene.totalEnergy(); return result; } } // namespace ZIRAN
[ "wxlwxl1993@zju.edu.cn" ]
wxlwxl1993@zju.edu.cn
d48015580b85853fd218c237cb21dcf703048b6d
04cbaea0cd4ca0a018ae673437a6063cefbb443f
/src/shadow_pa10_trajectory_1_foam.cpp
4ed06274d75939b3b9bcea999c16c65b7a0d2f86
[]
no_license
AngelDR/trajectory_execution
1e616c2bf2b539ade2494cffaa4a776bee6a851e
f472ec3a7ca3e9b9f7202c3f1da488a580e4543a
refs/heads/master
2020-04-30T04:09:47.464200
2016-02-18T15:52:48
2016-02-18T15:52:48
39,887,917
0
0
null
null
null
null
UTF-8
C++
false
false
10,322
cpp
/* Author: Angel Delgado */ #include <ros/ros.h> // MoveIt! #include <moveit/robot_model_loader/robot_model_loader.h> #include <moveit/robot_model/robot_model.h> #include <moveit/robot_state/robot_state.h> #include <moveit_msgs/DisplayRobotState.h> #include <moveit/move_group_interface/move_group.h> #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <moveit/robot_trajectory/robot_trajectory.h> #include <moveit/trajectory_processing/iterative_time_parameterization.h> #include <moveit_msgs/DisplayRobotState.h> #include <moveit_msgs/DisplayTrajectory.h> // Robot state publishing #include <moveit/robot_state/conversions.h> #include <std_msgs/Float64.h> // PI #include <boost/math/constants/constants.hpp> #include <math.h> #include <tf/LinearMath/Quaternion.h> int main(int argc, char **argv) { ros::init (argc, argv, "shadow_pa10_trajectory_foam"); ros::AsyncSpinner spinner(1); spinner.start(); ros::NodeHandle nh; ros::Rate loop_rate(1); // Robot Model /**robot_model_loader::RobotModelLoader robot_model_loader("robot_description"); robot_model::RobotModelPtr kinematic_model = robot_model_loader.getModel(); robot_state::RobotStatePtr kinematic_state(new robot_state::RobotState(kinematic_model)); kinematic_state->setToDefaultValues(); const robot_state::JointModelGroup* joint_model_group = kinematic_model->getJointModelGroup("pa10_shadow"); const std::vector<std::string> &joint_names = joint_model_group->getJointModelNames();*/ // Move Group ::Planning scene moveit::planning_interface::MoveGroup group("pa10_shadow"); moveit::planning_interface::PlanningSceneInterface planning_scene_interface; ros::Publisher display_publisher = nh.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true); moveit_msgs::DisplayTrajectory display_trajectory_0,display_trajectory_1,display_trajectory_2,display_trajectory_3; moveit::planning_interface::MoveGroup::Plan plan_0,plan_1,plan_2,plan_3; std::vector<double> group_variable_values; group.setPoseReferenceFrame ("link_base"); group.setGoalOrientationTolerance (0.17); group.setGoalPositionTolerance (0.05); group.setPlannerId("KPIECE"); double angle_x_roll = 1.57; double angle_y_pitch = 0; double angle_z_yaw = 0; // Ejemplo Coordenadas articulares: /** double joint_position_list[9] = {1.27, -0.55, 0.0, 0.98, 0.78, 0.82, 0.10, 0.0, 0.0}; for(int i = 0; i < 10; i++ ){ group_variable_values.push_back(joint_position_list[i]); } //bool setJointValueTarget (const std::vector< double > &group_variable_values) //group.setJointValueTarget(group_variable_values); */ // PUNTO REFERENCIA 0 : ENCIMA PLANTILLA (Coordenadas cartesianas) geometry_msgs::Pose target_pose0; group.setStartStateToCurrentState(); target_pose0.orientation = tf::createQuaternionMsgFromRollPitchYaw(angle_x_roll,angle_y_pitch,angle_z_yaw); target_pose0.position.x = -0.10; target_pose0.position.y = -0.60; target_pose0.position.z = 0.70; group.setPoseTarget(target_pose0,"palm"); //group.setPositionTarget (0.0, -0.5, 0.5, "palm"); //plan: publish display planned path-> mover robot si conexion_pa10=1 group.plan(plan_0); ROS_INFO("Visualizing plan 0"); display_trajectory_0.trajectory_start = plan_0.start_state_; display_trajectory_0.trajectory.push_back(plan_0.trajectory_); display_publisher.publish(display_trajectory_0); group.execute(plan_0); sleep(5.0); // PUNTO REFERENCIA 1 : AGARRE PLANTILLA (Coordenadas cartesianas, cartesian path) std::vector<geometry_msgs::Pose> waypoints_1; moveit_msgs::RobotTrajectory trajectory_msg_1; group. setPoseReferenceFrame("link_base"); group.setStartStateToCurrentState(); geometry_msgs::Pose initial_pose_1 = group.getCurrentPose().pose; group.setPlanningTime(3.0); waypoints_1.push_back(initial_pose_1); geometry_msgs::Pose waypoint_pose_1; waypoint_pose_1.orientation = initial_pose_1.orientation; waypoint_pose_1.position.x = initial_pose_1.position.x; waypoint_pose_1.position.y = initial_pose_1.position.y; waypoint_pose_1.position.z = initial_pose_1.position.z - 0.10; waypoints_1.push_back(waypoint_pose_1); double fraction = group.computeCartesianPath(waypoints_1, 0.2, 100.0, trajectory_msg_1, false); ROS_INFO("Computed cartesian path %f", fraction); // The trajectory needs to be modified so it will include velocities as well. // First to create a RobotTrajectory object robot_trajectory::RobotTrajectory rt(group.getCurrentState()->getRobotModel(), "pa10_shadow"); // Second get a RobotTrajectory from trajectory rt.setRobotTrajectoryMsg(*group.getCurrentState(), trajectory_msg_1); // Thrid create a IterativeParabolicTimeParameterization object trajectory_processing::IterativeParabolicTimeParameterization iptp; // Fourth compute computeTimeStamps bool success = iptp.computeTimeStamps(rt); ROS_INFO("Computed time stamp %s",success?"SUCCEDED":"FAILED"); // Get RobotTrajectory_msg from RobotTrajectory rt.getRobotTrajectoryMsg(trajectory_msg_1); // Check trajectory_msg for velocities not empty //std::cout << trajectory_msg << std::endl; plan_1.trajectory_ = trajectory_msg_1; //group.plan(plan_4); ROS_INFO("Visualizing plan 1"); display_trajectory_1.trajectory_start = plan_1.start_state_; display_trajectory_1.trajectory.push_back(plan_1.trajectory_); display_publisher.publish(display_trajectory_1); /* Sleep to give Rviz time to visualize the plan. */ group.execute(plan_1); sleep(5.0); // PUNTO REFERENCIA 2 : ENCIMA PLANTILLA (Coordenadas cartesianas, cartesian path) std::vector<geometry_msgs::Pose> waypoints_2; moveit_msgs::RobotTrajectory trajectory_msg_2; group. setPoseReferenceFrame("link_base"); group.setStartStateToCurrentState(); geometry_msgs::Pose initial_pose_2 = group.getCurrentPose().pose; group.setPlanningTime(3.0); waypoints_2.push_back(initial_pose_2); geometry_msgs::Pose waypoint_pose_2; waypoint_pose_2.orientation = initial_pose_2.orientation; waypoint_pose_2.position.x = initial_pose_2.position.x; waypoint_pose_2.position.y = initial_pose_2.position.y; waypoint_pose_2.position.z = initial_pose_2.position.z + 0.20; waypoints_2.push_back(waypoint_pose_2); fraction = group.computeCartesianPath(waypoints_2, 0.2, 100.0, trajectory_msg_2, false); ROS_INFO("Computed cartesian path %f", fraction); // The trajectory needs to be modified so it will include velocities as well. // First to create a RobotTrajectory object robot_trajectory::RobotTrajectory rt_2(group.getCurrentState()->getRobotModel(), "pa10_shadow"); // Second get a RobotTrajectory from trajectory rt_2.setRobotTrajectoryMsg(*group.getCurrentState(), trajectory_msg_2); // Thrid create a IterativeParabolicTimeParameterization object //trajectory_processing::IterativeParabolicTimeParameterization iptp; // Fourth compute computeTimeStamps success = iptp.computeTimeStamps(rt_2); ROS_INFO("Computed time stamp %s",success?"SUCCEDED":"FAILED"); // Get RobotTrajectory_msg from RobotTrajectory rt_2.getRobotTrajectoryMsg(trajectory_msg_2); // Check trajectory_msg for velocities not empty //std::cout << trajectory_msg << std::endl; plan_2.trajectory_ = trajectory_msg_2; //group.plan(plan_4); ROS_INFO("Visualizing plan 2"); display_trajectory_2.trajectory_start = plan_2.start_state_; display_trajectory_2.trajectory.push_back(plan_2.trajectory_); display_publisher.publish(display_trajectory_2); /* Sleep to give Rviz time to visualize the plan. */ group.execute(plan_2); sleep(5.0); // PUNTO REFERENCIA 3 : ENCIMA ZAPATO (Coordenadas cartesianas, cartesian path) std::vector<geometry_msgs::Pose> waypoints_3; moveit_msgs::RobotTrajectory trajectory_msg_3; group. setPoseReferenceFrame("link_base"); group.setStartStateToCurrentState(); geometry_msgs::Pose initial_pose_3 = group.getCurrentPose().pose; group.setPlanningTime(3.0); waypoints_3.push_back(initial_pose_3); geometry_msgs::Pose waypoint_pose_3; angle_x_roll = 1.57; angle_y_pitch = 0.78; angle_z_yaw = -0.0; waypoint_pose_3.orientation = tf::createQuaternionMsgFromRollPitchYaw(angle_x_roll,angle_y_pitch,angle_z_yaw); waypoint_pose_3.position.x = initial_pose_3.position.x + 0.20; waypoint_pose_3.position.y = initial_pose_3.position.y; waypoint_pose_3.position.z = initial_pose_3.position.z - 0.10; waypoints_3.push_back(waypoint_pose_3); fraction = group.computeCartesianPath(waypoints_3, 0.2, 100.0, trajectory_msg_3, false); ROS_INFO("Computed cartesian path %f", fraction); // The trajectory needs to be modified so it will include velocities as well. // First to create a RobotTrajectory object robot_trajectory::RobotTrajectory rt_3(group.getCurrentState()->getRobotModel(), "pa10_shadow"); // Second get a RobotTrajectory from trajectory rt_3.setRobotTrajectoryMsg(*group.getCurrentState(), trajectory_msg_3); // Thrid create a IterativeParabolicTimeParameterization object //trajectory_processing::IterativeParabolicTimeParameterization iptp; // Fourth compute computeTimeStamps success = iptp.computeTimeStamps(rt_3); ROS_INFO("Computed time stamp %s",success?"SUCCEDED":"FAILED"); // Get RobotTrajectory_msg from RobotTrajectory rt_3.getRobotTrajectoryMsg(trajectory_msg_3); // Check trajectory_msg for velocities not empty //std::cout << trajectory_msg << std::endl; plan_3.trajectory_ = trajectory_msg_3; //group.plan(plan_4); ROS_INFO("Visualizing plan 3"); display_trajectory_3.trajectory_start = plan_3.start_state_; display_trajectory_3.trajectory.push_back(plan_3.trajectory_); display_publisher.publish(display_trajectory_3); /* Sleep to give Rviz time to visualize the plan. */ group.execute(plan_3); sleep(5.0); // FIN TAREA ROS_INFO("End..."); ros::shutdown(); return 0; }
[ "angeldelrod@gmail.com" ]
angeldelrod@gmail.com
e65229ae8ab0aa16d0ba556edbdafab68c9a83ed
87483f2d2d6ba74a6d05332d02ca042e379bae4c
/citizen.cpp
4f6234137e6b1a6d151a59cdfe42c90b5b9cb36a
[]
no_license
Yossi-boop/electionFinal
045ee55f3213624dd1b95158d5b58f920e9a8a56
19cd3b4c4168b9413d2369dcd6920e9bff7297c0
refs/heads/master
2022-11-15T20:17:18.420326
2020-06-21T10:00:02
2020-06-21T10:00:02
273,877,127
0
0
null
null
null
null
UTF-8
C++
false
false
2,941
cpp
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; #include "citizen.h" int const VALID_YEAR = 2002; //all citizens in our electios system must be over 18 //C'tor Citizen::Citizen(const string name, const Date& birthday, int id, int ballotNum, bool isIsolated) throw (string, string) : birthday(std::move(birthday)) { if (!setId(id)) throw "invalid id!"; if (birthday.getYear() > VALID_YEAR) throw "invalid age!"; setName(name); //We set name - beacuse the throw is before the name set, if have need to throw we will throw (exit the c'tor) and not allocate the name so no need to realse the name setBallotNum(ballotNum); //We set ballot number setIsIsolated(isIsolated); //We set his isolation status } Citizen::Citizen(ifstream& in) { in >> *this; } const string& Citizen::getName() const { return name; } const Date& Citizen::getBirth() const { return birthday; } const int Citizen::getId() const { return id; } int Citizen::getBallotNum() const { return ballotNum; } bool Citizen::getIsIsolated() const { return isIsolated; } bool nameChar(char c) //This function check is a given charcter is a letter (big or small) or a space. //if yes, the function return true, else return false. { return (('a' <= c && c <= 'z') || ('A' <= c && c < 'Z') || (c == ' ')); } bool validNameCheck(string str) //This function returns true if a given string is made of letters and spaces, //else the function return false. { int i, len = str.length(); for (i = 0; i < len; i++) { if (!nameChar(str[i])) { return false; } } return true; } bool Citizen::setName(const string citizenName) { if (!(validNameCheck(citizenName))) { cout << "Invalid citizen name\n"; return false; } else { name = citizenName; return true; } } bool Citizen::setBirth(Date citizenBirth) { birthday = citizenBirth; return true; } /*This function is a helper funtion for "set id".*/ bool checkID(int idNum) { return (idNum >= 100000000 && idNum <= 999999999); } bool Citizen::setId(int citizenId) { if (checkID(citizenId)) { id = citizenId; return true; } else return false; } bool Citizen::setBallotNum(int bn) { if (bn <= 0) { cout << "Ballot num must be a positive number. Number unchanged.\n"; return false; } else { ballotNum = bn; return true; } } bool Citizen::setIsIsolated(bool ans) { if (ans != 1 || ans != 0) { this->isIsolated = ans; return true; } else return false; } void Citizen::show() const { cout << "Name: " << name << ".\n" << "Date of birth: " << birthday << "." << endl << "ID: " << id << ".\n"; if (isIsolated) cout << "In isolation.\n"; else cout << "Not in isolation.\n"; } Citizen::~Citizen() { } //No need in d'tor - no dynamic allocations in citizen class itself
[ "noreply@github.com" ]
noreply@github.com
af13609715b8ab4afc1dbd39d34a55a556ff7d06
c78f01652444caa083ca75211bae6903d98363cb
/devel/include/mavlink/v2.0/matrixpilot/mavlink_msg_serial_udb_extra_f2_b.hpp
f77107da9ec54569f04b99b527483a952ebc83ab
[ "Apache-2.0" ]
permissive
arijitnoobstar/UAVProjectileCatcher
9179980f8095652811b69b70930f65b17fbb4901
3c1bed80df167192cb4b971b58c891187628142e
refs/heads/master
2023-05-01T11:03:09.595821
2021-05-16T15:10:03
2021-05-16T15:10:03
341,154,017
19
7
null
null
null
null
UTF-8
C++
false
false
14,324
hpp
// MESSAGE SERIAL_UDB_EXTRA_F2_B support class #pragma once namespace mavlink { namespace matrixpilot { namespace msg { /** * @brief SERIAL_UDB_EXTRA_F2_B message * * Backwards compatible version of SERIAL_UDB_EXTRA - F2: Part B */ struct SERIAL_UDB_EXTRA_F2_B : mavlink::Message { static constexpr msgid_t MSG_ID = 171; static constexpr size_t LENGTH = 108; static constexpr size_t MIN_LENGTH = 108; static constexpr uint8_t CRC_EXTRA = 245; static constexpr auto NAME = "SERIAL_UDB_EXTRA_F2_B"; uint32_t sue_time; /*< Serial UDB Extra Time */ int16_t sue_pwm_input_1; /*< Serial UDB Extra PWM Input Channel 1 */ int16_t sue_pwm_input_2; /*< Serial UDB Extra PWM Input Channel 2 */ int16_t sue_pwm_input_3; /*< Serial UDB Extra PWM Input Channel 3 */ int16_t sue_pwm_input_4; /*< Serial UDB Extra PWM Input Channel 4 */ int16_t sue_pwm_input_5; /*< Serial UDB Extra PWM Input Channel 5 */ int16_t sue_pwm_input_6; /*< Serial UDB Extra PWM Input Channel 6 */ int16_t sue_pwm_input_7; /*< Serial UDB Extra PWM Input Channel 7 */ int16_t sue_pwm_input_8; /*< Serial UDB Extra PWM Input Channel 8 */ int16_t sue_pwm_input_9; /*< Serial UDB Extra PWM Input Channel 9 */ int16_t sue_pwm_input_10; /*< Serial UDB Extra PWM Input Channel 10 */ int16_t sue_pwm_input_11; /*< Serial UDB Extra PWM Input Channel 11 */ int16_t sue_pwm_input_12; /*< Serial UDB Extra PWM Input Channel 12 */ int16_t sue_pwm_output_1; /*< Serial UDB Extra PWM Output Channel 1 */ int16_t sue_pwm_output_2; /*< Serial UDB Extra PWM Output Channel 2 */ int16_t sue_pwm_output_3; /*< Serial UDB Extra PWM Output Channel 3 */ int16_t sue_pwm_output_4; /*< Serial UDB Extra PWM Output Channel 4 */ int16_t sue_pwm_output_5; /*< Serial UDB Extra PWM Output Channel 5 */ int16_t sue_pwm_output_6; /*< Serial UDB Extra PWM Output Channel 6 */ int16_t sue_pwm_output_7; /*< Serial UDB Extra PWM Output Channel 7 */ int16_t sue_pwm_output_8; /*< Serial UDB Extra PWM Output Channel 8 */ int16_t sue_pwm_output_9; /*< Serial UDB Extra PWM Output Channel 9 */ int16_t sue_pwm_output_10; /*< Serial UDB Extra PWM Output Channel 10 */ int16_t sue_pwm_output_11; /*< Serial UDB Extra PWM Output Channel 11 */ int16_t sue_pwm_output_12; /*< Serial UDB Extra PWM Output Channel 12 */ int16_t sue_imu_location_x; /*< Serial UDB Extra IMU Location X */ int16_t sue_imu_location_y; /*< Serial UDB Extra IMU Location Y */ int16_t sue_imu_location_z; /*< Serial UDB Extra IMU Location Z */ int16_t sue_location_error_earth_x; /*< Serial UDB Location Error Earth X */ int16_t sue_location_error_earth_y; /*< Serial UDB Location Error Earth Y */ int16_t sue_location_error_earth_z; /*< Serial UDB Location Error Earth Z */ uint32_t sue_flags; /*< Serial UDB Extra Status Flags */ int16_t sue_osc_fails; /*< Serial UDB Extra Oscillator Failure Count */ int16_t sue_imu_velocity_x; /*< Serial UDB Extra IMU Velocity X */ int16_t sue_imu_velocity_y; /*< Serial UDB Extra IMU Velocity Y */ int16_t sue_imu_velocity_z; /*< Serial UDB Extra IMU Velocity Z */ int16_t sue_waypoint_goal_x; /*< Serial UDB Extra Current Waypoint Goal X */ int16_t sue_waypoint_goal_y; /*< Serial UDB Extra Current Waypoint Goal Y */ int16_t sue_waypoint_goal_z; /*< Serial UDB Extra Current Waypoint Goal Z */ int16_t sue_aero_x; /*< Aeroforce in UDB X Axis */ int16_t sue_aero_y; /*< Aeroforce in UDB Y Axis */ int16_t sue_aero_z; /*< Aeroforce in UDB Z axis */ int16_t sue_barom_temp; /*< SUE barometer temperature */ int32_t sue_barom_press; /*< SUE barometer pressure */ int32_t sue_barom_alt; /*< SUE barometer altitude */ int16_t sue_bat_volt; /*< SUE battery voltage */ int16_t sue_bat_amp; /*< SUE battery current */ int16_t sue_bat_amp_hours; /*< SUE battery milli amp hours used */ int16_t sue_desired_height; /*< Sue autopilot desired height */ int16_t sue_memory_stack_free; /*< Serial UDB Extra Stack Memory Free */ inline std::string get_name(void) const override { return NAME; } inline Info get_message_info(void) const override { return { MSG_ID, LENGTH, MIN_LENGTH, CRC_EXTRA }; } inline std::string to_yaml(void) const override { std::stringstream ss; ss << NAME << ":" << std::endl; ss << " sue_time: " << sue_time << std::endl; ss << " sue_pwm_input_1: " << sue_pwm_input_1 << std::endl; ss << " sue_pwm_input_2: " << sue_pwm_input_2 << std::endl; ss << " sue_pwm_input_3: " << sue_pwm_input_3 << std::endl; ss << " sue_pwm_input_4: " << sue_pwm_input_4 << std::endl; ss << " sue_pwm_input_5: " << sue_pwm_input_5 << std::endl; ss << " sue_pwm_input_6: " << sue_pwm_input_6 << std::endl; ss << " sue_pwm_input_7: " << sue_pwm_input_7 << std::endl; ss << " sue_pwm_input_8: " << sue_pwm_input_8 << std::endl; ss << " sue_pwm_input_9: " << sue_pwm_input_9 << std::endl; ss << " sue_pwm_input_10: " << sue_pwm_input_10 << std::endl; ss << " sue_pwm_input_11: " << sue_pwm_input_11 << std::endl; ss << " sue_pwm_input_12: " << sue_pwm_input_12 << std::endl; ss << " sue_pwm_output_1: " << sue_pwm_output_1 << std::endl; ss << " sue_pwm_output_2: " << sue_pwm_output_2 << std::endl; ss << " sue_pwm_output_3: " << sue_pwm_output_3 << std::endl; ss << " sue_pwm_output_4: " << sue_pwm_output_4 << std::endl; ss << " sue_pwm_output_5: " << sue_pwm_output_5 << std::endl; ss << " sue_pwm_output_6: " << sue_pwm_output_6 << std::endl; ss << " sue_pwm_output_7: " << sue_pwm_output_7 << std::endl; ss << " sue_pwm_output_8: " << sue_pwm_output_8 << std::endl; ss << " sue_pwm_output_9: " << sue_pwm_output_9 << std::endl; ss << " sue_pwm_output_10: " << sue_pwm_output_10 << std::endl; ss << " sue_pwm_output_11: " << sue_pwm_output_11 << std::endl; ss << " sue_pwm_output_12: " << sue_pwm_output_12 << std::endl; ss << " sue_imu_location_x: " << sue_imu_location_x << std::endl; ss << " sue_imu_location_y: " << sue_imu_location_y << std::endl; ss << " sue_imu_location_z: " << sue_imu_location_z << std::endl; ss << " sue_location_error_earth_x: " << sue_location_error_earth_x << std::endl; ss << " sue_location_error_earth_y: " << sue_location_error_earth_y << std::endl; ss << " sue_location_error_earth_z: " << sue_location_error_earth_z << std::endl; ss << " sue_flags: " << sue_flags << std::endl; ss << " sue_osc_fails: " << sue_osc_fails << std::endl; ss << " sue_imu_velocity_x: " << sue_imu_velocity_x << std::endl; ss << " sue_imu_velocity_y: " << sue_imu_velocity_y << std::endl; ss << " sue_imu_velocity_z: " << sue_imu_velocity_z << std::endl; ss << " sue_waypoint_goal_x: " << sue_waypoint_goal_x << std::endl; ss << " sue_waypoint_goal_y: " << sue_waypoint_goal_y << std::endl; ss << " sue_waypoint_goal_z: " << sue_waypoint_goal_z << std::endl; ss << " sue_aero_x: " << sue_aero_x << std::endl; ss << " sue_aero_y: " << sue_aero_y << std::endl; ss << " sue_aero_z: " << sue_aero_z << std::endl; ss << " sue_barom_temp: " << sue_barom_temp << std::endl; ss << " sue_barom_press: " << sue_barom_press << std::endl; ss << " sue_barom_alt: " << sue_barom_alt << std::endl; ss << " sue_bat_volt: " << sue_bat_volt << std::endl; ss << " sue_bat_amp: " << sue_bat_amp << std::endl; ss << " sue_bat_amp_hours: " << sue_bat_amp_hours << std::endl; ss << " sue_desired_height: " << sue_desired_height << std::endl; ss << " sue_memory_stack_free: " << sue_memory_stack_free << std::endl; return ss.str(); } inline void serialize(mavlink::MsgMap &map) const override { map.reset(MSG_ID, LENGTH); map << sue_time; // offset: 0 map << sue_flags; // offset: 4 map << sue_barom_press; // offset: 8 map << sue_barom_alt; // offset: 12 map << sue_pwm_input_1; // offset: 16 map << sue_pwm_input_2; // offset: 18 map << sue_pwm_input_3; // offset: 20 map << sue_pwm_input_4; // offset: 22 map << sue_pwm_input_5; // offset: 24 map << sue_pwm_input_6; // offset: 26 map << sue_pwm_input_7; // offset: 28 map << sue_pwm_input_8; // offset: 30 map << sue_pwm_input_9; // offset: 32 map << sue_pwm_input_10; // offset: 34 map << sue_pwm_input_11; // offset: 36 map << sue_pwm_input_12; // offset: 38 map << sue_pwm_output_1; // offset: 40 map << sue_pwm_output_2; // offset: 42 map << sue_pwm_output_3; // offset: 44 map << sue_pwm_output_4; // offset: 46 map << sue_pwm_output_5; // offset: 48 map << sue_pwm_output_6; // offset: 50 map << sue_pwm_output_7; // offset: 52 map << sue_pwm_output_8; // offset: 54 map << sue_pwm_output_9; // offset: 56 map << sue_pwm_output_10; // offset: 58 map << sue_pwm_output_11; // offset: 60 map << sue_pwm_output_12; // offset: 62 map << sue_imu_location_x; // offset: 64 map << sue_imu_location_y; // offset: 66 map << sue_imu_location_z; // offset: 68 map << sue_location_error_earth_x; // offset: 70 map << sue_location_error_earth_y; // offset: 72 map << sue_location_error_earth_z; // offset: 74 map << sue_osc_fails; // offset: 76 map << sue_imu_velocity_x; // offset: 78 map << sue_imu_velocity_y; // offset: 80 map << sue_imu_velocity_z; // offset: 82 map << sue_waypoint_goal_x; // offset: 84 map << sue_waypoint_goal_y; // offset: 86 map << sue_waypoint_goal_z; // offset: 88 map << sue_aero_x; // offset: 90 map << sue_aero_y; // offset: 92 map << sue_aero_z; // offset: 94 map << sue_barom_temp; // offset: 96 map << sue_bat_volt; // offset: 98 map << sue_bat_amp; // offset: 100 map << sue_bat_amp_hours; // offset: 102 map << sue_desired_height; // offset: 104 map << sue_memory_stack_free; // offset: 106 } inline void deserialize(mavlink::MsgMap &map) override { map >> sue_time; // offset: 0 map >> sue_flags; // offset: 4 map >> sue_barom_press; // offset: 8 map >> sue_barom_alt; // offset: 12 map >> sue_pwm_input_1; // offset: 16 map >> sue_pwm_input_2; // offset: 18 map >> sue_pwm_input_3; // offset: 20 map >> sue_pwm_input_4; // offset: 22 map >> sue_pwm_input_5; // offset: 24 map >> sue_pwm_input_6; // offset: 26 map >> sue_pwm_input_7; // offset: 28 map >> sue_pwm_input_8; // offset: 30 map >> sue_pwm_input_9; // offset: 32 map >> sue_pwm_input_10; // offset: 34 map >> sue_pwm_input_11; // offset: 36 map >> sue_pwm_input_12; // offset: 38 map >> sue_pwm_output_1; // offset: 40 map >> sue_pwm_output_2; // offset: 42 map >> sue_pwm_output_3; // offset: 44 map >> sue_pwm_output_4; // offset: 46 map >> sue_pwm_output_5; // offset: 48 map >> sue_pwm_output_6; // offset: 50 map >> sue_pwm_output_7; // offset: 52 map >> sue_pwm_output_8; // offset: 54 map >> sue_pwm_output_9; // offset: 56 map >> sue_pwm_output_10; // offset: 58 map >> sue_pwm_output_11; // offset: 60 map >> sue_pwm_output_12; // offset: 62 map >> sue_imu_location_x; // offset: 64 map >> sue_imu_location_y; // offset: 66 map >> sue_imu_location_z; // offset: 68 map >> sue_location_error_earth_x; // offset: 70 map >> sue_location_error_earth_y; // offset: 72 map >> sue_location_error_earth_z; // offset: 74 map >> sue_osc_fails; // offset: 76 map >> sue_imu_velocity_x; // offset: 78 map >> sue_imu_velocity_y; // offset: 80 map >> sue_imu_velocity_z; // offset: 82 map >> sue_waypoint_goal_x; // offset: 84 map >> sue_waypoint_goal_y; // offset: 86 map >> sue_waypoint_goal_z; // offset: 88 map >> sue_aero_x; // offset: 90 map >> sue_aero_y; // offset: 92 map >> sue_aero_z; // offset: 94 map >> sue_barom_temp; // offset: 96 map >> sue_bat_volt; // offset: 98 map >> sue_bat_amp; // offset: 100 map >> sue_bat_amp_hours; // offset: 102 map >> sue_desired_height; // offset: 104 map >> sue_memory_stack_free; // offset: 106 } }; } // namespace msg } // namespace matrixpilot } // namespace mavlink
[ "arijit.dg@hotmail.com" ]
arijit.dg@hotmail.com
e263b566f085fbfbf86dabbeacbb6e0cd8d1bfe6
c90d34884688a881679bf9580764431ae3ff7448
/include/RaZ/Render/Camera.hpp
74d35e7dc4509d0854519c20ab51e2534df2d5ba
[ "MIT" ]
permissive
mtola/RaZ
dac5d508ea732d261fa07a0ecb937e63e717c685
51f8853d94d3e9d5939582dbdd64ac1766916259
refs/heads/master
2021-04-15T17:07:28.559056
2018-03-21T12:02:28
2018-03-21T12:02:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,070
hpp
#pragma once #ifndef RAZ_CAMERA_HPP #define RAZ_CAMERA_HPP #include <memory> #include "RaZ/Math/Matrix.hpp" #include "RaZ/Math/Vector.hpp" #include "RaZ/Math/Constants.hpp" #include "RaZ/Math/Transform.hpp" namespace Raz { class Camera : public Transform { public: Camera(unsigned int frameWidth, unsigned int frameHeight, float fieldOfViewDegrees, float nearPlane, float farPlane, const Vec3f& position = Vec3f(0.f)) : m_frameRatio{ static_cast<float>(frameWidth) / frameHeight }, m_fieldOfView{ fieldOfViewDegrees * pi<float> / 180 }, m_nearPlane{ nearPlane }, m_farPlane{ farPlane } { m_position = position; } Mat4f computePerspectiveMatrix() const; Mat4f lookAt(const Vec3f& target = Vec3f(0.f), const Vec3f& orientation = Vec3f({ 0.f, 1.f, 0.f })) const; private: float m_frameRatio; float m_fieldOfView; float m_nearPlane; float m_farPlane; }; using CameraPtr = std::unique_ptr<Camera>; } // namespace Raz #endif // RAZ_CAMERA_HPP
[ "romain.milbert@gmail.com" ]
romain.milbert@gmail.com
7f1f680069111d05243df6bdfb0028f0facfc79a
c6c159fb17a5ac18a7710f6bce826277f1385883
/home_sen_net/working-sever-08-12/HomeSenNet.cpp
c72a94666926f96d7d87e6f6ca0864c10a2a2e87
[]
no_license
sepulvedareinaldo/ard_rxtx
062af41b5929db1c45ed31bf20cded060eca7b01
b4f404373f2ddeaaa7ce6d46e30c1fd7bb3497cd
refs/heads/master
2020-03-27T06:27:36.925073
2018-09-09T18:14:15
2018-09-09T18:14:15
146,107,789
0
0
null
null
null
null
UTF-8
C++
false
false
8,838
cpp
/* open to anyone 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. */ /** * first shot at home sensor network as a standard library to load to all Arduino-Sensors that varies only by initialization * * Class declaration for home_sen_net * */ /* _Ihave definition mapping: 0 - Emitter node (connected to a Sever) 1 - Red led Bookshelf 2 - Green led Bookshelf 3 - Blue led Bookshelf 4 - Dim-able light TV */ #include "Arduino.h" #include "HomeSenNet.h" #include "Arduino.h" #include <SPI.h> #include <nRF24L01.h> #include <RF24.h> #include <stdarg.h> //for variable length arg functions #include <stdio.h> //for variable length arg functions /****************************************************************************/ HSN::HSN() { //_Ihave = _Ihave; //state who this Arduino will control - check _Ihave map table _FeedBackTimer = millis(); // initialize feedback timer for use in FeedBack loop (time out for resend request) _version = 2; //PERIPHERAL detail } /****************************************************************************/ void HSN::I_Have(int Ihave , ...){//declare sensors/node - initialize: Peripherals matrix; Sensor Pins va_list args; //creates list of arguments va_start( args, Ihave ); //starts iterator of arguments for ( int x = 0; x < Ihave; x++ ) // iterate over all arguments and initialize peripherals matrix { int peri = va_arg ( args, int ); Peripherals[peri] = 1; // Peripherals linked to this network if (peri==0){ Serial.print("I am: "); Serial.print(sensor_map[peri]); //let host know who I am/have Serial.print(" (");Serial.print(peri);Serial.println( ")"); }else{ Serial.print("I have: "); Serial.print(sensor_map[peri]); //let host know who I am/have Serial.print(" (");Serial.print(peri);Serial.print( ") "); Serial.print("initializing pin: ");Serial.println(sensor_pin_map[peri]); pinMode(sensor_pin_map[peri],(OUTPUT)); //initialize pin-mode if I'm a sensor } } va_end ( args ); //Show Peripherals matrix int peri_size = sizeof(Peripherals) / sizeof(int); Serial.print("Peripherals: [");Serial.print(Peripherals[0]); for ( int x = 1; x < peri_size; x++ ) { Serial.print(",");Serial.print(Peripherals[x]); } Serial.println("]"); //end - show peripherals matrix _Ihave = Ihave; //state how many peripherals on this micro-controller } /****************************************************************************/ void HSN::ReadSerial() { if (Serial.available()) { // read messages form host server - messages shall be no longer that 5 digits (largest 2 byte _SerialBuffer = Serial.read()-'0'; _inByte[_tempCount]=_SerialBuffer; _tempCount += 1; } } /****************************************************************************/ bool HSN::MessageAvailable(RF24 RADIO) { //RF24 radio(9,10); //??? if (_tempCount == _messageSize) {//messageSize = 5 - size of message coming form host int i; unsigned int sendByte = 0; for ( i = 0; i <_messageSize ; i=i+1) { sendByte = sendByte + (int)ceil(_inByte[i]*(pow(10,_messageSize-1-i)));//encode message so we sent last 3 digits as value and identifyier in front _inByte[i] = 0; } New_Message[0] = sendByte; // store message as a int array to be able to send _tempCount = 0; // reset serialBuffer count (so we only read 5 int to send to sensors) //// Serial.print("SM "); Serial.println(New_Message[0]); RADIO.write(New_Message, 2); //send message to sensors - 2 bytes RADIO.startListening(); //set nrf24 back to listening - after right is needs to be set back to listining //// unsigned int x = (New_Message[0] / 1000U) % 10;//update feedback matrix to listen for feedback FeedBackTimer[x]=millis(); //Serial.print("feedback matrix index "); Serial.print(x); Serial.print(" timer started at ");Serial.println(FeedBackTimer[x]); //// return true; // message is available to send } return false; // no message in que } bool HSN::FeedBackChecker(RF24 RADIO) { if (RADIO.available()){ // receiving message - need to check if it's feedback bool done = false; unsigned int feedback[1]; while (!done){ done = RADIO.read(feedback, 2); } Serial.print("RF "); Serial.println(feedback[0]); /// unsigned int sensor = (New_Message[0] / 1000U) % 10; unsigned int value = New_Message[0] - sensor*1000 ; //Serial.print("message value is: ");Serial.println(value) if (feedback[0]==New_Message[0]){//check that the message is the same as the previous (may need to change for info requests) unsigned int x = (feedback[0] / 1000U) % 10; //identify sensor that sent feedback (in the thousands) FeedBackTimer[x]=0; //restart feedback timer FeedBackCounter[x]=0;//update feedback matrix to stop listening for feedback } else if(value>255){ // for cases that I send information request unsigned int x = (feedback[0] / 1000U) % 10; //identify sensor that sent feedback (in the thousands) FeedBackTimer[x]=0; //restart feedback timer FeedBackCounter[x]=0;//update feedback matrix to stop listening for feedback } //Serial.print("feedback matrix index "); Serial.print(x); Serial.println(" is false (0)"); /// return true; } /////resend message if above criteria is not meat int elementCount = sizeof(FeedBackTimer) / sizeof(long); for (int i = 0; i < elementCount; i++){ //Serial.print("in loop ");Serial.println(i); if ((FeedBackTimer[i]!=0) && ((millis() - FeedBackTimer[i]) > 200)){ //Serial.print("elapsed time "); Serial.println(((millis() - FeedBackTimer[i]))); FeedBackTimer[i]=millis(); //reset timer since meesage has not arrived //Serial.print("elapsed time "); Serial.println(((millis() - FeedBackTimer[i]))); FeedBackCounter[i]+=1; //store lost attempted Serial.print(FeedBackCounter[i]);Serial.print(" resending message ");Serial.println(New_Message[0]); RADIO.write(New_Message, 2); //re-write message RADIO.startListening(); //re-start listening } if (FeedBackCounter[i]>4){ // how many times should we try to right message Serial.print("Failed to write to device: ");Serial.print(i);Serial.print(" message "); Serial.println(New_Message[0]); FeedBackCounter[i] = 0; //reset counter off lost message FeedBackTimer[i] = 0; //reset counter off lost message } } return false; } /****************************************************************************/ bool HSN::RadioMessageAvailable(RF24 RADIO){ if (RADIO.available()){ bool done = false; unsigned int RadioMessage[1]; while (!done){ done = RADIO.read(RadioMessage, 2); } New_Message[0] = RadioMessage[0]; //Serial.print("received message: ");Serial.println(RadioMessage[0]); delay(20); // small brake to ensure system ready to start listening RADIO.startListening(); return true; }else{ //Serial.println("No radio available"); return false; } } void HSN::ExecuteCommand(RF24 RADIO){ unsigned int sensor = (New_Message[0] / 1000U) % 10; unsigned int value = New_Message[0] - sensor*1000 ; //Serial.print("Sensor: "); Serial.print(sensor); Serial.print(" Value: "); Serial.println(value); //UPDATE SELECTED SENSOR if ((sensor == 1) && (value <256)){ //1 - Red led Bookshelf - pin 6 analogWrite(sensor_pin_map[sensor],255-value); sensor_state[sensor]=value; //Serial.print(sensor_map[sensor]);Serial.print(" value: "); Serial.println(value); ProvideFeedback(RADIO); } else if ((sensor == 1) && (value == 300)) { //on info request (300 message) New_Message[0] = sensor_state[sensor] + (int)ceil(sensor*(pow(10,3))); ProvideFeedback(RADIO); } if ((sensor == 2)&& (value <256)){ //2 - Blue Led Bookshelf - pin 5 analogWrite(sensor_pin_map[sensor],255-value); sensor_state[sensor]=value; //Serial.print(sensor_map[sensor]);Serial.print(" value: "); Serial.println(value); ProvideFeedback(RADIO); } else if ((sensor == 2) && (value == 300)) { //on info request (300 message) New_Message[0] = sensor_state[sensor] + (int)ceil(sensor*(pow(10,3))); ProvideFeedback(RADIO); } if ((sensor == 3)&& (value <256)){ //3 - Green Led Bookshelf - pin 3 analogWrite(sensor_pin_map[sensor],255-value); sensor_state[sensor]=value; //Serial.print(sensor_map[sensor]);Serial.print(" value: "); Serial.println(value); ProvideFeedback(RADIO); } else if ((sensor == 3) && (value == 300)) { //on info request (300 message) New_Message[0] = sensor_state[sensor] + (int)ceil(sensor*(pow(10,3))); ProvideFeedback(RADIO); } } bool HSN::ProvideFeedback(RF24 RADIO){ Serial.print("Sent feedback for ");Serial.println(New_Message[0]); RADIO.write(New_Message, 2); RADIO.startListening(); New_Message[0] = 0; return true; }
[ "rsepulveda3@gatech.edu" ]
rsepulveda3@gatech.edu
c60e536717158ff7e5cd691ea0e24e6f8374c67a
2d209723d1a723df319d60c3805aa598f0677f6f
/include/ArrayDatasetReaderT.h
2801622ac54f3bc6a8ddab3a077cf37080f55139
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
HDFGroup/psh5x
d81bcf7a4b92cc59b43ef0e3c508de53e2193eb9
4d1521ed79cd894b34329ab019213bd783721e6b
refs/heads/master
2020-05-18T11:20:23.635946
2015-07-15T20:57:53
2015-07-15T20:57:53
39,159,932
6
1
null
null
null
null
UTF-8
C++
false
false
5,454
h
#pragma once #include "ArrayUtils.h" #include "H5ArrayT.h" #include "HDF5Exception.h" #include "PSH5XException.h" extern "C" { #include "H5Dpublic.h" #include "H5Spublic.h" #include "H5Tpublic.h" } #include <vector> namespace PSH5X { template <typename T> public ref class ArrayDatasetReaderT : System::Management::Automation::Provider::IContentReader { public: ArrayDatasetReaderT(hid_t dset, hid_t ftype, hid_t fspace, hid_t mspace) : m_array(nullptr), m_ienum(nullptr), m_position(0) { hid_t mtype = -1; array<hsize_t>^ adims = nullptr; try { mtype = H5Tget_native_type(ftype, H5T_DIR_ASCEND); if (mtype < 0) { throw gcnew HDF5Exception("H5Tget_native_type failed!"); } hssize_t npoints = 1; int rank = 1; H5S_class_t cls = H5Sget_simple_extent_type(fspace); array<hsize_t>^ dims = gcnew array<hsize_t>(1); dims[0] = 1; if (cls == H5S_SIMPLE) { rank = H5Sget_simple_extent_ndims(fspace); if (rank < 0) { throw gcnew HDF5Exception("H5Sget_simple_extent_ndims failed!"); } dims = gcnew array<hsize_t>(rank); pin_ptr<hsize_t> dims_ptr = &dims[0]; if (mspace == H5S_ALL) { rank = H5Sget_simple_extent_dims(fspace, dims_ptr, NULL); npoints = H5Sget_simple_extent_npoints(fspace); } else { rank = H5Sget_simple_extent_dims(mspace, dims_ptr, NULL); npoints = H5Sget_simple_extent_npoints(mspace); } if (rank < 0) { throw gcnew HDF5Exception("H5Sget_simple_extent_dims failed!"); } } // get the array dimensions of the data elements int arank = H5Tget_array_ndims(ftype); if (arank < 0) { throw gcnew HDF5Exception("H5Tget_array_ndims failed!"); } adims = gcnew array<hsize_t>(arank); pin_ptr<hsize_t> adims_ptr = &adims[0]; if (H5Tget_array_dims2(ftype, adims_ptr) < 0) { throw gcnew HDF5Exception("H5Tget_array_dims2 failed!"); } int arrayLength = 1; for (int i = 0; i < arank; ++i) { arrayLength *= safe_cast<int>(adims[i]); } array<T>^ rdata = gcnew array<T>(safe_cast<int>(npoints*arrayLength)); pin_ptr<T> rdata_ptr = &rdata[0]; if (H5Dread(dset, mtype, mspace, fspace, H5P_DEFAULT, rdata_ptr) < 0) { throw gcnew HDF5Exception("H5Dread failed!"); } H5Array<T>^ dummy = gcnew H5Array<T>(adims); m_array = Array::CreateInstance(dummy->GetArray()->GetType(), (array<long long>^) dims); if (rank > 1) { array<long long>^ index = gcnew array<long long>(rank); for (int i = 0; i < npoints; ++i) { H5Array<T>^ arr = gcnew H5Array<T>(adims); interior_ptr<T> arr_ptr = arr->GetHandle(); for (int j = 0; j < arrayLength; ++j) { arr_ptr[j] = rdata[i*arrayLength+j]; } index = ArrayUtils::GetIndex((array<long long>^)dims, i); m_array->SetValue(arr->GetArray(), index); } } else { for (int i = 0; i < npoints; ++i) { H5Array<T>^ arr = gcnew H5Array<T>(adims); interior_ptr<T> arr_ptr = arr->GetHandle(); for (int j = 0; j < arrayLength; ++j) { arr_ptr[j] = rdata[i*arrayLength+j]; } m_array->SetValue(arr->GetArray(), i); } } m_ienum = m_array->GetEnumerator(); m_ienum->MoveNext(); } finally { if (mtype >= 0) { H5Tclose(mtype); } } } ~ArrayDatasetReaderT() { this->!ArrayDatasetReaderT(); } !ArrayDatasetReaderT() {} virtual void Close() {} virtual System::Collections::IList^ Read(long long readCount) { array<Array^>^ result = nullptr; long long remaining = m_array->LongLength - m_position; if (remaining > 0) { long long length = 0; if (readCount > remaining) { length = remaining; } else { if (readCount > 0) { length = readCount; } else { // return the full array w/o copying m_position = m_array->LongLength; return m_array; } } result = gcnew array<Array^>(safe_cast<int>(length)); // I have no idea how to efficiently copy a multidimensional array // into a onedimensional array for (int i = 0; i < length; ++i) { result[i] = safe_cast<Array^>(m_ienum->Current); m_ienum->MoveNext(); } m_position += length; } return result; } virtual void Seek(long long offset, System::IO::SeekOrigin origin) { offset = 0; origin = System::IO::SeekOrigin::End; throw gcnew PSH5XException("ArrayDatasetReaderT::Seek() not implemented!"); } private: System::Array^ m_array; System::Collections::IEnumerator^ m_ienum; long long m_position; }; }
[ "gheber@bc1736a7-42db-4d61-a5e1-31a1cdc50de3" ]
gheber@bc1736a7-42db-4d61-a5e1-31a1cdc50de3
18f6f2361c6d1ba2dc0d7926647dbfe3b0b48986
bb867828b2aa7211d08e86591c4fcabc3870edc6
/322-coin-change/solution.cpp
aa9838b385684bd43efb47269f093b3b14a31c7c
[]
no_license
zhiwei1988/LeetCode
de3c2b608a4837614c46139657b86f573c93eb12
ba2342998f40597c3e27c1cf09f0b90fa71e233a
refs/heads/master
2023-09-04T04:36:46.502821
2021-10-27T13:24:16
2021-10-27T13:24:16
239,124,852
0
0
null
null
null
null
UTF-8
C++
false
false
603
cpp
class Solution { public: int coinChange(vector<int>& coins, int amount) { // dp[i] 表示当总金额为 i 时所需的最小硬币个数 vector<int> dp(amount+1, amount+1); dp[0] = 0; for (int i = 1; i <= amount; i++) { for (int j = 0; j < coins.size(); j++) { int coin = coins[j]; if (i - coin < 0) { continue; } else { dp[i] = min(dp[i], dp[i-coin] + 1); } } } return dp[amount] == amount+1 ? -1 : dp[amount]; } };
[ "zhiweix1988@gmail.com" ]
zhiweix1988@gmail.com
d5756cc0ca44d7ded1cf758bb9c16472b45d6856
5acf116c716f09357ffa703edd1ddde954c08a45
/src/srv/fs/cfg_pre_process.cpp
32bb16ea7971175f50de0d93a38a9fab5b6f3962
[]
no_license
terencejia/demo-test
b372f2cec66034c0ca60395cc88dbb156dd29968
ed9c2f9eed4f8c0d383c8daed68df9235d24b925
refs/heads/master
2021-01-01T06:28:00.247361
2017-07-18T00:46:25
2017-07-18T00:46:25
97,428,512
0
0
null
2017-07-17T03:46:06
2017-07-17T02:48:18
null
UTF-8
C++
false
false
8,795
cpp
#include <fs_log.hpp> #include <zmsg/zmsg_utils.hpp> #include "cfg_pre_process.hpp" namespace svcFS { static void clamp_hvb_volt(double & dst, const double & max_volt) { if (dst < 0.0) { log_warning("hvb strength underflow %f increase to 0.0", dst); dst = 0.0; return; } if (dst > max_volt) { log_warning("hvb strength overflow %f decreased to %f", dst, max_volt); dst = max_volt; return; } } /** * \brief calculate the delta value for revising discharge magnitude */ double delta_discharge_magnitude( const discharge_data_t & base_data, const discharge_data_t & revise_data, const double prs_a1, const double prs_a2, const bool revise_for_temp, const double env_temp, const bool revise_for_prs, const double env_prs, const double logic_magnitude) { log_debug("logic_mag: %f, env_temp: %f, revise_temp: %f", logic_magnitude, env_temp, revise_data.temp); if (base_data.empty()) { log_warning("fs_spec: discharge base info is empty"); return 0; } if (revise_data.empty()) { log_warning("fs_spec: discharge revise info is empty"); return 0; } /// \note use double for all caclulation, to avoid minus on uint16_t double x = logic_magnitude; auto const pb = base_data.p; double y = (x - pb[0].x) * ((double)(pb[1].y) - pb[0].y) / ((double)(pb[1].x) - pb[0].x) + pb[0].y; auto const pr = revise_data.p; double ret = (y - pr[0].y) * ((double)(pr[1].x) - pr[0].x) / ((double)(pr[1].y) - pr[0].y) + pr[0].x; log_debug("b0x = %f, b0y = %f, b1x = %f, b1y = %f", pb[0].x, pb[0].y, pb[1].x, pb[1].y); log_debug("r0x = %f, r0y = %f, r1x = %f, r1y = %f", pr[0].x, pr[0].y, pr[1].x, pr[1].y); ret -= logic_magnitude; if (revise_for_temp) { log_warning("before temp revise %f", ret); ret += (revise_data.temp - env_temp) * 0.002; log_warning("after temp revisr %f", ret); } log_warning("before pressure revise : %f, %d", ret, (int)revise_for_prs); if (revise_for_prs) { static const double prs_p = 1.013; ret += (revise_data.pressure - env_prs) * (prs_a1 + prs_a2 * (prs_p * 2 - revise_data.pressure - env_prs)); log_warning("env pressure (%f). store pressure (%f), a1(%f), a2(%f)", env_prs, revise_data.pressure, prs_a1, prs_a2); } log_warning("after pressure revise : %f", ret); return ret; } void cfg_pre_process(fs_cfg_t & cfg, fs_data_t & new_data, const fs_data_t & last_data, fs_spec & spec, double env_temp, double env_prs) { const double delta_clr = delta_discharge_magnitude(spec.discharge_base, spec.discharge_revise, spec.hvb_pressure_compensate_coefficent1, spec.hvb_pressure_compensate_coefficent2, cfg.Temperature, env_temp, cfg.AirPressure, env_prs, cfg.CleanDischargeStrength); const double delta_pre = delta_discharge_magnitude(spec.discharge_base, spec.discharge_revise, spec.hvb_pressure_compensate_coefficent1, spec.hvb_pressure_compensate_coefficent2, cfg.Temperature, env_temp, cfg.AirPressure, env_prs, cfg.FiberPreFSStrength); const double delta_dis1 = delta_discharge_magnitude(spec.discharge_base, spec.discharge_revise, spec.hvb_pressure_compensate_coefficent1, spec.hvb_pressure_compensate_coefficent2, cfg.Temperature, env_temp, cfg.AirPressure, env_prs, cfg.Discharge1Strength); const double delta_dis2 = delta_discharge_magnitude(spec.discharge_base, spec.discharge_revise, spec.hvb_pressure_compensate_coefficent1, spec.hvb_pressure_compensate_coefficent2, cfg.Temperature, env_temp, cfg.AirPressure, env_prs, cfg.Discharge2Strength); bool realtime_revise = false; switch (cfg.FSPattern) { case fs_pattern_t::automatic: case fs_pattern_t::calibrate: case fs_pattern_t::normal: if (zmsg::to_val(fiber_t::sm) <= cfg.FiberType && cfg.FiberType < zmsg::to_val(fiber_t::max)) { realtime_revise = cfg.RealTimeRevise; } break; default: break; } cfg.RealTimeRevise = realtime_revise; double delta_clr_rt = 0; double delta_dis1_rt = 0; double delta_pre_rt = 0; double delta_dis2_rt = 0; if (realtime_revise && zmsg::to_val(fiber_t::sm) <= cfg.FiberType && cfg.FiberType <= zmsg::to_val(fiber_t::mm)) { double * prt_offset = nullptr; auto & rt_rev_info = spec.rt_revise_data[cfg.FiberType]; switch(cfg.FSPattern) { case fs_pattern_t::automatic: prt_offset = &rt_rev_info.rt_offset_auto; break; case fs_pattern_t::calibrate: case fs_pattern_t::normal: prt_offset = &rt_rev_info.rt_offset_cal; break; default: break; } if (prt_offset) { const double dis1_final = cfg.Discharge1Strength + delta_dis1 + *prt_offset; if (dis1_final > spec.hvb_max_volt) { *prt_offset -= dis1_final - spec.hvb_max_volt; } else if (dis1_final < 0) { *prt_offset -= dis1_final; } delta_dis1_rt = *prt_offset; delta_clr_rt = delta_dis1_rt * cfg.CleanDischargeStrength / cfg.Discharge1Strength; delta_dis2_rt = delta_dis1_rt * cfg.Discharge2Strength / cfg.Discharge1Strength; delta_pre_rt = delta_dis1_rt * cfg.FiberPreFSStrength / cfg.Discharge1Strength; } } cfg.CleanDischargeStrength += delta_clr + delta_clr_rt; clamp_hvb_volt(cfg.CleanDischargeStrength, spec.hvb_max_volt); cfg.FiberPreFSStrength += delta_pre + delta_pre_rt; clamp_hvb_volt(cfg.FiberPreFSStrength, spec.hvb_max_volt); cfg.Discharge1Strength += delta_dis1 + delta_dis1_rt; clamp_hvb_volt(cfg.Discharge1Strength, spec.hvb_max_volt); cfg.Discharge2Strength += delta_dis2 + delta_dis2_rt; clamp_hvb_volt(cfg.Discharge2Strength, spec.hvb_max_volt); #if 0 /// \todo if (last_data.cfg.FSPattern == cfg.FSPattern) { switch (cfg.FSPattern) { case fs_pattern_t::automatic: if (0.04 <= last_data.loss_db && last_data.loss_db <= 0.1 && last_data.pattern_compensate < 0.1) { new_data.pattern_compensate = last_data.pattern_compensate + 0.02; cfg.Discharge1Strength *= (1.0 + new_data.pattern_compensate); } break; case fs_pattern_t::calibrate: break; default: break; } } #else (void)new_data; (void)last_data; #endif } void cfg_pre_process(rt_cfg_t & /*cfg*/, rt_data_t & /*new_data*/, const rt_data_t & /*last_data*/, fs_spec & /*spec*/, double /*env_temp*/, double /*env_prs*/) { } void cfg_pre_process(da_cfg_t & /*cfg*/, da_data_t & /*new_data*/, const da_data_t & /*last_data*/, fs_spec & /*spec*/, double /*env_temp*/, double /*env_prs*/) { } void cfg_pre_process(mt_cfg_t & /*cfg*/, mt_data_t & /*new_data*/, const mt_data_t & /*last_data*/, fs_spec & /*spec*/, double /*env_temp*/, double /*env_prs*/) { } void cfg_pre_process(dc_cfg_t & /*cfg*/, dc_data_t & /*new_data*/, const dc_data_t & /*last_data*/, fs_spec & /*spec*/, double /*env_temp*/, double /*env_prs*/) { } void cfg_pre_process(fc_cfg_t & /*cfg*/, fc_data_t & /*new_data*/, const fc_data_t & /*last_data*/, fs_spec & /*spec*/, double /*env_temp*/, double /*env_prs*/) { } void cfg_pre_process(se_cfg_t & /*cfg*/, se_data_t & /*new_data*/, const se_data_t & /*last_data*/, fs_spec & /*spec*/, double /*env_temp*/, double /*env_prs*/) { } void cfg_pre_process(st_cfg_t & /*cfg*/, st_data_t & /*new_data*/, const st_data_t & /*last_data*/, fs_spec & /*spec*/, double /*env_temp*/, double /*env_prs*/) { } void cfg_pre_process(rr_cfg_t & cfg, rr_data_t & new_data, const rr_data_t & last_data, fs_spec & spec, double env_temp, double env_prs) { const double delta_clr = delta_discharge_magnitude(spec.discharge_base, spec.discharge_revise, spec.hvb_pressure_compensate_coefficent1, spec.hvb_pressure_compensate_coefficent2, cfg.Temperature, env_temp, cfg.AirPressure, env_prs, cfg.CleanDischargeStrength); const double delta_pre = delta_discharge_magnitude(spec.discharge_base, spec.discharge_revise, spec.hvb_pressure_compensate_coefficent1, spec.hvb_pressure_compensate_coefficent2, cfg.Temperature, env_temp, cfg.AirPressure, env_prs, cfg.FiberPreFSStrength); const double delta_dis1 = delta_discharge_magnitude(spec.discharge_base, spec.discharge_revise, spec.hvb_pressure_compensate_coefficent1, spec.hvb_pressure_compensate_coefficent2, cfg.Temperature, env_temp, cfg.AirPressure, env_prs, cfg.Discharge1Strength); const double delta_dis2 = delta_discharge_magnitude(spec.discharge_base, spec.discharge_revise, spec.hvb_pressure_compensate_coefficent1, spec.hvb_pressure_compensate_coefficent2, cfg.Temperature, env_temp, cfg.AirPressure, env_prs, cfg.Discharge2Strength); cfg.CleanDischargeStrength += delta_clr; clamp_hvb_volt(cfg.CleanDischargeStrength, spec.hvb_max_volt); cfg.FiberPreFSStrength += delta_pre; clamp_hvb_volt(cfg.FiberPreFSStrength, spec.hvb_max_volt); cfg.Discharge1Strength += delta_dis1; clamp_hvb_volt(cfg.Discharge1Strength, spec.hvb_max_volt); cfg.Discharge2Strength += delta_dis2; clamp_hvb_volt(cfg.Discharge2Strength, spec.hvb_max_volt); (void)new_data; (void)last_data; } } /* namespace svcFS */
[ "terence.jia@163.com" ]
terence.jia@163.com
18b0f8a0f1a42493ed18767fa0114dcd85f64382
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/WebKit/Source/modules/notifications/NotificationPermissionCallback.h
6aa5aec038ca5eb4d9a1f4381860cdc530d136fc
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
1,844
h
/* * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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. */ #ifndef NotificationPermissionCallback_h #define NotificationPermissionCallback_h #include "platform/heap/Handle.h" #include "wtf/Forward.h" namespace blink { class NotificationPermissionCallback : public GarbageCollectedFinalized<NotificationPermissionCallback> { public: virtual ~NotificationPermissionCallback() {} DEFINE_INLINE_VIRTUAL_TRACE() {} virtual void handleEvent(const String& permission) = 0; }; } // namespace blink #endif // NotificationPermissionCallback_h
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
336e972655d3093f96ebb58d335d9d4aae01cbde
f294032af74bb76a72a640cad3fe5e051c54a232
/Mapbox/MapboxAR/Classes/Native/Il2CppCompilerCalculateTypeValues_32Table.cpp
da90644f93a83881a2b6b26b6ead608a88254e38
[]
no_license
cgathergood/DomainAR
751faad5acc2806036fa82e7b61d01ab72d8cf16
28c5a9347eed5e1f66aa413e09f743a6e69887e4
refs/heads/master
2021-01-19T00:58:47.356117
2017-07-13T03:27:51
2017-07-13T03:27:51
95,612,386
0
0
null
null
null
null
UTF-8
C++
false
false
11,671
cpp
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include "class-internals.h" #include "codegen/il2cpp-codegen.h" #include "AssemblyU2DCSharp_Mapbox_Unity_Telemetry_Telemetry4023756181.h" #include "AssemblyU2DCSharp_Mapbox_Unity_Telemetry_TelemetryI582153264.h" #include "AssemblyU2DCSharp_Mapbox_Unity_Utilities_Conversion156910749.h" #include "AssemblyU2DCSharp_Mapbox_Unity_Utilities_GeocodeAtt630057338.h" #include "AssemblyU2DCSharp_Mapbox_Unity_Utilities_HTTPReque1810968295.h" #include "AssemblyU2DCSharp_Mapbox_Unity_Utilities_HTTPReque2787124111.h" #include "AssemblyU2DCSharp_Mapbox_Unity_Utilities_OpenUrlOn3313525014.h" #include "AssemblyU2DCSharp_Mapbox_Unity_Utilities_Runnable3925483335.h" #include "AssemblyU2DCSharp_Mapbox_Unity_Utilities_Runnable_1575210082.h" #include "AssemblyU2DCSharp_Mapbox_Unity_Utilities_Telemetry3421230039.h" #include "AssemblyU2DCSharp_Mapbox_Unity_Utilities_VectorExt1080051393.h" #include "AssemblyU2DCSharp_ParticlePainter1073897267.h" #include "AssemblyU2DCSharp_UnityEngine_XR_iOS_UnityARAmbient680084560.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU1486305137.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU3379926265.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU3469664187.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU4186495411.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU2306864765.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU3762068660.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU1568637719.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU1568637717.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU3740780830.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU2731437132.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU1459944470.h" #include "AssemblyU2DCSharp_U3CPrivateImplementationDetailsU3762068664.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3200 = { sizeof (TelemetryDummy_t4023756181), -1, sizeof(TelemetryDummy_t4023756181_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable3200[1] = { TelemetryDummy_t4023756181_StaticFields::get_offset_of__instance_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3201 = { sizeof (TelemetryIos_t582153264), -1, sizeof(TelemetryIos_t582153264_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable3201[1] = { TelemetryIos_t582153264_StaticFields::get_offset_of__instance_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3202 = { sizeof (Conversions_t156910749), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3202[4] = { 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3203 = { sizeof (GeocodeAttribute_t630057338), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3204 = { sizeof (HTTPRequest_t1810968295), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3204[5] = { HTTPRequest_t1810968295::get_offset_of__request_0(), HTTPRequest_t1810968295::get_offset_of__timeout_1(), HTTPRequest_t1810968295::get_offset_of__callback_2(), HTTPRequest_t1810968295::get_offset_of__wasCancelled_3(), HTTPRequest_t1810968295::get_offset_of_U3CIsCompletedU3Ek__BackingField_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3205 = { sizeof (U3CDoRequestU3Ec__Iterator0_t2787124111), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3205[5] = { U3CDoRequestU3Ec__Iterator0_t2787124111::get_offset_of_U3CresponseU3E__0_0(), U3CDoRequestU3Ec__Iterator0_t2787124111::get_offset_of_U24this_1(), U3CDoRequestU3Ec__Iterator0_t2787124111::get_offset_of_U24current_2(), U3CDoRequestU3Ec__Iterator0_t2787124111::get_offset_of_U24disposing_3(), U3CDoRequestU3Ec__Iterator0_t2787124111::get_offset_of_U24PC_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3206 = { sizeof (OpenUrlOnButtonClick_t3313525014), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3206[1] = { OpenUrlOnButtonClick_t3313525014::get_offset_of__url_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3207 = { sizeof (Runnable_t3925483335), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3207[2] = { Runnable_t3925483335::get_offset_of_m_Routines_2(), Runnable_t3925483335::get_offset_of_m_NextRoutineId_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3208 = { sizeof (Routine_t1575210082), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3208[4] = { Routine_t1575210082::get_offset_of_U3CIDU3Ek__BackingField_0(), Routine_t1575210082::get_offset_of_U3CStopU3Ek__BackingField_1(), Routine_t1575210082::get_offset_of_m_bMoveNext_2(), Routine_t1575210082::get_offset_of_m_Enumerator_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3209 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable3209[1] = { 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3210 = { sizeof (TelemetryConfigurationButton_t3421230039), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3210[1] = { TelemetryConfigurationButton_t3421230039::get_offset_of__booleanValue_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3211 = { sizeof (VectorExtensions_t1080051393), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3212 = { sizeof (ParticlePainter_t1073897267), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3212[14] = { ParticlePainter_t1073897267::get_offset_of_painterParticlePrefab_2(), ParticlePainter_t1073897267::get_offset_of_minDistanceThreshold_3(), ParticlePainter_t1073897267::get_offset_of_maxDistanceThreshold_4(), ParticlePainter_t1073897267::get_offset_of_frameUpdated_5(), ParticlePainter_t1073897267::get_offset_of_particleSize_6(), ParticlePainter_t1073897267::get_offset_of_penDistance_7(), ParticlePainter_t1073897267::get_offset_of_colorPicker_8(), ParticlePainter_t1073897267::get_offset_of_currentPS_9(), ParticlePainter_t1073897267::get_offset_of_particles_10(), ParticlePainter_t1073897267::get_offset_of_previousPosition_11(), ParticlePainter_t1073897267::get_offset_of_currentPaintVertices_12(), ParticlePainter_t1073897267::get_offset_of_currentColor_13(), ParticlePainter_t1073897267::get_offset_of_paintSystems_14(), ParticlePainter_t1073897267::get_offset_of_paintMode_15(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3213 = { sizeof (UnityARAmbient_t680084560), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3213[2] = { UnityARAmbient_t680084560::get_offset_of_l_2(), UnityARAmbient_t680084560::get_offset_of_m_Session_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3214 = { sizeof (U3CPrivateImplementationDetailsU3E_t1486305147), -1, sizeof(U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable3214[16] = { U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2D373B494F210C656134C5728D551D4C97B013EB33_0(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2DF5B52AE718355A38E8190D5F947B52DFB427A1D7_1(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2D81D5D8B4DDFA3FBB954AC400415044EB9F11E33E_2(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2DC0C10EC6AF4A4101F894B153E1CD493ADC01A67F_3(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2D6A94F0C3DCA389344CEDB99F171FA1E092E842E6_4(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2D8ED4E99B936B26A09EDFAB9E336CF75F4913B454_5(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2DF5F598DAC7D3E479CD72BAAB99EE6617D8190398_6(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2D2492606636F4A4666E0D617B51116A5A68539881_7(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2D472655E8FD2B8B97DB5D188D273A20E8834C19BB_8(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2DD8E4ACBC2D957C3344A3CAD69FCF9A60C8034DBF_9(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2DFD5BE77C4372533D7C16BF67D58A3ABBE604ED81_10(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2DAE6B2897A8B88E297D61124152931A88D5D977F4_11(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2D794CB2CC08B7EC30CA04323EFAC1B017E5B5D2C6_12(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2DAF107E8E5539AA04145F09728F7CE4E2B4AC5E72_13(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2DD3759F70F1732218F863B5A15ED41A79466DAF58_14(), U3CPrivateImplementationDetailsU3E_t1486305147_StaticFields::get_offset_of_U24fieldU2DBEEEBCEF33AF5B72B0463DF9185C0226DE5909AD_15(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3215 = { sizeof (U24ArrayTypeU3D1024_t3379926265)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D1024_t3379926265 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3216 = { sizeof (U24ArrayTypeU3D100_t3469664187)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D100_t3469664187 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3217 = { sizeof (U24ArrayTypeU3D2052_t4186495411)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D2052_t4186495411 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3218 = { sizeof (U24ArrayTypeU3D128_t2306864765)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D128_t2306864765 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3219 = { sizeof (U24ArrayTypeU3D64_t762068660)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D64_t762068660 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3220 = { sizeof (U24ArrayTypeU3D32_t1568637719)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D32_t1568637719 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3221 = { sizeof (U24ArrayTypeU3D12_t1568637718)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D12_t1568637718 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3222 = { sizeof (U24ArrayTypeU3D116_t740780830)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D116_t740780830 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3223 = { sizeof (U24ArrayTypeU3D20_t2731437132)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D20_t2731437132 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3224 = { sizeof (U24ArrayTypeU3D4_t1459944470)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D4_t1459944470 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3225 = { sizeof (U24ArrayTypeU3D24_t762068665)+ sizeof (Il2CppObject), sizeof(U24ArrayTypeU3D24_t762068665 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3226 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable3226[2] = { 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3227 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable3227[2] = { 0, 0, }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "calumgathergood@gmail.com" ]
calumgathergood@gmail.com
4e5b728069bdedc97cd4dc1d8e77b40bfa15c1d9
54ea76530e2f0823cc39bbfebc9c5f2ab28014c6
/remove-duplicates-from-sorted-array/remove-duplicates-from-sorted-array.cpp
cd77fab8291c95b1056082e318e683081711c7a9
[]
no_license
adithyagaurav/Cpp_problems
28e7323049adb99827ed4ba673e00121a69fe6e6
f1cc9ecd8d08c0c5311548edc7cfb306af251e45
refs/heads/main
2023-06-29T07:04:24.928404
2021-07-24T11:21:25
2021-07-24T11:21:25
380,239,666
0
0
null
null
null
null
UTF-8
C++
false
false
1,237
cpp
/* Solving the question using stack, each number from vector is popped, it is pushed to stack only if its not equal to the top of stack. Once all the elements from the vector have been popped, all the elements in stack are pushed back to the vector */ class Solution { public: int removeDuplicates(vector<int>& nums) { stack<int> st; int len = nums.size(), n; // Check for corner case if(len==0) return 0; // Pop last element from the vector and push it to stack without checks st.push(nums[nums.size()-1]); nums.pop_back(); // For each element popped from vector, push it to stack only if its not equal to the top for(int i=len-2;i>=0;i--){ cout<<nums.size()<<" "; n = nums[i]; nums.pop_back(); if(st.top() != n){ st.push(n); } } // All the elements have been popped and distinct elements filtered in stack. Push stack elements back to vector and return new length while(!st.empty()){ n = st.top(); st.pop(); nums.push_back(n); } return nums.size(); } };
[ "41729963+adithyagaurav@users.noreply.github.com" ]
41729963+adithyagaurav@users.noreply.github.com
4a38456abd3ba83d84cf44932962ef05799b6bd8
91b73204301dc0d26a196ec03da4d1f20d6834ec
/javac.cpp
7b388454c73ace340f474d8d0ac5235121f4c648
[]
no_license
kkathpal153/Spoj-
eec8347a0e64661798ebfb1057fcd6cef0d54006
37a947a22d0936a7f354854bff72dcb2d3d76b64
refs/heads/master
2021-01-10T08:29:32.415944
2018-09-24T12:19:56
2018-09-24T12:19:56
52,425,031
0
0
null
null
null
null
UTF-8
C++
false
false
1,117
cpp
#include<iostream> #include<string.h> using namespace std; void cp (string s) { int i; if(s[0]=='_'||s[s.length()-1]=='_') { cout<<"Error!\n"; return; } for(i=0;i<s.length();i++) { if((s[i]=='_'&&s[i+1]!='_')&&islower(s[i+1])) { s.erase(s.begin()+i); s[i]=toupper(s[i]); } else if(isupper(s[i])||(s[i]=='_'&&s[i+1]=='_')) { cout<<"Error!\n"; return; } } cout<<s<<endl; } void java(string s) { int i; bool d; if(isupper(s[0])) { cout<<"Error!\n"; return; } for(i=0;i<s.length();i++) { if(isupper(s[i])) { s.insert(s.begin()+i,'_'); s[i+1]=tolower(s[i+1]); i++; } } cout<<s<<"\n"; } void check(string s) { bool l,d; int i; for(i=0;i<s.length();i++){ if(s[i]=='_') { d=true; cp(s); return; } } if(!d) { for(i=0;i<s.length();i++){ if(isupper(s[i])) { l=true; java(s); return; } } } cout<<s<<"\n"; } int main() { char c[102]; string s; int i,j,l,k; while(cin>>s) { check(s); } }
[ "kunalkathpal153@gmail.com" ]
kunalkathpal153@gmail.com
9d73cd62a08f0d0d5d1d792bc6f7eab2926ff8b1
548f0ab0398613c5221778010e865c3652d0d00b
/SampleOSXCocoaPodsProject/Pods/BRCLucene/src/core/CLucene/index/SegmentReader.cpp
a109e486051864f6ecf2d81fa3e244310d09c219
[ "Apache-2.0", "LGPL-2.0-or-later", "LGPL-2.1-or-later" ]
permissive
vlado-rudenok/BRFullTextSearch
921cdeab5600f843f2bafb0a6607f52f4f0c867d
22e50bc92e48c5af3803f0ad503298b2438b8e79
refs/heads/master
2020-07-01T06:50:03.027375
2017-07-19T03:35:15
2017-07-19T03:35:15
201,080,316
0
0
Apache-2.0
2019-08-07T15:45:44
2019-08-07T15:45:43
null
UTF-8
C++
false
false
36,121
cpp
/*------------------------------------------------------------------------------ * Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team * * Distributable under the terms of either the Apache License (Version 2.0) or * the GNU Lesser General Public License, as specified in the COPYING file. ------------------------------------------------------------------------------*/ #include "CLucene/_ApiHeader.h" #include "CLucene/util/Misc.h" #include "_SegmentHeader.h" #include "_MultiSegmentReader.h" #include "_FieldInfos.h" #include "_FieldsReader.h" #include "IndexReader.h" #include "_TermInfosReader.h" #include "Terms.h" #include "CLucene/search/Similarity.h" #include "CLucene/store/FSDirectory.h" #include "CLucene/util/PriorityQueue.h" #include "_SegmentMerger.h" #include <assert.h> CL_NS_USE(util) CL_NS_USE(store) CL_NS_USE(document) CL_NS_USE(search) CL_NS_DEF(index) SegmentReader::Norm::Norm(IndexInput* instrm, bool _useSingleNormStream, int32_t n, int64_t ns, SegmentReader* r, const char* seg): number(n), normSeek(ns), _this(r), segment(seg), useSingleNormStream(_useSingleNormStream), in(instrm), bytes(NULL), dirty(false){ //Func - Constructor //Pre - instrm is a valid reference to an IndexInput //Post - A Norm instance has been created with an empty bytes array refCount = 1; bytes = NULL; dirty = false; } SegmentReader::Norm::~Norm() { //Func - Destructor //Pre - true //Post - The IndexInput in has been deleted (and closed by its destructor) // and the array too. //Close and destroy the inputstream in-> The inputstream will be closed // by its destructor. Note that the IndexInput 'in' actually is a pointer!!!!! if ( in != _this->singleNormStream ) _CLDELETE(in); //Delete the bytes array _CLDELETE_ARRAY(bytes); } void SegmentReader::Norm::doDelete(Norm* norm){ if ( norm->refCount == 0 ){ _CLLDELETE(norm); } } void SegmentReader::Norm::close(){ SCOPED_LOCK_MUTEX(THIS_LOCK) if (in != NULL && !useSingleNormStream) { in->close(); _CLDELETE(in); } in = NULL; } void SegmentReader::Norm::incRef() { SCOPED_LOCK_MUTEX(THIS_LOCK) assert (refCount > 0); refCount++; } void SegmentReader::Norm::decRef(){ SCOPED_LOCK_MUTEX(THIS_LOCK) assert (refCount > 0); if (refCount == 1) { close(); } refCount--; } void SegmentReader::Norm::reWrite(SegmentInfo* si){ // NOTE: norms are re-written in regular directory, not cfs si->advanceNormGen(this->number); IndexOutput* out = _this->directory()->createOutput(si->getNormFileName(this->number).c_str()); try { out->writeBytes(bytes, _this->maxDoc()); }_CLFINALLY( out->close(); _CLDELETE(out) ); this->dirty = false; } void SegmentReader::initialize(SegmentInfo* si, int32_t readBufferSize, bool doOpenStores, bool doingReopen){ //Pre - si-> is a valid reference to SegmentInfo instance // identified by si-> //Post - All files of the segment have been read this->deletedDocs = NULL; this->ones = NULL; //There are no documents yet marked as deleted this->deletedDocsDirty = false; this->normsDirty=false; this->undeleteAll=false; this->rollbackDeletedDocsDirty = false; this->rollbackNormsDirty = false; this->rollbackUndeleteAll = false; //Duplicate the name of the segment from SegmentInfo to segment this->segment = si->name; // make sure that all index files have been read or are kept open // so that if an index update removes them we'll still have them this->freqStream = NULL; this->proxStream = NULL; this->singleNormStream = NULL; this->termVectorsReaderOrig = NULL; this->_fieldInfos = NULL; this->tis = NULL; this->fieldsReader = NULL; this->cfsReader = NULL; this->storeCFSReader = NULL; this->segment = si->name; this->si = si; this->readBufferSize = readBufferSize; if ( doingReopen ) return; // the rest is done in the reopen code... bool success = false; try { // Use compound file directory for some files, if it exists Directory* cfsDir = directory(); if (si->getUseCompoundFile()) { cfsReader = _CLNEW CompoundFileReader(directory(), (segment + "." + IndexFileNames::COMPOUND_FILE_EXTENSION).c_str(), readBufferSize); cfsDir = cfsReader; } Directory* storeDir; if (doOpenStores) { if (si->getDocStoreOffset() != -1) { if (si->getDocStoreIsCompoundFile()) { storeCFSReader = _CLNEW CompoundFileReader(directory(), (si->getDocStoreSegment() + "." + IndexFileNames::COMPOUND_FILE_STORE_EXTENSION).c_str(), readBufferSize); storeDir = storeCFSReader; } else { storeDir = directory(); } } else { storeDir = cfsDir; } } else storeDir = NULL; // No compound file exists - use the multi-file format _fieldInfos = _CLNEW FieldInfos(cfsDir, (segment + ".fnm").c_str() ); string fieldsSegment; if (si->getDocStoreOffset() != -1) fieldsSegment = si->getDocStoreSegment(); else fieldsSegment = segment; if (doOpenStores) { fieldsReader = _CLNEW FieldsReader(storeDir, fieldsSegment.c_str(), _fieldInfos, readBufferSize, si->getDocStoreOffset(), si->docCount); // Verify two sources of "maxDoc" agree: if (si->getDocStoreOffset() == -1 && fieldsReader->size() != si->docCount) { string err = "doc counts differ for segment "; err += si->name; err += ": fieldsReader shows "; err += fieldsReader->size(); err += " but segmentInfo shows "; err += si->docCount; _CLTHROWA(CL_ERR_CorruptIndex, err.c_str() ); } } tis = _CLNEW TermInfosReader(cfsDir, segment.c_str(), _fieldInfos, readBufferSize); loadDeletedDocs(); // make sure that all index files have been read or are kept open // so that if an index update removes them we'll still have them freqStream = cfsDir->openInput( (segment + ".frq").c_str(), readBufferSize); proxStream = cfsDir->openInput( (segment + ".prx").c_str(), readBufferSize); openNorms(cfsDir, readBufferSize); if (doOpenStores && _fieldInfos->hasVectors()) { // open term vector files only as needed string vectorsSegment; if (si->getDocStoreOffset() != -1) vectorsSegment = si->getDocStoreSegment(); else vectorsSegment = segment; termVectorsReaderOrig = _CLNEW TermVectorsReader(storeDir, vectorsSegment.c_str(), _fieldInfos, readBufferSize, si->getDocStoreOffset(), si->docCount); } success = true; } _CLFINALLY ( // With lock-less commits, it's entirely possible (and // fine) to hit a FileNotFound exception above. In // this case, we want to explicitly close any subset // of things that were opened so that we don't have to // wait for a GC to do so. if (!success) { doClose(); } ) } SegmentReader* SegmentReader::get(SegmentInfo* si, bool doOpenStores) { return get(si->dir, si, NULL, false, false, BufferedIndexInput::BUFFER_SIZE, doOpenStores); } SegmentReader* SegmentReader::get(SegmentInfo* si, int32_t readBufferSize, bool doOpenStores){ return get(si->dir, si, NULL, false, false, readBufferSize, doOpenStores); } SegmentReader* SegmentReader::get(SegmentInfos* sis, SegmentInfo* si, bool closeDir) { return get(si->dir, si, sis, closeDir, true, BufferedIndexInput::BUFFER_SIZE, true); } /** * @throws CorruptIndexException if the index is corrupt * @throws IOException if there is a low-level IO error */ SegmentReader* SegmentReader::get(Directory* dir, SegmentInfo* si, SegmentInfos* sis, bool closeDir, bool ownDir, int32_t readBufferSize, bool doOpenStores){ SegmentReader* instance = _CLNEW SegmentReader(); //todo: make this configurable... instance->init(dir, sis, closeDir); instance->initialize(si, readBufferSize==-1 ? BufferedIndexInput::BUFFER_SIZE : readBufferSize, doOpenStores, false); return instance; } SegmentReader::SegmentReader(): DirectoryIndexReader(), _norms(false,true) { } SegmentReader::~SegmentReader(){ //Func - Destructor. //Pre - doClose has been invoked! //Post - the instance has been destroyed doClose(); //this means that index reader doesn't need to be closed manually _CLDELETE(_fieldInfos); _CLDELETE(fieldsReader); _CLDELETE(tis); _CLDELETE(freqStream); _CLDELETE(proxStream); _CLDELETE(deletedDocs); _CLDELETE_ARRAY(ones); _CLDELETE(termVectorsReaderOrig) _CLDECDELETE(cfsReader); //termVectorsLocal->unregister(this); } void SegmentReader::commitChanges(){ if (deletedDocsDirty) { // re-write deleted si->advanceDelGen(); // We can write directly to the actual name (vs to a // .tmp & renaming it) because the file is not live // until segments file is written: deletedDocs->write(directory(), si->getDelFileName().c_str()); } if (undeleteAll && si->hasDeletions()) { si->clearDelGen(); } if (normsDirty) { // re-write norms si->setNumFields(_fieldInfos->size()); NormsType::iterator it = _norms.begin(); while (it != _norms.end()) { Norm* norm = it->second; if (norm->dirty) { norm->reWrite(si); } it++; } } deletedDocsDirty = false; normsDirty = false; undeleteAll = false; } void SegmentReader::doClose() { //Func - Closes all streams to the files of a single segment //Pre - fieldsReader != NULL // tis != NULL //Post - All streams to files have been closed _CLDELETE(deletedDocs); // close the single norms stream if (singleNormStream != NULL) { // we can close this stream, even if the norms // are shared, because every reader has it's own // singleNormStream singleNormStream->close(); _CLDELETE(singleNormStream); } // re-opened SegmentReaders have their own instance of FieldsReader if (fieldsReader != NULL) { fieldsReader->close(); _CLDELETE(fieldsReader); } if (tis != NULL) { tis->close(); _CLDELETE(tis); } //Close the frequency stream if (freqStream != NULL){ freqStream->close(); _CLDELETE(freqStream); } //Close the prox stream if (proxStream != NULL){ proxStream->close(); _CLDELETE(proxStream); } if (termVectorsReaderOrig != NULL){ termVectorsReaderOrig->close(); _CLDELETE(termVectorsReaderOrig); } if (cfsReader != NULL){ cfsReader->close(); _CLDECDELETE(cfsReader); } if (storeCFSReader != NULL){ storeCFSReader->close(); _CLDELETE(storeCFSReader); } this->decRefNorms(); _norms.clear(); // maybe close directory DirectoryIndexReader::doClose(); } bool SegmentReader::hasDeletions() const{ // Don't call ensureOpen() here (it could affect performance) return deletedDocs != NULL; } //static bool SegmentReader::usesCompoundFile(SegmentInfo* si) { return si->getUseCompoundFile(); } //static bool SegmentReader::hasSeparateNorms(SegmentInfo* si) { return si->hasSeparateNorms(); } bool SegmentReader::hasDeletions(const SegmentInfo* si) { //Func - Static method // Checks if a segment managed by SegmentInfo si-> has deletions //Pre - si-> holds a valid reference to an SegmentInfo instance //Post - if the segement contains deleteions true is returned otherwise flas // Don't call ensureOpen() here (it could affect performance) return si->hasDeletions(); } //synchronized void SegmentReader::doDelete(const int32_t docNum){ //Func - Marks document docNum as deleted //Pre - docNum >=0 and DocNum < maxDoc() // docNum contains the number of the document that must be // marked deleted //Post - The document identified by docNum has been marked deleted SCOPED_LOCK_MUTEX(THIS_LOCK) CND_PRECONDITION(docNum >= 0, "docNum is a negative number"); CND_PRECONDITION(docNum < maxDoc(), "docNum is bigger than the total number of documents"); //Check if deletedDocs exists if (deletedDocs == NULL){ deletedDocs = _CLNEW BitSet(maxDoc()); //Condition check to see if deletedDocs points to a valid instance CND_CONDITION(deletedDocs != NULL,"No memory could be allocated for deletedDocs"); } //Flag that there are documents marked deleted deletedDocsDirty = true; undeleteAll = false; //Mark document identified by docNum as deleted deletedDocs->set(docNum); } void SegmentReader::doUndeleteAll(){ _CLDELETE(deletedDocs); deletedDocsDirty = false; undeleteAll = true; } void SegmentReader::files(vector<string>& retarray) { //Func - Returns all file names managed by this SegmentReader //Pre - segment != NULL //Post - All filenames managed by this SegmentRead have been returned vector<string> tmp = si->files(); retarray.insert(retarray.end(),tmp.begin(),tmp.end()); } TermEnum* SegmentReader::terms() { //Func - Returns an enumeration of all the Terms and TermInfos in the set. //Pre - tis != NULL //Post - An enumeration of all the Terms and TermInfos in the set has been returned CND_PRECONDITION(tis != NULL, "tis is NULL"); ensureOpen(); return tis->terms(); } TermEnum* SegmentReader::terms(const Term* t) { //Func - Returns an enumeration of terms starting at or after the named term t //Pre - t != NULL // tis != NULL //Post - An enumeration of terms starting at or after the named term t CND_PRECONDITION(t != NULL, "t is NULL"); CND_PRECONDITION(tis != NULL, "tis is NULL"); ensureOpen(); return tis->terms(t); } bool SegmentReader::document(int32_t n, Document& doc, const FieldSelector* fieldSelector) { //Func - writes the fields of document n into doc //Pre - n >=0 and identifies the document n //Post - if the document has been deleted then an exception has been thrown // otherwise a reference to the found document has been returned SCOPED_LOCK_MUTEX(THIS_LOCK) ensureOpen(); CND_PRECONDITION(n >= 0, "n is a negative number"); //Check if the n-th document has been marked deleted if (isDeleted(n)){ _CLTHROWA( CL_ERR_InvalidState,"attempt to access a deleted document" ); } //Retrieve the n-th document return fieldsReader->doc(n, doc, fieldSelector); } bool SegmentReader::isDeleted(const int32_t n){ //Func - Checks if the n-th document has been marked deleted //Pre - n >=0 and identifies the document n //Post - true has been returned if document n has been deleted otherwise fralse SCOPED_LOCK_MUTEX(THIS_LOCK) CND_PRECONDITION(n >= 0, "n is a negative number"); //Is document n deleted bool ret = (deletedDocs != NULL && deletedDocs->get(n)); return ret; } TermDocs* SegmentReader::termDocs() { //Func - Returns an unpositioned TermDocs enumerator. //Pre - true //Post - An unpositioned TermDocs enumerator has been returned ensureOpen(); return _CLNEW SegmentTermDocs(this); } TermPositions* SegmentReader::termPositions() { //Func - Returns an unpositioned TermPositions enumerator. //Pre - true //Post - An unpositioned TermPositions enumerator has been returned ensureOpen(); return _CLNEW SegmentTermPositions(this); } int32_t SegmentReader::docFreq(const Term* t) { //Func - Returns the number of documents which contain the term t //Pre - t holds a valid reference to a Term //Post - The number of documents which contain term t has been returned ensureOpen(); //Get the TermInfo ti for Term t in the set TermInfo* ti = tis->get(t); //Check if an TermInfo has been returned if (ti){ //Get the frequency of the term int32_t ret = ti->docFreq; //TermInfo ti is not needed anymore so delete it _CLDELETE( ti ); //return the number of documents which containt term t return ret; } else //No TermInfo returned so return 0 return 0; } int32_t SegmentReader::numDocs() { //Func - Returns the actual number of documents in the segment //Pre - true //Post - The actual number of documents in the segments ensureOpen(); //Get the number of all the documents in the segment including the ones that have //been marked deleted int32_t n = maxDoc(); //Check if there any deleted docs if (deletedDocs != NULL) //Substract the number of deleted docs from the number returned by maxDoc n -= deletedDocs->count(); //return the actual number of documents in the segment return n; } int32_t SegmentReader::maxDoc() const { //Func - Returns the number of all the documents in the segment including // the ones that have been marked deleted //Pre - true //Post - The total number of documents in the segment has been returned // Don't call ensureOpen() here (it could affect performance) return si->docCount; } void SegmentReader::setTermInfosIndexDivisor(int32_t indexDivisor){ tis->setIndexDivisor(indexDivisor); } int32_t SegmentReader::getTermInfosIndexDivisor() { return tis->getIndexDivisor(); } void SegmentReader::getFieldNames(FieldOption fldOption, StringArrayWithDeletor& retarray){ ensureOpen(); size_t len = _fieldInfos->size(); for (size_t i = 0; i < len; i++) { FieldInfo* fi = _fieldInfos->fieldInfo(i); bool v=false; if (fldOption & IndexReader::ALL) { v=true; }else { if (!fi->isIndexed && (fldOption & IndexReader::UNINDEXED) ) v=true; else if (fi->isIndexed && (fldOption & IndexReader::INDEXED) ) v=true; else if (fi->storePayloads && (fldOption & IndexReader::STORES_PAYLOADS) ) v=true; else if (fi->isIndexed && fi->storeTermVector == false && ( fldOption & IndexReader::INDEXED_NO_TERMVECTOR) ) v=true; else if ( (fldOption & IndexReader::TERMVECTOR) && fi->storeTermVector == true && fi->storePositionWithTermVector == false && fi->storeOffsetWithTermVector == false ) v=true; else if (fi->isIndexed && fi->storeTermVector && (fldOption & IndexReader::INDEXED_WITH_TERMVECTOR) ) v=true; else if (fi->storePositionWithTermVector && fi->storeOffsetWithTermVector == false && (fldOption & IndexReader::TERMVECTOR_WITH_POSITION)) v=true; else if (fi->storeOffsetWithTermVector && fi->storePositionWithTermVector == false && (fldOption & IndexReader::TERMVECTOR_WITH_OFFSET) ) v=true; else if ((fi->storeOffsetWithTermVector && fi->storePositionWithTermVector) && (fldOption & IndexReader::TERMVECTOR_WITH_POSITION_OFFSET) ) v=true; } if ( v ) retarray.push_back(STRDUP_TtoT(fi->name)); } } bool SegmentReader::hasNorms(const TCHAR* field){ ensureOpen(); return _norms.find(field) != _norms.end(); } void SegmentReader::norms(const TCHAR* field, uint8_t* bytes) { //Func - Reads the Norms for field from disk starting at offset in the inputstream //Pre - field != NULL // bytes != NULL is an array of bytes which is to be used to read the norms into. // it is advisable to have bytes initalized by zeroes! //Post - The if an inputstream to the norm file could be retrieved the bytes have been read // You are never sure whether or not the norms have been read into bytes properly!!!!!!!!!!!!!!!!! CND_PRECONDITION(field != NULL, "field is NULL"); CND_PRECONDITION(bytes != NULL, "field is NULL"); SCOPED_LOCK_MUTEX(THIS_LOCK) ensureOpen(); Norm* norm = _norms.get(field); if ( norm == NULL ){ memcpy(bytes, fakeNorms(), maxDoc()); return; } {SCOPED_LOCK_MUTEX(norm->THIS_LOCK) if (norm->bytes != NULL) { // can copy from cache memcpy(bytes, norm->bytes, maxDoc()); return; } // Read from disk. norm.in may be shared across multiple norms and // should only be used in a synchronized context. IndexInput* normStream; if (norm->useSingleNormStream) { normStream = singleNormStream; } else { normStream = norm->in; } normStream->seek(norm->normSeek); normStream->readBytes(bytes, maxDoc()); } } uint8_t* SegmentReader::createFakeNorms(int32_t size) { uint8_t* ones = _CL_NEWARRAY(uint8_t,size); if ( size > 0 ) memset(ones, DefaultSimilarity::encodeNorm(1.0f), size); return ones; } uint8_t* SegmentReader::fakeNorms() { if (ones==NULL) ones=createFakeNorms(maxDoc()); return ones; } // can return NULL if norms aren't stored uint8_t* SegmentReader::getNorms(const TCHAR* field) { SCOPED_LOCK_MUTEX(THIS_LOCK) Norm* norm = _norms.get(field); if (norm == NULL) return NULL; // not indexed, or norms not stored {SCOPED_LOCK_MUTEX(norm->THIS_LOCK) if (norm->bytes == NULL) { // value not yet read uint8_t* bytes = _CL_NEWARRAY(uint8_t, maxDoc()); norms(field, bytes); norm->bytes = bytes; // cache it // it's OK to close the underlying IndexInput as we have cached the // norms and will never read them again. norm->close(); } return norm->bytes; } } void SegmentReader::decRefNorms(){ SCOPED_LOCK_MUTEX(THIS_LOCK) NormsType::iterator it = _norms.begin(); while (it != _norms.end()) { Norm* norm = it->second; norm->decRef(); it++; } } DirectoryIndexReader* SegmentReader::doReopen(SegmentInfos* infos){ SCOPED_LOCK_MUTEX(THIS_LOCK) DirectoryIndexReader* newReader; if (infos->size() == 1) { SegmentInfo* si = infos->info(0); if (segment.compare(si->name)==0 && si->getUseCompoundFile() == this->si->getUseCompoundFile()) { newReader = reopenSegment(si); } else { // segment not referenced anymore, reopen not possible // or segment format changed newReader = SegmentReader::get(infos, infos->info(0), false); } } else { ValueArray<IndexReader*> readers(1); readers.values[0] = this; return _CLNEW MultiSegmentReader(_directory, infos, closeDirectory, &readers, NULL, NULL); } return newReader; } uint8_t* SegmentReader::norms(const TCHAR* field) { //Func - Returns the bytes array that holds the norms of a named field //Pre - field != NULL and contains the name of the field for which the norms // must be retrieved //Post - If there was norm for the named field then a bytes array has been allocated // and returned containing the norms for that field. If the named field is unknown NULL is returned. CND_PRECONDITION(field != NULL, "field is NULL"); SCOPED_LOCK_MUTEX(THIS_LOCK) ensureOpen(); uint8_t* bytes = getNorms(field); if (bytes==NULL) bytes=fakeNorms(); return bytes; } void SegmentReader::doSetNorm(int32_t doc, const TCHAR* field, uint8_t value){ Norm* norm = _norms.get(field); if (norm == NULL) // not an indexed field return; norm->dirty = true; // mark it dirty normsDirty = true; uint8_t* bits = norms(field); bits[doc] = value; // set the value } string SegmentReader::SegmentName(const char* ext, const int32_t x){ //Func - Returns an allocated buffer in which it creates a filename by // concatenating segment with ext and x //Pre ext != NULL and holds the extension // x contains a number //Post - A buffer has been instantiated an when x = -1 buffer contains the concatenation of // segment and ext otherwise buffer contains the contentation of segment, ext and x CND_PRECONDITION(ext != NULL, "ext is NULL"); return Misc::segmentname(segment.c_str(),ext,x); } void SegmentReader::openNorms(Directory* cfsDir, int32_t readBufferSize) { //Func - Open all norms files for all fields // Creates for each field a norm Instance with an open inputstream to // a corresponding norm file ready to be read //Pre - true //Post - For each field a norm instance has been created with an open inputstream to // a corresponding norm file ready to be read int64_t nextNormSeek = SegmentMerger::NORMS_HEADER_length; //skip header (header unused for now) int32_t _maxDoc = maxDoc(); for (size_t i = 0; i < _fieldInfos->size(); i++) { FieldInfo* fi = _fieldInfos->fieldInfo(i); if (_norms.find(fi->name) != _norms.end()) { // in case this SegmentReader is being re-opened, we might be able to // reuse some norm instances and skip loading them here continue; } if (fi->isIndexed && !fi->omitNorms) { Directory* d = directory(); string fileName = si->getNormFileName(fi->number); if (!si->hasSeparateNorms(fi->number)) { d = cfsDir; } // singleNormFile means multiple norms share this file string ext = string(".") + IndexFileNames::NORMS_EXTENSION; bool singleNormFile = fileName.compare(fileName.length()-ext.length(),ext.length(),ext)==0; IndexInput* normInput = NULL; int64_t normSeek; if (singleNormFile) { normSeek = nextNormSeek; if (singleNormStream==NULL) { singleNormStream = d->openInput(fileName.c_str(), readBufferSize); } // All norms in the .nrm file can share a single IndexInput since // they are only used in a synchronized context. // If this were to change in the future, a clone could be done here. normInput = singleNormStream; } else { normSeek = 0; normInput = d->openInput(fileName.c_str()); } _norms[fi->name] = _CLNEW Norm(normInput, singleNormFile, fi->number, normSeek, this, segment.c_str()); nextNormSeek += _maxDoc; // increment also if some norms are separate } } } TermVectorsReader* SegmentReader::getTermVectorsReader() { TermVectorsReader* tvReader = termVectorsLocal.get(); if (tvReader == NULL) { tvReader = termVectorsReaderOrig->clone(); termVectorsLocal.set(tvReader); } return tvReader; } FieldsReader* SegmentReader::getFieldsReader() { return fieldsReader; } FieldInfos* SegmentReader::getFieldInfos() { return _fieldInfos; } TermFreqVector* SegmentReader::getTermFreqVector(int32_t docNumber, const TCHAR* field){ ensureOpen(); if ( field != NULL ){ // Check if this field is invalid or has no stored term vector FieldInfo* fi = _fieldInfos->fieldInfo(field); if (fi == NULL || !fi->storeTermVector || termVectorsReaderOrig == NULL ) return NULL; } TermVectorsReader* termVectorsReader = getTermVectorsReader(); if (termVectorsReader == NULL) return NULL; return termVectorsReader->get(docNumber, field); } ArrayBase<TermFreqVector*>* SegmentReader::getTermFreqVectors(int32_t docNumber) { ensureOpen(); if (termVectorsReaderOrig == NULL) return NULL; TermVectorsReader* termVectorsReader = getTermVectorsReader(); if (termVectorsReader == NULL) return NULL; return termVectorsReader->get(docNumber); } void SegmentReader::getTermFreqVector(int32_t docNumber, const TCHAR* field, TermVectorMapper* mapper) { ensureOpen(); FieldInfo* fi = _fieldInfos->fieldInfo(field); if (fi == NULL || !fi->storeTermVector || termVectorsReaderOrig == NULL) return; TermVectorsReader* termVectorsReader = getTermVectorsReader(); if (termVectorsReader == NULL) { return; } termVectorsReader->get(docNumber, field, mapper); } void SegmentReader::getTermFreqVector(int32_t docNumber, TermVectorMapper* mapper){ ensureOpen(); if (termVectorsReaderOrig == NULL) return; TermVectorsReader* termVectorsReader = getTermVectorsReader(); if (termVectorsReader == NULL) return; termVectorsReader->get(docNumber, mapper); } void SegmentReader::loadDeletedDocs(){ // NOTE: the bitvector is stored using the regular directory, not cfs if (hasDeletions(si)) { deletedDocs = _CLNEW BitVector(directory(), si->getDelFileName().c_str()); // Verify # deletes does not exceed maxDoc for this segment: if (deletedDocs->count() > maxDoc()) { string err = "number of deletes ("; err += deletedDocs->count(); err += ") exceeds max doc ("; err += maxDoc(); err += ") for segment "; err += si->name; _CLTHROWA(CL_ERR_CorruptIndex, err.c_str()); } } } SegmentReader* SegmentReader::reopenSegment(SegmentInfo* si){ SCOPED_LOCK_MUTEX(THIS_LOCK) bool deletionsUpToDate = (this->si->hasDeletions() == si->hasDeletions()) && (!si->hasDeletions() || this->si->getDelFileName().compare(si->getDelFileName())==0 ); bool normsUpToDate = true; ValueArray<bool>fieldNormsChanged(_fieldInfos->size()); if (normsUpToDate) { for (size_t i = 0; i < _fieldInfos->size(); i++) { if (this->si->getNormFileName(i).compare(si->getNormFileName(i)) != 0) { normsUpToDate = false; fieldNormsChanged.values[i] = true; } } } if (normsUpToDate && deletionsUpToDate) { this->si = si; //force the result to use the new segment info (the old one is going to go away!) return this; } // clone reader SegmentReader* clone = NULL; bool success = false; try { clone = _CLNEW SegmentReader(); clone->init(_directory, NULL, false); clone->initialize(si, readBufferSize, false, true); clone->cfsReader = cfsReader; clone->storeCFSReader = storeCFSReader; clone->_fieldInfos = _fieldInfos; clone->tis = tis; clone->freqStream = freqStream; clone->proxStream = proxStream; clone->termVectorsReaderOrig = termVectorsReaderOrig; // we have to open a new FieldsReader, because it is not thread-safe // and can thus not be shared among multiple SegmentReaders // TODO: Change this in case FieldsReader becomes thread-safe in the future string fieldsSegment; Directory* storeDir = directory(); if (si->getDocStoreOffset() != -1) { fieldsSegment = si->getDocStoreSegment(); if (storeCFSReader != NULL) { storeDir = storeCFSReader; } } else { fieldsSegment = segment; if (cfsReader != NULL) { storeDir = cfsReader; } } if (fieldsReader != NULL) { clone->fieldsReader = _CLNEW FieldsReader(storeDir, fieldsSegment.c_str(), _fieldInfos, readBufferSize, si->getDocStoreOffset(), si->docCount); } if (!deletionsUpToDate) { // load deleted docs clone->deletedDocs = NULL; clone->loadDeletedDocs(); } else { clone->deletedDocs = this->deletedDocs; } if (!normsUpToDate) { // load norms for (size_t i = 0; i < fieldNormsChanged.length; i++) { // copy unchanged norms to the cloned reader and incRef those norms if (!fieldNormsChanged[i]) { const TCHAR* curField = _fieldInfos->fieldInfo(i)->name; Norm* norm = this->_norms.get(curField); norm->incRef(); norm->_this = clone; //give the norm to the clone clone->_norms.put(curField, norm); } } clone->openNorms(si->getUseCompoundFile() ? cfsReader : directory(), readBufferSize); } else { NormsType::iterator it = _norms.begin(); while (it != _norms.end()) { const TCHAR* field = it->first; Norm* norm = _norms[field]; norm->incRef(); norm->_this = clone; //give the norm to the clone clone->_norms.put(field, norm); it++; } } if (clone->singleNormStream == NULL) { for (size_t i = 0; i < _fieldInfos->size(); i++) { FieldInfo* fi = _fieldInfos->fieldInfo(i); if (fi->isIndexed && !fi->omitNorms) { Directory* d = si->getUseCompoundFile() ? cfsReader : directory(); string fileName = si->getNormFileName(fi->number); if (si->hasSeparateNorms(fi->number)) { continue; } string ext = string(".") + IndexFileNames::NORMS_EXTENSION; if (fileName.compare(fileName.length()-ext.length(),ext.length(),ext)==0) { clone->singleNormStream = d->openInput(fileName.c_str(), readBufferSize); break; } } } } success = true; } _CLFINALLY ( if (!success) { // An exception occured during reopen, we have to decRef the norms // that we incRef'ed already and close singleNormsStream and FieldsReader clone->decRefNorms(); } ) //disown this memory this->freqStream = NULL; this->_fieldInfos = NULL; this->tis = NULL; this->deletedDocs = NULL; this->ones = NULL; this->termVectorsReaderOrig = NULL; this->cfsReader = NULL; this->freqStream = NULL; this->proxStream = NULL; this->termVectorsReaderOrig = NULL; this->cfsReader = NULL; this->storeCFSReader = NULL; _CLDELETE( this->singleNormStream ); return clone; } /** Returns the field infos of this segment */ FieldInfos* SegmentReader::fieldInfos() { return _fieldInfos; } /** * Return the name of the segment this reader is reading. */ const char* SegmentReader::getSegmentName() { return segment.c_str(); } /** * Return the SegmentInfo of the segment this reader is reading. */ SegmentInfo* SegmentReader::getSegmentInfo() { return si; } void SegmentReader::setSegmentInfo(SegmentInfo* info) { si = info; } void SegmentReader::startCommit() { DirectoryIndexReader::startCommit(); rollbackDeletedDocsDirty = deletedDocsDirty; rollbackNormsDirty = normsDirty; rollbackUndeleteAll = undeleteAll; NormsType::iterator it = _norms.begin(); while (it != _norms.end()) { Norm* norm = it->second; norm->rollbackDirty = norm->dirty; } } void SegmentReader::rollbackCommit() { DirectoryIndexReader::rollbackCommit(); deletedDocsDirty = rollbackDeletedDocsDirty; normsDirty = rollbackNormsDirty; undeleteAll = rollbackUndeleteAll; NormsType::iterator it = _norms.begin(); while (it != _norms.end()) { Norm* norm = it->second; norm->dirty = norm->rollbackDirty; } } const char* SegmentReader::getClassName(){ return "SegmentReader"; } const char* SegmentReader::getObjectName() const{ return getClassName(); } bool SegmentReader::normsClosed() { if (singleNormStream != NULL) { return false; } NormsType::iterator it = _norms.begin(); while ( it != _norms.end() ) { Norm* norm = it->second; if (norm->refCount > 0) { return false; } } return true; } CL_NS_END
[ "git+matt@msqr.us" ]
git+matt@msqr.us
b4bf15eba38c4144b3e1ec9c9dee67975a072ed3
037e25818ffabad34b9888f1e32a2264e8dabd98
/include/Intrusion/Services/TowerPlaceableSurfaceService.hpp
d2d4accc67bd27e3ffa81edbf9b815570fd7f61b
[]
no_license
MarkRDavison/Games
b5e8e06f61e0b0c0a8c885d8d998531f50ffb32a
004d8021b50e49748a846484599050560e31594a
refs/heads/master
2018-11-15T04:28:55.001571
2018-11-09T05:30:35
2018-11-09T05:30:35
141,380,765
0
0
null
null
null
null
UTF-8
C++
false
false
683
hpp
#ifndef INCLUDED_INTRUSION_SERVICES_TOWER_PLACEABLE_SURFACE_SERVICE_HPP_ #define INCLUDED_INTRUSION_SERVICES_TOWER_PLACEABLE_SURFACE_SERVICE_HPP_ #include <Intrusion/Services/ITowerPlaceableSurfaceService.hpp> namespace itr { class TowerPlaceableSurfaceService : public ITowerPlaceableSurfaceService { public: TowerPlaceableSurfaceService(void); ~TowerPlaceableSurfaceService(void) override; void setActiveSurface(ITowerPlaceableSurface *_surface) override; ITowerPlaceableSurface *getActiveSurface(void) const override; private: ITowerPlaceableSurface *m_ActiveSurface{ nullptr }; }; } #endif // INCLUDED_INTRUSION_SERVICES_TOWER_PLACEABLE_SURFACE_SERVICE_HPP_
[ "markdavison0+github@gmail.com" ]
markdavison0+github@gmail.com
8db314fe02bb12fd57c8eabf5879dfbf0dbfd8cb
d829d426e100e5f204bab15661db4e1da15515f9
/tst/EnergyPlus/unit/ConstructionInternalSource.unit.cc
8f268854d58937a02c1771ad1a949747d26bf416
[ "BSD-2-Clause" ]
permissive
VB6Hobbyst7/EnergyPlus2
a49409343e6c19a469b93c8289545274a9855888
622089b57515a7b8fbb20c8e9109267a4bb37eb3
refs/heads/main
2023-06-08T06:47:31.276257
2021-06-29T04:40:23
2021-06-29T04:40:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,671
cc
// EnergyPlus, Copyright (c) 1996-2020, The Board of Trustees of the University of Illinois, // The Regents of the University of California, through Lawrence Berkeley National Laboratory // (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge // National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other // contributors. All rights reserved. // // NOTICE: This Software was developed under funding from the U.S. Department of Energy and the // U.S. Government consequently retains certain rights. As such, the U.S. Government has been // granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable, // worldwide license in the Software to reproduce, distribute copies to the public, prepare // derivative works, and perform publicly and display publicly, and to permit others to do so. // // 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 University of California, Lawrence Berkeley National Laboratory, // the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form // without changes from the version obtained under this License, or (ii) Licensee makes a // reference solely to the software portion of its product, Licensee must refer to the // software as "EnergyPlus version X" software, where "X" is the version number Licensee // obtained under this License and may not use a different name for the software. Except as // specifically required in this Section (4), Licensee shall not use in a company name, a // product name, in advertising, publicity, or other promotional activities any name, trade // name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly // similar designation, without the U.S. Department of Energy's prior written consent. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // EnergyPlus::AirflowNetworkSolver unit tests // Google test headers #include <gtest/gtest.h> // EnergyPlus Headers #include <EnergyPlus/DataHeatBalance.hh> #include <EnergyPlus/HeatBalanceManager.hh> #include "Fixtures/EnergyPlusFixture.hh" using namespace EnergyPlus; using namespace DataHeatBalance; using namespace HeatBalanceManager; TEST_F(EnergyPlusFixture, ConstructionInternalSource) { std::string const idf_objects = delimited_string({ " Construction:InternalSource, ", " Slab Floor with Radiant, !- Name", " 4, !- Source Present After Layer Number", " 4, !- Temperature Calculation Requested After Layer Number", " 2, !- Dimensions for the CTF Calculation", " 0.3048, !- Tube Spacing {m}", " CONCRETE - DRIED SAND AND GRAVEL 4 IN, !- Outside Layer", " INS - EXPANDED EXT POLYSTYRENE R12 2 IN, !- Layer 2", " GYP1, !- Layer 3", " GYP2, !- Layer 4", " FINISH FLOORING - TILE 1 / 16 IN; !- Layer 5", }); ASSERT_TRUE(process_idf(idf_objects)); bool errorsFound(false); GetConstructData(errorsFound); EXPECT_NEAR(0.1524, Construct(1).ThicknessPerpend, 0.0001); }
[ "ffeng@tamu.edu" ]
ffeng@tamu.edu
fe17de6ce1b2699bfb8149625c13e99736c6dc76
04b1803adb6653ecb7cb827c4f4aa616afacf629
/sql/recover_module/btree.h
6538c0b61d2125b9317742e91f0aad9650f08dd2
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
6,822
h
// Copyright 2019 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. #ifndef SQL_RECOVER_MODULE_BTREE_H_ #define SQL_RECOVER_MODULE_BTREE_H_ #include <cstdint> #include "base/logging.h" #include "base/sequence_checker.h" namespace sql { namespace recover { class DatabasePageReader; // Streaming decoder for inner pages in SQLite table B-trees. // // The decoder outputs the page IDs of the inner page's children pages. // // An instance can only be used to decode a single page. Instances are not // thread-safe. class InnerPageDecoder { public: // Creates a decoder for a DatabasePageReader's last read page. // // |db_reader| must have been used to read an inner page of a table B-tree. // |db_reader| must outlive this instance. explicit InnerPageDecoder(DatabasePageReader* db_reader) noexcept; ~InnerPageDecoder() noexcept = default; InnerPageDecoder(const InnerPageDecoder&) = delete; InnerPageDecoder& operator=(const InnerPageDecoder&) = delete; // The ID of the database page decoded by this instance. int page_id() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return page_id_; } // Returns true iff TryAdvance() may be called. bool CanAdvance() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // The <= below is not a typo. Inner nodes store the right-most child // pointer in their headers, so their child count is (cell_count + 1). return next_read_index_ <= cell_count_; } // Advances the reader and returns the last read value. // // May return an invalid page ID if database was corrupted or the read failed. // The caller must use DatabasePageReader::IsValidPageId() to verify the // returned page ID. The caller should continue attempting to read as long as // CanAdvance() returns true. int TryAdvance(); // True if the given reader may point to an inner page in a table B-tree. // // The last ReadPage() call on |db_reader| must have succeeded. static bool IsOnValidPage(DatabasePageReader* db_reader); private: // Returns the number of cells in the B-tree page. // // Checks for database corruption. The caller can assume that the cell pointer // array with the returned size will not extend past the page buffer. static int ComputeCellCount(DatabasePageReader* db_reader); // The number of the B-tree page this reader is reading. const int page_id_; // Used to read the tree page. // // Raw pointer usage is acceptable because this instance's owner is expected // to ensure that the DatabasePageReader outlives this. DatabasePageReader* const db_reader_; // Caches the ComputeCellCount() value for this reader's page. const int cell_count_ = ComputeCellCount(db_reader_); // The reader's cursor state. // // Each B-tree page has a header and many cells. In an inner B-tree page, each // cell points to a child page, and the header points to the last child page. // So, an inner page with N cells has N+1 children, and |next_read_index_| // takes values between 0 and |cell_count_| + 1. int next_read_index_ = 0; SEQUENCE_CHECKER(sequence_checker_); }; // Streaming decoder for leaf pages in SQLite table B-trees. // // Conceptually, the decoder outputs (rowid, record size, record offset) tuples // for all the values stored in the leaf page. The tuple members can be accessed // via last_record_{rowid, size, offset}() methods. // // An instance can only be used to decode a single page. Instances are not // thread-safe. class LeafPageDecoder { public: // Creates a decoder for a DatabasePageReader's last read page. // // |db_reader| must have been used to read an inner page of a table B-tree. // |db_reader| must outlive this instance. explicit LeafPageDecoder(DatabasePageReader* db_reader) noexcept; ~LeafPageDecoder() noexcept = default; LeafPageDecoder(const LeafPageDecoder&) = delete; LeafPageDecoder& operator=(const LeafPageDecoder&) = delete; // The rowid of the most recent record read by TryAdvance(). // // Must only be called after a successful call to TryAdvance(). int64_t last_record_rowid() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(last_record_size_ != 0) << "TryAdvance() not called / did not succeed"; return last_record_rowid_; } // The size of the most recent record read by TryAdvance(). // // Must only be called after a successful call to TryAdvance(). int64_t last_record_size() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(last_record_size_ != 0) << "TryAdvance() not called / did not succeed"; return last_record_size_; } // The page offset of the most recent record read by TryAdvance(). // // Must only be called after a successful call to TryAdvance(). int64_t last_record_offset() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(last_record_size_ != 0) << "TryAdvance() not called / did not succeed"; return last_record_offset_; } // Returns true iff TryAdvance() may be called. bool CanAdvance() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return next_read_index_ < cell_count_; } // Advances the reader and returns the last read value. // // Returns false if the read fails. The caller should continue attempting to // read as long as CanAdvance() returns true. bool TryAdvance(); // True if the given reader may point to an inner page in a table B-tree. // // The last ReadPage() call on |db_reader| must have succeeded. static bool IsOnValidPage(DatabasePageReader* db_reader); private: // Returns the number of cells in the B-tree page. // // Checks for database corruption. The caller can assume that the cell pointer // array with the returned size will not extend past the page buffer. static int ComputeCellCount(DatabasePageReader* db_reader); // The number of the B-tree page this reader is reading. const int64_t page_id_; // Used to read the tree page. // // Raw pointer usage is acceptable because this instance's owner is expected // to ensure that the DatabasePageReader outlives this. DatabasePageReader* const db_reader_; // Caches the ComputeCellCount() value for this reader's page. const int cell_count_ = ComputeCellCount(db_reader_); // The reader's cursor state. // // Each B-tree cell contains a value. So, this member takes values in // [0, cell_count_). int next_read_index_ = 0; int64_t last_record_size_ = 0; int64_t last_record_rowid_ = 0; int last_record_offset_ = 0; SEQUENCE_CHECKER(sequence_checker_); }; } // namespace recover } // namespace sql #endif // SQL_RECOVER_MODULE_BTREE_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
bb02510bbca2923adcb34ad29ee7044083b9fad4
386e80cb6120123c217a28b4440df05231e934be
/contest_5/solutions/1004.cpp
6c44544ae4dae0e475e3557608216c56c42120d3
[]
no_license
luojinrong/ACM
93170a71f9ca138925b7c84cd16272d237aba270
c0df9dfb1e862749f5ef2902941b925b1648b245
refs/heads/master
2020-03-26T18:04:51.108682
2019-07-29T09:15:21
2019-07-29T09:15:21
145,195,181
0
1
null
null
null
null
UTF-8
C++
false
false
5,349
cpp
#include <bits/stdc++.h> using namespace std; const int maxn = (int)1e5 + 1, maxd = 17; int t, n, m, lnk[maxn], rdep[maxn], mx, rfa[maxd][maxn]; struct Edge { int nxt, v; } e[maxn << 1 | 1]; bool ban[maxn]; int tot, ord[maxn], fa[maxn], dep[maxn]; void bfs(int rt) { // fa[rt], dep[rt] have been set tot = 0; ord[tot++] = rt; for(int i = 0; i < tot; ++i) { int u = ord[i]; for(int it = lnk[u]; it != -1; it = e[it].nxt) { int v = e[it].v; if(v == fa[u] || ban[v]) continue; fa[v] = u; dep[v] = dep[u] + 1; ord[tot++] = v; } } } int ptot, idx[maxd][maxn], idx2[maxd][maxn], dis[maxd][maxn]; int len[maxn << 1 | 1], *cnt[maxn << 1 | 1]; int pool[(maxn * maxd) << 1 | 1], *tail; int sz[maxn]; void build(int depth, int rt) { assert(depth < mx); fa[rt] = dep[rt] = 0; bfs(rt); int val = maxn; rt = -1; for(int i = tot - 1; i >= 0; --i) { int u = ord[i], mx = 0; sz[u] = 1; for(int it = lnk[u]; it != -1; it = e[it].nxt) { int v = e[it].v; if(v == fa[u] || ban[v]) continue; mx = max(mx, sz[v]); sz[u] += sz[v]; } mx = max(mx, tot - sz[u]); if(mx < val) { val = mx; rt = u; } } int pid = ptot++; idx[depth][rt] = idx2[depth][rt] = pid; dis[depth][rt] = fa[rt] = dep[rt] = 0; len[pid] = 1; for(int it = lnk[rt]; it != -1; it = e[it].nxt) { int tr = e[it].v; if(ban[tr]) continue; fa[tr] = rt; dep[tr] = dep[rt] + 1; bfs(tr); int cid = ptot++; len[cid] = dep[ord[tot - 1]] + 1; cnt[cid] = tail; tail += len[cid]; assert(tail - pool <= (maxn * maxd << 1)); memset(cnt[cid], 0, len[cid] * sizeof(int)); len[pid] = max(len[pid], len[cid]); for(int i = 0; i < tot; ++i) { int u = ord[i]; idx[depth][u] = pid; idx2[depth][u] = cid; dis[depth][u] = dep[u]; ++cnt[cid][dep[u]]; } } cnt[pid] = tail; tail += len[pid]; assert(tail - pool <= (maxn * maxd << 1)); memset(cnt[pid], 0, len[pid] * sizeof(int)); for(int it = lnk[rt]; it != -1; it = e[it].nxt) { int tr = e[it].v; if(ban[tr]) continue; int cid = idx2[depth][tr]; for(int i = 1; i < len[cid]; ++i) { cnt[pid][i] += cnt[cid][i]; cnt[cid][i] += cnt[cid][i - 1]; } } cnt[pid][0] = 1; // because dis[depth][rt] = 0 for(int i = 1; i < len[pid]; ++i) cnt[pid][i] += cnt[pid][i - 1]; ban[rt] = 1; for(int it = lnk[rt]; it != -1; it = e[it].nxt) { int tr = e[it].v; if(!ban[tr]) build(depth + 1, tr); } } int query(int u, int w) { int ret = 0; for(int i = 0; ; ++i) { int pid = idx[i][u], cid = idx2[i][u], dt = w - dis[i][u]; if(dt >= 0 && len[pid]) ret += cnt[pid][min(dt, len[pid] - 1)]; if(pid == cid) break; if(dt >= 0 && len[cid]) ret -= cnt[cid][min(dt, len[cid] - 1)]; } return ret; } int query(int u, int v, int w) { if(w < 0) return 0; if(u == v) return query(u, w); int ret = 0; bool chku = 1, chkv = 1; for(int i = 0; chku || chkv; ++i) { int pidu = idx[i][u], cidu = idx2[i][u], dtu = w - dis[i][u]; int pidv = idx[i][v], cidv = idx2[i][v], dtv = w - dis[i][v]; if(chku && chkv && pidu == pidv) { dtu = dtv = max(dtu, dtv); if(dtu >= 0 && len[pidu]) ret += cnt[pidu][min(dtu, len[pidu] - 1)]; } else { if(chku && dtu >= 0 && len[pidu]) ret += cnt[pidu][min(dtu, len[pidu] - 1)]; if(chkv && dtv >= 0 && len[pidv]) ret += cnt[pidv][min(dtv, len[pidv] - 1)]; } chku &= pidu != cidu; chkv &= pidv != cidv; if(chku && chkv && cidu == cidv) { if(dtu >= 0 && len[cidu]) ret -= cnt[cidu][min(dtu, len[cidu] - 1)]; } else { if(chku && dtu >= 0 && len[cidu]) ret -= cnt[cidu][min(dtu, len[cidu] - 1)]; if(chkv && dtv >= 0 && len[cidv]) ret -= cnt[cidv][min(dtv, len[cidv] - 1)]; } } return ret; } int lca(int u, int v) { for(int i = 0, j = rdep[u] - rdep[v]; j > 0; ++i, j >>= 1) (j & 1) && (u = rfa[i][u]); for(int i = 0, j = rdep[v] - rdep[u]; j > 0; ++i, j >>= 1) (j & 1) && (v = rfa[i][v]); if(u == v) return u; for(int i = mx - 1; i >= 0; --i) if(rfa[i][u] != rfa[i][v]) { u = rfa[i][u]; v = rfa[i][v]; } return rfa[0][u]; } int main() { scanf("%d", &t); while(t--) { scanf("%d%d", &n, &m); tot = 0; memset(lnk + 1, -1, n * sizeof(int)); for(int i = 1; i < n; ++i) { int u, v; scanf("%d%d", &u, &v); e[tot] = (Edge){lnk[u], v}; lnk[u] = tot++; e[tot] = (Edge){lnk[v], u}; lnk[v] = tot++; } memset(ban + 1, 0, n * sizeof(bool)); fa[1] = dep[1] = 0; bfs(1); memcpy(rdep + 1, dep + 1, n * sizeof(int)); memcpy(rfa[0] + 1, fa + 1, n * sizeof(int)); for(mx = 1; 1 << mx <= n; ++mx) for(int i = 1; i <= n; ++i) rfa[mx][i] = rfa[mx - 1][rfa[mx - 1][i]]; ptot = 0; tail = pool; build(0, 1); int ans = 0; while(m--) { int u, v, w; scanf("%d%d%d", &u, &v, &w); u = (u + ans) % n + 1; v = (v + ans) % n + 1; w = (w + ans) % n; int pp = lca(u, v), dt = rdep[u] + rdep[v] - (rdep[pp] << 1); int x = rdep[u] < rdep[v] ? v : u; for(int i = 0, j = dt >> 1; j > 0; ++i, j >>= 1) (j & 1) && (x = rfa[i][x]); int y = dt & 1 ? rfa[0][x] : x; printf("%d\n", ans = query(u, w) + query(v, w) - query(x, y, w - ((dt + 1) >> 1))); } } return 0; }
[ "840841939@qq.com" ]
840841939@qq.com
88206df239091dc67bc625290c606aa9d58821ee
3a578cc42c4b740f15bc594dbaaa31bb9d87c947
/src/util/overflow.h
369762b5fef42c663872b16edcc20f5a6397d242
[ "MIT" ]
permissive
syscoin/syscoin
7dded55aaf33a454bf1be1e80cb89b60f4fe5409
310151bd2e4860375de146c0568293559ad8b459
refs/heads/master
2023-08-17T06:35:29.025512
2023-08-16T11:57:03
2023-08-17T01:25:08
52,762,278
144
90
MIT
2023-09-08T17:52:13
2016-02-29T03:47:32
C++
UTF-8
C++
false
false
1,477
h
// Copyright (c) 2021-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef SYSCOIN_UTIL_OVERFLOW_H #define SYSCOIN_UTIL_OVERFLOW_H #include <limits> #include <optional> #include <type_traits> template <class T> [[nodiscard]] bool AdditionOverflow(const T i, const T j) noexcept { static_assert(std::is_integral<T>::value, "Integral required."); if constexpr (std::numeric_limits<T>::is_signed) { return (i > 0 && j > std::numeric_limits<T>::max() - i) || (i < 0 && j < std::numeric_limits<T>::min() - i); } return std::numeric_limits<T>::max() - i < j; } template <class T> [[nodiscard]] std::optional<T> CheckedAdd(const T i, const T j) noexcept { if (AdditionOverflow(i, j)) { return std::nullopt; } return i + j; } template <class T> [[nodiscard]] T SaturatingAdd(const T i, const T j) noexcept { if constexpr (std::numeric_limits<T>::is_signed) { if (i > 0 && j > std::numeric_limits<T>::max() - i) { return std::numeric_limits<T>::max(); } if (i < 0 && j < std::numeric_limits<T>::min() - i) { return std::numeric_limits<T>::min(); } } else { if (std::numeric_limits<T>::max() - i < j) { return std::numeric_limits<T>::max(); } } return i + j; } #endif // SYSCOIN_UTIL_OVERFLOW_H
[ "jsidhu@blockchainfoundry.co" ]
jsidhu@blockchainfoundry.co
bc229c14a8e4b83b0f6143567c020afe2b0afbe9
46279163a543cd8820bdc38133404d79e787c5d2
/test/cpp/jit/test_class_type.cpp
21229594d56d0f6ef0f6017a22f3e96b7bd66dbb
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0", "BSD-2-Clause" ]
permissive
erwincoumans/pytorch
31738b65e7b998bfdc28d0e8afa7dadeeda81a08
ae9f39eb580c4d92157236d64548b055f71cf14b
refs/heads/master
2023-01-23T10:27:33.628897
2020-12-06T01:22:00
2020-12-06T01:23:40
318,930,000
5
1
NOASSERTION
2020-12-06T01:58:57
2020-12-06T01:58:56
null
UTF-8
C++
false
false
1,916
cpp
#include <gtest/gtest.h> #include <test/cpp/jit/test_utils.h> #include <torch/torch.h> namespace torch { namespace jit { TEST(ClassTypeTest, AddRemoveAttr) { auto cu = std::make_shared<CompilationUnit>(); auto cls = ClassType::create("foo.bar", cu, true); cls->addAttribute("attr1", TensorType::get(), true); cls->addAttribute("attr2", TensorType::get()); cls->addAttribute("attr3", TensorType::get()); ASSERT_TRUE(cls->hasAttribute("attr1")); ASSERT_TRUE(cls->hasAttribute("attr2")); ASSERT_TRUE(cls->hasAttribute("attr3")); // removing attribute attr2 cls->unsafeRemoveAttribute("attr2"); ASSERT_TRUE(cls->hasAttribute("attr1")); ASSERT_FALSE(cls->hasAttribute("attr2")); ASSERT_TRUE(cls->hasAttribute("attr3")); // removing parameter attr1 cls->unsafeRemoveAttribute("attr1"); ASSERT_FALSE(cls->hasAttribute("attr1")); ASSERT_FALSE(cls->hasAttribute("attr2")); ASSERT_TRUE(cls->hasAttribute("attr3")); // check that we can still add a non-parameter attr1 with // different type cls->addAttribute("attr1", IntType::get()); } TEST(ClassTypeTest, AddRemoveConstant) { auto cu = std::make_shared<CompilationUnit>(); auto cls = ClassType::create("foo.bar", cu); cls->addConstant("const1", IValue(1)); cls->addConstant("const2", IValue(2)); cls->addConstant("const3", IValue(3)); ASSERT_EQ(cls->numConstants(), 3); ASSERT_TRUE(cls->hasConstant("const1")); ASSERT_TRUE(cls->hasConstant("const2")); ASSERT_TRUE(cls->hasConstant("const3")); ASSERT_FALSE(cls->hasConstant("const4")); ASSERT_EQ(cls->getConstant("const1").toInt(), 1); ASSERT_EQ(cls->getConstant("const2").toInt(), 2); ASSERT_EQ(cls->getConstant("const3").toInt(), 3); cls->unsafeRemoveConstant("const2"); ASSERT_TRUE(cls->hasConstant("const1")); ASSERT_FALSE(cls->hasConstant("const2")); ASSERT_TRUE(cls->hasConstant("const3")); } } // namespace jit } // namespace torch
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
29d32d2dbb09125c0ddc1a6154f83668a14a80fb
c42cbe94d0bfd1b68392a84d6c7f045918d73f35
/Scanner/src/Symbol.cpp
0eed836e78aa13e99fd0ce3ba41aa06874cf7abd
[]
no_license
coltonmorris/compiler
34c4e9cc7f6c06ed5f8a8828ab8cc78cde48dcbd
ec7dbc5ff33f4add9855da2e5b6720054ca108e1
refs/heads/master
2020-12-30T22:43:55.297035
2017-02-01T21:49:55
2017-02-01T21:49:55
80,657,295
0
0
null
null
null
null
UTF-8
C++
false
false
1,629
cpp
#include "Symbol.h" bool SymbolTableClass::Exists(std::string s){ std::vector<Variable>::const_iterator ptr; for (ptr = SymbolTable.begin();ptr != SymbolTable.end();ptr++){ if (ptr->mLabel == s){ return true; } } return false; } void SymbolTableClass::AddEntry(std::string s){ if (!Exists(s)){ Variable entry = {s,0}; SymbolTable.push_back(entry); } else { MSG("Symbol already exists: "<<s); } } int SymbolTableClass::GetValue(std::string s){ if (!Exists(s)){ std::cerr << "Error, variable does not exist: "<<s<<std::endl; exit(1); } //return value of s std::vector<Variable>::const_iterator ptr; for (ptr = SymbolTable.begin();ptr != SymbolTable.end();ptr++){ if (ptr->mLabel == s){ return ptr->mValue; } } } void SymbolTableClass::SetValue(std::string s, int v){ if (!Exists(s)){ std::cerr << "Error, variable does not exist: "<<s<<std::endl; exit(1); } //set value std::vector<Variable>::iterator ptr; for (ptr = SymbolTable.begin();ptr != SymbolTable.end();ptr++){ if (ptr->mLabel == s){ ptr->mValue = v; } } } int SymbolTableClass::GetIndex(std::string s){ if (!Exists(s)){ return -1; } //return index of s int count = 0; std::vector<Variable>::const_iterator ptr; for (ptr = SymbolTable.begin();ptr != SymbolTable.end();ptr++){ if (ptr->mLabel == s){ return count; } count ++; } } int SymbolTableClass::GetCount(){ int count = 0; std::vector<Variable>::const_iterator ptr; for (ptr = SymbolTable.begin();ptr != SymbolTable.end();ptr++){ count ++; } return count; }
[ "coltonmorris94@gmail.com" ]
coltonmorris94@gmail.com
a503b0fd45c903d0ea812391b054a396d4678521
fbd03f99969e62922ec785efd0105da7d18cf15b
/Impl/Test.cpp
9894cd18cb4f201a773bfea454dcd2ac1d08695b
[]
no_license
nycshisan/DI2020
e47db6ba6645ef9438489c3ae785d7ee2ccf271f
541b5c9485c3e0532b679a8c5b333a8d50d6b852
refs/heads/master
2022-11-29T18:04:04.930966
2020-08-02T08:49:45
2020-08-02T08:49:45
280,866,703
0
0
null
null
null
null
UTF-8
C++
false
false
6,697
cpp
#include "PCH.h" #include "Test.h" #include "WordRAM.h" #include "BitVector.h" void SelfTest() { WordRAM::CompressedArray::Test(); BitVector::Test(); } void _TestCAImpl(RandomGenerator &rg, Int length, Int wordSize, std::ostream *logger = nullptr) { rg.reseed(); Int *buf = new Int[length]; Int maxValue = (Int(1) << wordSize) - 1; std::uniform_int_distribution<Int> vd(0, maxValue), rd(0, length - 1); for (int i = 0; i < length; ++i) { buf[i] = vd(rg); } Int *la = (Int *)malloc(length * sizeof(Int)); WordRAM::CompressedArray ca(length, wordSize); if (logger) { *logger << length << " " << wordSize << " "; } // Test space if (logger) { *logger << length * sizeof(Int) << " " << ca.totalSize() << " "; } else { std::cout << "Storing `" << length << "` length of `" << wordSize << "` bit data." << std::endl; std::cout << "Uncompressed size: " << length * sizeof(Int) << std::endl; std::cout << "Compressed size: " << ca.totalSize() << std::endl; } // Test time NanosecondsTimer laTimer("Uncompressed Array Timer"), caTimer("Compressed Array Timer"); if (logger == nullptr) std::cout << "Test reading:" << std::endl; for (int i = 0; i < length; ++i) { auto r = rd(rg); Int x; laTimer.start(); x = la[r]; laTimer.end(); caTimer.start(); x = ca.get(r); caTimer.end(); } if (logger) { *logger << laTimer.durationAvg(length) << " " << caTimer.durationAvg(length) << " "; } else { laTimer.printAvg(length); caTimer.printAvg(length); } laTimer.clear(); caTimer.clear(); if (logger == nullptr) std::cout << "Test writing:" << std::endl; for (int i = 0; i < length; ++i) { auto v = vd(rg), r = rd(rg); laTimer.start(); la[r] = v; laTimer.end(); caTimer.start(); ca.set(r, v); caTimer.end(); } if (logger) { *logger << laTimer.durationAvg(length) << " " << caTimer.durationAvg(length) << std::endl; } else { laTimer.printAvg(length); caTimer.printAvg(length); } delete[] buf; free(la); } void TestCA() { std::ofstream logger("../TestCAResult.txt"); assert(logger.good()); std::vector<Int> lengths = { 100, 200, 300, 400, 500, 600, 700, 800, 900 }; Int lengthBase = 1; Int shortWordSize = 7, longWordSize = 47; std::cout << "Test Compressed Array:" << std::endl; auto rg = RandomGenerator("Test Compressed Array"); for (int i = 0; i < 5; ++i) { for (int j = 0; j < lengths.size(); ++j) { Int length = lengths[j] * lengthBase; std::cout << "Test size = " << length << std::endl; _TestCAImpl(rg, length, shortWordSize, &logger); _TestCAImpl(rg, length, longWordSize, &logger); } lengthBase *= 10; } std::cout << std::endl; } void _TestBVImpl(RandomGenerator &rg, Int length, std::ostream *logger = nullptr) { rg.reseed(); BitVector bvBF(length, DataStructureType::BruteForce), bvCA(length, DataStructureType::SuccinctWithCompressedArray); bvBF.randomize(); bvCA.randomize(); if (logger) { *logger << length << " "; } else { std::cout << "Test build index speed for `" << length << "` length:" << std::endl; } MicrosecondsTimer bfIndexTimer("Build brute force index"), caIndexTimer("Build succinct index"); bfIndexTimer.start(); bvBF.buildIndex(); bfIndexTimer.end(); if (logger) { *logger << bfIndexTimer.duration() << " "; } else { bfIndexTimer.print(); } caIndexTimer.start(); bvCA.buildIndex(); caIndexTimer.end(); if (logger) { *logger << caIndexTimer.duration() << " "; } else { caIndexTimer.print(); } // Test space if (logger) { *logger << bvBF.totalSize() << " " << bvCA.totalSize() << " "; } else { std::cout << "Storing `" << length << "` bits data." << std::endl; std::cout << "Uncompressed size: " << bvBF.totalSize() << std::endl; std::cout << "Compressed size: " << bvCA.totalSize() << std::endl; } NanosecondsTimer bfTimer("Brute force ranking"), caTimer("Succinct ranking"); // Test rank speed if (logger == nullptr) std::cout << "Test rank speed:" << std::endl; bfTimer.clear(); caTimer.clear(); for (int i = 0; i < length; ++i) { bfTimer.start(); Int r0bf = bvBF.rank0(i); Int r1bf = bvBF.rank1(i); bfTimer.end(); caTimer.start(); Int r0ca = bvCA.rank0(i); Int r1ca = bvCA.rank1(i); caTimer.end(); assert(r0ca == r0bf && r1ca == r1bf); } if (logger) { *logger << bfTimer.durationAvg(length) << " "; *logger << caTimer.durationAvg(length) << " "; } else { bfTimer.printAvg(length); caTimer.printAvg(length); } // Test select speed assert(bvBF.n0 == bvCA.n0 && bvBF.n1 == bvCA.n1); if (logger == nullptr) std::cout << "Test select speed:" << std::endl; bfTimer.name = "Brute force selecting"; caTimer.name = "Succinct selecting"; bfTimer.clear(); caTimer.clear(); for (int i = 1; i <= bvBF.n0; ++i) { bfTimer.start(); Int s0bf = bvBF.select0(i); bfTimer.end(); caTimer.start(); Int s0ca = bvCA.select0(i); caTimer.end(); assert(s0ca == s0bf); } for (int i = 1; i <= bvBF.n1; ++i) { bfTimer.start(); Int s1bf = bvBF.select1(i); bfTimer.end(); caTimer.start(); Int s1ca = bvCA.select1(i); caTimer.end(); assert(s1ca == s1bf); } if (logger) { *logger << bfTimer.durationAvg(bvBF.n0 + bvBF.n1) << " "; *logger << caTimer.durationAvg(bvCA.n0 + bvCA.n1) << std::endl; } else { bfTimer.printAvg(bvBF.n0 + bvBF.n1); caTimer.printAvg(bvCA.n0 + bvCA.n1); } } void TestBV() { std::ofstream logger("../TestBVResult.txt"); assert(logger.good()); std::vector<Int> lengths = { 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000 }; Int lengthBase = 1; std::cout << "Test Bit Vector:" << std::endl; auto rg = RandomGenerator("Test Bit Vector"); for (int i = 0; i < 5; ++i) { for (int j = 0; j < lengths.size(); ++j) { Int length = lengths[j] * lengthBase; std::cout << "Test size = " << length << std::endl; _TestBVImpl(rg, length, &logger); } lengthBase *= 10; } std::cout << std::endl; } void Playground() { }
[ "14307110157@fudan.edu.cn" ]
14307110157@fudan.edu.cn
f4bae1ecbbf4ef1d46cee11215ad158203e586e0
67a46851a67f0a93d7312c5a9a89c942e37b73eb
/algorithm/HDU-ACM/HDU_ACM_C++/1979.cpp
eeff9e1f2a2ac3775bb60e4238f076105c94b571
[]
no_license
zhangwj0101/codestudy
e8c0a0c55b0ee556c217dc58273711a18e4194c9
06ce3bb9f9d9f977e0e4dc7687c561ab74f1980b
refs/heads/master
2021-01-15T09:28:32.054331
2016-09-17T11:11:06
2016-09-17T11:11:06
44,471,951
0
0
null
null
null
null
UTF-8
C++
false
false
3,500
cpp
////////////////////System Comment//////////////////// ////Welcome to Hangzhou Dianzi University Online Judge ////http://acm.hdu.edu.cn ////////////////////////////////////////////////////// ////Username: devil_momo ////Nickname: Lucifer ////Run ID: ////Submit time: 2008-11-20 20:44:00 ////Compiler: Visual C++ ////////////////////////////////////////////////////// ////Problem ID: 1979 ////Problem Title: ////Run result: Accept ////Run time:0MS ////Run memory:0KB //////////////////System Comment End////////////////// #include<iostream> using namespace std; int result[]={ 1193,1009,9221,3191,1193,1021,9029,3911,1193,1201,9209,3911,1193,1229,9001,3191,1193,7043,3697,3911, 1193,7253,3821,3319,1193,7253,3851,3319,1193,7457,3821,3719,1193,7963,3407,3911,1193,9001,1229,3191, 1193,9011,1669,3911,1193,9013,1669,3911,1193,9029,1021,3911,1193,9041,1399,3371,1193,9209,1201,3911, 1193,9221,1009,3191,1193,9257,3821,3319,1193,9257,3851,3319,1193,9479,1381,3917,1193,9661,1109,3911, 1193,9661,3109,3911,1193,9923,1009,3191,1733,1069,9491,3371,1733,1283,9521,3319,1733,1283,9551,3319, 1733,1487,9521,3719,1733,1949,9601,3371,1733,9227,1021,3719,1733,9931,1409,3911,1913,1009,9221,3911, 1913,1021,9029,3191,1913,1033,9497,3191,1913,1069,9161,3191,1913,1069,9161,3391,1913,1201,9209,3191, 1913,1229,9001,3911,1913,1439,9781,3917,1913,1619,9601,3191,1913,1901,9209,3391,1913,7207,3221,3719, 1913,7949,3301,3191,1913,9001,1229,3911,1913,9001,3299,3911,1913,9029,1021,3191,1913,9173,3389,3391, 1913,9209,1201,3191,1913,9221,1009,3911,1933,1283,9521,3719,1933,1283,9551,3719,1933,1619,9601,3191, 1933,9029,1091,3191,1933,9133,1789,3391,1933,9833,3719,3191,1933,9871,3319,3391,3191,1009,9221,1193, 3191,1009,9923,1193,3191,1021,9029,1913,3191,1091,9029,1933,3191,1201,9209,1913,3191,1229,9001,1193, 3191,3301,7949,1913,3191,3719,9833,1933,3191,7027,1223,9173,3191,9001,1229,1193,3191,9029,1021,1913, 3191,9161,1069,1913,3191,9209,1201,1913,3191,9221,1009,1193,3191,9341,1879,7193,3191,9497,1033,1913, 3191,9601,1619,1913,3191,9601,1619,1933,3319,3821,7253,1193,3319,3821,9257,1193,3319,3851,7253,1193, 3319,3851,9257,1193,3319,9521,1283,1733,3319,9551,1283,1733,3371,1399,9041,1193,3371,3821,1259,9133, 3371,3821,1559,9133,3371,7229,1201,9173,3371,7841,1259,9173,3371,9491,1069,1733,3371,9601,1949,1733, 3391,1789,9133,1933,3391,3319,9871,1933,3391,3389,9173,1913,3391,3821,1259,9173,3391,3821,1559,9173, 3391,9161,1069,1913,3391,9209,1901,1913,3719,1021,9227,1733,3719,3221,7207,1913,3719,3821,7457,1193, 3719,9521,1283,1933,3719,9521,1487,1733,3719,9551,1283,1933,3911,1009,9221,1913,3911,1021,9029,1193, 3911,1109,9661,1193,3911,1201,9209,1193,3911,1229,9001,1913,3911,1409,9931,1733,3911,1669,9011,1193, 3911,1669,9013,1193,3911,3109,9661,1193,3911,3299,9001,1913,3911,3407,7963,1193,3911,3527,1283,9133, 3911,3527,1583,9133,3911,3697,7043,1193,3911,7529,1283,9133,3911,7529,1583,9133,3911,7547,1283,9173, 3911,9001,1229,1913,3911,9029,1021,1193,3911,9209,1201,1193,3911,9221,1009,1913,3911,9749,1831,7193, 3917,1381,9479,1193,3917,9781,1439,1913,7193,1831,9749,3911,7193,1879,9341,3191,9133,1259,3821,3371, 9133,1283,3527,3911,9133,1283,7529,3911,9133,1559,3821,3371,9133,1583,3527,3911,9133,1583,7529,3911, 9173,1201,7229,3371,9173,1223,7027,3191,9173,1259,3821,3391,9173,1259,7841,3371,9173,1283,7547,3911, 9173,1559,3821,3391}; int main() { int i; for(i=0;i<544;i++) { if(i%4==0&&i) puts(""); printf("%d\n",result[i]); } return 0; }
[ "zhangwj@zhangwj-MacBook-Pro.local" ]
zhangwj@zhangwj-MacBook-Pro.local
2b5200bc7de761d373fadc5a0c4745458d8acbf6
41d6b7e3b34b10cc02adb30c6dcf6078c82326a3
/src/plugins/azoth/plugins/vader/avatarstimestampstorage.h
4aab7a2fe5813c0bf93015ed5cb1db63d965999c
[ "BSL-1.0" ]
permissive
ForNeVeR/leechcraft
1c84da3690303e539e70c1323e39d9f24268cb0b
384d041d23b1cdb7cc3c758612ac8d68d3d3d88c
refs/heads/master
2020-04-04T19:08:48.065750
2016-11-27T02:08:30
2016-11-27T02:08:30
2,294,915
1
0
null
null
null
null
UTF-8
C++
false
false
2,193
h
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #pragma once #include <boost/optional.hpp> #include <QSqlDatabase> #include <util/db/oralfwd.h> #include <util/db/closingdb.h> class QDateTime; namespace LeechCraft { namespace Azoth { namespace Vader { class AvatarsTimestampStorage { public: struct AvatarTimestamp; private: Util::ClosingDB DB_; Util::oral::ObjectInfo_ptr<AvatarTimestamp> Adapted_; public: AvatarsTimestampStorage (); boost::optional<QDateTime> GetTimestamp (const QString&); void SetTimestamp (const QString&, const QDateTime&); }; } } }
[ "0xd34df00d@gmail.com" ]
0xd34df00d@gmail.com
53366eba1d485a0f478b9adfe506a720132dce27
c85df84d7c98ad8e379b20714fb26723d567b001
/src/messageRobotics.pb.cc
b199f65d240c3ebb48a64cb440816f3cc9182be5
[]
no_license
klauski/get_polaris3d_deep_dataset
910078f1d5d669203fd87adcdbffda0f68ec5e0f
85a5d2f87a931334511e30391feb2ea5b7e56561
refs/heads/master
2020-04-11T23:39:42.775806
2018-12-17T18:47:04
2018-12-17T18:47:04
162,174,513
0
0
null
null
null
null
UTF-8
C++
false
true
77,190
cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: messageRobotics.proto #include "messageRobotics.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace protobuf_messageRobotics_2eproto { extern PROTOBUF_INTERNAL_EXPORT_protobuf_messageRobotics_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_mRobotMetadata; } // namespace protobuf_messageRobotics_2eproto class mControl8ChDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<mControl8Ch> _instance; } _mControl8Ch_default_instance_; class mDifferentialControl8ChDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<mDifferentialControl8Ch> _instance; } _mDifferentialControl8Ch_default_instance_; class mRobotMetadataDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<mRobotMetadata> _instance; } _mRobotMetadata_default_instance_; class mPathMetadataDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<mPathMetadata> _instance; } _mPathMetadata_default_instance_; namespace protobuf_messageRobotics_2eproto { static void InitDefaultsmControl8Ch() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::_mControl8Ch_default_instance_; new (ptr) ::mControl8Ch(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::mControl8Ch::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_mControl8Ch = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsmControl8Ch}, {}}; static void InitDefaultsmDifferentialControl8Ch() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::_mDifferentialControl8Ch_default_instance_; new (ptr) ::mDifferentialControl8Ch(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::mDifferentialControl8Ch::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_mDifferentialControl8Ch = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsmDifferentialControl8Ch}, {}}; static void InitDefaultsmRobotMetadata() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::_mRobotMetadata_default_instance_; new (ptr) ::mRobotMetadata(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::mRobotMetadata::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_mRobotMetadata = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsmRobotMetadata}, {}}; static void InitDefaultsmPathMetadata() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::_mPathMetadata_default_instance_; new (ptr) ::mPathMetadata(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::mPathMetadata::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_mPathMetadata = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsmPathMetadata}, { &protobuf_messageRobotics_2eproto::scc_info_mRobotMetadata.base,}}; void InitDefaults() { ::google::protobuf::internal::InitSCC(&scc_info_mControl8Ch.base); ::google::protobuf::internal::InitSCC(&scc_info_mDifferentialControl8Ch.base); ::google::protobuf::internal::InitSCC(&scc_info_mRobotMetadata.base); ::google::protobuf::internal::InitSCC(&scc_info_mPathMetadata.base); } ::google::protobuf::Metadata file_level_metadata[4]; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mControl8Ch, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mControl8Ch, roll_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mControl8Ch, pitch_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mControl8Ch, throttle_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mControl8Ch, yaw_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mControl8Ch, reserved_0_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mControl8Ch, reserved_1_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mControl8Ch, reserved_2_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mControl8Ch, reserved_3_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mDifferentialControl8Ch, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mDifferentialControl8Ch, time_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mDifferentialControl8Ch, roll_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mDifferentialControl8Ch, pitch_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mDifferentialControl8Ch, throttle_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mDifferentialControl8Ch, yaw_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mDifferentialControl8Ch, reserved_0_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mDifferentialControl8Ch, reserved_1_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mDifferentialControl8Ch, reserved_2_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mDifferentialControl8Ch, reserved_3_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, mac_addr_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, qw_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, qx_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, qy_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, qz_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, tx_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, ty_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, tz_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, scan_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, timestamp_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mRobotMetadata, writable_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mPathMetadata, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mPathMetadata, map_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mPathMetadata, robot_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mPathMetadata, waypoints_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::mPathMetadata, path_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::mControl8Ch)}, { 13, -1, sizeof(::mDifferentialControl8Ch)}, { 27, -1, sizeof(::mRobotMetadata)}, { 43, -1, sizeof(::mPathMetadata)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::_mControl8Ch_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::_mDifferentialControl8Ch_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::_mRobotMetadata_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::_mPathMetadata_default_instance_), }; void protobuf_AssignDescriptors() { AddDescriptors(); AssignDescriptors( "messageRobotics.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 4); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\025messageRobotics.proto\"\231\001\n\013mControl8Ch\022" "\014\n\004roll\030\001 \001(\r\022\r\n\005pitch\030\002 \001(\r\022\020\n\010throttle" "\030\003 \001(\r\022\013\n\003yaw\030\004 \001(\r\022\022\n\nreserved_0\030\005 \001(\r\022" "\022\n\nreserved_1\030\006 \001(\r\022\022\n\nreserved_2\030\007 \001(\r\022" "\022\n\nreserved_3\030\010 \001(\r\"\263\001\n\027mDifferentialCon" "trol8Ch\022\014\n\004time\030\001 \001(\001\022\014\n\004roll\030\002 \001(\005\022\r\n\005p" "itch\030\003 \001(\005\022\020\n\010throttle\030\004 \001(\005\022\013\n\003yaw\030\005 \001(" "\005\022\022\n\nreserved_0\030\006 \001(\005\022\022\n\nreserved_1\030\007 \001(" "\005\022\022\n\nreserved_2\030\010 \001(\005\022\022\n\nreserved_3\030\t \001(" "\005\"\251\001\n\016mRobotMetadata\022\020\n\010mac_addr\030\001 \001(\006\022\n" "\n\002qw\030\002 \001(\002\022\n\n\002qx\030\003 \001(\002\022\n\n\002qy\030\004 \001(\002\022\n\n\002qz" "\030\005 \001(\002\022\n\n\002tx\030\006 \001(\002\022\n\n\002ty\030\007 \001(\002\022\n\n\002tz\030\010 \001" "(\002\022\014\n\004scan\030\t \001(\014\022\021\n\ttimestamp\030\n \001(\001\022\020\n\010w" "ritable\030\013 \001(\010\"`\n\rmPathMetadata\022\016\n\006map_id" "\030\001 \001(\r\022\036\n\005robot\030\002 \001(\0132\017.mRobotMetadata\022\021" "\n\twaypoints\030\003 \001(\014\022\014\n\004path\030\004 \001(\014b\006proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 639); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "messageRobotics.proto", &protobuf_RegisterTypes); } void AddDescriptors() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_messageRobotics_2eproto // =================================================================== void mControl8Ch::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int mControl8Ch::kRollFieldNumber; const int mControl8Ch::kPitchFieldNumber; const int mControl8Ch::kThrottleFieldNumber; const int mControl8Ch::kYawFieldNumber; const int mControl8Ch::kReserved0FieldNumber; const int mControl8Ch::kReserved1FieldNumber; const int mControl8Ch::kReserved2FieldNumber; const int mControl8Ch::kReserved3FieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 mControl8Ch::mControl8Ch() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_messageRobotics_2eproto::scc_info_mControl8Ch.base); SharedCtor(); // @@protoc_insertion_point(constructor:mControl8Ch) } mControl8Ch::mControl8Ch(const mControl8Ch& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&roll_, &from.roll_, static_cast<size_t>(reinterpret_cast<char*>(&reserved_3_) - reinterpret_cast<char*>(&roll_)) + sizeof(reserved_3_)); // @@protoc_insertion_point(copy_constructor:mControl8Ch) } void mControl8Ch::SharedCtor() { ::memset(&roll_, 0, static_cast<size_t>( reinterpret_cast<char*>(&reserved_3_) - reinterpret_cast<char*>(&roll_)) + sizeof(reserved_3_)); } mControl8Ch::~mControl8Ch() { // @@protoc_insertion_point(destructor:mControl8Ch) SharedDtor(); } void mControl8Ch::SharedDtor() { } void mControl8Ch::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* mControl8Ch::descriptor() { ::protobuf_messageRobotics_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_messageRobotics_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const mControl8Ch& mControl8Ch::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_messageRobotics_2eproto::scc_info_mControl8Ch.base); return *internal_default_instance(); } void mControl8Ch::Clear() { // @@protoc_insertion_point(message_clear_start:mControl8Ch) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; ::memset(&roll_, 0, static_cast<size_t>( reinterpret_cast<char*>(&reserved_3_) - reinterpret_cast<char*>(&roll_)) + sizeof(reserved_3_)); _internal_metadata_.Clear(); } bool mControl8Ch::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:mControl8Ch) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // uint32 roll = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &roll_))); } else { goto handle_unusual; } break; } // uint32 pitch = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &pitch_))); } else { goto handle_unusual; } break; } // uint32 throttle = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &throttle_))); } else { goto handle_unusual; } break; } // uint32 yaw = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &yaw_))); } else { goto handle_unusual; } break; } // uint32 reserved_0 = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &reserved_0_))); } else { goto handle_unusual; } break; } // uint32 reserved_1 = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &reserved_1_))); } else { goto handle_unusual; } break; } // uint32 reserved_2 = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &reserved_2_))); } else { goto handle_unusual; } break; } // uint32 reserved_3 = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(64u /* 64 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &reserved_3_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:mControl8Ch) return true; failure: // @@protoc_insertion_point(parse_failure:mControl8Ch) return false; #undef DO_ } void mControl8Ch::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:mControl8Ch) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 roll = 1; if (this->roll() != 0) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->roll(), output); } // uint32 pitch = 2; if (this->pitch() != 0) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->pitch(), output); } // uint32 throttle = 3; if (this->throttle() != 0) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(3, this->throttle(), output); } // uint32 yaw = 4; if (this->yaw() != 0) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(4, this->yaw(), output); } // uint32 reserved_0 = 5; if (this->reserved_0() != 0) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(5, this->reserved_0(), output); } // uint32 reserved_1 = 6; if (this->reserved_1() != 0) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(6, this->reserved_1(), output); } // uint32 reserved_2 = 7; if (this->reserved_2() != 0) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(7, this->reserved_2(), output); } // uint32 reserved_3 = 8; if (this->reserved_3() != 0) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(8, this->reserved_3(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:mControl8Ch) } ::google::protobuf::uint8* mControl8Ch::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:mControl8Ch) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 roll = 1; if (this->roll() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->roll(), target); } // uint32 pitch = 2; if (this->pitch() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(2, this->pitch(), target); } // uint32 throttle = 3; if (this->throttle() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(3, this->throttle(), target); } // uint32 yaw = 4; if (this->yaw() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(4, this->yaw(), target); } // uint32 reserved_0 = 5; if (this->reserved_0() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(5, this->reserved_0(), target); } // uint32 reserved_1 = 6; if (this->reserved_1() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(6, this->reserved_1(), target); } // uint32 reserved_2 = 7; if (this->reserved_2() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(7, this->reserved_2(), target); } // uint32 reserved_3 = 8; if (this->reserved_3() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(8, this->reserved_3(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:mControl8Ch) return target; } size_t mControl8Ch::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mControl8Ch) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // uint32 roll = 1; if (this->roll() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->roll()); } // uint32 pitch = 2; if (this->pitch() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->pitch()); } // uint32 throttle = 3; if (this->throttle() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->throttle()); } // uint32 yaw = 4; if (this->yaw() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->yaw()); } // uint32 reserved_0 = 5; if (this->reserved_0() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->reserved_0()); } // uint32 reserved_1 = 6; if (this->reserved_1() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->reserved_1()); } // uint32 reserved_2 = 7; if (this->reserved_2() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->reserved_2()); } // uint32 reserved_3 = 8; if (this->reserved_3() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->reserved_3()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void mControl8Ch::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mControl8Ch) GOOGLE_DCHECK_NE(&from, this); const mControl8Ch* source = ::google::protobuf::internal::DynamicCastToGenerated<const mControl8Ch>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mControl8Ch) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mControl8Ch) MergeFrom(*source); } } void mControl8Ch::MergeFrom(const mControl8Ch& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mControl8Ch) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.roll() != 0) { set_roll(from.roll()); } if (from.pitch() != 0) { set_pitch(from.pitch()); } if (from.throttle() != 0) { set_throttle(from.throttle()); } if (from.yaw() != 0) { set_yaw(from.yaw()); } if (from.reserved_0() != 0) { set_reserved_0(from.reserved_0()); } if (from.reserved_1() != 0) { set_reserved_1(from.reserved_1()); } if (from.reserved_2() != 0) { set_reserved_2(from.reserved_2()); } if (from.reserved_3() != 0) { set_reserved_3(from.reserved_3()); } } void mControl8Ch::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mControl8Ch) if (&from == this) return; Clear(); MergeFrom(from); } void mControl8Ch::CopyFrom(const mControl8Ch& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mControl8Ch) if (&from == this) return; Clear(); MergeFrom(from); } bool mControl8Ch::IsInitialized() const { return true; } void mControl8Ch::Swap(mControl8Ch* other) { if (other == this) return; InternalSwap(other); } void mControl8Ch::InternalSwap(mControl8Ch* other) { using std::swap; swap(roll_, other->roll_); swap(pitch_, other->pitch_); swap(throttle_, other->throttle_); swap(yaw_, other->yaw_); swap(reserved_0_, other->reserved_0_); swap(reserved_1_, other->reserved_1_); swap(reserved_2_, other->reserved_2_); swap(reserved_3_, other->reserved_3_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata mControl8Ch::GetMetadata() const { protobuf_messageRobotics_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_messageRobotics_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void mDifferentialControl8Ch::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int mDifferentialControl8Ch::kTimeFieldNumber; const int mDifferentialControl8Ch::kRollFieldNumber; const int mDifferentialControl8Ch::kPitchFieldNumber; const int mDifferentialControl8Ch::kThrottleFieldNumber; const int mDifferentialControl8Ch::kYawFieldNumber; const int mDifferentialControl8Ch::kReserved0FieldNumber; const int mDifferentialControl8Ch::kReserved1FieldNumber; const int mDifferentialControl8Ch::kReserved2FieldNumber; const int mDifferentialControl8Ch::kReserved3FieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 mDifferentialControl8Ch::mDifferentialControl8Ch() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_messageRobotics_2eproto::scc_info_mDifferentialControl8Ch.base); SharedCtor(); // @@protoc_insertion_point(constructor:mDifferentialControl8Ch) } mDifferentialControl8Ch::mDifferentialControl8Ch(const mDifferentialControl8Ch& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&time_, &from.time_, static_cast<size_t>(reinterpret_cast<char*>(&reserved_3_) - reinterpret_cast<char*>(&time_)) + sizeof(reserved_3_)); // @@protoc_insertion_point(copy_constructor:mDifferentialControl8Ch) } void mDifferentialControl8Ch::SharedCtor() { ::memset(&time_, 0, static_cast<size_t>( reinterpret_cast<char*>(&reserved_3_) - reinterpret_cast<char*>(&time_)) + sizeof(reserved_3_)); } mDifferentialControl8Ch::~mDifferentialControl8Ch() { // @@protoc_insertion_point(destructor:mDifferentialControl8Ch) SharedDtor(); } void mDifferentialControl8Ch::SharedDtor() { } void mDifferentialControl8Ch::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* mDifferentialControl8Ch::descriptor() { ::protobuf_messageRobotics_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_messageRobotics_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const mDifferentialControl8Ch& mDifferentialControl8Ch::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_messageRobotics_2eproto::scc_info_mDifferentialControl8Ch.base); return *internal_default_instance(); } void mDifferentialControl8Ch::Clear() { // @@protoc_insertion_point(message_clear_start:mDifferentialControl8Ch) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; ::memset(&time_, 0, static_cast<size_t>( reinterpret_cast<char*>(&reserved_3_) - reinterpret_cast<char*>(&time_)) + sizeof(reserved_3_)); _internal_metadata_.Clear(); } bool mDifferentialControl8Ch::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:mDifferentialControl8Ch) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // double time = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(9u /* 9 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &time_))); } else { goto handle_unusual; } break; } // int32 roll = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &roll_))); } else { goto handle_unusual; } break; } // int32 pitch = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &pitch_))); } else { goto handle_unusual; } break; } // int32 throttle = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &throttle_))); } else { goto handle_unusual; } break; } // int32 yaw = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &yaw_))); } else { goto handle_unusual; } break; } // int32 reserved_0 = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &reserved_0_))); } else { goto handle_unusual; } break; } // int32 reserved_1 = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &reserved_1_))); } else { goto handle_unusual; } break; } // int32 reserved_2 = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(64u /* 64 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &reserved_2_))); } else { goto handle_unusual; } break; } // int32 reserved_3 = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(72u /* 72 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &reserved_3_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:mDifferentialControl8Ch) return true; failure: // @@protoc_insertion_point(parse_failure:mDifferentialControl8Ch) return false; #undef DO_ } void mDifferentialControl8Ch::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:mDifferentialControl8Ch) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // double time = 1; if (this->time() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->time(), output); } // int32 roll = 2; if (this->roll() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->roll(), output); } // int32 pitch = 3; if (this->pitch() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->pitch(), output); } // int32 throttle = 4; if (this->throttle() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->throttle(), output); } // int32 yaw = 5; if (this->yaw() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(5, this->yaw(), output); } // int32 reserved_0 = 6; if (this->reserved_0() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(6, this->reserved_0(), output); } // int32 reserved_1 = 7; if (this->reserved_1() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(7, this->reserved_1(), output); } // int32 reserved_2 = 8; if (this->reserved_2() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(8, this->reserved_2(), output); } // int32 reserved_3 = 9; if (this->reserved_3() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(9, this->reserved_3(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:mDifferentialControl8Ch) } ::google::protobuf::uint8* mDifferentialControl8Ch::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:mDifferentialControl8Ch) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // double time = 1; if (this->time() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->time(), target); } // int32 roll = 2; if (this->roll() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->roll(), target); } // int32 pitch = 3; if (this->pitch() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->pitch(), target); } // int32 throttle = 4; if (this->throttle() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->throttle(), target); } // int32 yaw = 5; if (this->yaw() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(5, this->yaw(), target); } // int32 reserved_0 = 6; if (this->reserved_0() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(6, this->reserved_0(), target); } // int32 reserved_1 = 7; if (this->reserved_1() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(7, this->reserved_1(), target); } // int32 reserved_2 = 8; if (this->reserved_2() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(8, this->reserved_2(), target); } // int32 reserved_3 = 9; if (this->reserved_3() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(9, this->reserved_3(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:mDifferentialControl8Ch) return target; } size_t mDifferentialControl8Ch::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mDifferentialControl8Ch) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // double time = 1; if (this->time() != 0) { total_size += 1 + 8; } // int32 roll = 2; if (this->roll() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->roll()); } // int32 pitch = 3; if (this->pitch() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->pitch()); } // int32 throttle = 4; if (this->throttle() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->throttle()); } // int32 yaw = 5; if (this->yaw() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->yaw()); } // int32 reserved_0 = 6; if (this->reserved_0() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->reserved_0()); } // int32 reserved_1 = 7; if (this->reserved_1() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->reserved_1()); } // int32 reserved_2 = 8; if (this->reserved_2() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->reserved_2()); } // int32 reserved_3 = 9; if (this->reserved_3() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->reserved_3()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void mDifferentialControl8Ch::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mDifferentialControl8Ch) GOOGLE_DCHECK_NE(&from, this); const mDifferentialControl8Ch* source = ::google::protobuf::internal::DynamicCastToGenerated<const mDifferentialControl8Ch>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mDifferentialControl8Ch) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mDifferentialControl8Ch) MergeFrom(*source); } } void mDifferentialControl8Ch::MergeFrom(const mDifferentialControl8Ch& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mDifferentialControl8Ch) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.time() != 0) { set_time(from.time()); } if (from.roll() != 0) { set_roll(from.roll()); } if (from.pitch() != 0) { set_pitch(from.pitch()); } if (from.throttle() != 0) { set_throttle(from.throttle()); } if (from.yaw() != 0) { set_yaw(from.yaw()); } if (from.reserved_0() != 0) { set_reserved_0(from.reserved_0()); } if (from.reserved_1() != 0) { set_reserved_1(from.reserved_1()); } if (from.reserved_2() != 0) { set_reserved_2(from.reserved_2()); } if (from.reserved_3() != 0) { set_reserved_3(from.reserved_3()); } } void mDifferentialControl8Ch::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mDifferentialControl8Ch) if (&from == this) return; Clear(); MergeFrom(from); } void mDifferentialControl8Ch::CopyFrom(const mDifferentialControl8Ch& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mDifferentialControl8Ch) if (&from == this) return; Clear(); MergeFrom(from); } bool mDifferentialControl8Ch::IsInitialized() const { return true; } void mDifferentialControl8Ch::Swap(mDifferentialControl8Ch* other) { if (other == this) return; InternalSwap(other); } void mDifferentialControl8Ch::InternalSwap(mDifferentialControl8Ch* other) { using std::swap; swap(time_, other->time_); swap(roll_, other->roll_); swap(pitch_, other->pitch_); swap(throttle_, other->throttle_); swap(yaw_, other->yaw_); swap(reserved_0_, other->reserved_0_); swap(reserved_1_, other->reserved_1_); swap(reserved_2_, other->reserved_2_); swap(reserved_3_, other->reserved_3_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata mDifferentialControl8Ch::GetMetadata() const { protobuf_messageRobotics_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_messageRobotics_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void mRobotMetadata::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int mRobotMetadata::kMacAddrFieldNumber; const int mRobotMetadata::kQwFieldNumber; const int mRobotMetadata::kQxFieldNumber; const int mRobotMetadata::kQyFieldNumber; const int mRobotMetadata::kQzFieldNumber; const int mRobotMetadata::kTxFieldNumber; const int mRobotMetadata::kTyFieldNumber; const int mRobotMetadata::kTzFieldNumber; const int mRobotMetadata::kScanFieldNumber; const int mRobotMetadata::kTimestampFieldNumber; const int mRobotMetadata::kWritableFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 mRobotMetadata::mRobotMetadata() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_messageRobotics_2eproto::scc_info_mRobotMetadata.base); SharedCtor(); // @@protoc_insertion_point(constructor:mRobotMetadata) } mRobotMetadata::mRobotMetadata(const mRobotMetadata& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); scan_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.scan().size() > 0) { scan_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.scan_); } ::memcpy(&mac_addr_, &from.mac_addr_, static_cast<size_t>(reinterpret_cast<char*>(&timestamp_) - reinterpret_cast<char*>(&mac_addr_)) + sizeof(timestamp_)); // @@protoc_insertion_point(copy_constructor:mRobotMetadata) } void mRobotMetadata::SharedCtor() { scan_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&mac_addr_, 0, static_cast<size_t>( reinterpret_cast<char*>(&timestamp_) - reinterpret_cast<char*>(&mac_addr_)) + sizeof(timestamp_)); } mRobotMetadata::~mRobotMetadata() { // @@protoc_insertion_point(destructor:mRobotMetadata) SharedDtor(); } void mRobotMetadata::SharedDtor() { scan_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void mRobotMetadata::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* mRobotMetadata::descriptor() { ::protobuf_messageRobotics_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_messageRobotics_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const mRobotMetadata& mRobotMetadata::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_messageRobotics_2eproto::scc_info_mRobotMetadata.base); return *internal_default_instance(); } void mRobotMetadata::Clear() { // @@protoc_insertion_point(message_clear_start:mRobotMetadata) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; scan_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&mac_addr_, 0, static_cast<size_t>( reinterpret_cast<char*>(&timestamp_) - reinterpret_cast<char*>(&mac_addr_)) + sizeof(timestamp_)); _internal_metadata_.Clear(); } bool mRobotMetadata::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:mRobotMetadata) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // fixed64 mac_addr = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(9u /* 9 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_FIXED64>( input, &mac_addr_))); } else { goto handle_unusual; } break; } // float qw = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(21u /* 21 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &qw_))); } else { goto handle_unusual; } break; } // float qx = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(29u /* 29 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &qx_))); } else { goto handle_unusual; } break; } // float qy = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(37u /* 37 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &qy_))); } else { goto handle_unusual; } break; } // float qz = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(45u /* 45 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &qz_))); } else { goto handle_unusual; } break; } // float tx = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(53u /* 53 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &tx_))); } else { goto handle_unusual; } break; } // float ty = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(61u /* 61 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &ty_))); } else { goto handle_unusual; } break; } // float tz = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(69u /* 69 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &tz_))); } else { goto handle_unusual; } break; } // bytes scan = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_scan())); } else { goto handle_unusual; } break; } // double timestamp = 10; case 10: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(81u /* 81 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &timestamp_))); } else { goto handle_unusual; } break; } // bool writable = 11; case 11: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(88u /* 88 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &writable_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:mRobotMetadata) return true; failure: // @@protoc_insertion_point(parse_failure:mRobotMetadata) return false; #undef DO_ } void mRobotMetadata::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:mRobotMetadata) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // fixed64 mac_addr = 1; if (this->mac_addr() != 0) { ::google::protobuf::internal::WireFormatLite::WriteFixed64(1, this->mac_addr(), output); } // float qw = 2; if (this->qw() != 0) { ::google::protobuf::internal::WireFormatLite::WriteFloat(2, this->qw(), output); } // float qx = 3; if (this->qx() != 0) { ::google::protobuf::internal::WireFormatLite::WriteFloat(3, this->qx(), output); } // float qy = 4; if (this->qy() != 0) { ::google::protobuf::internal::WireFormatLite::WriteFloat(4, this->qy(), output); } // float qz = 5; if (this->qz() != 0) { ::google::protobuf::internal::WireFormatLite::WriteFloat(5, this->qz(), output); } // float tx = 6; if (this->tx() != 0) { ::google::protobuf::internal::WireFormatLite::WriteFloat(6, this->tx(), output); } // float ty = 7; if (this->ty() != 0) { ::google::protobuf::internal::WireFormatLite::WriteFloat(7, this->ty(), output); } // float tz = 8; if (this->tz() != 0) { ::google::protobuf::internal::WireFormatLite::WriteFloat(8, this->tz(), output); } // bytes scan = 9; if (this->scan().size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 9, this->scan(), output); } // double timestamp = 10; if (this->timestamp() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(10, this->timestamp(), output); } // bool writable = 11; if (this->writable() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(11, this->writable(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:mRobotMetadata) } ::google::protobuf::uint8* mRobotMetadata::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:mRobotMetadata) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // fixed64 mac_addr = 1; if (this->mac_addr() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteFixed64ToArray(1, this->mac_addr(), target); } // float qw = 2; if (this->qw() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(2, this->qw(), target); } // float qx = 3; if (this->qx() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(3, this->qx(), target); } // float qy = 4; if (this->qy() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(4, this->qy(), target); } // float qz = 5; if (this->qz() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(5, this->qz(), target); } // float tx = 6; if (this->tx() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(6, this->tx(), target); } // float ty = 7; if (this->ty() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(7, this->ty(), target); } // float tz = 8; if (this->tz() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(8, this->tz(), target); } // bytes scan = 9; if (this->scan().size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 9, this->scan(), target); } // double timestamp = 10; if (this->timestamp() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(10, this->timestamp(), target); } // bool writable = 11; if (this->writable() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(11, this->writable(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:mRobotMetadata) return target; } size_t mRobotMetadata::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mRobotMetadata) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // bytes scan = 9; if (this->scan().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->scan()); } // fixed64 mac_addr = 1; if (this->mac_addr() != 0) { total_size += 1 + 8; } // float qw = 2; if (this->qw() != 0) { total_size += 1 + 4; } // float qx = 3; if (this->qx() != 0) { total_size += 1 + 4; } // float qy = 4; if (this->qy() != 0) { total_size += 1 + 4; } // float qz = 5; if (this->qz() != 0) { total_size += 1 + 4; } // float tx = 6; if (this->tx() != 0) { total_size += 1 + 4; } // float ty = 7; if (this->ty() != 0) { total_size += 1 + 4; } // float tz = 8; if (this->tz() != 0) { total_size += 1 + 4; } // bool writable = 11; if (this->writable() != 0) { total_size += 1 + 1; } // double timestamp = 10; if (this->timestamp() != 0) { total_size += 1 + 8; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void mRobotMetadata::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mRobotMetadata) GOOGLE_DCHECK_NE(&from, this); const mRobotMetadata* source = ::google::protobuf::internal::DynamicCastToGenerated<const mRobotMetadata>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mRobotMetadata) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mRobotMetadata) MergeFrom(*source); } } void mRobotMetadata::MergeFrom(const mRobotMetadata& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mRobotMetadata) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.scan().size() > 0) { scan_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.scan_); } if (from.mac_addr() != 0) { set_mac_addr(from.mac_addr()); } if (from.qw() != 0) { set_qw(from.qw()); } if (from.qx() != 0) { set_qx(from.qx()); } if (from.qy() != 0) { set_qy(from.qy()); } if (from.qz() != 0) { set_qz(from.qz()); } if (from.tx() != 0) { set_tx(from.tx()); } if (from.ty() != 0) { set_ty(from.ty()); } if (from.tz() != 0) { set_tz(from.tz()); } if (from.writable() != 0) { set_writable(from.writable()); } if (from.timestamp() != 0) { set_timestamp(from.timestamp()); } } void mRobotMetadata::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mRobotMetadata) if (&from == this) return; Clear(); MergeFrom(from); } void mRobotMetadata::CopyFrom(const mRobotMetadata& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mRobotMetadata) if (&from == this) return; Clear(); MergeFrom(from); } bool mRobotMetadata::IsInitialized() const { return true; } void mRobotMetadata::Swap(mRobotMetadata* other) { if (other == this) return; InternalSwap(other); } void mRobotMetadata::InternalSwap(mRobotMetadata* other) { using std::swap; scan_.Swap(&other->scan_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(mac_addr_, other->mac_addr_); swap(qw_, other->qw_); swap(qx_, other->qx_); swap(qy_, other->qy_); swap(qz_, other->qz_); swap(tx_, other->tx_); swap(ty_, other->ty_); swap(tz_, other->tz_); swap(writable_, other->writable_); swap(timestamp_, other->timestamp_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata mRobotMetadata::GetMetadata() const { protobuf_messageRobotics_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_messageRobotics_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void mPathMetadata::InitAsDefaultInstance() { ::_mPathMetadata_default_instance_._instance.get_mutable()->robot_ = const_cast< ::mRobotMetadata*>( ::mRobotMetadata::internal_default_instance()); } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int mPathMetadata::kMapIdFieldNumber; const int mPathMetadata::kRobotFieldNumber; const int mPathMetadata::kWaypointsFieldNumber; const int mPathMetadata::kPathFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 mPathMetadata::mPathMetadata() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_messageRobotics_2eproto::scc_info_mPathMetadata.base); SharedCtor(); // @@protoc_insertion_point(constructor:mPathMetadata) } mPathMetadata::mPathMetadata(const mPathMetadata& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); waypoints_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.waypoints().size() > 0) { waypoints_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.waypoints_); } path_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.path().size() > 0) { path_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.path_); } if (from.has_robot()) { robot_ = new ::mRobotMetadata(*from.robot_); } else { robot_ = NULL; } map_id_ = from.map_id_; // @@protoc_insertion_point(copy_constructor:mPathMetadata) } void mPathMetadata::SharedCtor() { waypoints_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); path_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&robot_, 0, static_cast<size_t>( reinterpret_cast<char*>(&map_id_) - reinterpret_cast<char*>(&robot_)) + sizeof(map_id_)); } mPathMetadata::~mPathMetadata() { // @@protoc_insertion_point(destructor:mPathMetadata) SharedDtor(); } void mPathMetadata::SharedDtor() { waypoints_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); path_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete robot_; } void mPathMetadata::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* mPathMetadata::descriptor() { ::protobuf_messageRobotics_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_messageRobotics_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const mPathMetadata& mPathMetadata::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_messageRobotics_2eproto::scc_info_mPathMetadata.base); return *internal_default_instance(); } void mPathMetadata::Clear() { // @@protoc_insertion_point(message_clear_start:mPathMetadata) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; waypoints_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); path_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (GetArenaNoVirtual() == NULL && robot_ != NULL) { delete robot_; } robot_ = NULL; map_id_ = 0u; _internal_metadata_.Clear(); } bool mPathMetadata::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:mPathMetadata) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // uint32 map_id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &map_id_))); } else { goto handle_unusual; } break; } // .mRobotMetadata robot = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_robot())); } else { goto handle_unusual; } break; } // bytes waypoints = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_waypoints())); } else { goto handle_unusual; } break; } // bytes path = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_path())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:mPathMetadata) return true; failure: // @@protoc_insertion_point(parse_failure:mPathMetadata) return false; #undef DO_ } void mPathMetadata::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:mPathMetadata) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 map_id = 1; if (this->map_id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->map_id(), output); } // .mRobotMetadata robot = 2; if (this->has_robot()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->_internal_robot(), output); } // bytes waypoints = 3; if (this->waypoints().size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 3, this->waypoints(), output); } // bytes path = 4; if (this->path().size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 4, this->path(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:mPathMetadata) } ::google::protobuf::uint8* mPathMetadata::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:mPathMetadata) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 map_id = 1; if (this->map_id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->map_id(), target); } // .mRobotMetadata robot = 2; if (this->has_robot()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, this->_internal_robot(), deterministic, target); } // bytes waypoints = 3; if (this->waypoints().size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 3, this->waypoints(), target); } // bytes path = 4; if (this->path().size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 4, this->path(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:mPathMetadata) return target; } size_t mPathMetadata::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mPathMetadata) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // bytes waypoints = 3; if (this->waypoints().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->waypoints()); } // bytes path = 4; if (this->path().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->path()); } // .mRobotMetadata robot = 2; if (this->has_robot()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *robot_); } // uint32 map_id = 1; if (this->map_id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->map_id()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void mPathMetadata::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mPathMetadata) GOOGLE_DCHECK_NE(&from, this); const mPathMetadata* source = ::google::protobuf::internal::DynamicCastToGenerated<const mPathMetadata>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mPathMetadata) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mPathMetadata) MergeFrom(*source); } } void mPathMetadata::MergeFrom(const mPathMetadata& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mPathMetadata) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.waypoints().size() > 0) { waypoints_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.waypoints_); } if (from.path().size() > 0) { path_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.path_); } if (from.has_robot()) { mutable_robot()->::mRobotMetadata::MergeFrom(from.robot()); } if (from.map_id() != 0) { set_map_id(from.map_id()); } } void mPathMetadata::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mPathMetadata) if (&from == this) return; Clear(); MergeFrom(from); } void mPathMetadata::CopyFrom(const mPathMetadata& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mPathMetadata) if (&from == this) return; Clear(); MergeFrom(from); } bool mPathMetadata::IsInitialized() const { return true; } void mPathMetadata::Swap(mPathMetadata* other) { if (other == this) return; InternalSwap(other); } void mPathMetadata::InternalSwap(mPathMetadata* other) { using std::swap; waypoints_.Swap(&other->waypoints_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); path_.Swap(&other->path_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(robot_, other->robot_); swap(map_id_, other->map_id_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata mPathMetadata::GetMetadata() const { protobuf_messageRobotics_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_messageRobotics_2eproto::file_level_metadata[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) namespace google { namespace protobuf { template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::mControl8Ch* Arena::CreateMaybeMessage< ::mControl8Ch >(Arena* arena) { return Arena::CreateInternal< ::mControl8Ch >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::mDifferentialControl8Ch* Arena::CreateMaybeMessage< ::mDifferentialControl8Ch >(Arena* arena) { return Arena::CreateInternal< ::mDifferentialControl8Ch >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::mRobotMetadata* Arena::CreateMaybeMessage< ::mRobotMetadata >(Arena* arena) { return Arena::CreateInternal< ::mRobotMetadata >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::mPathMetadata* Arena::CreateMaybeMessage< ::mPathMetadata >(Arena* arena) { return Arena::CreateInternal< ::mPathMetadata >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope)
[ "noreply@github.com" ]
noreply@github.com
ca77de482e384fb2f80da7d3016b599a9ab67d6f
612325535126eaddebc230d8c27af095c8e5cc2f
/src/net/disk_cache/blockfile/sparse_control.cc
a20012628122b539df961b6c4a4b578ff48fba3b
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/proto-quic_1V94
1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673
feee14d96ee95313f236e0f0e3ff7719246c84f7
refs/heads/master
2023-04-01T14:36:53.888576
2019-10-17T02:23:04
2019-10-17T02:23:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,740
cc
// 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 "net/disk_cache/blockfile/sparse_control.h" #include <stdint.h> #include "base/bind.h" #include "base/format_macros.h" #include "base/location.h" #include "base/logging.h" #include "base/macros.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/disk_cache/blockfile/backend_impl.h" #include "net/disk_cache/blockfile/entry_impl.h" #include "net/disk_cache/blockfile/file.h" #include "net/disk_cache/net_log_parameters.h" #include "net/log/net_log.h" #include "net/log/net_log_event_type.h" #include "net/log/net_log_with_source.h" using base::Time; namespace { // Stream of the sparse data index. const int kSparseIndex = 2; // Stream of the sparse data. const int kSparseData = 1; // We can have up to 64k children. const int kMaxMapSize = 8 * 1024; // The maximum number of bytes that a child can store. const int kMaxEntrySize = 0x100000; // The size of each data block (tracked by the child allocation bitmap). const int kBlockSize = 1024; // Returns the name of a child entry given the base_name and signature of the // parent and the child_id. // If the entry is called entry_name, child entries will be named something // like Range_entry_name:XXX:YYY where XXX is the entry signature and YYY is the // number of the particular child. std::string GenerateChildName(const std::string& base_name, int64_t signature, int64_t child_id) { return base::StringPrintf("Range_%s:%" PRIx64 ":%" PRIx64, base_name.c_str(), signature, child_id); } // This class deletes the children of a sparse entry. class ChildrenDeleter : public base::RefCounted<ChildrenDeleter>, public disk_cache::FileIOCallback { public: ChildrenDeleter(disk_cache::BackendImpl* backend, const std::string& name) : backend_(backend->GetWeakPtr()), name_(name), signature_(0) {} void OnFileIOComplete(int bytes_copied) override; // Two ways of deleting the children: if we have the children map, use Start() // directly, otherwise pass the data address to ReadData(). void Start(char* buffer, int len); void ReadData(disk_cache::Addr address, int len); private: friend class base::RefCounted<ChildrenDeleter>; ~ChildrenDeleter() override {} void DeleteChildren(); base::WeakPtr<disk_cache::BackendImpl> backend_; std::string name_; disk_cache::Bitmap children_map_; int64_t signature_; std::unique_ptr<char[]> buffer_; DISALLOW_COPY_AND_ASSIGN(ChildrenDeleter); }; // This is the callback of the file operation. void ChildrenDeleter::OnFileIOComplete(int bytes_copied) { char* buffer = buffer_.release(); Start(buffer, bytes_copied); } void ChildrenDeleter::Start(char* buffer, int len) { buffer_.reset(buffer); if (len < static_cast<int>(sizeof(disk_cache::SparseData))) return Release(); // Just copy the information from |buffer|, delete |buffer| and start deleting // the child entries. disk_cache::SparseData* data = reinterpret_cast<disk_cache::SparseData*>(buffer); signature_ = data->header.signature; int num_bits = (len - sizeof(disk_cache::SparseHeader)) * 8; children_map_.Resize(num_bits, false); children_map_.SetMap(data->bitmap, num_bits / 32); buffer_.reset(); DeleteChildren(); } void ChildrenDeleter::ReadData(disk_cache::Addr address, int len) { DCHECK(address.is_block_file()); if (!backend_.get()) return Release(); disk_cache::File* file(backend_->File(address)); if (!file) return Release(); size_t file_offset = address.start_block() * address.BlockSize() + disk_cache::kBlockHeaderSize; buffer_.reset(new char[len]); bool completed; if (!file->Read(buffer_.get(), len, file_offset, this, &completed)) return Release(); if (completed) OnFileIOComplete(len); // And wait until OnFileIOComplete gets called. } void ChildrenDeleter::DeleteChildren() { int child_id = 0; if (!children_map_.FindNextSetBit(&child_id) || !backend_.get()) { // We are done. Just delete this object. return Release(); } std::string child_name = GenerateChildName(name_, signature_, child_id); backend_->SyncDoomEntry(child_name); children_map_.Set(child_id, false); // Post a task to delete the next child. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&ChildrenDeleter::DeleteChildren, this)); } // Returns the NetLog event type corresponding to a SparseOperation. net::NetLogEventType GetSparseEventType( disk_cache::SparseControl::SparseOperation operation) { switch (operation) { case disk_cache::SparseControl::kReadOperation: return net::NetLogEventType::SPARSE_READ; case disk_cache::SparseControl::kWriteOperation: return net::NetLogEventType::SPARSE_WRITE; case disk_cache::SparseControl::kGetRangeOperation: return net::NetLogEventType::SPARSE_GET_RANGE; default: NOTREACHED(); return net::NetLogEventType::CANCELLED; } } // Logs the end event for |operation| on a child entry. Range operations log // no events for each child they search through. void LogChildOperationEnd(const net::NetLogWithSource& net_log, disk_cache::SparseControl::SparseOperation operation, int result) { if (net_log.IsCapturing()) { net::NetLogEventType event_type; switch (operation) { case disk_cache::SparseControl::kReadOperation: event_type = net::NetLogEventType::SPARSE_READ_CHILD_DATA; break; case disk_cache::SparseControl::kWriteOperation: event_type = net::NetLogEventType::SPARSE_WRITE_CHILD_DATA; break; case disk_cache::SparseControl::kGetRangeOperation: return; default: NOTREACHED(); return; } net_log.EndEventWithNetErrorCode(event_type, result); } } } // namespace. namespace disk_cache { SparseControl::SparseControl(EntryImpl* entry) : entry_(entry), child_(NULL), operation_(kNoOperation), pending_(false), finished_(false), init_(false), range_found_(false), abort_(false), child_map_(child_data_.bitmap, kNumSparseBits, kNumSparseBits / 32), offset_(0), buf_len_(0), child_offset_(0), child_len_(0), result_(0) { memset(&sparse_header_, 0, sizeof(sparse_header_)); memset(&child_data_, 0, sizeof(child_data_)); } SparseControl::~SparseControl() { if (child_) CloseChild(); if (init_) WriteSparseData(); } int SparseControl::Init() { DCHECK(!init_); // We should not have sparse data for the exposed entry. if (entry_->GetDataSize(kSparseData)) return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; // Now see if there is something where we store our data. int rv = net::OK; int data_len = entry_->GetDataSize(kSparseIndex); if (!data_len) { rv = CreateSparseEntry(); } else { rv = OpenSparseEntry(data_len); } if (rv == net::OK) init_ = true; return rv; } bool SparseControl::CouldBeSparse() const { DCHECK(!init_); if (entry_->GetDataSize(kSparseData)) return false; // We don't verify the data, just see if it could be there. return (entry_->GetDataSize(kSparseIndex) != 0); } int SparseControl::StartIO(SparseOperation op, int64_t offset, net::IOBuffer* buf, int buf_len, const CompletionCallback& callback) { DCHECK(init_); // We don't support simultaneous IO for sparse data. if (operation_ != kNoOperation) return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; if (offset < 0 || buf_len < 0) return net::ERR_INVALID_ARGUMENT; // We only support up to 64 GB. if (static_cast<uint64_t>(offset) + static_cast<unsigned int>(buf_len) >= UINT64_C(0x1000000000)) { return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; } DCHECK(!user_buf_.get()); DCHECK(user_callback_.is_null()); if (!buf && (op == kReadOperation || op == kWriteOperation)) return 0; // Copy the operation parameters. operation_ = op; offset_ = offset; user_buf_ = buf ? new net::DrainableIOBuffer(buf, buf_len) : NULL; buf_len_ = buf_len; user_callback_ = callback; result_ = 0; pending_ = false; finished_ = false; abort_ = false; if (entry_->net_log().IsCapturing()) { entry_->net_log().BeginEvent( GetSparseEventType(operation_), CreateNetLogSparseOperationCallback(offset_, buf_len_)); } DoChildrenIO(); if (!pending_) { // Everything was done synchronously. operation_ = kNoOperation; user_buf_ = NULL; user_callback_.Reset(); return result_; } return net::ERR_IO_PENDING; } int SparseControl::GetAvailableRange(int64_t offset, int len, int64_t* start) { DCHECK(init_); // We don't support simultaneous IO for sparse data. if (operation_ != kNoOperation) return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; DCHECK(start); range_found_ = false; int result = StartIO( kGetRangeOperation, offset, NULL, len, CompletionCallback()); if (range_found_) { *start = offset_; return result; } // This is a failure. We want to return a valid start value in any case. *start = offset; return result < 0 ? result : 0; // Don't mask error codes to the caller. } void SparseControl::CancelIO() { if (operation_ == kNoOperation) return; abort_ = true; } int SparseControl::ReadyToUse(const CompletionCallback& callback) { if (!abort_) return net::OK; // We'll grab another reference to keep this object alive because we just have // one extra reference due to the pending IO operation itself, but we'll // release that one before invoking user_callback_. entry_->AddRef(); // Balanced in DoAbortCallbacks. abort_callbacks_.push_back(callback); return net::ERR_IO_PENDING; } // Static void SparseControl::DeleteChildren(EntryImpl* entry) { DCHECK(entry->GetEntryFlags() & PARENT_ENTRY); int data_len = entry->GetDataSize(kSparseIndex); if (data_len < static_cast<int>(sizeof(SparseData)) || entry->GetDataSize(kSparseData)) return; int map_len = data_len - sizeof(SparseHeader); if (map_len > kMaxMapSize || map_len % 4) return; char* buffer; Addr address; entry->GetData(kSparseIndex, &buffer, &address); if (!buffer && !address.is_initialized()) return; entry->net_log().AddEvent(net::NetLogEventType::SPARSE_DELETE_CHILDREN); DCHECK(entry->backend_.get()); ChildrenDeleter* deleter = new ChildrenDeleter(entry->backend_.get(), entry->GetKey()); // The object will self destruct when finished. deleter->AddRef(); if (buffer) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&ChildrenDeleter::Start, deleter, buffer, data_len)); } else { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&ChildrenDeleter::ReadData, deleter, address, data_len)); } } // We are going to start using this entry to store sparse data, so we have to // initialize our control info. int SparseControl::CreateSparseEntry() { if (CHILD_ENTRY & entry_->GetEntryFlags()) return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; memset(&sparse_header_, 0, sizeof(sparse_header_)); sparse_header_.signature = Time::Now().ToInternalValue(); sparse_header_.magic = kIndexMagic; sparse_header_.parent_key_len = entry_->GetKey().size(); children_map_.Resize(kNumSparseBits, true); // Save the header. The bitmap is saved in the destructor. scoped_refptr<net::IOBuffer> buf( new net::WrappedIOBuffer(reinterpret_cast<char*>(&sparse_header_))); int rv = entry_->WriteData(kSparseIndex, 0, buf.get(), sizeof(sparse_header_), CompletionCallback(), false); if (rv != sizeof(sparse_header_)) { DLOG(ERROR) << "Unable to save sparse_header_"; return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; } entry_->SetEntryFlags(PARENT_ENTRY); return net::OK; } // We are opening an entry from disk. Make sure that our control data is there. int SparseControl::OpenSparseEntry(int data_len) { if (data_len < static_cast<int>(sizeof(SparseData))) return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; if (entry_->GetDataSize(kSparseData)) return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; if (!(PARENT_ENTRY & entry_->GetEntryFlags())) return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; // Dont't go over board with the bitmap. 8 KB gives us offsets up to 64 GB. int map_len = data_len - sizeof(sparse_header_); if (map_len > kMaxMapSize || map_len % 4) return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; scoped_refptr<net::IOBuffer> buf( new net::WrappedIOBuffer(reinterpret_cast<char*>(&sparse_header_))); // Read header. int rv = entry_->ReadData(kSparseIndex, 0, buf.get(), sizeof(sparse_header_), CompletionCallback()); if (rv != static_cast<int>(sizeof(sparse_header_))) return net::ERR_CACHE_READ_FAILURE; // The real validation should be performed by the caller. This is just to // double check. if (sparse_header_.magic != kIndexMagic || sparse_header_.parent_key_len != static_cast<int>(entry_->GetKey().size())) return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; // Read the actual bitmap. buf = new net::IOBuffer(map_len); rv = entry_->ReadData(kSparseIndex, sizeof(sparse_header_), buf.get(), map_len, CompletionCallback()); if (rv != map_len) return net::ERR_CACHE_READ_FAILURE; // Grow the bitmap to the current size and copy the bits. children_map_.Resize(map_len * 8, false); children_map_.SetMap(reinterpret_cast<uint32_t*>(buf->data()), map_len); return net::OK; } bool SparseControl::OpenChild() { DCHECK_GE(result_, 0); std::string key = GenerateChildKey(); if (child_) { // Keep using the same child or open another one?. if (key == child_->GetKey()) return true; CloseChild(); } // See if we are tracking this child. if (!ChildPresent()) return ContinueWithoutChild(key); if (!entry_->backend_.get()) return false; child_ = entry_->backend_->OpenEntryImpl(key); if (!child_) return ContinueWithoutChild(key); if (!(CHILD_ENTRY & child_->GetEntryFlags()) || child_->GetDataSize(kSparseIndex) < static_cast<int>(sizeof(child_data_))) return KillChildAndContinue(key, false); scoped_refptr<net::WrappedIOBuffer> buf( new net::WrappedIOBuffer(reinterpret_cast<char*>(&child_data_))); // Read signature. int rv = child_->ReadData(kSparseIndex, 0, buf.get(), sizeof(child_data_), CompletionCallback()); if (rv != sizeof(child_data_)) return KillChildAndContinue(key, true); // This is a fatal failure. if (child_data_.header.signature != sparse_header_.signature || child_data_.header.magic != kIndexMagic) return KillChildAndContinue(key, false); if (child_data_.header.last_block_len < 0 || child_data_.header.last_block_len >= kBlockSize) { // Make sure these values are always within range. child_data_.header.last_block_len = 0; child_data_.header.last_block = -1; } return true; } void SparseControl::CloseChild() { scoped_refptr<net::WrappedIOBuffer> buf( new net::WrappedIOBuffer(reinterpret_cast<char*>(&child_data_))); // Save the allocation bitmap before closing the child entry. int rv = child_->WriteData(kSparseIndex, 0, buf.get(), sizeof(child_data_), CompletionCallback(), false); if (rv != sizeof(child_data_)) DLOG(ERROR) << "Failed to save child data"; child_ = NULL; } std::string SparseControl::GenerateChildKey() { return GenerateChildName(entry_->GetKey(), sparse_header_.signature, offset_ >> 20); } // We are deleting the child because something went wrong. bool SparseControl::KillChildAndContinue(const std::string& key, bool fatal) { SetChildBit(false); child_->DoomImpl(); child_ = NULL; if (fatal) { result_ = net::ERR_CACHE_READ_FAILURE; return false; } return ContinueWithoutChild(key); } // We were not able to open this child; see what we can do. bool SparseControl::ContinueWithoutChild(const std::string& key) { if (kReadOperation == operation_) return false; if (kGetRangeOperation == operation_) return true; if (!entry_->backend_.get()) return false; child_ = entry_->backend_->CreateEntryImpl(key); if (!child_) { child_ = NULL; result_ = net::ERR_CACHE_READ_FAILURE; return false; } // Write signature. InitChildData(); return true; } bool SparseControl::ChildPresent() { int child_bit = static_cast<int>(offset_ >> 20); if (children_map_.Size() <= child_bit) return false; return children_map_.Get(child_bit); } void SparseControl::SetChildBit(bool value) { int child_bit = static_cast<int>(offset_ >> 20); // We may have to increase the bitmap of child entries. if (children_map_.Size() <= child_bit) children_map_.Resize(Bitmap::RequiredArraySize(child_bit + 1) * 32, true); children_map_.Set(child_bit, value); } void SparseControl::WriteSparseData() { scoped_refptr<net::IOBuffer> buf(new net::WrappedIOBuffer( reinterpret_cast<const char*>(children_map_.GetMap()))); int len = children_map_.ArraySize() * 4; int rv = entry_->WriteData(kSparseIndex, sizeof(sparse_header_), buf.get(), len, CompletionCallback(), false); if (rv != len) { DLOG(ERROR) << "Unable to save sparse map"; } } bool SparseControl::VerifyRange() { DCHECK_GE(result_, 0); child_offset_ = static_cast<int>(offset_) & (kMaxEntrySize - 1); child_len_ = std::min(buf_len_, kMaxEntrySize - child_offset_); // We can write to (or get info from) anywhere in this child. if (operation_ != kReadOperation) return true; // Check that there are no holes in this range. int last_bit = (child_offset_ + child_len_ + 1023) >> 10; int start = child_offset_ >> 10; if (child_map_.FindNextBit(&start, last_bit, false)) { // Something is not here. DCHECK_GE(child_data_.header.last_block_len, 0); DCHECK_LT(child_data_.header.last_block_len, kBlockSize); int partial_block_len = PartialBlockLength(start); if (start == child_offset_ >> 10) { // It looks like we don't have anything. if (partial_block_len <= (child_offset_ & (kBlockSize - 1))) return false; } // We have the first part. child_len_ = (start << 10) - child_offset_; if (partial_block_len) { // We may have a few extra bytes. child_len_ = std::min(child_len_ + partial_block_len, buf_len_); } // There is no need to read more after this one. buf_len_ = child_len_; } return true; } void SparseControl::UpdateRange(int result) { if (result <= 0 || operation_ != kWriteOperation) return; DCHECK_GE(child_data_.header.last_block_len, 0); DCHECK_LT(child_data_.header.last_block_len, kBlockSize); // Write the bitmap. int first_bit = child_offset_ >> 10; int block_offset = child_offset_ & (kBlockSize - 1); if (block_offset && (child_data_.header.last_block != first_bit || child_data_.header.last_block_len < block_offset)) { // The first block is not completely filled; ignore it. first_bit++; } int last_bit = (child_offset_ + result) >> 10; block_offset = (child_offset_ + result) & (kBlockSize - 1); // This condition will hit with the following criteria: // 1. The first byte doesn't follow the last write. // 2. The first byte is in the middle of a block. // 3. The first byte and the last byte are in the same block. if (first_bit > last_bit) return; if (block_offset && !child_map_.Get(last_bit)) { // The last block is not completely filled; save it for later. child_data_.header.last_block = last_bit; child_data_.header.last_block_len = block_offset; } else { child_data_.header.last_block = -1; } child_map_.SetRange(first_bit, last_bit, true); } int SparseControl::PartialBlockLength(int block_index) const { if (block_index == child_data_.header.last_block) return child_data_.header.last_block_len; // This is really empty. return 0; } void SparseControl::InitChildData() { child_->SetEntryFlags(CHILD_ENTRY); memset(&child_data_, 0, sizeof(child_data_)); child_data_.header = sparse_header_; scoped_refptr<net::WrappedIOBuffer> buf( new net::WrappedIOBuffer(reinterpret_cast<char*>(&child_data_))); int rv = child_->WriteData(kSparseIndex, 0, buf.get(), sizeof(child_data_), CompletionCallback(), false); if (rv != sizeof(child_data_)) DLOG(ERROR) << "Failed to save child data"; SetChildBit(true); } void SparseControl::DoChildrenIO() { while (DoChildIO()) continue; // Range operations are finished synchronously, often without setting // |finished_| to true. if (kGetRangeOperation == operation_ && entry_->net_log().IsCapturing()) { entry_->net_log().EndEvent( net::NetLogEventType::SPARSE_GET_RANGE, CreateNetLogGetAvailableRangeResultCallback(offset_, result_)); } if (finished_) { if (kGetRangeOperation != operation_ && entry_->net_log().IsCapturing()) { entry_->net_log().EndEvent(GetSparseEventType(operation_)); } if (pending_) DoUserCallback(); // Don't touch this object after this point. } } bool SparseControl::DoChildIO() { finished_ = true; if (!buf_len_ || result_ < 0) return false; if (!OpenChild()) return false; if (!VerifyRange()) return false; // We have more work to do. Let's not trigger a callback to the caller. finished_ = false; CompletionCallback callback; if (!user_callback_.is_null()) { callback = base::Bind(&SparseControl::OnChildIOCompleted, base::Unretained(this)); } int rv = 0; switch (operation_) { case kReadOperation: if (entry_->net_log().IsCapturing()) { entry_->net_log().BeginEvent( net::NetLogEventType::SPARSE_READ_CHILD_DATA, CreateNetLogSparseReadWriteCallback(child_->net_log().source(), child_len_)); } rv = child_->ReadDataImpl(kSparseData, child_offset_, user_buf_.get(), child_len_, callback); break; case kWriteOperation: if (entry_->net_log().IsCapturing()) { entry_->net_log().BeginEvent( net::NetLogEventType::SPARSE_WRITE_CHILD_DATA, CreateNetLogSparseReadWriteCallback(child_->net_log().source(), child_len_)); } rv = child_->WriteDataImpl(kSparseData, child_offset_, user_buf_.get(), child_len_, callback, false); break; case kGetRangeOperation: rv = DoGetAvailableRange(); break; default: NOTREACHED(); } if (rv == net::ERR_IO_PENDING) { if (!pending_) { pending_ = true; // The child will protect himself against closing the entry while IO is in // progress. However, this entry can still be closed, and that would not // be a good thing for us, so we increase the refcount until we're // finished doing sparse stuff. entry_->AddRef(); // Balanced in DoUserCallback. } return false; } if (!rv) return false; DoChildIOCompleted(rv); return true; } int SparseControl::DoGetAvailableRange() { if (!child_) return child_len_; // Move on to the next child. // Bits on the bitmap should only be set when the corresponding block was // fully written (it's really being used). If a block is partially used, it // has to start with valid data, the length of the valid data is saved in // |header.last_block_len| and the block itself should match // |header.last_block|. // // In other words, (|header.last_block| + |header.last_block_len|) is the // offset where the last write ended, and data in that block (which is not // marked as used because it is not full) will only be reused if the next // write continues at that point. // // This code has to find if there is any data between child_offset_ and // child_offset_ + child_len_. int last_bit = (child_offset_ + child_len_ + kBlockSize - 1) >> 10; int start = child_offset_ >> 10; int partial_start_bytes = PartialBlockLength(start); int found = start; int bits_found = child_map_.FindBits(&found, last_bit, true); bool is_last_block_in_range = start < child_data_.header.last_block && child_data_.header.last_block < last_bit; int block_offset = child_offset_ & (kBlockSize - 1); if (!bits_found && partial_start_bytes <= block_offset) { if (!is_last_block_in_range) return child_len_; found = last_bit - 1; // There are some bytes here. } // We are done. Just break the loop and reset result_ to our real result. range_found_ = true; int bytes_found = bits_found << 10; bytes_found += PartialBlockLength(found + bits_found); // found now points to the first bytes. Lets see if we have data before it. int empty_start = std::max((found << 10) - child_offset_, 0); if (empty_start >= child_len_) return child_len_; // At this point we have bytes_found stored after (found << 10), and we want // child_len_ bytes after child_offset_. The first empty_start bytes after // child_offset_ are invalid. if (start == found) bytes_found -= block_offset; // If the user is searching past the end of this child, bits_found is the // right result; otherwise, we have some empty space at the start of this // query that we have to subtract from the range that we searched. result_ = std::min(bytes_found, child_len_ - empty_start); if (partial_start_bytes) { result_ = std::min(partial_start_bytes - block_offset, child_len_); empty_start = 0; } // Only update offset_ when this query found zeros at the start. if (empty_start) offset_ += empty_start; // This will actually break the loop. buf_len_ = 0; return 0; } void SparseControl::DoChildIOCompleted(int result) { LogChildOperationEnd(entry_->net_log(), operation_, result); if (result < 0) { // We fail the whole operation if we encounter an error. result_ = result; return; } UpdateRange(result); result_ += result; offset_ += result; buf_len_ -= result; // We'll be reusing the user provided buffer for the next chunk. if (buf_len_ && user_buf_.get()) user_buf_->DidConsume(result); } void SparseControl::OnChildIOCompleted(int result) { DCHECK_NE(net::ERR_IO_PENDING, result); DoChildIOCompleted(result); if (abort_) { // We'll return the current result of the operation, which may be less than // the bytes to read or write, but the user cancelled the operation. abort_ = false; if (entry_->net_log().IsCapturing()) { entry_->net_log().AddEvent(net::NetLogEventType::CANCELLED); entry_->net_log().EndEvent(GetSparseEventType(operation_)); } // We have an indirect reference to this object for every callback so if // there is only one callback, we may delete this object before reaching // DoAbortCallbacks. bool has_abort_callbacks = !abort_callbacks_.empty(); DoUserCallback(); if (has_abort_callbacks) DoAbortCallbacks(); return; } // We are running a callback from the message loop. It's time to restart what // we were doing before. DoChildrenIO(); } void SparseControl::DoUserCallback() { DCHECK(!user_callback_.is_null()); CompletionCallback cb = user_callback_; user_callback_.Reset(); user_buf_ = NULL; pending_ = false; operation_ = kNoOperation; int rv = result_; entry_->Release(); // Don't touch object after this line. cb.Run(rv); } void SparseControl::DoAbortCallbacks() { std::vector<CompletionCallback> abort_callbacks; abort_callbacks.swap(abort_callbacks_); for (CompletionCallback& callback : abort_callbacks) { // Releasing all references to entry_ may result in the destruction of this // object so we should not be touching it after the last Release(). entry_->Release(); callback.Run(net::OK); } } } // namespace disk_cache
[ "2100639007@qq.com" ]
2100639007@qq.com
94b4af62bc5f412473844d9ff02219a4185175e9
42c3e312765e4835150584ee09ce3a01ad286e00
/csx/csx.cc
1c5089343714e3695be230bdc937dcef1699ddfb
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cslab-ntua/csx
8ca6a842103f17b5d2124778911601053d5d8979
94dbf1471a7c55d637b824e92011ce7b9cb123ab
refs/heads/master
2016-09-06T00:30:10.903237
2012-09-14T09:10:27
2012-09-14T09:14:27
1,351,039
7
0
null
null
null
null
UTF-8
C++
false
false
12,679
cc
/* * csx.cc -- The CSX Manager implementation * * Copyright (C) 2009-2011, Computing Systems Laboratory (CSLab), NTUA. * Copyright (C) 2009-2011, Kornilios Kourtis * Copyright (C) 2010-2012, Theodoros Gkountouvas * Copyright (C) 2011-2012, Vasileios Karakasis * All rights reserved. * * This file is distributed under the BSD License. See LICENSE.txt for details. */ #include <map> #include <algorithm> #include <boost/foreach.hpp> #define FOREACH BOOST_FOREACH #include "dynarray.h" #include "spm.h" #include "delta.h" #include "csx.h" #ifdef SPM_NUMA # include <numa.h> # include "numa_util.h" # define DYNARRAY_CREATE dynarray_create_numa #else # define DYNARRAY_CREATE dynarray_create #endif void DestroyCsx(csx_double_t *csx) { #ifdef SPM_NUMA free_interleaved(csx->ctl, csx->ctl_size*sizeof(*csx->ctl)); free_interleaved(csx->values, csx->nnz*sizeof(*csx->values)); free_interleaved(csx, sizeof(*csx)); #else free(csx->ctl); free(csx->values); free(csx); #endif } void DestroyCsxSym(csx_double_sym_t *csx_sym) { #ifdef SPM_NUMA uint64_t diag_size = csx_sym->lower_matrix->nrows; #endif DestroyCsx(csx_sym->lower_matrix); #ifdef SPM_NUMA numa_free(csx_sym->dvalues, diag_size*sizeof(*csx_sym->dvalues)); numa_free(csx_sym, sizeof(*csx_sym)); #else free(csx_sym->dvalues); free(csx_sym); #endif } using namespace csx; static bool debug = false; template<typename IterT, typename ValT> void DeltaEncode(IterT start, IterT end, ValT &x0) { IterT i; ValT prev, tmp; prev = x0; for (i = start; i != end; ++i){ tmp = *i; *i -= prev; prev = tmp; } } template<typename T> void Copy(T *dst, uint64_t *src, long nr_items) { for (long i = 0; i < nr_items; i++){ dst[i] = static_cast<T>(src[i]); } } uint8_t CsxManager::GetFlag(long pattern_id, uint64_t nnz) { CsxManager::PatMap::iterator pi; uint8_t ret; pi = this->patterns.find(pattern_id); if (pi == this->patterns.end()) { ret = flag_avail_++; assert(ret <= CTL_PATTERNS_MAX && "too many patterns"); CsxManager::PatInfo pat_info(ret, 1, nnz); this->patterns[pattern_id] = pat_info; } else { ret = pi->second.flag; pi->second.npatterns++; pi->second.nr += nnz; } return ret; } csx_double_sym_t *CsxManager::MakeCsxSym() { csx_double_sym_t *csx; double *diagonal = spm_sym_->GetDiagonal(); uint64_t diagonal_size = spm_sym_->GetDiagonalSize(); spm_ = spm_sym_->GetLowerMatrix(); #ifdef SPM_NUMA int cpu = sched_getcpu(); if (cpu < 0) { perror("sched_getcpu() failed"); exit(1); } int node = numa_node_of_cpu(cpu); if (node < 0) { perror("numa_node_of_cpu() failed"); exit(1); } csx = (csx_double_sym_t *) numa_alloc_onnode(sizeof(csx_double_sym_t), node); csx->dvalues = (double *) numa_alloc_onnode(diagonal_size * sizeof(double), node); #else csx = (csx_double_sym_t *) malloc(sizeof(csx_double_sym_t)); csx->dvalues = (double *) malloc(diagonal_size * sizeof(double)); #endif for (uint64_t i = 0; i < diagonal_size; i++) csx->dvalues[i] = diagonal[i]; csx->lower_matrix = MakeCsx(true); return csx; } csx_double_t *CsxManager::MakeCsx(bool symmetric) { csx_double_t *csx; #ifdef SPM_NUMA int cpu = sched_getcpu(); if (cpu < 0) { perror("sched_getcpu() failed"); exit(1); } int node = numa_node_of_cpu(cpu); if (node < 0) { perror("numa_node_of_cpu() failed"); exit(1); } csx = (csx_double_t *) alloc_onnode(sizeof(csx_double_t), node); values_ = (double *) alloc_onnode(sizeof(double)*spm_->nr_nzeros_, node); #else csx = (csx_double_t *) malloc(sizeof(csx_double_t)); values_ = (double *) malloc(sizeof(double)*spm_->nr_nzeros_); #endif // SPM_NUMA if (!csx || !values_) { std::cerr << __FUNCTION__ << ": malloc failed\n"; exit(1); } // Be greedy with the initial capacity (equal to CSR col_ind size) // to avoid realloc()'s. ctl_da_ = DYNARRAY_CREATE(sizeof(uint8_t), 512, 6*spm_->nr_nzeros_); csx->nnz = spm_->nr_nzeros_; csx->nrows = spm_->nr_rows_; csx->ncols = spm_->nr_cols_; csx->row_start = spm_->row_start_; values_idx_ = 0; new_row_ = false; // Do not mark first row. if (!symmetric) { for (uint64_t i = 0; i < spm_->GetNrRows(); i++) { const SpmRowElem *rbegin, *rend; rbegin = spm_->RowBegin(i); rend = spm_->RowEnd(i); if (debug) std::cerr << "MakeCsx(): row: " << i << "\n"; if (rbegin == rend){ // Check if row is empty. if (debug) std::cerr << "MakeCsx(): row is empty" << std::endl; if (new_row_ == false) new_row_ = true; // In case the first row is empty. else empty_rows_++; continue; } DoRow(rbegin, rend); new_row_ = true; } } else { for (uint64_t i = 0; i < spm_->GetNrRows(); i++) { const SpmRowElem *rbegin, *rend; rbegin = spm_->RowBegin(i); rend = spm_->RowEnd(i); if (debug) std::cerr << "MakeCsx(): row: " << i << "\n"; if (rbegin == rend){ // Check if row is empty. if (debug) std::cerr << "MakeCsx(): row is empty" << std::endl; if (new_row_ == false) new_row_ = true; // In case the first row is empty. else empty_rows_++; continue; } DoSymRow(rbegin, rend); new_row_ = true; } } csx->ctl_size = dynarray_size(ctl_da_); csx->ctl = (uint8_t *) dynarray_destroy(ctl_da_); ctl_da_ = NULL; assert(values_idx_ == spm_->nr_nzeros_); csx->values = values_; values_ = NULL; values_idx_ = 0; return csx; } /* * Ctl Rules * 1. Each unit leaves the x index at the last element it calculated on the * current row. * 2. Size is the number of elements that will be calculated. */ void CsxManager::DoRow(const SpmRowElem *rbegin, const SpmRowElem *rend) { std::vector<uint64_t> xs; last_col_ = 1; for (const SpmRowElem *spm_elem = rbegin; spm_elem < rend; spm_elem++) { if (debug) std::cerr << "\t" << *spm_elem << "\n"; // Check if this element contains a pattern. if (spm_elem->pattern != NULL) { PreparePat(xs, *spm_elem); assert(xs.size() == 0); AddPattern(*spm_elem); for (long i = 0; i < spm_elem->pattern->GetSize(); i++) values_[values_idx_++] = spm_elem->vals[i]; continue; } // Check if we exceeded the maximum size for a unit. assert(xs.size() <= CTL_SIZE_MAX); if (xs.size() == CTL_SIZE_MAX) AddXs(xs); xs.push_back(spm_elem->x); values_[values_idx_++] = spm_elem->val; } if (xs.size() > 0) AddXs(xs); } /* * Ctl Rules * 1. Each unit leaves the x index at the last element it calculated on the * current row. * 2. Size is the number of elements that will be calculated. */ void CsxManager::DoSymRow(const SpmRowElem *rbegin, const SpmRowElem *rend) { std::vector<uint64_t> xs; const SpmRowElem *spm_elem = rbegin; last_col_ = 1; for ( ; spm_elem < rend && spm_elem->x < spm_->GetRowStart() + 1; spm_elem++) { if (debug) std::cerr << "\t" << *spm_elem << "\n"; // Check if this element contains a pattern. if (spm_elem->pattern != NULL) { PreparePat(xs, *spm_elem); assert(xs.size() == 0); AddPattern(*spm_elem); for (long i=0; i < spm_elem->pattern->GetSize(); i++) values_[values_idx_++] = spm_elem->vals[i]; continue; } // Check if we exceeded the maximum size for a unit. assert(xs.size() <= CTL_SIZE_MAX); if (xs.size() == CTL_SIZE_MAX) AddXs(xs); xs.push_back(spm_elem->x); values_[values_idx_++] = spm_elem->val; } if (xs.size() > 0) AddXs(xs); for ( ; spm_elem < rend; spm_elem++) { if (debug) std::cerr << "\t" << *spm_elem << "\n"; // Check if this element contains a pattern. if (spm_elem->pattern != NULL) { PreparePat(xs, *spm_elem); assert(xs.size() == 0); AddPattern(*spm_elem); for (long i=0; i < spm_elem->pattern->GetSize(); i++) values_[values_idx_++] = spm_elem->vals[i]; continue; } // Check if we exceeded the maximum size for a unit. assert(xs.size() <= CTL_SIZE_MAX); if (xs.size() == CTL_SIZE_MAX) AddXs(xs); xs.push_back(spm_elem->x); values_[values_idx_++] = spm_elem->val; } if (xs.size() > 0) AddXs(xs); } // Note that this function may allocate space in ctl_da. void CsxManager::UpdateNewRow(uint8_t *flags) { if (!new_row_) return; set_bit(flags, CTL_NR_BIT); new_row_ = false; if (empty_rows_ != 0){ set_bit(flags, CTL_RJMP_BIT); da_put_ul(ctl_da_, empty_rows_ + 1); empty_rows_ = 0; row_jmps_ = true; } } void CsxManager::AddXs(std::vector<uint64_t> &xs) { uint8_t *ctl_flags, *ctl_size; long pat_id, xs_size, delta_bytes; uint64_t last_col, max; DeltaSize delta_size; std::vector<uint64_t>::iterator vi; void *dst; // Do delta encoding. xs_size = xs.size(); last_col = xs[xs_size-1]; uint64_t x_start = xs[0]; DeltaEncode(xs.begin(), xs.end(), last_col_); last_col_ = last_col; // Calculate the delta's size and the pattern id. max = 0; if (xs_size > 1) { vi = xs.begin(); std::advance(vi, 1); max = *(std::max_element(vi, xs.end())); } delta_size = getDeltaSize(max); pat_id = (8<<delta_size) + PID_DELTA_BASE; // Set flags. ctl_flags = (uint8_t *) dynarray_alloc_nr(ctl_da_, 2); *ctl_flags = GetFlag(PID_DELTA_BASE + pat_id, xs_size); // Set size. ctl_size = ctl_flags + 1; assert( (xs_size > 0) && (xs_size <= CTL_SIZE_MAX)); *ctl_size = xs_size; // Variables ctls_size, ctl_flags are not valid after this call. UpdateNewRow(ctl_flags); // Add the column index if (full_column_indices_) da_put_u32(ctl_da_, x_start-1); else da_put_ul(ctl_da_, xs[0]); // Add deltas (if needed). if (xs_size > 1) { delta_bytes = DeltaSize_getBytes(delta_size); dst = dynarray_alloc_nr_aligned(ctl_da_, delta_bytes*(xs_size-1), delta_bytes); switch (delta_size) { case DELTA_U8: Copy((uint8_t *) dst, &xs[1], xs_size-1); break; case DELTA_U16: Copy((uint16_t *) dst, &xs[1], xs_size-1); break; case DELTA_U32: Copy((uint32_t *) dst, &xs[1], xs_size-1); break; default: assert(false); } } xs.clear(); return; } void CsxManager::AddPattern(const SpmRowElem &elem) { uint8_t *ctl_flags, *ctl_size; long pat_size, pat_id; uint64_t ucol; pat_size = elem.pattern->GetSize(); pat_id = elem.pattern->GetPatternId(); ctl_flags = (uint8_t *) dynarray_alloc_nr(ctl_da_, 2); *ctl_flags = GetFlag(pat_id, pat_size); ctl_size = ctl_flags + 1; assert(pat_size <= CTL_SIZE_MAX); *ctl_size = pat_size; UpdateNewRow(ctl_flags); if (full_column_indices_) ucol = elem.x; else ucol = elem.x - last_col_; if (debug) std::cerr << "AddPattern ujmp " << ucol << "\n"; if (full_column_indices_) da_put_u32(ctl_da_, ucol-1); else da_put_ul(ctl_da_, ucol); last_col_ = elem.pattern->ColIncreaseJmp(spm_->type_, elem.x); if (debug) std::cerr << "last_col:" << last_col_ << "\n"; } // return ujmp void CsxManager::PreparePat(std::vector<uint64_t> &xs, const SpmRowElem &elem) { if (xs.size() != 0) AddXs(xs); } // vim:expandtab:tabstop=8:shiftwidth=4:softtabstop=4
[ "bkk@scirouter" ]
bkk@scirouter
653f14be27d1679da407d09096b922f33a658899
6cc69d2446fb12f8660df7863d8866d29d52ce08
/src/Practice/Websites/GeeksForGeeks/Linkedlist/Page 3/SinglyLinkedListPalindrome.h
7602de4e1b8dc530edf306c4d0f7e862caeea0f6
[]
no_license
kodakandlaavinash/DoOrDie
977e253b048668561fb56ec5c6d3c40d9b57a440
f961e068e435a5cedb66d0fba5c21b63afe37390
refs/heads/master
2021-01-23T02:30:10.606394
2013-09-12T08:06:45
2013-09-12T08:06:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,889
h
/* * SinglyLinkedListPalindrome.h * * Created on: Apr 18, 2013 * Author: Avinash */ // // Testing Status // #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include "../LinkedListDS.h" #include "../LinkedListUtil.h" #include "../Page 4/GetMiddleOfLinkedList.h" #include "ReverseALinkedList.h" using namespace std; using namespace __gnu_cxx; #define null NULL //int main(){ // return -1; //} #ifndef SINGLYLINKEDLISTPALINDROME_H_ #define SINGLYLINKEDLISTPALINDROME_H_ bool isSinglyLinkedListAPalindrome(linkedListNode *ptr){ int length = lengthOfLinkedList(ptr); if(length == 0){ return true; } int middleIndex = length/2; stack<linkedListNode *> auxSpace; linkedListNode *crawler = ptr; while(middleIndex--){ auxSpace.push(crawler); crawler = crawler->next; } if(length%2 == 0){ crawler = crawler->next; } while(!auxSpace.empty() && crawler != NULL){ if(crawler->value != auxSpace.top()->value){ return false; } crawler = crawler->next; auxSpace.pop(); } if(!auxSpace.empty() || crawler != NULL){ return false; } return true; } bool SinglyLinkedListPalindrome(linkedListNode *ptr,linkedListNode **frontPtr){ if(ptr == NULL){ return true; } bool statusTillHere = SinglyLinkedListPalindrome(ptr->next,frontPtr); if(!statusTillHere){ return false; } if(ptr->next == NULL){ if(ptr->value == (*frontPtr)->value){ (*frontPtr) = (*frontPtr)->next; return true; }else{ return false; } } } bool SinglyLinkedListPalindromeHashMap(linkedListNode *ptr){ hash_map<int,linkedListNode *> auxSpace; linkedListNode *crawler = ptr; int counter = 0; while(crawler != NULL){ auxSpace.insert(pair<int,linkedListNode *>(counter,crawler)); counter++; crawler = crawler->next; } counter--; int middle = counter/2; int flagMiddle = middle; if(middle%2 == 1){ middle--; } while(middle--){ if(auxSpace[middle] != auxSpace[counter]){ return false; } } if(middle != -1 && counter != flagMiddle){ return false; } return true; } bool SinglyLinkedListPalindromeReverse(linkedListNode *ptr){ if(ptr == NULL){ return false; } linkedListNode *middle = GetMiddleListUsingRunningPtrs(ptr); linkedListNode *reverse = ReverseLinkedListNewList(middle->next); linkedListNode *crawler = ptr; while(ptr != middle->next && reverse != NULL){ if(ptr->value != reverse->value){ return false; } ptr = ptr->next; reverse = reverse->next; } if(ptr != middle->next || reverse != NULL){ return false; } return true; } #endif /* SINGLYLINKEDLISTPALINDROME_H_ */
[ "kodakandlaavinash@gmail.com" ]
kodakandlaavinash@gmail.com
e4001ab5e19fbbb587511552a073e05996002a55
dd2bcd6e829347eef6ab8020bd8e31a18c335acc
/ThisIsASoftRenderer/Editor/XTP/Source/SyntaxEdit/XTPSyntaxEditLineMarksManager.h
4dd8f1dfacba8c0502cb828ece6b38160a1aec59
[]
no_license
lai3d/ThisIsASoftRenderer
4dab4cac0e0ee82ac4f7f796aeafae40a4cb478a
a8d65af36f11a079e754c739a37803484df05311
refs/heads/master
2021-01-22T17:14:03.064181
2014-03-24T16:02:16
2014-03-24T16:02:16
56,359,042
1
0
null
2016-04-16T01:19:22
2016-04-16T01:19:20
null
UTF-8
C++
false
false
23,183
h
// XTPSyntaxEditLineMarksManager.h : header file // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME SYNTAX EDIT LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ////////////////////////////////////////////////////////////////////// //{{AFX_CODEJOCK_PRIVATE #if !defined(__XTPSYNTAXEDITLINEMARKSMANAGER_H__) #define __XTPSYNTAXEDITLINEMARKSMANAGER_H__ //}}AFX_CODEJOCK_PRIVATE #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 typedef LPCTSTR XTP_EDIT_LINEMARKTYPE; // You can define your own line mark types (as string constants) // Strings are case sensitive! // static const XTP_EDIT_LINEMARKTYPE xtpEditLMT_Bookmark = _T("Bookmark"); static const XTP_EDIT_LINEMARKTYPE xtpEditLMT_Breakpoint = _T("Breakpoint"); static const XTP_EDIT_LINEMARKTYPE xtpEditLMT_Collapsed = _T("Collapsed"); //=========================================================================== // Summary: Enumerates types of mark refreshing //=========================================================================== enum XTPSyntaxEditLineMarksRefreshType { xtpEditLMRefresh_Unknown = 0, // unknown refresh state xtpEditLMRefresh_Insert = 0x01, // mark inserted xtpEditLMRefresh_Delete = 0x02, // mark deleted xtpEditLMRefresh_Delete_only1 = 0x10, // delete mark for first row of deleted text block; xtpEditLMRefresh_Delete_only2 = 0x20, // delete mark for last row of deleted text block; xtpEditLMRefresh_InsertAt0 = 0x40, // move mark for first row of inserted text block; }; //{{AFX_CODEJOCK_PRIVATE //=========================================================================== class _XTP_EXT_CLASS CXTPSyntaxEditVoidObj : public CXTPCmdTarget { public: typedef void (AFX_CDECL* TPFDeleter)(void*); protected: void* m_pPtr; // A pointer to a handled object TPFDeleter m_pfDeleter; public: //----------------------------------------------------------------------- // Parameters: pPtr : [in]Pointer to the handled object. // bCallInternalAddRef : [in]If this parameter is TRUE // pPtr->InternalAddRef() will be // called in constructor. // By default this parameter is FALSE. // Summary: Default class constructor. // See Also: ~CXTPSmartPtrInternalT() //----------------------------------------------------------------------- CXTPSyntaxEditVoidObj(void* pPtr, TPFDeleter pfDeleter = NULL) { m_pPtr = pPtr; m_pfDeleter = pfDeleter; }; //----------------------------------------------------------------------- // Summary: Default class destructor. // Remarks: Call InternalRelease() for the not NULL handled object. // See Also: CXTPSmartPtrInternalT constructors //----------------------------------------------------------------------- virtual ~CXTPSyntaxEditVoidObj() { if(m_pfDeleter) { m_pfDeleter(m_pPtr); } else { SAFE_DELETE(m_pPtr); } }; //----------------------------------------------------------------------- // Summary: Get a handled object. // Returns: Pointer to the handled object. //----------------------------------------------------------------------- operator void*() const { return m_pPtr; } void* GetPtr() const { return m_pPtr; } //----------------------------------------------------------------------- // Summary: Check is handled object equal NULL. // Returns: TRUE if handled object equal NULL, else FALSE. //----------------------------------------------------------------------- BOOL operator !() const { return !m_pPtr; } }; //--------------------------------------------------------------------------- typedef CXTPSmartPtrInternalT<CXTPSyntaxEditVoidObj> CXTPSyntaxEditVoidObjPtr; //=========================================================================== enum XTPSyntaxEditLMParamType { xtpEditLMPT_Unknown = 0, // unknown refresh state xtpEditLMPT_DWORD = 1, xtpEditLMPT_double = 2, xtpEditLMPT_Ptr = 3, }; struct _XTP_EXT_CLASS XTP_EDIT_LMPARAM { // Data type XTPSyntaxEditLMParamType m_eType; // Data union { DWORD m_dwValue; // xtpEditLMPT_DWORD double m_dblValue; // xtpEditLMPT_double }; protected: CXTPSyntaxEditVoidObjPtr m_Ptr; public: // END Data XTP_EDIT_LMPARAM(); virtual ~XTP_EDIT_LMPARAM(); XTP_EDIT_LMPARAM(const XTP_EDIT_LMPARAM& rSrc); XTP_EDIT_LMPARAM(DWORD dwVal); XTP_EDIT_LMPARAM(double dblValue); XTP_EDIT_LMPARAM(void* pPtr); const XTP_EDIT_LMPARAM& operator=(const XTP_EDIT_LMPARAM& rSrc); const XTP_EDIT_LMPARAM& operator=(DWORD dwValue); const XTP_EDIT_LMPARAM& operator=(double dblValue); const XTP_EDIT_LMPARAM& operator=(void* pPtr); operator DWORD() const; operator double() const; operator void*() const; void SetPtr(void* pPtr, CXTPSyntaxEditVoidObj::TPFDeleter pfDeleter = NULL); void* GetPtr() const; BOOL IsValid() const; void Clear(); }; //=========================================================================== struct _XTP_EXT_CLASS XTP_EDIT_LMDATA { int m_nRow; XTP_EDIT_LMPARAM m_Param; //------------------------------- XTP_EDIT_LMDATA(); virtual ~XTP_EDIT_LMDATA(); XTP_EDIT_LMDATA(const XTP_EDIT_LMDATA& rSrc); const XTP_EDIT_LMDATA& operator=(const XTP_EDIT_LMDATA& rSrc); }; //}}AFX_CODEJOCK_PRIVATE //=========================================================================== // Summary: CXTPSyntaxEditLineMarksManager class provides functionality to // to manipulate marks on text lines. // Used internally by the Smart Edit control. //=========================================================================== class _XTP_EXT_CLASS CXTPSyntaxEditLineMarksManager : public CXTPCmdTarget { //{{AFX_CODEJOCK_PRIVATE DECLARE_DYNAMIC(CXTPSyntaxEditLineMarksManager) //}}AFX_CODEJOCK_PRIVATE public: //----------------------------------------------------------------------- // Summary: // Default object constructor. //----------------------------------------------------------------------- CXTPSyntaxEditLineMarksManager(); //----------------------------------------------------------------------- // Summary: // Destroys a CXTPSyntaxEditLineMarksManager object, handles // cleanup and de-allocation. //----------------------------------------------------------------------- virtual ~CXTPSyntaxEditLineMarksManager(); //----------------------------------------------------------------------- // Summary: // Adds/removes required mark on given text line. // Parameters: // nRow : [in] row number. // lmType : [in] mark type identifier. // pParam : [in] pointer to XTP_EDIT_LMPARAM. Default is NULL. // Remarks: // Call this member function to add or remove mark on the given // text line: if line don't have specified mark it will be added; // otherwise mark will be deleted. // See also: // struct XTP_EDIT_LMPARAM. //----------------------------------------------------------------------- void AddRemoveLineMark(int nRow, const XTP_EDIT_LINEMARKTYPE lmType, XTP_EDIT_LMPARAM* pParam = NULL); //----------------------------------------------------------------------- // Summary: // Sets required mark on given text line. // Parameters: // nRow : [in]row number. // lmType : [in]mark type identifier. // pParam : [in] pointer to XTP_EDIT_LMPARAM. Default is NULL. // Remarks: // Call this member function to add mark on the given text line. // See also: // struct XTP_EDIT_LMPARAM. //----------------------------------------------------------------------- void SetLineMark(int nRow, const XTP_EDIT_LINEMARKTYPE lmType, XTP_EDIT_LMPARAM* pParam = NULL); //----------------------------------------------------------------------- // Summary: // Removes required mark on given text line. // Parameters: // nRow : [in] row number. // lmType : [in] mark type identifier. // Remarks: // Call this member function to remove mark on the given text // line. //----------------------------------------------------------------------- void DeleteLineMark(int nRow, const XTP_EDIT_LINEMARKTYPE lmType); //----------------------------------------------------------------------- // Summary: // Determines if row has mark. // Parameters: // nRow : [in]row number. // lmType : [in]mark type identifier. // pParam : [in] pointer to XTP_EDIT_LMPARAM. Default is NULL. // Remarks: // Call this member function to determine if specified row has // given type of mark. // Returns: // Returns TRUE if row has marked by the specified mark type; // otherwise returns FALSE. //----------------------------------------------------------------------- BOOL HasRowMark(int nRow, const XTP_EDIT_LINEMARKTYPE& lmType, XTP_EDIT_LMPARAM* pParam = NULL) const; //----------------------------------------------------------------------- // Summary: // Returns identifier of the marked line. // Parameters: // nRow : [in]row number. // lmType : [in]mark type identifier. // Remarks: // Call this member function to get line identifier that have // given mark type and precedes specified line number. // Returns: // Number identifier of the marked line. //----------------------------------------------------------------------- POSITION FindPrevLineMark(int& nRow, const XTP_EDIT_LINEMARKTYPE lmType) const; //----------------------------------------------------------------------- // Summary: // Returns identifier of the marked line. // Parameters: // nRow : [in]row number. // lmType : [in]mark type identifier. // Remarks: // Call this member function to get line identifier that have // given mark type and following specified line number. // Returns: // Number identifier of the marked line. //----------------------------------------------------------------------- POSITION FindNextLineMark(int& nRow, const XTP_EDIT_LINEMARKTYPE lmType) const; //----------------------------------------------------------------------- // Summary: // Returns identifier of the marked line. // Parameters: // nRow : [in]row number. // lmType : [in]mark type identifier. // Remarks: // Call this member function to get the last line identifier that // have given mark type and following specified line number. // Returns: // Number identifier of the marked line. //----------------------------------------------------------------------- POSITION GetLastLineMark(const XTP_EDIT_LINEMARKTYPE lmType) const; //----------------------------------------------------------------------- // Summary: // Returns reference to the of the first marked line position // for the specific line marks type. // Parameters: // lmType : [in]mark type identifier. // Remarks: // Call this member function to get the first line identifier that // have given mark type. // Returns: // Number identifier of the marked line; //----------------------------------------------------------------------- POSITION GetFirstLineMark(const XTP_EDIT_LINEMARKTYPE lmType) const; //----------------------------------------------------------------------- // Summary: // Returns reference to the of the next marked line position // for the specific line marks type. // Parameters: // pos : [in]Start POSITION value. // lmType : [in]mark type identifier. // Remarks: // Call this member function to get the next line identifier that // have given mark type. // Returns: // Pointer to XTP_EDIT_LMDATA with number identifier of the marked line. // See also: // struct XTP_EDIT_LMDATA. //----------------------------------------------------------------------- XTP_EDIT_LMDATA* GetNextLineMark(POSITION& pos, const XTP_EDIT_LINEMARKTYPE lmType) const; //----------------------------------------------------------------------- // Summary: // Returns mark from given position. // Parameters: // pos : [in]Current POSITION value. // lmType : [in]mark type identifier. // Remarks: // Call this member function to get the next line identifier that // have given mark type. // Returns: // Number identifier of the marked line. //----------------------------------------------------------------------- XTP_EDIT_LMDATA* GetLineMarkAt(const POSITION pos, const XTP_EDIT_LINEMARKTYPE lmType) const; //----------------------------------------------------------------------- // Summary: // Updates line marks for given range of rows. // Parameters: // nRowFrom : [in] Start row identifier. // nRowTo : [in] End row identifier. // nRefreshType : [in] refresh type. // See also: // XTPSyntaxEditLineMarksRefreshType. //----------------------------------------------------------------------- virtual void RefreshLineMarks(int nRowFrom, int nRowTo, int nRefreshType); //----------------------------------------------------------------------- // Summary: // Removes all line marks from the corresponding types list. // Parameters: // lmType : [in] pointer to null terminated string with types list. //----------------------------------------------------------------------- void RemoveAll(const XTP_EDIT_LINEMARKTYPE lmType); //----------------------------------------------------------------------- // Summary: // Returns count of line marks of the specified type. // Parameters: // lmType : [in] pointer to null terminated string with types list. // Returns: // Count of line marks as integer value. //----------------------------------------------------------------------- int GetCount(const XTP_EDIT_LINEMARKTYPE lmType) const; private: //----------------------------------------------------------------------- // Summary: // This internal helper class is designed to store sorted list of line // marks data objects, based on CArray and provides typical // operations like fast binary searching inside it and basic line // marks manipulations. //----------------------------------------------------------------------- class CLineMarksList : public CXTPCmdTarget { public: //----------------------------------------------------------------------- // Summary: // Default object destructor. //----------------------------------------------------------------------- virtual ~CLineMarksList(); //----------------------------------------------------------------------- // Summary: // Inserts element in the list at proper position. // Parameters: // lmData : [in] Pointer to element description structure. // See also: // XTP_EDIT_LMDATA. //----------------------------------------------------------------------- void Add(const XTP_EDIT_LMDATA& lmData); //----------------------------------------------------------------------- // Summary: // Removes element from the list. // Parameters: // nKey : [in] id of element //----------------------------------------------------------------------- void Remove(const int nKey); //----------------------------------------------------------------------- // Summary: // Removes all elements from the list. //----------------------------------------------------------------------- void RemoveAll(); //----------------------------------------------------------------------- // Summary: // Returns count of line marks of the specified type. // Returns: //----------------------------------------------------------------------- int GetCount() const; //----------------------------------------------------------------------- // Summary: // Returns position of the element with the specified key if exists. // Parameters: // nKey : [in] id of element. // Returns: // POSITION value for an element. //----------------------------------------------------------------------- POSITION FindAt(int nKey) const; //----------------------------------------------------------------------- // Summary: // Returns position of the element with the key following the // specified. // Parameters: // nKey : [in] id of element. // Returns: // POSITION value for an element. //----------------------------------------------------------------------- POSITION FindNext(int nKey) const; //----------------------------------------------------------------------- // Summary: // Returns position of the element with the key previous to the // specified. // Parameters: // nKey : [in] id of element. // Returns: // POSITION value for an element. //----------------------------------------------------------------------- POSITION FindPrev(int nKey) const; //----------------------------------------------------------------------- // Summary: // Refreshes marks for all corresponding lines. // Parameters: // nRowFrom : [in] Start row. // nRowTo : [in] End row. // eRefreshType : [in] Refresh type. // See also: // XTPSyntaxEditLineMarksRefreshType //----------------------------------------------------------------------- void RefreshLineMarks(int nRowFrom, int nRowTo, int nRefreshType); //----------------------------------------------------------------------- // Summary: // Returns line mark by give position. // Parameters: // pos : [in] Current POSITION value. // Remarks: // Call this member function to get the next line identifier that // have given mark type. // Returns: // Number identifier of the marked line. //----------------------------------------------------------------------- XTP_EDIT_LMDATA* GetLineMarkAt(const POSITION pos) const; //----------------------------------------------------------------------- // Summary: // Returns reference to the of the first marked line position // Remarks: // Call this member function to get the first line identifier that // have given mark type. // Returns: // Number identifier of the marked line. //----------------------------------------------------------------------- POSITION GetFirstLineMark() const; //----------------------------------------------------------------------- // Summary: // Returns reference to the of the next marked line position // Parameters: // pos : [in] Current POSITION value. // Remarks: // Call this member function to get the next line identifier that // have given mark type. // Returns: // Number identifier of the marked line. //----------------------------------------------------------------------- XTP_EDIT_LMDATA* GetNextLineMark(POSITION& pos) const; private: //----------------------------------------------------------------------- // Summary: // Finds index of the element with the specified key. // Parameters: // nKey : [in] id of element. // Returns: // -1 if key was not found. //----------------------------------------------------------------------- int FindIndex(const int nKey) const; //----------------------------------------------------------------------- // Summary: // Finds index of the element with the key value previous up to the specified. // Parameters: // nKey : [in] id of element. // Returns: // -1 if key was not found. //----------------------------------------------------------------------- int FindLowerIndex(const int nKey) const; //----------------------------------------------------------------------- // Summary: // Finds index of the element with the key value next to the specified. // Parameters: // nKey : [in] id of element. // Returns: // -1 if key was not found. //----------------------------------------------------------------------- int FindUpperIndex(const int nKey) const; private: typedef CArray<XTP_EDIT_LMDATA*, XTP_EDIT_LMDATA*> CXTPSyntaxEditLineMarkPointersArray; CXTPSyntaxEditLineMarkPointersArray m_array; // The array with the actual line data. }; public: typedef CXTPSmartPtrInternalT<CLineMarksList> CLineMarksListPtr; // SmartPointer for the class. private: //----------------------------------------------------------------------- // Summary: // This class contains a map of line marks lists corresponding to the // string values of line marks types. // It allows adding a new list with the new line mark type // and retrieving a smart pointer of the requested list by its // line mark type. //----------------------------------------------------------------------- class CLineMarksListsMap { public: //----------------------------------------------------------------------- // Summary: // Returns list associated with the specified mark type string. // Parameters: // szMarkType : [in] mark type string. // See also: // CLineMarksListPtr //----------------------------------------------------------------------- CLineMarksListPtr GetList(LPCTSTR szMarkType) const; //----------------------------------------------------------------------- // Summary: // Adds new list associated with the specified mark type string // Parameters: // szMarkType : [in] mark type string. // Returns: // Pointer to the added list. // See also: // CLineMarksListPtr //----------------------------------------------------------------------- CLineMarksListPtr AddList(LPCTSTR szMarkType); //----------------------------------------------------------------------- // Summary: // Calls RefreshLineMarks for all lists inside. // Parameters: // nRowFrom : [in] Start row. // nRowTo : [in] End row. // eRefreshType : [in] Refresh type. // See also: // XTPSyntaxEditLineMarksRefreshType //----------------------------------------------------------------------- void RefreshLineMarks(int nRowFrom, int nRowTo, int nRefreshType); private: CMap<CString, LPCTSTR, CLineMarksListPtr, CLineMarksListPtr&> m_map; // A map containing line marks lists for every mark type. }; CLineMarksListsMap m_mapLists; // A collection of line marks lists for all line mark types. }; #endif // !defined(__XTPSYNTAXEDITLINEMARKSMANAGER_H__)
[ "54639976@qq.com" ]
54639976@qq.com
2de624358b5ffb0b07a3d24f6e60450c2a6ba5e7
a4112183fe925673d75a825fe22379f34e85a108
/VID.cpp
115fef893950cbe057070e995b81cd3971a5c1b5
[]
no_license
irfanrah/OpenCV_Learn
fa1c41738d7b001e4b1ed1ab7a7055229861ca88
9edf20523af68ed9ebe1420c28b6658fba33c1bc
refs/heads/master
2022-05-29T00:35:27.390468
2019-08-17T17:20:36
2019-08-17T17:20:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,079
cpp
#include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> #include <string> #include <sstream> #include <cmath> using namespace cv; using namespace std; //convert double to string namespace patch { template<typename T> std::string to_string(const T& n) { std::ostringstream stm ; stm << n ; return stm.str() ; } } static double angle(Point pt1, Point pt2, Point pt0) { double dx1 = pt1.x - pt0.x; double dy1 = pt1.y - pt0.y; double dx2 = pt2.x - pt0.x; double dy2 = pt2.y - pt0.y; return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10); } /** * Helper function to display text in the center of a contour */ void setLabel(Mat& im, const std::string label, std::vector<Point>& contour) { int fontface = FONT_HERSHEY_SIMPLEX; double scale = 0.4; int thickness = 1; int baseline = 0; Size text = getTextSize(label, fontface, scale, thickness, &baseline); Rect r = boundingRect(contour); Point pt(r.x + ((r.width - text.width) / 2), r.y + ((r.height + text.height) / 2)); rectangle(im, pt + Point(0, baseline), pt + Point(text.width, -text.height), CV_RGB(255,255,255), CV_FILLED); putText(im, label, pt, fontface, scale, CV_RGB(0,0,0), thickness, 8); } int main(int argc, char** argv) { VideoCapture cap(0); if (!cap.isOpened()) { cout << "CAP BROKEN" << endl; return -1; } namedWindow("Circle Detector", CV_WINDOW_AUTOSIZE); while (1) { Mat Original; bool yes = cap.read(Original); if (!yes) { cout << "MAT BROKEN" << endl; break; } Mat gray,bw,gray2; cvtColor(Original, gray, COLOR_BGR2GRAY); threshold( gray, bw,0, 115,3 ); Canny(bw, gray2, 0, 50, 5); vector<vector<Point> > contours; findContours(gray.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); vector<Point> approx; Mat dst = Original.clone(); for (int i = 0; i < contours.size(); i++) { // Approximate contour with accuracy proportional // to the contour perimeter approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true); // Skip small or non-convex objects if (std::fabs(contourArea(contours[i])) < 700 || !isContourConvex(approx)) continue; if (approx.size() == 3) { if (std::fabs(contourArea(contours[i])) < 10000 || !isContourConvex(approx)) { continue; } setLabel(dst, "TRI", contours[i]); } else if (approx.size() >= 4 && approx.size() <= 6) { // Number of vertices of polygonal curve int vtc = approx.size(); // Get the cosines of all corners std::vector<double> cos; for (int j = 2; j < vtc+1; j++) cos.push_back(angle(approx[j%vtc], approx[j-2], approx[j-1])); // Sort ascending the cosine values std::sort(cos.begin(), cos.end()); // Get the lowest and the highest cosine double mincos = cos.front(); double maxcos = cos.back(); // Use the degrees obtained above and the number of vertices // to determine the shape of the contour if (vtc == 4 && mincos >= -0.1 && maxcos <= 0.3) { double area = contourArea(contours[i]); double keliling = arcLength( contours[i], true ); double ganteng = (keliling*keliling)/(16*area); if (ganteng >= 0.8 and ganteng <= 1.15) { setLabel(dst, "SQR", contours[i]); } else { setLabel(dst, "RECT", contours[i]); } } else if (vtc == 5 && mincos >= -0.34 && maxcos <= -0.27) setLabel(dst, "PENTA", contours[i]); else if (vtc == 6 && mincos >= -0.55 && maxcos <= -0.45) setLabel(dst, "HEXA", contours[i]); } else { // Detect and label circles double area = contourArea(contours[i]); Rect r = boundingRect(contours[i]); int radius = r.width / 2; if (std::abs(1 - ((double)r.width / r.height)) <= 0.2 && std::abs(1 - (area / (CV_PI * std::pow(radius, 2)))) <= 0.2) setLabel(dst, "CIR", contours[i]); } } imshow("Circle Detector", dst); if (waitKey(1) == 27) { cout << "EXIT" << endl; break; } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
87b21039909cacba5845c9668e263faed792928e
c79dc016ca85e461e89393ab59a4ebce80160161
/Ice Climber Clone/TopiWalkingDeadState.h
c4c78199c01fd02f2be0e62c650cdeb737063ab9
[]
no_license
janplaehn/Ice-Climber
e37d6e112aeb6e8164e1d8cab60036e5d896c3e2
1d0dcfc7aaa234aa0f9152d90c43ab285dd4398b
refs/heads/main
2023-06-28T08:01:55.388763
2021-07-27T18:06:53
2021-07-27T18:06:53
331,251,484
0
0
null
null
null
null
UTF-8
C++
false
false
282
h
#pragma once #include "State.h" class Topi; class TopiWalkingDeadState : public State { virtual void Enter() override; virtual void Run() override; virtual State* GetNextState() override; virtual void Exit() override; private: Topi* _topi; const float WALKSPEED = 20; };
[ "janplaehn@yahoo.de" ]
janplaehn@yahoo.de
eafdd86182b579a9db9b7d4a0e4a9690a0e52cca
6cd1641193c43fa3dfbd5fc631e3579260b3a45b
/PocketMonster/Main.cpp
719507861abd7d4f75ba940afa0ee7f163439729
[]
no_license
weronika-sleboda/PocketMonsterCpp
a35c7b0fd6fe96dcc522c9f9e5b79472243b57d2
547029ab1c7811c210e96cf0e867452b57d51706
refs/heads/master
2023-08-23T09:02:34.496042
2021-10-10T09:45:27
2021-10-10T09:45:27
415,543,694
0
0
null
null
null
null
UTF-8
C++
false
false
81
cpp
#include "Game.h" #include <iostream> int main() { Game game; game.run(); }
[ "weron@LAPTOP-USNN67N0" ]
weron@LAPTOP-USNN67N0
974fbf68872b185ca21b48381203dd047fecd94d
7c59f80ad58d11650b2bc89d17b47f3d2ab8327d
/Part A/Enemy.h
a113daac9d2d3a118102ec54b07229df25df6ca2
[ "MIT" ]
permissive
Blekiusz/ControllerProject
f473b1d1526916bf30d8824a4fcc7c614f1e75cd
ac0c19922dcc338cd8de82dce3d1c37c8aaaf03f
refs/heads/master
2020-05-14T17:12:27.797244
2019-05-01T13:48:52
2019-05-01T13:48:52
181,887,289
0
0
null
null
null
null
UTF-8
C++
false
false
445
h
#pragma once #include "SDL.h" #include <stdlib.h> class Enemy { public: Enemy(); ~Enemy(); SDL_Surface * image; SDL_Texture * texture; SDL_Rect * rect; SDL_Point * center; void LoadImage(SDL_Renderer * renderer, int pos_x, int pos_y, const char * image_path); void Render(SDL_Renderer * renderer, double rotation); SDL_Rect position; void RandomSpawnOffScreen(Enemy * Enemy); void Move() { rect->y += speed; } int speed = 3; };
[ "kk215953@falmouth.ac.uk" ]
kk215953@falmouth.ac.uk
8b24a2b8ce0fd2db1f2327083853d27cd8539e57
e2a57a1903ffd40513344abb42f14e5dcc049696
/Beautiful_Matrix.cpp
5ad3ea69c443cc7ccc10e6ca2a1764727d32f94c
[ "MIT" ]
permissive
amitkumar0902/The_Quiet_Revolution
f18be4355d0930095f9c77b2ce2029aabf24251a
7713787ef27c0c144e4c2d852d826ee1c4176a95
refs/heads/master
2020-03-18T18:48:14.278175
2019-09-14T19:20:15
2019-09-14T19:20:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
588
cpp
#include <iostream> #include<stdlib.h> using namespace std; int main() { int a[27],i,y; for(i=1;i<=26;i++) { cin>>a[i]; } for(i=1;i<=26;i++) { if(a[i]==1) { break; } } if(i==1||i==5||i==21||i==25) { cout<<4; } else if(i==2||i==4||i==6||i==10||i==20||i==24||i==22||i==16) { cout<<3; } else if(i==3||i==9||i==7||i==17||i==23||i==19||i==15||i==11) { cout<<2; } else if(i==13) { cout<<0; } else{ cout<<1; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
f0981aaefa60deb344d79ddc3163538fc664d2c6
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/97/886.c
f4cbfec0d7490acfd205f7cc88d475e2d3fe5720
[]
no_license
GabeOchieng/ggnn.tensorflow
f5d7d0bca52258336fc12c9de6ae38223f28f786
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
refs/heads/master
2022-05-30T11:17:42.278048
2020-05-02T11:33:31
2020-05-02T11:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
691
c
int main () { int n,a,b,c,d,e,i,zong; scanf("%d",&n); for(i=0;i<=1000;i++) { if(100*i<=n&&100*(i+1)>n) a=i; } for(i=0;i<=1000;i++) { if(50*i<=(n-100*a)&&50*(i+1)>(n-100*a)) {b=i; zong=n-100*a-50*b;} } for(i=0;i<=1000;i++) { if(20*i<=zong&&20*(i+1)>zong) { c=i; zong=n-100*a-50*b-20*c;} } for(i=0;i<=1000;i++) { if(10*i<=zong&&10*(i+1)>zong) { d=i; zong=n-100*a-50*b-20*c-10*d;}} for(i=0;i<=1000;i++) { if(5*i<=zong&&5*(i+1)>zong) { e=i; zong=n-100*a-50*b-20*c-10*d-5*e;}} printf("%d\n%d\n%d\n%d\n%d\n%d\n",a,b,c,d,e,zong); return 0; }
[ "bdqnghi@gmail.com" ]
bdqnghi@gmail.com
ae435f2b1fa1a9b9b77505889d0359bf8ba46d67
d324b3d4ce953574c5945cda64e179f33c36c71b
/php/php-sky/grpc/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc
87ba3a36b78aa13596c1024d0051a15a35df9db4
[ "Apache-2.0" ]
permissive
Denticle/docker-base
decc36cc8eb01be1157d0c0417958c2c80ac0d2f
232115202594f4ea334d512dffb03f34451eb147
refs/heads/main
2023-04-21T10:08:29.582031
2021-05-13T07:27:52
2021-05-13T07:27:52
320,431,033
1
1
null
null
null
null
UTF-8
C++
false
false
8,570
cc
/* * * Copyright 2015 gRPC authors. * * 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 <grpc/support/port_platform.h> #include <grpc/grpc.h> #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/string_util.h> #include "src/core/ext/filters/client_channel/client_channel.h" #include "src/core/ext/filters/client_channel/resolver_registry.h" #include "src/core/ext/transport/chttp2/client/chttp2_connector.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gprpp/memory.h" #include "src/core/lib/iomgr/sockaddr_utils.h" #include "src/core/lib/security/credentials/credentials.h" #include "src/core/lib/security/security_connector/security_connector.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/channel.h" #include "src/core/lib/transport/authority_override.h" #include "src/core/lib/uri/uri_parser.h" namespace grpc_core { class Chttp2SecureClientChannelFactory : public ClientChannelFactory { public: Subchannel* CreateSubchannel(const grpc_channel_args* args) override { grpc_channel_args* new_args = GetSecureNamingChannelArgs(args); if (new_args == nullptr) { gpr_log(GPR_ERROR, "Failed to create channel args during subchannel creation."); return nullptr; } Subchannel* s = Subchannel::Create(MakeOrphanable<Chttp2Connector>(), new_args); grpc_channel_args_destroy(new_args); return s; } private: static grpc_channel_args* GetSecureNamingChannelArgs( const grpc_channel_args* args) { grpc_channel_credentials* channel_credentials = grpc_channel_credentials_find_in_args(args); if (channel_credentials == nullptr) { gpr_log(GPR_ERROR, "Can't create subchannel: channel credentials missing for secure " "channel."); return nullptr; } // Make sure security connector does not already exist in args. if (grpc_security_connector_find_in_args(args) != nullptr) { gpr_log(GPR_ERROR, "Can't create subchannel: security connector already present in " "channel args."); return nullptr; } // Find the authority to use in the security connector. // First, check the authority override channel arg. // Otherwise, get it from the server name used to construct the // channel. grpc_core::UniquePtr<char> authority( gpr_strdup(FindAuthorityOverrideInArgs(args))); if (authority == nullptr) { const char* server_uri_str = grpc_channel_args_find_string(args, GRPC_ARG_SERVER_URI); GPR_ASSERT(server_uri_str != nullptr); authority = ResolverRegistry::GetDefaultAuthority(server_uri_str); } grpc_arg args_to_add[2]; size_t num_args_to_add = 0; if (grpc_channel_args_find(args, GRPC_ARG_DEFAULT_AUTHORITY) == nullptr) { // If the channel args don't already contain GRPC_ARG_DEFAULT_AUTHORITY, // add the arg, setting it to the value just obtained. args_to_add[num_args_to_add++] = grpc_channel_arg_string_create( const_cast<char*>(GRPC_ARG_DEFAULT_AUTHORITY), authority.get()); } grpc_channel_args* args_with_authority = grpc_channel_args_copy_and_add(args, args_to_add, num_args_to_add); // Create the security connector using the credentials and target name. grpc_channel_args* new_args_from_connector = nullptr; RefCountedPtr<grpc_channel_security_connector> subchannel_security_connector = channel_credentials->create_security_connector( /*call_creds=*/nullptr, authority.get(), args_with_authority, &new_args_from_connector); if (subchannel_security_connector == nullptr) { gpr_log(GPR_ERROR, "Failed to create secure subchannel for secure name '%s'", authority.get()); grpc_channel_args_destroy(args_with_authority); return nullptr; } grpc_arg new_security_connector_arg = grpc_security_connector_to_arg(subchannel_security_connector.get()); grpc_channel_args* new_args = grpc_channel_args_copy_and_add( new_args_from_connector != nullptr ? new_args_from_connector : args_with_authority, &new_security_connector_arg, 1); subchannel_security_connector.reset(DEBUG_LOCATION, "lb_channel_create"); if (new_args_from_connector != nullptr) { grpc_channel_args_destroy(new_args_from_connector); } grpc_channel_args_destroy(args_with_authority); return new_args; } }; namespace { grpc_channel* CreateChannel(const char* target, const grpc_channel_args* args, grpc_error** error) { if (target == nullptr) { gpr_log(GPR_ERROR, "cannot create channel with NULL target name"); if (error != nullptr) { *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("channel target is NULL"); } return nullptr; } // Add channel arg containing the server URI. grpc_core::UniquePtr<char> canonical_target = ResolverRegistry::AddDefaultPrefixIfNeeded(target); grpc_arg arg = grpc_channel_arg_string_create( const_cast<char*>(GRPC_ARG_SERVER_URI), canonical_target.get()); const char* to_remove[] = {GRPC_ARG_SERVER_URI}; grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(args, to_remove, 1, &arg, 1); grpc_channel* channel = grpc_channel_create( target, new_args, GRPC_CLIENT_CHANNEL, nullptr, nullptr, error); grpc_channel_args_destroy(new_args); return channel; } } // namespace } // namespace grpc_core namespace { grpc_core::Chttp2SecureClientChannelFactory* g_factory; gpr_once g_factory_once = GPR_ONCE_INIT; void FactoryInit() { g_factory = new grpc_core::Chttp2SecureClientChannelFactory(); } } // namespace // Create a secure client channel: // Asynchronously: - resolve target // - connect to it (trying alternatives as presented) // - perform handshakes grpc_channel* grpc_secure_channel_create(grpc_channel_credentials* creds, const char* target, const grpc_channel_args* args, void* reserved) { grpc_core::ExecCtx exec_ctx; GRPC_API_TRACE( "grpc_secure_channel_create(creds=%p, target=%s, args=%p, " "reserved=%p)", 4, ((void*)creds, target, (void*)args, (void*)reserved)); GPR_ASSERT(reserved == nullptr); grpc_channel* channel = nullptr; grpc_error* error = GRPC_ERROR_NONE; if (creds != nullptr) { // Add channel args containing the client channel factory and channel // credentials. gpr_once_init(&g_factory_once, FactoryInit); grpc_arg channel_factory_arg = grpc_core::ClientChannelFactory::CreateChannelArg(g_factory); grpc_arg args_to_add[] = {channel_factory_arg, grpc_channel_credentials_to_arg(creds)}; const char* arg_to_remove = channel_factory_arg.key; grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove( args, &arg_to_remove, 1, args_to_add, GPR_ARRAY_SIZE(args_to_add)); new_args = creds->update_arguments(new_args); // Create channel. channel = grpc_core::CreateChannel(target, new_args, &error); // Clean up. grpc_channel_args_destroy(new_args); } if (channel == nullptr) { intptr_t integer; grpc_status_code status = GRPC_STATUS_INTERNAL; if (grpc_error_get_int(error, GRPC_ERROR_INT_GRPC_STATUS, &integer)) { status = static_cast<grpc_status_code>(integer); } GRPC_ERROR_UNREF(error); channel = grpc_lame_client_channel_create( target, status, "Failed to create secure client channel"); } return channel; }
[ "root@localhost.localdomain" ]
root@localhost.localdomain
9ce39fe0921a5511f371a26ac6d554484c609237
f9599ba3a5fa64b1b23c9a051e7759788c8cab9c
/android/build/generated/jni/ti.fcm.FcmModule.cpp
1ccfcae6d15b57e4c9836711da9af54c6b41f957
[ "MIT" ]
permissive
rocket13011/Ti.FCM
d0197d35129570c781625a9c5718de98b3fa1c01
39f97279b178752ea512cf495da3bb4629b62892
refs/heads/master
2021-05-14T16:17:55.493753
2017-11-08T07:08:13
2017-11-08T07:08:13
116,016,260
0
0
null
2018-01-02T13:08:44
2018-01-02T13:08:42
null
UTF-8
C++
false
false
31,923
cpp
/** * Appcelerator Titanium Mobile * Copyright (c) 2011-2016 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ /** This code is generated, do not edit by hand. **/ #include "ti.fcm.FcmModule.h" #include "AndroidUtil.h" #include "EventEmitter.h" #include "JNIUtil.h" #include "JSException.h" #include "Proxy.h" #include "ProxyFactory.h" #include "TypeConverter.h" #include "V8Util.h" #include "org.appcelerator.kroll.KrollModule.h" #define TAG "FcmModule" using namespace v8; namespace ti { namespace fcm { Persistent<FunctionTemplate> FcmModule::proxyTemplate; jclass FcmModule::javaClass = NULL; FcmModule::FcmModule(jobject javaObject) : titanium::Proxy(javaObject) { } void FcmModule::bindProxy(Local<Object> exports, Local<Context> context) { Isolate* isolate = context->GetIsolate(); Local<FunctionTemplate> pt = getProxyTemplate(isolate); Local<Function> proxyConstructor = pt->GetFunction(context).ToLocalChecked(); Local<String> nameSymbol = NEW_SYMBOL(isolate, "Fcm"); // use symbol over string for efficiency Local<Object> moduleInstance = proxyConstructor->NewInstance(context).ToLocalChecked(); exports->Set(nameSymbol, moduleInstance); } void FcmModule::dispose(Isolate* isolate) { LOGD(TAG, "dispose()"); if (!proxyTemplate.IsEmpty()) { proxyTemplate.Reset(); } titanium::KrollModule::dispose(isolate); } Local<FunctionTemplate> FcmModule::getProxyTemplate(Isolate* isolate) { if (!proxyTemplate.IsEmpty()) { return proxyTemplate.Get(isolate); } LOGD(TAG, "GetProxyTemplate"); javaClass = titanium::JNIUtil::findClass("ti/fcm/FcmModule"); EscapableHandleScope scope(isolate); // use symbol over string for efficiency Local<String> nameSymbol = NEW_SYMBOL(isolate, "Fcm"); Local<FunctionTemplate> t = titanium::Proxy::inheritProxyTemplate(isolate, titanium::KrollModule::getProxyTemplate(isolate) , javaClass, nameSymbol); proxyTemplate.Reset(isolate, t); t->Set(titanium::Proxy::inheritSymbol.Get(isolate), FunctionTemplate::New(isolate, titanium::Proxy::inherit<FcmModule>)->GetFunction()); titanium::ProxyFactory::registerProxyPair(javaClass, *t); // Method bindings -------------------------------------------------------- titanium::SetProtoMethod(isolate, t, "cancelAll", FcmModule::cancelAll); titanium::SetProtoMethod(isolate, t, "cancel", FcmModule::cancel); titanium::SetProtoMethod(isolate, t, "init", FcmModule::init); titanium::SetProtoMethod(isolate, t, "setAppBadge", FcmModule::setAppBadge); titanium::SetProtoMethod(isolate, t, "getAppBadge", FcmModule::getAppBadge); titanium::SetProtoMethod(isolate, t, "setDebug", FcmModule::setDebug); titanium::SetProtoMethod(isolate, t, "isRemoteNotificationsEnabled", FcmModule::isRemoteNotificationsEnabled); titanium::SetProtoMethod(isolate, t, "isGooglePlayServicesAvailable", FcmModule::isGooglePlayServicesAvailable); titanium::SetProtoMethod(isolate, t, "unregisterForPushNotifications", FcmModule::unregisterForPushNotifications); titanium::SetProtoMethod(isolate, t, "getRemoteDeviceUUID", FcmModule::getRemoteDeviceUUID); titanium::SetProtoMethod(isolate, t, "cancelWithTag", FcmModule::cancelWithTag); titanium::SetProtoMethod(isolate, t, "getSenderId", FcmModule::getSenderId); titanium::SetProtoMethod(isolate, t, "checkPlayServices", FcmModule::checkPlayServices); titanium::SetProtoMethod(isolate, t, "registerForPushNotifications", FcmModule::registerForPushNotifications); Local<ObjectTemplate> prototypeTemplate = t->PrototypeTemplate(); Local<ObjectTemplate> instanceTemplate = t->InstanceTemplate(); // Delegate indexed property get and set to the Java proxy. instanceTemplate->SetIndexedPropertyHandler(titanium::Proxy::getIndexedProperty, titanium::Proxy::setIndexedProperty); // Constants -------------------------------------------------------------- JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { LOGE(TAG, "Failed to get environment in FcmModule"); //return; } DEFINE_INT_CONSTANT(isolate, prototypeTemplate, "SERVICE_INVALID", 9); DEFINE_INT_CONSTANT(isolate, prototypeTemplate, "SERVICE_MISSING", 1); DEFINE_INT_CONSTANT(isolate, prototypeTemplate, "SERVICE_SUCCESS", 0); DEFINE_INT_CONSTANT(isolate, prototypeTemplate, "SERVICE_DISABLED", 3); DEFINE_INT_CONSTANT(isolate, prototypeTemplate, "SERVICE_UPDATING", 18); DEFINE_INT_CONSTANT(isolate, prototypeTemplate, "SERVICE_VERSION_UPDATE_REQUIRED", 2); // Dynamic properties ----------------------------------------------------- instanceTemplate->SetAccessor(NEW_SYMBOL(isolate, "remoteNotificationsEnabled"), FcmModule::getter_remoteNotificationsEnabled, titanium::Proxy::onPropertyChanged, Local<Value>(), DEFAULT, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete) ); instanceTemplate->SetAccessor(NEW_SYMBOL(isolate, "remoteDeviceUUID"), FcmModule::getter_remoteDeviceUUID, titanium::Proxy::onPropertyChanged, Local<Value>(), DEFAULT, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete) ); // Accessors -------------------------------------------------------------- return scope.Escape(t); } // Methods -------------------------------------------------------------------- void FcmModule::cancelAll(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "cancelAll()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "cancelAll", "()V"); if (!methodID) { const char *error = "Couldn't find proxy method 'cancelAll' with signature '()V'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); env->CallVoidMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); } args.GetReturnValue().Set(v8::Undefined(isolate)); } void FcmModule::cancel(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "cancel()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "cancel", "(I)V"); if (!methodID) { const char *error = "Couldn't find proxy method 'cancel' with signature '(I)V'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); if (args.Length() < 1) { char errorStringBuffer[100]; sprintf(errorStringBuffer, "cancel: Invalid number of arguments. Expected 1 but got %d", args.Length()); titanium::JSException::Error(isolate, errorStringBuffer); return; } jvalue jArguments[1]; if ((titanium::V8Util::isNaN(isolate, args[0]) && !args[0]->IsUndefined()) || args[0]->ToString(isolate)->Length() == 0) { const char *error = "Invalid value, expected type Number."; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } if (!args[0]->IsNull()) { Local<Number> arg_0 = args[0]->ToNumber(isolate); jArguments[0].i = titanium::TypeConverter::jsNumberToJavaInt( env, arg_0); } else { jArguments[0].i = NULL; } jobject javaProxy = proxy->getJavaObject(); env->CallVoidMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); } args.GetReturnValue().Set(v8::Undefined(isolate)); } void FcmModule::init(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "init()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "init", "()V"); if (!methodID) { const char *error = "Couldn't find proxy method 'init' with signature '()V'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); env->CallVoidMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); } args.GetReturnValue().Set(v8::Undefined(isolate)); } void FcmModule::setAppBadge(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "setAppBadge()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "setAppBadge", "(I)V"); if (!methodID) { const char *error = "Couldn't find proxy method 'setAppBadge' with signature '(I)V'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); if (args.Length() < 1) { char errorStringBuffer[100]; sprintf(errorStringBuffer, "setAppBadge: Invalid number of arguments. Expected 1 but got %d", args.Length()); titanium::JSException::Error(isolate, errorStringBuffer); return; } jvalue jArguments[1]; if ((titanium::V8Util::isNaN(isolate, args[0]) && !args[0]->IsUndefined()) || args[0]->ToString(isolate)->Length() == 0) { const char *error = "Invalid value, expected type Number."; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } if (!args[0]->IsNull()) { Local<Number> arg_0 = args[0]->ToNumber(isolate); jArguments[0].i = titanium::TypeConverter::jsNumberToJavaInt( env, arg_0); } else { jArguments[0].i = NULL; } jobject javaProxy = proxy->getJavaObject(); env->CallVoidMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); } args.GetReturnValue().Set(v8::Undefined(isolate)); } void FcmModule::getAppBadge(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "getAppBadge()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "getAppBadge", "()I"); if (!methodID) { const char *error = "Couldn't find proxy method 'getAppBadge' with signature '()I'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); jint jResult = (jint)env->CallIntMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { Local<Value> jsException = titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); return; } Local<Number> v8Result = titanium::TypeConverter::javaIntToJsNumber(isolate, env, jResult); args.GetReturnValue().Set(v8Result); } void FcmModule::setDebug(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "setDebug()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "setDebug", "(Z)V"); if (!methodID) { const char *error = "Couldn't find proxy method 'setDebug' with signature '(Z)V'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); if (args.Length() < 1) { char errorStringBuffer[100]; sprintf(errorStringBuffer, "setDebug: Invalid number of arguments. Expected 1 but got %d", args.Length()); titanium::JSException::Error(isolate, errorStringBuffer); return; } jvalue jArguments[1]; if (!args[0]->IsBoolean() && !args[0]->IsNull()) { const char *error = "Invalid value, expected type Boolean."; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } if (!args[0]->IsNull()) { Local<Boolean> arg_0 = args[0]->ToBoolean(isolate); jArguments[0].z = titanium::TypeConverter::jsBooleanToJavaBoolean( env, arg_0); } else { jArguments[0].z = NULL; } jobject javaProxy = proxy->getJavaObject(); env->CallVoidMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); } args.GetReturnValue().Set(v8::Undefined(isolate)); } void FcmModule::isRemoteNotificationsEnabled(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "isRemoteNotificationsEnabled()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "isRemoteNotificationsEnabled", "()Ljava/lang/Boolean;"); if (!methodID) { const char *error = "Couldn't find proxy method 'isRemoteNotificationsEnabled' with signature '()Ljava/lang/Boolean;'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); jobject jResult = (jobject)env->CallObjectMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { Local<Value> jsException = titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); return; } if (jResult == NULL) { args.GetReturnValue().Set(Null(isolate)); return; } Local<Value> v8Result = titanium::TypeConverter::javaObjectToJsValue(isolate, env, jResult); env->DeleteLocalRef(jResult); args.GetReturnValue().Set(v8Result); } void FcmModule::isGooglePlayServicesAvailable(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "isGooglePlayServicesAvailable()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "isGooglePlayServicesAvailable", "()I"); if (!methodID) { const char *error = "Couldn't find proxy method 'isGooglePlayServicesAvailable' with signature '()I'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); jint jResult = (jint)env->CallIntMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { Local<Value> jsException = titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); return; } Local<Number> v8Result = titanium::TypeConverter::javaIntToJsNumber(isolate, env, jResult); args.GetReturnValue().Set(v8Result); } void FcmModule::unregisterForPushNotifications(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "unregisterForPushNotifications()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "unregisterForPushNotifications", "()V"); if (!methodID) { const char *error = "Couldn't find proxy method 'unregisterForPushNotifications' with signature '()V'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); env->CallVoidMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); } args.GetReturnValue().Set(v8::Undefined(isolate)); } void FcmModule::getRemoteDeviceUUID(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "getRemoteDeviceUUID()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "getRemoteDeviceUUID", "()Ljava/lang/String;"); if (!methodID) { const char *error = "Couldn't find proxy method 'getRemoteDeviceUUID' with signature '()Ljava/lang/String;'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); jstring jResult = (jstring)env->CallObjectMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { Local<Value> jsException = titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); return; } if (jResult == NULL) { args.GetReturnValue().Set(Null(isolate)); return; } Local<Value> v8Result = titanium::TypeConverter::javaStringToJsString(isolate, env, jResult); env->DeleteLocalRef(jResult); args.GetReturnValue().Set(v8Result); } void FcmModule::cancelWithTag(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "cancelWithTag()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "cancelWithTag", "(Ljava/lang/String;I)V"); if (!methodID) { const char *error = "Couldn't find proxy method 'cancelWithTag' with signature '(Ljava/lang/String;I)V'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); if (args.Length() < 2) { char errorStringBuffer[100]; sprintf(errorStringBuffer, "cancelWithTag: Invalid number of arguments. Expected 2 but got %d", args.Length()); titanium::JSException::Error(isolate, errorStringBuffer); return; } jvalue jArguments[2]; if (!args[0]->IsNull()) { Local<Value> arg_0 = args[0]; jArguments[0].l = titanium::TypeConverter::jsValueToJavaString( isolate, env, arg_0); } else { jArguments[0].l = NULL; } if ((titanium::V8Util::isNaN(isolate, args[1]) && !args[1]->IsUndefined()) || args[1]->ToString(isolate)->Length() == 0) { const char *error = "Invalid value, expected type Number."; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } if (!args[1]->IsNull()) { Local<Number> arg_1 = args[1]->ToNumber(isolate); jArguments[1].i = titanium::TypeConverter::jsNumberToJavaInt( env, arg_1); } else { jArguments[1].i = NULL; } jobject javaProxy = proxy->getJavaObject(); env->CallVoidMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } env->DeleteLocalRef(jArguments[0].l); if (env->ExceptionCheck()) { titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); } args.GetReturnValue().Set(v8::Undefined(isolate)); } void FcmModule::getSenderId(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "getSenderId()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "getSenderId", "()Ljava/lang/String;"); if (!methodID) { const char *error = "Couldn't find proxy method 'getSenderId' with signature '()Ljava/lang/String;'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); jstring jResult = (jstring)env->CallObjectMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { Local<Value> jsException = titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); return; } if (jResult == NULL) { args.GetReturnValue().Set(Null(isolate)); return; } Local<Value> v8Result = titanium::TypeConverter::javaStringToJsString(isolate, env, jResult); env->DeleteLocalRef(jResult); args.GetReturnValue().Set(v8Result); } void FcmModule::checkPlayServices(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "checkPlayServices()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "checkPlayServices", "()Z"); if (!methodID) { const char *error = "Couldn't find proxy method 'checkPlayServices' with signature '()Z'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); jboolean jResult = (jboolean)env->CallBooleanMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { Local<Value> jsException = titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); return; } Local<Boolean> v8Result = titanium::TypeConverter::javaBooleanToJsBoolean(isolate, env, jResult); args.GetReturnValue().Set(v8Result); } void FcmModule::registerForPushNotifications(const FunctionCallbackInfo<Value>& args) { LOGD(TAG, "registerForPushNotifications()"); Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "registerForPushNotifications", "(Lorg/appcelerator/kroll/KrollDict;)V"); if (!methodID) { const char *error = "Couldn't find proxy method 'registerForPushNotifications' with signature '(Lorg/appcelerator/kroll/KrollDict;)V'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } Local<Object> holder = args.Holder(); // If holder isn't the JavaObject wrapper we expect, look up the prototype chain if (!JavaObject::isJavaObject(holder)) { holder = holder->FindInstanceInPrototypeChain(getProxyTemplate(isolate)); } titanium::Proxy* proxy = titanium::Proxy::unwrap(holder); if (args.Length() < 1) { char errorStringBuffer[100]; sprintf(errorStringBuffer, "registerForPushNotifications: Invalid number of arguments. Expected 1 but got %d", args.Length()); titanium::JSException::Error(isolate, errorStringBuffer); return; } jvalue jArguments[1]; bool isNew_0; if (!args[0]->IsNull()) { Local<Value> arg_0 = args[0]; jArguments[0].l = titanium::TypeConverter::jsObjectToJavaKrollDict( isolate, env, arg_0, &isNew_0); } else { jArguments[0].l = NULL; } jobject javaProxy = proxy->getJavaObject(); env->CallVoidMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (isNew_0) { env->DeleteLocalRef(jArguments[0].l); } if (env->ExceptionCheck()) { titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); } args.GetReturnValue().Set(v8::Undefined(isolate)); } // Dynamic property accessors ------------------------------------------------- void FcmModule::getter_remoteNotificationsEnabled(Local<Name> property, const PropertyCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "isRemoteNotificationsEnabled", "()Ljava/lang/Boolean;"); if (!methodID) { const char *error = "Couldn't find proxy method 'isRemoteNotificationsEnabled' with signature '()Ljava/lang/Boolean;'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } titanium::Proxy* proxy = titanium::Proxy::unwrap(args.Holder()); if (!proxy) { args.GetReturnValue().Set(Undefined(isolate)); return; } jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); jobject jResult = (jobject)env->CallObjectMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { Local<Value> jsException = titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); return; } if (jResult == NULL) { args.GetReturnValue().Set(Null(isolate)); return; } Local<Value> v8Result = titanium::TypeConverter::javaObjectToJsValue(isolate, env, jResult); env->DeleteLocalRef(jResult); args.GetReturnValue().Set(v8Result); } void FcmModule::getter_remoteDeviceUUID(Local<Name> property, const PropertyCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); JNIEnv *env = titanium::JNIScope::getEnv(); if (!env) { titanium::JSException::GetJNIEnvironmentError(isolate); return; } static jmethodID methodID = NULL; if (!methodID) { methodID = env->GetMethodID(FcmModule::javaClass, "getRemoteDeviceUUID", "()Ljava/lang/String;"); if (!methodID) { const char *error = "Couldn't find proxy method 'getRemoteDeviceUUID' with signature '()Ljava/lang/String;'"; LOGE(TAG, error); titanium::JSException::Error(isolate, error); return; } } titanium::Proxy* proxy = titanium::Proxy::unwrap(args.Holder()); if (!proxy) { args.GetReturnValue().Set(Undefined(isolate)); return; } jvalue* jArguments = 0; jobject javaProxy = proxy->getJavaObject(); jstring jResult = (jstring)env->CallObjectMethodA(javaProxy, methodID, jArguments); if (!JavaObject::useGlobalRefs) { env->DeleteLocalRef(javaProxy); } if (env->ExceptionCheck()) { Local<Value> jsException = titanium::JSException::fromJavaException(isolate); env->ExceptionClear(); return; } if (jResult == NULL) { args.GetReturnValue().Set(Null(isolate)); return; } Local<Value> v8Result = titanium::TypeConverter::javaStringToJsString(isolate, env, jResult); env->DeleteLocalRef(jResult); args.GetReturnValue().Set(v8Result); } } // fcm } // ti
[ "“rs@hamburger-appwerft.de“" ]
“rs@hamburger-appwerft.de“
8262830eda4314941c9910593c7f4df9f0aa0443
1cae5a667d553bfd0bc51c33d80c18fe16764aeb
/codeforces/651/b.cpp
5834d786f18729e6665ca72290f57c20d3ae4974
[]
no_license
freeI3ird/competitive-programming
5b0775aebb85565b29eef72d581bfc306296d8a8
c33a27dfaaaf56537a72895d05a8905269f92840
refs/heads/master
2021-08-03T23:31:17.114091
2021-07-21T23:23:38
2021-07-21T23:23:38
160,525,643
0
0
null
null
null
null
UTF-8
C++
false
false
1,910
cpp
/**************************** Author : MANISH RATHI * Handle : free__bird * Institute : NIT KURUKSHETRA * *****************************/ #include<bits/stdc++.h> using namespace std; #define MAX 1000007 #define mode 1000000007 #define ll long long #define ii pair<int,int> #define vi vector<int> #define mp make_pair #define pb push_back #define read(x) scanf("%d",&x) #define print(x) printf("%d\n",x) #define read2(x,y) scanf("%d%d",&x,&y); #define tr(container,it) \ for(typeof(container.begin()) it= container.begin();it!=container.end();it++) ll power(ll x,ll y){ ll res = 1; while(y > 0){ if (y & 1) res = (res*x) ; x = (x*x); y = y>>1; } return res; } ll count_bits(ll n){ ll cnt = 0; while(n > 0) { n = n/2 ; cnt = (cnt + 1) ;} return cnt ; } int main() { //freopen("A-large.in", "r", stdin); //freopen("outout1b.txt", "w", stdout); int t,h; read(t); for(h=1;h<=t;h++) { int n; cin>>n; vector< ii > even, odd; for(int i = 1; i <= 2*n; i++) { int num; cin>>num; if(num&1) { odd.pb(mp(num,i)); } else { even.pb(mp(num, i)); } } int cnt = n-1; while(cnt > 0) { int s1 = odd.size(); int s2 = even.size(); if(s1 >= 2) { ii p1 = odd[s1-1]; ii p2 = odd[s1-2]; odd.pop_back(); odd.pop_back(); cout<<p1.second<<" "<<p2.second<<endl; cnt--; } else { ii p1 = even[s2-1]; ii p2 = even[s2-2]; even.pop_back(); even.pop_back(); cout<<p1.second<<" "<<p2.second<<endl; cnt--; } } } return 0; }
[ "manishrathi1503@gmail.com" ]
manishrathi1503@gmail.com
a2ccb0ab80c818387b3c93e9f0ce78b18441f2a3
33b567f6828bbb06c22a6fdf903448bbe3b78a4f
/opencascade/gce_MakeScale.hxx
672a9548fb7df7f4304120aff20b1f1a6a1a8409
[ "Apache-2.0" ]
permissive
CadQuery/OCP
fbee9663df7ae2c948af66a650808079575112b5
b5cb181491c9900a40de86368006c73f169c0340
refs/heads/master
2023-07-10T18:35:44.225848
2023-06-12T18:09:07
2023-06-12T18:09:07
228,692,262
64
28
Apache-2.0
2023-09-11T12:40:09
2019-12-17T20:02:11
C++
UTF-8
C++
false
false
1,841
hxx
// Created on: 1992-08-26 // Created by: Remi GILET // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _gce_MakeScale_HeaderFile #define _gce_MakeScale_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <gp_Trsf.hxx> class gp_Pnt; //! Implements an elementary construction algorithm for //! a scaling transformation in 3D space. The result is a gp_Trsf transformation. //! A MakeScale object provides a framework for: //! - defining the construction of the transformation, //! - implementing the construction algorithm, and //! - consulting the result. class gce_MakeScale { public: DEFINE_STANDARD_ALLOC //! Constructs a scaling transformation with //! - Point as the center of the transformation, and //! - Scale as the scale factor. Standard_EXPORT gce_MakeScale(const gp_Pnt& Point, const Standard_Real Scale); //! Returns the constructed transformation. Standard_EXPORT const gp_Trsf& Value() const; Standard_EXPORT const gp_Trsf& Operator() const; Standard_EXPORT operator gp_Trsf() const; protected: private: gp_Trsf TheScale; }; #endif // _gce_MakeScale_HeaderFile
[ "adam.jan.urbanczyk@gmail.com" ]
adam.jan.urbanczyk@gmail.com
b00fcd9f3eb63951fb4ec8d75eabcc56b0e29f39
c02e6a950d0bf2ee8c875c70ad707df8b074bb8e
/build/Android/Preview/bimcast/app/src/main/include/Fuse.Resources.ExpirationDisposalPolicy.h
085fe5ffb088cdd9c8229dd03c06dee24ad0c6a3
[]
no_license
BIMCast/bimcast-landing-ui
38c51ad5f997348f8c97051386552509ff4e3faf
a9c7ff963d32d625dfb0237a8a5d1933c7009516
refs/heads/master
2021-05-03T10:51:50.705052
2016-10-04T12:18:22
2016-10-04T12:18:22
69,959,209
0
0
null
null
null
null
UTF-8
C++
false
false
1,444
h
// This file was generated based on C:\ProgramData\Uno\Packages\FuseCore\0.35.12\Resources\$.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Resources.DisposalPolicy.h> namespace g{namespace Fuse{namespace Resources{struct ExpirationDisposalPolicy;}}} namespace g{ namespace Fuse{ namespace Resources{ // internal sealed class ExpirationDisposalPolicy :113 // { ::g::Fuse::Resources::DisposalPolicy_type* ExpirationDisposalPolicy_typeof(); void ExpirationDisposalPolicy__ctor_1_fn(ExpirationDisposalPolicy* __this); void ExpirationDisposalPolicy__CanDispose_fn(ExpirationDisposalPolicy* __this, int* dr, bool* pinned, bool* __retval); void ExpirationDisposalPolicy__Clone_fn(ExpirationDisposalPolicy* __this, ::g::Fuse::Resources::DisposalPolicy** __retval); void ExpirationDisposalPolicy__MarkUsed_fn(ExpirationDisposalPolicy* __this); void ExpirationDisposalPolicy__New1_fn(ExpirationDisposalPolicy** __retval); void ExpirationDisposalPolicy__get_Timeout_fn(ExpirationDisposalPolicy* __this, double* __retval); void ExpirationDisposalPolicy__set_Timeout_fn(ExpirationDisposalPolicy* __this, double* value); struct ExpirationDisposalPolicy : ::g::Fuse::Resources::DisposalPolicy { double lastUsedFrameTime; double _Timeout; void ctor_1(); double Timeout(); void Timeout(double value); static ExpirationDisposalPolicy* New1(); }; // } }}} // ::g::Fuse::Resources
[ "mabu@itechhub.co.za" ]
mabu@itechhub.co.za
3d6fd0b2ea25ff932ff9a1d3d9a53865c48c6281
52c0c7a726581ac8f915763ea922b77b26def0f4
/getMathML/getMathMLDlg.h
c3e0a461223031196ee302310b2b31c0c14db0c3
[ "MIT" ]
permissive
TanWei/getMathML
75182103044325f4cfafb9d443e0e2f21b8511c0
b6fbef24aaa5e80229cce42823f7595f1fe78ddf
refs/heads/master
2020-08-08T00:13:04.830112
2019-10-11T12:03:29
2019-10-11T12:03:29
213,636,393
0
0
null
null
null
null
UTF-8
C++
false
false
637
h
// getMathMLDlg.h : header file // #pragma once // CgetMathMLDlg dialog class CgetMathMLDlg : public CDialogEx { // Construction public: CgetMathMLDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data enum { IDD = IDD_GETMATHML_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedButton1(); };
[ "dcsvgwudi@gmail.com" ]
dcsvgwudi@gmail.com
ac5cd54644ddd7d55c0d442b8ec1ff4b41f96148
cd120e22caebd41a7e8dfa65e633d0479cee8631
/src/output/osgParticle/customCode/osgParticle/Version_pmoc.hpp
85d203d6cdbf2fb19058bd5b4938935266c9e06d
[]
no_license
mp3butcher/osg4noob
d61f510cecc4d07d827815fe01cdf21a45a34ebd
72a869d092e72456a01ec8d7ced2757f73a5cb29
refs/heads/master
2021-05-16T02:23:31.003765
2017-03-14T15:57:21
2017-03-14T15:57:21
23,710,611
4
5
null
null
null
null
UTF-8
C++
false
false
132
hpp
#ifndef osgParticle_Version_customHPP #define osgParticle_Version_customHPP 1 //includes #endif //osgParticle_Version_customHPP
[ "mp3butcher@gmail.com" ]
mp3butcher@gmail.com
b0ccf5e551bc8e8b60c245c4a76fde36cf755869
e27d9e460c374473e692f58013ca692934347ef1
/drafts/quickSpectrogram_2/libraries/liblsl/external/lslboost/asio/detail/tss_ptr.hpp
02f8709e980e22e2cb42dfaa93e526b205f30e1a
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
thoughtworksarts/Dual_Brains
84a0edf69d95299021daf4af9311aed5724a2e84
a7a6586b91a280950693b427d8269bd68bf8a7ab
refs/heads/master
2021-09-18T15:50:51.397078
2018-07-16T23:20:18
2018-07-16T23:20:18
119,759,649
3
0
null
2018-07-16T23:14:34
2018-02-01T00:09:16
HTML
UTF-8
C++
false
false
1,984
hpp
// // detail/tss_ptr.hpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.lslboost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DETAIL_TSS_PTR_HPP #define BOOST_ASIO_DETAIL_TSS_PTR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <lslboost/asio/detail/config.hpp> #if !defined(BOOST_ASIO_HAS_THREADS) # include <lslboost/asio/detail/null_tss_ptr.hpp> #elif defined(BOOST_ASIO_HAS_THREAD_KEYWORD_EXTENSION) # include <lslboost/asio/detail/keyword_tss_ptr.hpp> #elif defined(BOOST_ASIO_WINDOWS) # include <lslboost/asio/detail/win_tss_ptr.hpp> #elif defined(BOOST_ASIO_HAS_PTHREADS) # include <lslboost/asio/detail/posix_tss_ptr.hpp> #else # error Only Windows and POSIX are supported! #endif #include <lslboost/asio/detail/push_options.hpp> namespace lslboost { namespace asio { namespace detail { template <typename T> class tss_ptr #if !defined(BOOST_ASIO_HAS_THREADS) : public null_tss_ptr<T> #elif defined(BOOST_ASIO_HAS_THREAD_KEYWORD_EXTENSION) : public keyword_tss_ptr<T> #elif defined(BOOST_ASIO_WINDOWS) : public win_tss_ptr<T> #elif defined(BOOST_ASIO_HAS_PTHREADS) : public posix_tss_ptr<T> #endif { public: void operator=(T* value) { #if !defined(BOOST_ASIO_HAS_THREADS) null_tss_ptr<T>::operator=(value); #elif defined(BOOST_ASIO_HAS_THREAD_KEYWORD_EXTENSION) keyword_tss_ptr<T>::operator=(value); #elif defined(BOOST_ASIO_WINDOWS) win_tss_ptr<T>::operator=(value); #elif defined(BOOST_ASIO_HAS_PTHREADS) posix_tss_ptr<T>::operator=(value); #endif } }; } // namespace detail } // namespace asio } // namespace lslboost #include <lslboost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_DETAIL_TSS_PTR_HPP
[ "gabriel.ibagon@gmail.com" ]
gabriel.ibagon@gmail.com
aec870e8f13cc9d4c3fb55dc0530d17036b04b0b
d6a134b9b7248e5b1b694d4ef2d33e4a171876b5
/src/dungeon/dungeon.cpp
06fcc35ff4c0d27aefaf481e8fcae71e1c5789eb
[]
no_license
maomihz/kattis
c06edec3ecc77c6014b27eb88cced4fabcec0d3f
49a27f058426d5fac40f13af632fcf6672e5d469
refs/heads/master
2020-04-23T17:42:42.800837
2019-05-18T13:08:57
2019-05-18T13:21:38
171,341,276
0
0
null
null
null
null
UTF-8
C++
false
false
2,856
cpp
#include <iostream> #include <sstream> #include <stdexcept> #include <vector> #include <string> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <queue> #include <deque> #include <stack> #include <climits> #include <algorithm> #include <stdio.h> #include <stdlib.h> using namespace std; typedef tuple<int, int, int> coord; int main() { int z, h, w; char ch; while (cin >> z >> h >> w, z != 0 && h != 0 && w != 0) { char map[z][h][w]; bool seen[z][h][w]; coord start; for (int i = 0; i < z; i++) { for (int j = 0; j < h; j++) { for (int k = 0; k < w; k++) { cin >> ch; map[i][j][k] = ch; seen[i][j][k] = false; if (ch == 'S') { start = make_tuple(i,j,k); seen[i][j][k] = true; } } } } queue<pair<coord, int>> q; q.push(make_pair(start, 0)); bool done = false; while (!q.empty()) { pair<coord, int> cpair = q.front(); coord co = cpair.first; int depth = cpair.second; q.pop(); int a = get<0>(co); int b = get<1>(co); int c = get<2>(co); // cerr << a << "," << b << "," << c << endl; vector<coord> next = { make_tuple(a+1,b,c), make_tuple(a-1,b,c), make_tuple(a,b+1,c), make_tuple(a,b-1,c), make_tuple(a,b,c+1), make_tuple(a,b,c-1) }; for (coord& n : next) { int na = get<0>(n); int nb = get<1>(n); int nc = get<2>(n); // Boundary if (na < 0 || na >= z) continue; if (nb < 0 || nb >= h) continue; if (nc < 0 || nc >= w) continue; // Check for walls if (map[na][nb][nc] == '#') continue; // Check visited if (seen[na][nb][nc]) continue; seen[na][nb][nc] = true; // Check destination if (map[na][nb][nc] == 'E') { done = true; cout << "Escaped in " << depth+1 << " minute(s)." << endl; break; } q.push(make_pair(n, depth+1)); } if (done) break; } if (!done) { cout << "Trapped!" << endl; } } return 0; }
[ "maomihz@gmail.com" ]
maomihz@gmail.com
f82a11bea6b50000fc933c728e047c0831a852a3
e741f43e6f28669f1330faa422bbf44c496b63b4
/old/session13/hwGraphMain.cc
ae5e72aaac05d0e35c6c657ff3ab3251bc4b7497
[]
no_license
StevensDeptECE/CPE593
d5ee7816a42d9db112a9618fb95c14922ccd8e75
3ca8115e84287a2afd18d27976720c159ab056a2
refs/heads/master
2023-04-26T21:07:47.252333
2023-04-19T01:25:09
2023-04-19T01:25:09
102,521,068
50
51
null
2023-03-05T17:45:52
2017-09-05T19:22:17
C++
UTF-8
C++
false
false
587
cc
#include <iostream> #include <CSR.hh> int main() { CSR g("hwgraph.dat"); // g.save("graph.bin"); // CSR g2; // g2.load("graph.bin"); // cout << g2 << '\n'; g.DFS(0); // should print the graph depth first search starting with vertex 0 cout << '\n'; g.BFS(0); // should print the graph depth first search starting with vertex 0 cout << '\n'; float* costs = new float[6*6]; // this is hardcoded. CHEATING! g.floydWarshall(costs); int c = 0; for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++, c++) cout << costs[c++]; cout << '\n'; } delete[] costs; }
[ "Dov.Kruger@stevens.edu" ]
Dov.Kruger@stevens.edu