blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
3a14ec32f2c1064aee9f3e5595a34aac801fdac3
49d40cf9498ce02c614604a41f6b5bc0b5f77bc8
/day10/exam6/exam6.cpp
51ae66933214f1a27b994c07ca02c7b58a231cc5
[]
no_license
gbox3d/c_study2017
a2a1237a61d841f187497dd66a88f7ac137a26af
9ee8f8df10cb03dcf0b65eb3bd85710a7af99fec
refs/heads/master
2020-04-05T13:04:36.179679
2018-07-13T01:45:11
2018-07-13T01:45:11
95,062,916
0
5
null
null
null
null
UHC
C++
false
false
379
cpp
exam6.cpp
// exam6.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다. // #include "stdafx.h" #include <string.h> int main() { char szBuf[32] = "disco"; strcat(szBuf,"very"); printf("%s \n", szBuf); strcat(szBuf, "-channel"); printf("%s \n", szBuf); TCHAR wszBuf[32] = L"디스코"; wcscat(wszBuf, L"배리"); wcscat(wszBuf, L"체널"); return 0; }
73ee8f1d901af6a4b4584a8f7247deff4658cb32
b38e79b60909104a069f3f9a8a0fab64adf07665
/src/ivp.cpp
c2964fbaf1c22684d69ad210156db7e7acb29161
[]
no_license
pyrrhicPachyderm/interaction-partitioning
ec8b157195f5fa853092c97b4390504425355699
8d08ccd69159b5b2970ddbf48d5f85df4ee10dbb
refs/heads/master
2023-04-18T19:29:47.347692
2023-02-25T08:32:20
2023-02-25T08:32:20
398,422,947
0
0
null
null
null
null
UTF-8
C++
false
false
772
cpp
ivp.cpp
#include "ivp.hpp" Eigen::VectorXd IVPStepFuncs::forwardEuler(IVPDerivativeFunc f, Eigen::VectorXd y0, double t0, double h) { return y0 + h * f(t0, y0); } Eigen::VectorXd IVPStepFuncs::rungeKuttaFour(IVPDerivativeFunc f, Eigen::VectorXd y0, double t0, double h) { Eigen::VectorXd k1 = f(t0, y0); Eigen::VectorXd k2 = f(t0 + h/2, y0 + h/2 * k1); Eigen::VectorXd k3 = f(t0 + h/2, y0 + h/2 * k2); Eigen::VectorXd k4 = f(t0 + h, y0 + h * k3); return y0 + h * (k1 + 2*k2 + 2*k3 + k4)/6; } Eigen::VectorXd solveIVP(IVPDerivativeFunc f, Eigen::VectorXd y0, double t0, double tMax, size_t numSteps, IVPStepFunc stepFunc) { double h = (tMax - t0) / numSteps; for(size_t i = 0; i < numSteps; i++) { double t = t0 + i * h; y0 = stepFunc(f, y0, t, h); } return y0; }
4aa8c86b60282e6a1b07ae73cd122aa6b79adc86
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/iecp/src/v20210914/model/DeleteConfigMapRequest.cpp
189c81ca65b9477e49c095560191a3b3e91caafd
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
3,365
cpp
DeleteConfigMapRequest.cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/iecp/v20210914/model/DeleteConfigMapRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Iecp::V20210914::Model; using namespace std; DeleteConfigMapRequest::DeleteConfigMapRequest() : m_edgeUnitIDHasBeenSet(false), m_configMapNameHasBeenSet(false), m_configMapNamespaceHasBeenSet(false) { } string DeleteConfigMapRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_edgeUnitIDHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EdgeUnitID"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_edgeUnitID, allocator); } if (m_configMapNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ConfigMapName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_configMapName.c_str(), allocator).Move(), allocator); } if (m_configMapNamespaceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ConfigMapNamespace"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_configMapNamespace.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } uint64_t DeleteConfigMapRequest::GetEdgeUnitID() const { return m_edgeUnitID; } void DeleteConfigMapRequest::SetEdgeUnitID(const uint64_t& _edgeUnitID) { m_edgeUnitID = _edgeUnitID; m_edgeUnitIDHasBeenSet = true; } bool DeleteConfigMapRequest::EdgeUnitIDHasBeenSet() const { return m_edgeUnitIDHasBeenSet; } string DeleteConfigMapRequest::GetConfigMapName() const { return m_configMapName; } void DeleteConfigMapRequest::SetConfigMapName(const string& _configMapName) { m_configMapName = _configMapName; m_configMapNameHasBeenSet = true; } bool DeleteConfigMapRequest::ConfigMapNameHasBeenSet() const { return m_configMapNameHasBeenSet; } string DeleteConfigMapRequest::GetConfigMapNamespace() const { return m_configMapNamespace; } void DeleteConfigMapRequest::SetConfigMapNamespace(const string& _configMapNamespace) { m_configMapNamespace = _configMapNamespace; m_configMapNamespaceHasBeenSet = true; } bool DeleteConfigMapRequest::ConfigMapNamespaceHasBeenSet() const { return m_configMapNamespaceHasBeenSet; }
a1c75d835a8bea97e3d7e0626403c57eabed1a45
c395d588ab517c53339d120d0a1b6a007a375587
/header/custom_class/my_custom_smartpointor.h
520c1ab8b7ae578fb83293952086366bc7ef8d9c
[]
no_license
HungXum/C-TestProject
f3266fed3b367e4772554e6c7bbec7d1fc89d194
b6f55c3b0dab3871380044a38c4d49f3a5ca3dfe
refs/heads/master
2020-06-05T02:36:05.230299
2019-07-18T08:43:39
2019-07-18T08:43:39
192,284,893
0
0
null
null
null
null
UTF-8
C++
false
false
5,103
h
my_custom_smartpointor.h
/*自定义智能指针*/ #ifndef SMARTPOINTOR_H #define SMARTPOINTOR_H #include <iostream> using namespace std; template<typename T> class smartpointor { //输入输出运算符必须是非成员函数---<<C++Primer>>,因为它们是istream 或 ostream的成员,同时也不能被拷贝 friend ostream& operator << (ostream& os, const smartpointor<T>& sptr) { cout << "friend ostream& operator << (ostream& os, const smartpointor<T>& sptr)" << endl; os << *sptr << endl; return os; } // friend smartpointor<T> operator +(const smartpointor<T>& lhs, const smartpointor<T>& rhs) { // cout << "friend smartpointor<T> operator +(const smartpointor<T>& lhs, const smartpointor<T>& rhs)" << endl; // smartpointor<T> sum(new T(*lhs._data + *rhs._data)); // return sum; // } //友元函数必须是有两个参数,二元运算符成员函数只能有形参 // friend T operator +(const smartpointor<T>& sptr1, const smartpointor<T>& sptr2) { // cout << "friend T operator +(const smartpointor<T>& sptr1, const smartpointor<T>& sptr2)" << endl; // if(sptr1._data != nullptr) { // if(sptr2._data == nullptr) { // return *sptr1._data; // } else { // return *sptr1._data + *sptr2._data; // } // } else if(sptr1._data == nullptr) { // if(sptr2._data == nullptr){ // return 0; // } else { // return *sptr2._data; // } // } // return 0; // } public: smartpointor(T *_p = nullptr): _data(_p){ cout << "smartpointor(T *_p = nullptr)\n"; if(_p) _count = new size_t(1); else _count = new size_t(0); } ~smartpointor() { cout << "~smartpointor()\n"; (*_count)--; if((*_count) <= 0){ delete _data; delete _count; cout << "delete _data and _count\n"; } } smartpointor(const smartpointor& sptr) { cout << "smartpointor(const smartpointor& sptr)\n"; if(this != &sptr) { this->_data = sptr._data; this->_count = sptr._count; (*(this->_count))++; } } smartpointor& operator= (const smartpointor& sptr) { cout << "smartpointor& operator= (const smartpointor& sptr)\n"; if(this->_data == sptr._data) return *this; if(this->_data) { (*(this->_count))--; if((*(this->_count)) == 0) { delete _data; delete _count; } } this->_data = sptr._data; this->_count = sptr._count; (*(this->_count))++; return *this; } //重载解引用运算符 T& operator* () { cout << "T& operator* ()\n"; return *(this->_data); } //重载箭头运算符 smartpointor<T>* operator->() { cout << "T* operator->()\n"; return this; } //重载 +运算符,二元运算符成员函数只能有右侧参数,默认左侧参数为this,如果两个形参编译报错 smartpointor<T> operator +(const smartpointor<T>& rhs) { cout << "smartpointor<T> operator +(const smartpointor<T>& rhs)" << endl; smartpointor<T> sum(new T(*_data + *rhs._data)); return sum; } T* get() const{ cout << "T *get() const\n"; return _data; } size_t getCount() const { cout << "size_t getCount() const\n"; return *_count; } private: T *_data; size_t *_count; }; // template<typename T> // //输入输出流必须重载为友元函数,如果不在类内定义友元运算符函数,会一直报警告 // ostream& operator << (ostream& os, const smartpointor<T>& sptr) { // os << *sptr << endl; // return os; // } // template<typename T> // T operator +(const smartpointor<T>& sptr1, const smartpointor<T>& sptr2) { // if(sptr1._data != nullptr) { // if(sptr2._data == nullptr) { // return *sptr1._data; // } else { // return *sptr1._data + *sptr2._data; // } // } else if(sptr1._data == nullptr) { // if(sptr2._data == nullptr){ // return 0; // } else { // return *sptr2._data; // } // } // return 0; // } /************************************************ tips:关于重载运算符 1.重载运算符函数的参数数量与该运算符作用的运算对象数量一样多.一元运算符有一个参数,二元运算符有两个.如果一个运算符函数是一个成员函数,则它的第一个(左侧)运算对象绑定到隐式的this指针上,因此,成员运算符函数的(显式)参数数量比运算符的运算对象总数少一个. 2.输入输出运算符必须是'非成员函数' 3.下标运算符[],必须是'成员函数',vector中就是重载了operator[] 4.不能用友元函数重载的运算符:=, (), [], -> *************************************************/ #endif
7f907a3c3c12206b43881f72a42520618fa9e8a8
8d362d09997e0d05b7c4280704c444dbae9b7a6f
/p3d_ecs/native/source/perf_utility.h
1ce96f7472647feb2b13528714a1fa1725d3048e
[ "MIT" ]
permissive
PlumpMath/P3D-ECS
69b8f1936490ba632582ab6a632269f9031933d5
8ff2f9b067f812700c25e172f0e9026f3cc4bed3
refs/heads/master
2021-01-25T06:55:35.533900
2016-11-25T10:28:26
2016-11-25T10:28:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,567
h
perf_utility.h
#pragma once #ifndef P3D_ECS_PERFUTILTIY_H #define P3D_ECS_PERFUTILTIY_H #include "config_module.h" #include <vector> #include <algorithm> namespace p3d_ecs { namespace performance { template <typename T> ECS_FORCEINLINE typename ::std::vector<T>::const_iterator vector_find( const ::std::vector<T>& vec, const T& elem) { return ::std::find(vec.cbegin(), vec.cend(), elem); } template <typename T> ECS_FORCEINLINE typename ::std::vector<T>::iterator vector_find(::std::vector<T>& vec, const T& elem) { return ::std::find(vec.begin(), vec.end(), elem); } template <typename T> ECS_FORCEINLINE bool vector_contains(const ::std::vector<T>& vec, const T& elem) { return ::std::find(vec.cbegin(), vec.cend(), elem) != vec.cend(); } template <typename T> void vector_erase(::std::vector<T>& vec, typename ::std::vector<T>::iterator it) { ECS_ASSERT(!vec.empty()); auto last_element_iter = ::std::prev(vec.end()); if (it == last_element_iter) { // We are removing the last element, just reduce size by 1 vec.pop_back(); } else { // We are removing any arbitrary element, swap with last element and pop // last ::std::swap(*it, *last_element_iter); vec.pop_back(); } } template <typename T> bool vector_erase_if_contains(::std::vector<T>& vec, const T& elem) { // Fast removal by swapping with the last element and resizing by -1 if (vec.empty()) return false; auto it = vector_find(vec, elem); if (it != vec.end()) { vector_erase(vec, it); return true; } return false; } template <typename T> void vector_erase(::std::vector<T>& vec, const T& elem) { // Fast removal by swapping with the last element and resizing by -1 // Requires: vec contains elem ECS_ASSERT(!vec.empty()); auto it = vector_find(vec, elem); ECS_ASSERT(it != vec.end()); vector_erase(vec, it); } template <typename T> bool compare_flat_sets(const ::std::vector<T>& a, const ::std::vector<T>& b) { if (a.size() != b.size()) return false; // O(n^2), use with care for (const T& elem : a) { if (!vector_contains(b, elem)) return false; } return true; } } namespace utility { ECS_FORCEINLINE bool float_equals(float a, float b) { return ::std::abs(a - b) < 1e-10; } } } #endif
90b95cd41d068306ce85efa3cd5009e90782941f
5aa916bf1650c7c28818cf569cf717b3db32ead6
/TornadoEngine/Source/Base/MakerMarkupContainer/BasePacket.h
c6829ab31b67479cec96501b41196e370332f30d
[]
no_license
lxq2537664558/MMO-Framework
125c21d2cec6e29ec42bb72f05691ddaef9de448
b0bac7e040ec632543d3d3d4ee23be1bf6224dd9
refs/heads/master
2021-08-19T04:22:28.528036
2017-11-24T18:48:46
2017-11-24T18:48:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
843
h
BasePacket.h
/* Author: Gudakov Ramil Sergeevich a.k.a. Gauss Гудаков Рамиль Сергеевич Contacts: [ramil2085@mail.ru, ramil2085@gmail.com] See for more information License.h. */ #ifndef BasePacketH #define BasePacketH #include "IMarkUpContainer.h" #include "ContainerTypes.h" #include <vector> class TBasePacket { protected: IMarkUpContainer* mMarkUp; IMarkUpContainer::TDesc* mRootDesc; public: TBasePacket(); virtual ~TBasePacket(); virtual int Set(char* p, int size); virtual TContainer GetData(); virtual int GetID() = 0; virtual std::string GetName() = 0; virtual void GetStrContent(std::vector<std::string>& vecStr); private: void GetStrDescItem(std::vector<std::string>& vecStr, int sizeStack); protected: virtual std::string GetStrDescConstItem(std::string name) = 0; }; #endif
42c0718144b7825684f5eed1a1ceb16498cf802b
6d27a9f212bae7f85409ba95489b75386c170ce4
/vs_project/leetcode/Rotate Image/Rotate Image.cpp
50dad99a790155589a9e9c727b27aca165326317
[]
no_license
yumdeer/daily_practice
0b9dea55555070dd0f2ca1beb5e7b657d0b8f52b
9d30c89ef78bfb4b8723827070489d924c4d45ad
refs/heads/master
2023-07-28T09:08:29.190825
2021-09-05T01:14:41
2021-09-05T01:14:41
186,379,724
8
1
null
null
null
null
GB18030
C++
false
false
1,073
cpp
Rotate Image.cpp
#include <iostream> #include <vector> #include <iterator> #include <algorithm> using namespace std; //找规律 a[i][j]与a[n-j-1][i]互换 class Solution { public: void rotate(vector<vector<int>>& matrix) { int matrix_num = matrix.size(); vector<vector<int>> matrix_copy (matrix_num,vector<int>(matrix_num)) ; matrix_copy.insert(matrix_copy.begin(),matrix.begin(),matrix.end()); for (int i = 0; i < matrix_num; i++) for (int j = 0; j < matrix_num; j++) matrix[i][j] = matrix_copy[matrix_num - j-1][i]; } }; ///*四个角互换,然后收缩*/ //void rotate(vector<vector<int>>& matrix) { // int n = matrix.size(); // int a = 0; // int b = n - 1; // while (a < b) { // for (int i = 0; i < (b - a); ++i) { // swap(matrix[a][a + i], matrix[a + i][b]); // swap(matrix[a][a + i], matrix[b][b - i]); // swap(matrix[a][a + i], matrix[b - i][a]); // } // ++a; // --b; // } //} int main() { vector <vector<int>> Rotate = { {1,2,3}, {4,5,6}, {7,8,9} }; Solution m_Sudoku; m_Sudoku.rotate(Rotate); return 0; }
30ee799d8639291ee32b57833fb2962021c4bd7c
bbb0bc53dda330d866c97b2470cd800399e6787e
/owClient/Warden/Warden.h
6584da746dd7ab31da41476061752b346ab3d4c9
[ "Apache-2.0" ]
permissive
World0fWarcraft/OpenWow
b2a09eff76bc9e9c7ff16c370277c07ebfb252e6
1306f70a9069e032d9d52f223ad17fcf182d739d
refs/heads/master
2022-04-28T05:50:53.189149
2022-04-05T23:01:53
2022-04-05T23:01:53
247,746,897
3
2
Apache-2.0
2022-04-06T05:05:02
2020-03-16T15:29:36
C++
UTF-8
C++
false
false
1,191
h
Warden.h
#pragma once #include "../AuthSocket/Cryptography/BigNumber.h" #include "../AuthSocket/Cryptography/ARC4.h" #include "WardenStructs.h" #include "WardenChecks.h" // FORWARD BEGIN class CWorldSocket; // FORWARD END class CWarden { public: CWarden(CWorldSocket& WorldSocket, BigNumber Key); virtual ~CWarden(); bool ProcessPacket(CServerPacket& Bytes); private: void SendWardenPacket(EWardenOpcodes WardenOpcode, CByteBuffer& Bytes); private: void DecryptData(uint8* buffer, uint32 length); void EncryptData(uint8* buffer, uint32 length); void On_WARDEN_SMSG_MODULE_USE(CServerPacket& Buffer); void On_WARDEN_SMSG_MODULE_CACHE(CServerPacket& Buffer); void On_WARDEN_SMSG_CHEAT_CHECKS_REQUEST(CServerPacket& Buffer); void On_WARDEN_SMSG_MODULE_INITIALIZE(CServerPacket& Buffer); void On_WARDEN_SMSG_HASH_REQUEST(CServerPacket& Buffer); private: void Send_WARDEN_CMSG_CHEAT_CHECKS_RESULT(const std::vector<WardenCheck>& Checks); private: CWorldSocket& m_WorldSocket; ARC4 m_InputCrypto; ARC4 m_OutputCrypto; uint8 m_InputKey[16]; uint8 m_OutputKey[16]; uint8 m_Seed[16]; uint16 m_WARDEN_SMSG_MODULE_USE_DataSize; uint16 m_WARDEN_SMSG_MODULE_CACHE_DataPosition; };
8b3bd284e1292a9ee7b5c3c2825a67951e8adbd9
a6d3936eac053b55c600d961ce49c6537e9b1d9f
/C++/Varios/Principal.cpp
7e149761bd729b7ea8638dd49a1a09eb29b1ca50
[]
no_license
dcharua/code
233e382ca5c37983565ca6cb134fb5be18b1af82
781fefb8e87334ec3b060c2dcfa9cf142feea0e7
refs/heads/main
2021-06-23T20:50:35.493288
2020-12-17T20:16:42
2020-12-17T20:16:42
146,336,132
0
0
null
null
null
null
UTF-8
C++
false
false
1,143
cpp
Principal.cpp
#include "Alumno.h" #include <map> map<int,Alumno*> minilista; map<int,Alumno*>::iterator ita; void inicializa() { vector<int> va; va.push_back(1); va.push_back(2); va.push_back(3); va.push_back(4); va.push_back(5); va.push_back(6); Alumno *a = new Alumno("AAA",va); minilista[123] = a; vector<int> vb; vb.push_back(10); vb.push_back(9); vb.push_back(9); vb.push_back(9); vb.push_back(9); vb.push_back(9); Alumno *b = new Alumno("BB",vb); minilista[456] = b; vector<int> vc; vc.push_back(10); vc.push_back(5); vc.push_back(6); vc.push_back(7); vc.push_back(8); vc.push_back(7); Alumno *c = new Alumno("BB",vc); minilista[789] = c; } void calculaPromedios() { for(ita = minilista.begin(); ita != minilista.end(); ita++) { cout<<"Matricula "<<ita->first<<" "<<ita->second->getNombre()<<endl; vector<int> calificaciones = ita->second->getCalif(); int prom = 0; for(int i=0;i<6;i++) prom = prom + calificaciones[i]; prom = prom/6; cout<<" Promedio "<<prom<<endl; } } int main() { inicializa(); calculaPromedios(); return 0; }
570672b47307019be78c5e88358decdae8e442cb
098c88fecc65c8834906ea3dad6ecd30676952c5
/sem-03/hora_fecha_complejos/fecha/persona.h
1c9861051cf4b2863943dfb47479de3c44a625df
[ "Unlicense" ]
permissive
unmultimedio/im-umng-unmultimedio
627a31651ab65e591d231e1b58ddbd4f1c3cae53
4dda7984b8cd91bb096e2890b2f668553b823b04
refs/heads/master
2021-01-18T15:17:19.674977
2014-01-20T21:26:48
2014-01-20T21:26:48
12,092,707
2
1
null
null
null
null
UTF-8
C++
false
false
481
h
persona.h
/** * DOCUMENT CREATED BY JULIAN R. FIGUEROA * about.me/julianrfigueroa * This work is under a Creative * Commons License Atribution-ShareAlike * 3.0 Unported. CC-BY-SA */ // persona.h #include <iostream.h> #include "date.h" class persona { private : char nombre[25]; long cc; const Date fechaNac; public: // constructor persona(char*, long, Date); char* getNombre(void) { return nombre; } long getcc(void) { return cc; } Date getFechaNac(void) { return fechaNac; } };
b8adbab00bdf7aa9900ce97cb69f51080954319b
d20252afc53722c7a1dd2c95d03e2a58537fbbbd
/week10/FboTest/src/testApp.cpp
573d5edd7755777630e514185aa166e5e23e2b89
[]
no_license
gusfaria/gus_algo2013
d3a00ecf5daffcbb42fdc2f77e474401a5475d60
1ec470b019887251125b70a4179c9fbee3c27cde
refs/heads/master
2021-01-10T19:41:24.331695
2014-04-09T18:37:33
2014-04-09T18:37:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,030
cpp
testApp.cpp
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofEnableAlphaBlending(); pos = ofGetWindowSize()/2; vel.set( 20,9 ); mFbo.allocate(ofGetWindowWidth(), ofGetWindowHeight()); } //-------------------------------------------------------------- void testApp::update(){ pos += vel; if (pos.x < 0 || pos.x > ofGetWindowWidth()) { vel.x *= -1; } if (pos.y < 0 || pos.y > ofGetWindowHeight()) { vel.y *= -1; } } //-------------------------------------------------------------- void testApp::draw(){ mFbo.begin();{ ofClear(255, 255, 255, 0); ofPushMatrix();{ ofTranslate(pos); ofSetRectMode(OF_RECTMODE_CENTER); ofRect(-50, -50, 30, 30); ofSetRectMode(OF_RECTMODE_CORNER); }ofPopMatrix(); }mFbo.end(); mFbo.draw(0, 0); mFbo.draw(0, 200); mFbo.draw(200, 0); mFbo.draw(200,200); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }
8d99597060afa762ac3f8dae663f47a96f96a485
9a2176451c57b834ed2c2f7ca8d72b1379da5679
/reverseno.cpp
bab7bce4bb7a745d1b4a7e12665372bbca959529
[]
no_license
j33tmane/Cpp-Genral
d81a6d81c8f5f5aa9078d15c3493103b4b962a15
b0e17a6f7c753a228208067fc8f08f281d0f418e
refs/heads/master
2021-01-20T22:10:22.542503
2016-08-04T19:14:45
2016-08-04T19:14:45
64,960,794
2
0
null
null
null
null
UTF-8
C++
false
false
337
cpp
reverseno.cpp
#include<iostream> using namespace std; int main() { int ans=0,tcase,no; cin>>tcase; for(int i=0;i<tcase;i++) { cin>>no; while(no!=0) { int remainder = no%10; ans = ans*10 + remainder; no/=10; } cout<<ans<<endl; ans=0; } return 0; }
d991d731cdf034f8a8477e03912b64ba24f7dbed
79a2b47b6a6c903a243773b0c69ab25623edcbe0
/Task2/Lab1_3/Material/PhongMaterial.cpp
3d809cc0960ff5861d6dbf0f02dcb8b4ea9687da
[]
no_license
7kia/CG
3a9bb11f3018d16c38c809d79536ec0dea7703df
5a532afd685113b3a13a03dd03b08bf86cfef4bd
refs/heads/master
2020-04-12T09:03:30.731305
2016-12-18T17:49:53
2016-12-18T17:50:13
61,549,242
0
0
null
null
null
null
UTF-8
C++
false
false
859
cpp
PhongMaterial.cpp
#include "stdafx.h" #include "PhongMaterial.h" CPhongModelMaterial::CPhongModelMaterial() : CMaterialCharactiristics() { } void CPhongModelMaterial::Setup() const { glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, glm::value_ptr(m_emission)); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, glm::value_ptr(m_ambient)); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, glm::value_ptr(m_diffuse)); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, glm::value_ptr(m_specular)); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, m_shininess); } void CPhongModelMaterial::SetEmission(const glm::vec4 & emission) { m_emission = emission; } glm::vec4 CPhongModelMaterial::GetEmission() const { return m_emission; } float CPhongModelMaterial::GetShininess() const { return m_shininess; } void CPhongModelMaterial::SetShininess(float shininess) { m_shininess = shininess; }
5852aff6a02392b3607c84a8d57cc3ed6d157ec1
390d95f4cd02d66b493ff82047b37681d46fa341
/Func_Remotas.ino
e24536c654abe75c4462998f484393c37f33a3d9
[]
no_license
KevenSoares/Smart_Remote
fd5be3657efa557b4a4a94216e3642f80a6e55e3
4792476952a950a2c9f7001e904b1297bfb8703d
refs/heads/master
2020-09-14T01:16:04.086131
2019-11-28T18:59:38
2019-11-28T18:59:38
222,965,117
1
0
null
2019-11-28T03:30:36
2019-11-20T15:12:08
C++
UTF-8
C++
false
false
1,990
ino
Func_Remotas.ino
void control(char data) { switch(data){ case 'w': // função de ligar o ar via IR { //on Serial.println("w"); lcd.setCursor(0,0); lcd.print(" Ligando Ar "); int khz = 38; // 38kHz carrier frequency for the NEC protocol unsigned int irSignal[] = {9072,4544, 528,568, 528,568, 528,544, 556,1636, 552,568, 528,572, 528,568, 528,568, 528,1664, 528,568, 548,548, 528,1636, 576,1644, 528,568, 528,568, 528,568, 528,1664, 528,568, 528,568, 528,1664, 528,568, 528,568, 528,568, 528,568, 528,568, 528,544, 576,544, 552,548, 528,1660, 528,572, 528,568, 528,568, 528,544, 552,568, 528,1664, 528,1640, 552,568, 528,568, 532,564, 528,568, 544}; irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz); //Note the approach used to automatically calculate the size of the array. delay(2000); } break; case 'a': // função de ligar o ar via IR { //on Serial.println("a"); lcd.setCursor(0,0); lcd.print(" Desligando Ar "); int khz2 = 38; // 38kHz carrier frequency for the NEC protocol unsigned int irSignal2[] = {9064,4532, 576,544, 532,540, 576,548, 528,568, 528,568, 532,564, 528,568, 536,564, 532,1660, 528,544, 576,544, 548,1648, 528,1664, 528,568, 528,568, 528,568, 528,1668, 528,568, 528,568, 552,1640, 528,568, 528,568, 532,568, 528,568, 532,564, 528,568, 532,564, 528,568, 528,1668, 528,568, 528,568, 548,552, 548,524, 564,532, 576,1640, 528,1644, 556,564, 528,568, 528,544, 576,544, 540}; irsend.sendRaw(irSignal2, sizeof(irSignal2) / sizeof(irSignal2[0]), khz2); //Note the approach used to automatically calculate the size of the array. delay(2000); } break; default: { Serial.println("a"); lcd.setCursor(0,0); lcd.print(" ON/OFF: START "); lcd.setCursor(0,1); lcd.print(" TIME: Inc Time "); } break; } }
a92eba8e878da5fdfba68b891b9966e9956a92aa
b525696739538b467a9f216ca738af22f9adb704
/Day8/Day8Q2.c++
be88c8b7e734d2e4ddc2462b147d2c35c31c420e
[]
no_license
ujjwalrawat11/PlacementQuestion
cb8e189761bfbbf9e8b6fe2ceec28961f8f34339
df83881e2747aead542534ce50e0ec08a7e34ebc
refs/heads/main
2023-06-16T03:11:05.882357
2021-07-10T09:26:33
2021-07-10T09:26:33
381,073,099
0
0
null
null
null
null
UTF-8
C++
false
false
857
Day8Q2.c++
#include <bits/stdc++.h> using namespace std; string longestCommonPrefix(vector<string> &strs) { string s = ""; if (strs.empty()) return s; int len = strs[0].length(); for (int i = 0; i < len; i++) { bool flag = true; for (int j = 0; j < strs.size(); j++) { if (strs[j].length() < len) len = strs[j].length(); if (strs[j][i] != strs[0][i]) { flag = false; break; } } if (flag) s += strs[0][i]; else break; } return s; } int main() { int n; cin>>n; vector<string> strs(n); for(int i=0;i<n;i++){ cin>>strs[i]; } string s=longestCommonPrefix(strs); cout<<s<<endl; return 0; }
30c748951c60d1cb1e3f8ce17e63728004e90c58
e7c459ebe0b7a42d4c46d74aad233f51ae123570
/Longest Common Prefix .cpp
64faedc2748dc2a295e6178f2721797ddf487a86
[]
no_license
C5Compound/LeetCode
3f5c92f305d54ecc6b39d5d448b234a54850c1b5
c598c33c87b96c63388d8f44e89d852d860c5418
refs/heads/master
2021-01-10T19:36:51.674730
2015-09-12T00:43:34
2015-09-12T00:43:34
42,059,578
0
0
null
null
null
null
UTF-8
C++
false
false
725
cpp
Longest Common Prefix .cpp
class Solution { public: string longestCommonPrefix(vector<string>& strs) { string re; if (strs.empty()) { return re; } int minlen = INT_MAX; for (int i = 0; i < strs.size(); ++i) { if (strs[i].size() < minlen) { minlen = strs[i].size(); } } int maxlen = 0; for (int i = 0; i < minlen; ++i) { bool eq = true; char c = strs[0][i]; for (int j = 1; j < strs.size(); ++j) { if (strs[j][i] != c) { return re; } } re.push_back(c); } return re; } };
2e638eb3158f6c9625d423af6b27fcdc0b34c3f9
70c00133e353a5555514327f0a3a20e9bd3de737
/Problem-1192.cpp
8d0e978be81cb457daea3ef821ba8d2734e811a4
[]
no_license
VikasKumarRoy/Leetcode
536d33a67d5448d75171682d82be7518648f39af
953fe0380c0e64077fb2943d06b4ec0638a3c688
refs/heads/master
2021-06-25T16:18:47.367509
2021-03-21T16:58:45
2021-03-21T16:58:45
200,166,984
2
1
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
Problem-1192.cpp
// Problem - 1192 // https://leetcode.com/problems/critical-connections-in-a-network/ // O(v+e) time complexity and O(n) space complexity solution class Solution { public: int time = 0; vector <vector <int>> ans; void dfs(vector <int> adj[], vector <int>& disc, vector <int>& low, int u, vector <int>& parent) { disc[u] = low[u] = ++time; for(int v : adj[u]) { if(disc[v] == -1) { parent[v] = u; dfs(adj, disc, low, v, parent); low[u] = min(low[u], low[v]); if(low[v] > disc[u]) ans.push_back({u, v}); } else if(parent[u] != v) low[u] = min(low[u], disc[v]); } } vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) { vector <int> adj[n]; for(auto path : connections) { adj[path[0]].push_back(path[1]); adj[path[1]].push_back(path[0]); } vector <int> disc(n, -1), low(n, 0), parent(n, -1); for(int i = 0; i < n; i++) { if(disc[i] == -1) dfs(adj, disc, low, i, parent); } return ans; } };
b73564f6d84fc668ec256bedf30675ba2801c9a1
8cabe8e9bdcfadcd58fb2267f2b7984e3e1d3d17
/Test/SwarmBotData.cpp
ac6424818eded85c55e771fff8e35098866c1d15
[]
no_license
Samuel-Harden/Advanced-Tech-A2-Take-2
500095d147f4db09cec6df75126eb2088a17ab34
c077b7c41c22d1ae9ba39d8fd44323b8d2be7df8
refs/heads/master
2021-09-03T01:59:51.142506
2018-01-04T17:20:07
2018-01-04T17:20:07
112,836,282
0
0
null
null
null
null
UTF-8
C++
false
false
570
cpp
SwarmBotData.cpp
#include "SwarmBotData.h" SwarmBotData::SwarmBotData() { } SwarmBotData::~SwarmBotData() { } void SwarmBotData::setSepWeight(float _weight) { sep_weight = _weight; } void SwarmBotData::setPathWeight(float _weight) { path_weight = _weight; } void SwarmBotData::setBotMaxSpeed(float _speed) { bot_max_speed = _speed; } void SwarmBotData::setMaxForce(float _force) { bot_max_force = _force; } void SwarmBotData::setNeighbourDist(float _dist) { neighbour_distance = _dist; } void SwarmBotData::setDesiredSep(float _sep) { desired_separation = _sep; }
a87574fee4dfc19786c77778bfc4ddeb65ed983a
feaf5ed8ba4045ba149a77db276533bdb7b0a66f
/ClassExercise/EP10.cpp
188697d5cd2d78e894af2d2f54a4990612e36491
[]
no_license
OuyangRuihong/Euler
7f3f7289ef82d39bd5be8ef8de4b3db479a51f6c
5836445bb3ff5cd0da5be4f9f686ac17f12c4fef
refs/heads/master
2020-05-09T13:43:21.020986
2019-09-17T13:16:08
2019-09-17T13:16:08
181,164,992
0
0
null
null
null
null
UTF-8
C++
false
false
424
cpp
EP10.cpp
/************************************************************************* > File Name: EP10.cpp > Author:OuyangRuihong > Mail:845540021@qq.com > Created Time: 2019年06月15日 星期六 18时26分32秒 ************************************************************************/ /*素数筛*/ #include<iostream> using namespace std; #define MAX_N 2000000 int main() { int a[MAX_N] = {0}; return 0; }
8c84654e6c3d672e02d5e447f12270d1b2ddf824
2bdfec46f4725c9c7c0ad54935802d84076ff3e5
/source/core/laser-manager/context/MQClient.h
6bb2965388f406550e21316220103e2089750fcb
[ "Apache-2.0" ]
permissive
izenecloud/sf1r-ad-delivery
66f73bc7764216a1faed3d8de0ab3a569b8d4900
998eadb243098446854615de9a96e58a24bd2f4f
refs/heads/master
2021-01-19T14:09:42.842935
2014-09-23T10:41:15
2014-09-23T10:41:15
24,359,409
18
7
null
null
null
null
UTF-8
C++
false
false
1,047
h
MQClient.h
#ifndef SF1R_LASER_WEB_SCALE_METAQ_CLIENT_H #define SF1R_LASER_WEB_SCALE_METAQ_CLIENT_H #include <sf1r-net/RpcServerConnection.h> #include <3rdparty/msgpack/rpc/server.h> #include <glog/logging.h> namespace sf1r { namespace laser { namespace context { template <typename T> class ReqData { public: ReqData(const std::string& topic, const T& val) : topic_(topic) , val_(val) { } MSGPACK_DEFINE(topic_, val_); private: const std::string topic_; const T val_; }; class MQClient { public: MQClient(const std::string& addr, const int port); ~MQClient(); public: void shutdown(); void publish(const std::string& topic); template <typename T> bool produce(const std::string& topic, const T& val); private: const std::string addr_; const int port_; RpcServerConnection* conn_; }; template <typename T> bool MQClient::produce(const std::string& topic, const T& val) { ReqData<T> req(topic, val); conn_->asynRequest("produce", req); return true; } } } } #endif
02e4e8a21fc5097ff9ff076eb1cbcc710fe95ea5
d7253f871c1724626fe8bd0c64f71e03de9b8c2b
/lib/Color.h
a082161bd672cd8d69fde1270f244ae2eecd732b
[ "MIT" ]
permissive
amitkr/chess-knight-moves
e09ae3b07ad822ae033372735baa8601b1fe27d0
011c163935744f735215cf469081051998416e8a
refs/heads/master
2020-05-30T01:18:44.004364
2013-01-09T00:44:42
2013-01-09T00:44:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
787
h
Color.h
#ifndef __CHESS_COLOR_H #define __CHESS_COLOR_H namespace Chess { class Color { public: /* Color of the piece */ typedef enum { Black = 0, White = 1 } color; Color() { c = Black; } Color(const color& cc) { c = cc; } Color(const Color& cc) { c = cc.c; } const Color& operator= (const color &cc) { this->c = cc; return *this; } const Color& operator= (const Color &cc) { this->c = cc.c; return *this; } friend std::ostream& operator<< (std::ostream &o, const Color &col) { o << (int) col.c; return o; } private: color c; }; } //namespace #endif // __CHESS_COLOR_H
b9488cfefe0d087ded97dd78ce9ac197eed61685
2bfddaf9c0ceb7bf46931f80ce84a829672b0343
/tests/xtd.core.unit_tests/src/xtd/tests/environment_special_folder_tests.cpp
45da58449af8092eca51d74101c88eb848e396b6
[ "MIT" ]
permissive
gammasoft71/xtd
c6790170d770e3f581b0f1b628c4a09fea913730
ecd52f0519996b96025b196060280b602b41acac
refs/heads/master
2023-08-19T09:48:09.581246
2023-08-16T20:52:11
2023-08-16T20:52:11
170,525,609
609
53
MIT
2023-05-06T03:49:33
2019-02-13T14:54:22
C++
UTF-8
C++
false
false
27,141
cpp
environment_special_folder_tests.cpp
#include <xtd/environment.h> #include <xtd/tunit/assert.h> #include <xtd/tunit/test_class_attribute.h> #include <xtd/tunit/test_method_attribute.h> using namespace xtd; using namespace xtd::tunit; namespace xtd::tests { class test_class_(environment_special_folder_tests) { public: void test_method_(desktop) { assert::are_equal(0, enum_object<>::to_int32(environment::special_folder::desktop), csf_); assert::are_equal("desktop", enum_object<>::to_string(environment::special_folder::desktop), csf_); assert::are_equal(environment::special_folder::desktop, enum_object<>::parse<environment::special_folder>("desktop"), csf_); } void test_method_(programs) { assert::are_equal(2, enum_object<>::to_int32(environment::special_folder::programs), csf_); assert::are_equal("programs", enum_object<>::to_string(environment::special_folder::programs), csf_); assert::are_equal(environment::special_folder::programs, enum_object<>::parse<environment::special_folder>("programs"), csf_); } void test_method_(my_documents) { assert::are_equal(5, enum_object<>::to_int32(environment::special_folder::my_documents), csf_); assert::are_equal("my_documents", enum_object<>::to_string(environment::special_folder::my_documents), csf_); assert::are_equal(environment::special_folder::my_documents, enum_object<>::parse<environment::special_folder>("my_documents"), csf_); } void test_method_(favorites) { assert::are_equal(6, enum_object<>::to_int32(environment::special_folder::favorites), csf_); assert::are_equal("favorites", enum_object<>::to_string(environment::special_folder::favorites), csf_); assert::are_equal(environment::special_folder::favorites, enum_object<>::parse<environment::special_folder>("favorites"), csf_); } void test_method_(startup) { assert::are_equal(7, enum_object<>::to_int32(environment::special_folder::startup), csf_); assert::are_equal("startup", enum_object<>::to_string(environment::special_folder::startup), csf_); assert::are_equal(environment::special_folder::startup, enum_object<>::parse<environment::special_folder>("startup"), csf_); } void test_method_(recent) { assert::are_equal(8, enum_object<>::to_int32(environment::special_folder::recent), csf_); assert::are_equal("recent", enum_object<>::to_string(environment::special_folder::recent), csf_); assert::are_equal(environment::special_folder::recent, enum_object<>::parse<environment::special_folder>("recent"), csf_); } void test_method_(send_to) { assert::are_equal(9, enum_object<>::to_int32(environment::special_folder::send_to), csf_); assert::are_equal("send_to", enum_object<>::to_string(environment::special_folder::send_to), csf_); assert::are_equal(environment::special_folder::send_to, enum_object<>::parse<environment::special_folder>("send_to"), csf_); } void test_method_(start_menu) { assert::are_equal(11, enum_object<>::to_int32(environment::special_folder::start_menu), csf_); assert::are_equal("start_menu", enum_object<>::to_string(environment::special_folder::start_menu), csf_); assert::are_equal(environment::special_folder::start_menu, enum_object<>::parse<environment::special_folder>("start_menu"), csf_); } void test_method_(my_music) { assert::are_equal(13, enum_object<>::to_int32(environment::special_folder::my_music), csf_); assert::are_equal("my_music", enum_object<>::to_string(environment::special_folder::my_music), csf_); assert::are_equal(environment::special_folder::my_music, enum_object<>::parse<environment::special_folder>("my_music"), csf_); } void test_method_(my_videos) { assert::are_equal(14, enum_object<>::to_int32(environment::special_folder::my_videos), csf_); assert::are_equal("my_videos", enum_object<>::to_string(environment::special_folder::my_videos), csf_); assert::are_equal(environment::special_folder::my_videos, enum_object<>::parse<environment::special_folder>("my_videos"), csf_); } void test_method_(desktop_directory) { assert::are_equal(16, enum_object<>::to_int32(environment::special_folder::desktop_directory), csf_); assert::are_equal("desktop_directory", enum_object<>::to_string(environment::special_folder::desktop_directory), csf_); assert::are_equal(environment::special_folder::desktop_directory, enum_object<>::parse<environment::special_folder>("desktop_directory"), csf_); } void test_method_(my_computer) { assert::are_equal(17, enum_object<>::to_int32(environment::special_folder::my_computer), csf_); assert::are_equal("my_computer", enum_object<>::to_string(environment::special_folder::my_computer), csf_); assert::are_equal(environment::special_folder::my_computer, enum_object<>::parse<environment::special_folder>("my_computer"), csf_); } void test_method_(network_shortcuts) { assert::are_equal(19, enum_object<>::to_int32(environment::special_folder::network_shortcuts), csf_); assert::are_equal("network_shortcuts", enum_object<>::to_string(environment::special_folder::network_shortcuts), csf_); assert::are_equal(environment::special_folder::network_shortcuts, enum_object<>::parse<environment::special_folder>("network_shortcuts"), csf_); } void test_method_(fonts) { assert::are_equal(20, enum_object<>::to_int32(environment::special_folder::fonts), csf_); assert::are_equal("fonts", enum_object<>::to_string(environment::special_folder::fonts), csf_); assert::are_equal(environment::special_folder::fonts, enum_object<>::parse<environment::special_folder>("fonts"), csf_); } void test_method_(templates) { assert::are_equal(21, enum_object<>::to_int32(environment::special_folder::templates), csf_); assert::are_equal("templates", enum_object<>::to_string(environment::special_folder::templates), csf_); assert::are_equal(environment::special_folder::templates, enum_object<>::parse<environment::special_folder>("templates"), csf_); } void test_method_(common_start_menu) { assert::are_equal(22, enum_object<>::to_int32(environment::special_folder::common_start_menu), csf_); assert::are_equal("common_start_menu", enum_object<>::to_string(environment::special_folder::common_start_menu), csf_); assert::are_equal(environment::special_folder::common_start_menu, enum_object<>::parse<environment::special_folder>("common_start_menu"), csf_); } void test_method_(common_programs) { assert::are_equal(23, enum_object<>::to_int32(environment::special_folder::common_programs), csf_); assert::are_equal("common_programs", enum_object<>::to_string(environment::special_folder::common_programs), csf_); assert::are_equal(environment::special_folder::common_programs, enum_object<>::parse<environment::special_folder>("common_programs"), csf_); } void test_method_(common_startup) { assert::are_equal(24, enum_object<>::to_int32(environment::special_folder::common_startup), csf_); assert::are_equal("common_startup", enum_object<>::to_string(environment::special_folder::common_startup), csf_); assert::are_equal(environment::special_folder::common_startup, enum_object<>::parse<environment::special_folder>("common_startup"), csf_); } void test_method_(common_desktop_directory) { assert::are_equal(25, enum_object<>::to_int32(environment::special_folder::common_desktop_directory), csf_); assert::are_equal("common_desktop_directory", enum_object<>::to_string(environment::special_folder::common_desktop_directory), csf_); assert::are_equal(environment::special_folder::common_desktop_directory, enum_object<>::parse<environment::special_folder>("common_desktop_directory"), csf_); } void test_method_(application_data) { assert::are_equal(26, enum_object<>::to_int32(environment::special_folder::application_data), csf_); assert::are_equal("application_data", enum_object<>::to_string(environment::special_folder::application_data), csf_); assert::are_equal(environment::special_folder::application_data, enum_object<>::parse<environment::special_folder>("application_data"), csf_); } void test_method_(printer_shortcuts) { assert::are_equal(27, enum_object<>::to_int32(environment::special_folder::printer_shortcuts), csf_); assert::are_equal("printer_shortcuts", enum_object<>::to_string(environment::special_folder::printer_shortcuts), csf_); assert::are_equal(environment::special_folder::printer_shortcuts, enum_object<>::parse<environment::special_folder>("printer_shortcuts"), csf_); } void test_method_(local_application_data) { assert::are_equal(28, enum_object<>::to_int32(environment::special_folder::local_application_data), csf_); assert::are_equal("local_application_data", enum_object<>::to_string(environment::special_folder::local_application_data), csf_); assert::are_equal(environment::special_folder::local_application_data, enum_object<>::parse<environment::special_folder>("local_application_data"), csf_); } void test_method_(internet_cache) { assert::are_equal(32, enum_object<>::to_int32(environment::special_folder::internet_cache), csf_); assert::are_equal("internet_cache", enum_object<>::to_string(environment::special_folder::internet_cache), csf_); assert::are_equal(environment::special_folder::internet_cache, enum_object<>::parse<environment::special_folder>("internet_cache"), csf_); } void test_method_(cookies) { assert::are_equal(33, enum_object<>::to_int32(environment::special_folder::cookies), csf_); assert::are_equal("cookies", enum_object<>::to_string(environment::special_folder::cookies), csf_); assert::are_equal(environment::special_folder::cookies, enum_object<>::parse<environment::special_folder>("cookies"), csf_); } void test_method_(history) { assert::are_equal(34, enum_object<>::to_int32(environment::special_folder::history), csf_); assert::are_equal("history", enum_object<>::to_string(environment::special_folder::history), csf_); assert::are_equal(environment::special_folder::history, enum_object<>::parse<environment::special_folder>("history"), csf_); } void test_method_(common_application_data) { assert::are_equal(35, enum_object<>::to_int32(environment::special_folder::common_application_data), csf_); assert::are_equal("common_application_data", enum_object<>::to_string(environment::special_folder::common_application_data), csf_); assert::are_equal(environment::special_folder::common_application_data, enum_object<>::parse<environment::special_folder>("common_application_data"), csf_); } void test_method_(windows) { assert::are_equal(36, enum_object<>::to_int32(environment::special_folder::windows), csf_); assert::are_equal("windows", enum_object<>::to_string(environment::special_folder::windows), csf_); assert::are_equal(environment::special_folder::windows, enum_object<>::parse<environment::special_folder>("windows"), csf_); } void test_method_(system) { assert::are_equal(37, enum_object<>::to_int32(environment::special_folder::system), csf_); assert::are_equal("system", enum_object<>::to_string(environment::special_folder::system), csf_); assert::are_equal(environment::special_folder::system, enum_object<>::parse<environment::special_folder>("system"), csf_); } void test_method_(program_files) { assert::are_equal(38, enum_object<>::to_int32(environment::special_folder::program_files), csf_); assert::are_equal("program_files", enum_object<>::to_string(environment::special_folder::program_files), csf_); assert::are_equal(environment::special_folder::program_files, enum_object<>::parse<environment::special_folder>("program_files"), csf_); } void test_method_(my_pictures) { assert::are_equal(39, enum_object<>::to_int32(environment::special_folder::my_pictures), csf_); assert::are_equal("my_pictures", enum_object<>::to_string(environment::special_folder::my_pictures), csf_); assert::are_equal(environment::special_folder::my_pictures, enum_object<>::parse<environment::special_folder>("my_pictures"), csf_); } void test_method_(user_profile) { assert::are_equal(40, enum_object<>::to_int32(environment::special_folder::user_profile), csf_); assert::are_equal("user_profile", enum_object<>::to_string(environment::special_folder::user_profile), csf_); assert::are_equal(environment::special_folder::user_profile, enum_object<>::parse<environment::special_folder>("user_profile"), csf_); } void test_method_(system_x86) { assert::are_equal(41, enum_object<>::to_int32(environment::special_folder::system_x86), csf_); assert::are_equal("system_x86", enum_object<>::to_string(environment::special_folder::system_x86), csf_); assert::are_equal(environment::special_folder::system_x86, enum_object<>::parse<environment::special_folder>("system_x86"), csf_); } void test_method_(program_files_x86) { assert::are_equal(42, enum_object<>::to_int32(environment::special_folder::program_files_x86), csf_); assert::are_equal("program_files_x86", enum_object<>::to_string(environment::special_folder::program_files_x86), csf_); assert::are_equal(environment::special_folder::program_files_x86, enum_object<>::parse<environment::special_folder>("program_files_x86"), csf_); } void test_method_(common_program_files) { assert::are_equal(43, enum_object<>::to_int32(environment::special_folder::common_program_files), csf_); assert::are_equal("common_program_files", enum_object<>::to_string(environment::special_folder::common_program_files), csf_); assert::are_equal(environment::special_folder::common_program_files, enum_object<>::parse<environment::special_folder>("common_program_files"), csf_); } void test_method_(common_program_files_x86) { assert::are_equal(44, enum_object<>::to_int32(environment::special_folder::common_program_files_x86), csf_); assert::are_equal("common_program_files_x86", enum_object<>::to_string(environment::special_folder::common_program_files_x86), csf_); assert::are_equal(environment::special_folder::common_program_files_x86, enum_object<>::parse<environment::special_folder>("common_program_files_x86"), csf_); } void test_method_(common_templates) { assert::are_equal(45, enum_object<>::to_int32(environment::special_folder::common_templates), csf_); assert::are_equal("common_templates", enum_object<>::to_string(environment::special_folder::common_templates), csf_); assert::are_equal(environment::special_folder::common_templates, enum_object<>::parse<environment::special_folder>("common_templates"), csf_); } void test_method_(common_documents) { assert::are_equal(46, enum_object<>::to_int32(environment::special_folder::common_documents), csf_); assert::are_equal("common_documents", enum_object<>::to_string(environment::special_folder::common_documents), csf_); assert::are_equal(environment::special_folder::common_documents, enum_object<>::parse<environment::special_folder>("common_documents"), csf_); } void test_method_(common_admin_tools) { assert::are_equal(47, enum_object<>::to_int32(environment::special_folder::common_admin_tools), csf_); assert::are_equal("common_admin_tools", enum_object<>::to_string(environment::special_folder::common_admin_tools), csf_); assert::are_equal(environment::special_folder::common_admin_tools, enum_object<>::parse<environment::special_folder>("common_admin_tools"), csf_); } void test_method_(admin_tools) { assert::are_equal(48, enum_object<>::to_int32(environment::special_folder::admin_tools), csf_); assert::are_equal("admin_tools", enum_object<>::to_string(environment::special_folder::admin_tools), csf_); assert::are_equal(environment::special_folder::admin_tools, enum_object<>::parse<environment::special_folder>("admin_tools"), csf_); } void test_method_(common_music) { assert::are_equal(53, enum_object<>::to_int32(environment::special_folder::common_music), csf_); assert::are_equal("common_music", enum_object<>::to_string(environment::special_folder::common_music), csf_); assert::are_equal(environment::special_folder::common_music, enum_object<>::parse<environment::special_folder>("common_music"), csf_); } void test_method_(common_pictures) { assert::are_equal(54, enum_object<>::to_int32(environment::special_folder::common_pictures), csf_); assert::are_equal("common_pictures", enum_object<>::to_string(environment::special_folder::common_pictures), csf_); assert::are_equal(environment::special_folder::common_pictures, enum_object<>::parse<environment::special_folder>("common_pictures"), csf_); } void test_method_(common_videos) { assert::are_equal(55, enum_object<>::to_int32(environment::special_folder::common_videos), csf_); assert::are_equal("common_videos", enum_object<>::to_string(environment::special_folder::common_videos), csf_); assert::are_equal(environment::special_folder::common_videos, enum_object<>::parse<environment::special_folder>("common_videos"), csf_); } void test_method_(resources) { assert::are_equal(56, enum_object<>::to_int32(environment::special_folder::resources), csf_); assert::are_equal("resources", enum_object<>::to_string(environment::special_folder::resources), csf_); assert::are_equal(environment::special_folder::resources, enum_object<>::parse<environment::special_folder>("resources"), csf_); } void test_method_(localized_resources) { assert::are_equal(57, enum_object<>::to_int32(environment::special_folder::localized_resources), csf_); assert::are_equal("localized_resources", enum_object<>::to_string(environment::special_folder::localized_resources), csf_); assert::are_equal(environment::special_folder::localized_resources, enum_object<>::parse<environment::special_folder>("localized_resources"), csf_); } void test_method_(common_oem_links) { assert::are_equal(58, enum_object<>::to_int32(environment::special_folder::common_oem_links), csf_); assert::are_equal("common_oem_links", enum_object<>::to_string(environment::special_folder::common_oem_links), csf_); assert::are_equal(environment::special_folder::common_oem_links, enum_object<>::parse<environment::special_folder>("common_oem_links"), csf_); } void test_method_(cd_burning) { assert::are_equal(59, enum_object<>::to_int32(environment::special_folder::cd_burning), csf_); assert::are_equal("cd_burning", enum_object<>::to_string(environment::special_folder::cd_burning), csf_); assert::are_equal(environment::special_folder::cd_burning, enum_object<>::parse<environment::special_folder>("cd_burning"), csf_); } void test_method_(home) { assert::are_equal(64, enum_object<>::to_int32(environment::special_folder::home), csf_); assert::are_equal("home", enum_object<>::to_string(environment::special_folder::home), csf_); assert::are_equal(environment::special_folder::home, enum_object<>::parse<environment::special_folder>("home"), csf_); } void test_method_(xtd_install) { assert::are_equal(1000, enum_object<>::to_int32(environment::special_folder::xtd_install), csf_); assert::are_equal("xtd_install", enum_object<>::to_string(environment::special_folder::xtd_install), csf_); assert::are_equal(environment::special_folder::xtd_install, enum_object<>::parse<environment::special_folder>("xtd_install"), csf_); } void test_method_(xtd_locale) { assert::are_equal(1001, enum_object<>::to_int32(environment::special_folder::xtd_locale), csf_); assert::are_equal("xtd_locale", enum_object<>::to_string(environment::special_folder::xtd_locale), csf_); assert::are_equal(environment::special_folder::xtd_locale, enum_object<>::parse<environment::special_folder>("xtd_locale"), csf_); } void test_method_(xtd_reference_guide) { assert::are_equal(1002, enum_object<>::to_int32(environment::special_folder::xtd_reference_guide), csf_); assert::are_equal("xtd_reference_guide", enum_object<>::to_string(environment::special_folder::xtd_reference_guide), csf_); assert::are_equal(environment::special_folder::xtd_reference_guide, enum_object<>::parse<environment::special_folder>("xtd_reference_guide"), csf_); } void test_method_(xtd_themes) { assert::are_equal(1003, enum_object<>::to_int32(environment::special_folder::xtd_themes), csf_); assert::are_equal("xtd_themes", enum_object<>::to_string(environment::special_folder::xtd_themes), csf_); assert::are_equal(environment::special_folder::xtd_themes, enum_object<>::parse<environment::special_folder>("xtd_themes"), csf_); } void test_method_(xtd_include) { assert::are_equal(1004, enum_object<>::to_int32(environment::special_folder::xtd_include), csf_); assert::are_equal("xtd_include", enum_object<>::to_string(environment::special_folder::xtd_include), csf_); assert::are_equal(environment::special_folder::xtd_include, enum_object<>::parse<environment::special_folder>("xtd_include"), csf_); } void test_method_(xtd_libraries) { assert::are_equal(1005, enum_object<>::to_int32(environment::special_folder::xtd_libraries), csf_); assert::are_equal("xtd_libraries", enum_object<>::to_string(environment::special_folder::xtd_libraries), csf_); assert::are_equal(environment::special_folder::xtd_libraries, enum_object<>::parse<environment::special_folder>("xtd_libraries"), csf_); } void test_method_(xtd_resources) { assert::are_equal(1006, enum_object<>::to_int32(environment::special_folder::xtd_resources), csf_); assert::are_equal("xtd_resources", enum_object<>::to_string(environment::special_folder::xtd_resources), csf_); assert::are_equal(environment::special_folder::xtd_resources, enum_object<>::parse<environment::special_folder>("xtd_resources"), csf_); } void test_method_(xtd_console_include) { assert::are_equal(1007, enum_object<>::to_int32(environment::special_folder::xtd_console_include), csf_); assert::are_equal("xtd_console_include", enum_object<>::to_string(environment::special_folder::xtd_console_include), csf_); assert::are_equal(environment::special_folder::xtd_console_include, enum_object<>::parse<environment::special_folder>("xtd_console_include"), csf_); } void test_method_(xtd_console_libraries) { assert::are_equal(1008, enum_object<>::to_int32(environment::special_folder::xtd_console_libraries), csf_); assert::are_equal("xtd_console_libraries", enum_object<>::to_string(environment::special_folder::xtd_console_libraries), csf_); assert::are_equal(environment::special_folder::xtd_console_libraries, enum_object<>::parse<environment::special_folder>("xtd_console_libraries"), csf_); } void test_method_(xtd_drawing_include) { assert::are_equal(1009, enum_object<>::to_int32(environment::special_folder::xtd_drawing_include), csf_); assert::are_equal("xtd_drawing_include", enum_object<>::to_string(environment::special_folder::xtd_drawing_include), csf_); assert::are_equal(environment::special_folder::xtd_drawing_include, enum_object<>::parse<environment::special_folder>("xtd_drawing_include"), csf_); } void test_method_(xtd_drawing_libraries) { assert::are_equal(1010, enum_object<>::to_int32(environment::special_folder::xtd_drawing_libraries), csf_); assert::are_equal("xtd_drawing_libraries", enum_object<>::to_string(environment::special_folder::xtd_drawing_libraries), csf_); assert::are_equal(environment::special_folder::xtd_drawing_libraries, enum_object<>::parse<environment::special_folder>("xtd_drawing_libraries"), csf_); } void test_method_(xtd_drawing_resources) { assert::are_equal(1011, enum_object<>::to_int32(environment::special_folder::xtd_drawing_resources), csf_); assert::are_equal("xtd_drawing_resources", enum_object<>::to_string(environment::special_folder::xtd_drawing_resources), csf_); assert::are_equal(environment::special_folder::xtd_drawing_resources, enum_object<>::parse<environment::special_folder>("xtd_drawing_resources"), csf_); } void test_method_(xtd_forms_include) { assert::are_equal(1012, enum_object<>::to_int32(environment::special_folder::xtd_forms_include), csf_); assert::are_equal("xtd_forms_include", enum_object<>::to_string(environment::special_folder::xtd_forms_include), csf_); assert::are_equal(environment::special_folder::xtd_forms_include, enum_object<>::parse<environment::special_folder>("xtd_forms_include"), csf_); } void test_method_(xtd_forms_libraries) { assert::are_equal(1013, enum_object<>::to_int32(environment::special_folder::xtd_forms_libraries), csf_); assert::are_equal("xtd_forms_libraries", enum_object<>::to_string(environment::special_folder::xtd_forms_libraries), csf_); assert::are_equal(environment::special_folder::xtd_forms_libraries, enum_object<>::parse<environment::special_folder>("xtd_forms_libraries"), csf_); } void test_method_(xtd_forms_resources) { assert::are_equal(1014, enum_object<>::to_int32(environment::special_folder::xtd_forms_resources), csf_); assert::are_equal("xtd_forms_resources", enum_object<>::to_string(environment::special_folder::xtd_forms_resources), csf_); assert::are_equal(environment::special_folder::xtd_forms_resources, enum_object<>::parse<environment::special_folder>("xtd_forms_resources"), csf_); } void test_method_(xtd_tunit_include) { assert::are_equal(1015, enum_object<>::to_int32(environment::special_folder::xtd_tunit_include), csf_); assert::are_equal("xtd_tunit_include", enum_object<>::to_string(environment::special_folder::xtd_tunit_include), csf_); assert::are_equal(environment::special_folder::xtd_tunit_include, enum_object<>::parse<environment::special_folder>("xtd_tunit_include"), csf_); } void test_method_(xtd_tunit_libraries) { assert::are_equal(1016, enum_object<>::to_int32(environment::special_folder::xtd_tunit_libraries), csf_); assert::are_equal("xtd_tunit_libraries", enum_object<>::to_string(environment::special_folder::xtd_tunit_libraries), csf_); assert::are_equal(environment::special_folder::xtd_tunit_libraries, enum_object<>::parse<environment::special_folder>("xtd_tunit_libraries"), csf_); } }; }
e1046c9f7a6840dc686add5b1b233061d798759b
18764973fb6947c80114c95e52f5e20ff1c7eda4
/src/components/policy/src/policy/include/policy/policy_manager_impl.h
937d02e5a6c4fcfb8a97a37c9980bbcdd6da2784
[]
no_license
FaridJafarov-l/sdl_core
a75ff5f13572d92f09c995bc5e979c8815aaeb52
11d6463b47a00334a23e8e7cadea4ab818d54f60
refs/heads/master
2023-09-04T08:55:16.628093
2016-12-19T12:33:47
2016-12-19T12:33:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,521
h
policy_manager_impl.h
/* Copyright (c) 2013, Ford Motor Company All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Ford Motor Company 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. */ #ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_IMPL_H_ #define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_IMPL_H_ #include <list> #include "utils/shared_ptr.h" #include "utils/lock.h" #include "policy/policy_manager.h" #include "policy/policy_table.h" #include "policy/cache_manager_interface.h" #include "policy/update_status_manager.h" #include "./functions.h" #include "usage_statistics/statistics_manager.h" namespace policy_table = rpc::policy_table_interface_base; namespace policy { class AccessRemote; struct Subject; struct CheckAppPolicy; class PolicyManagerImpl : public PolicyManager { public: PolicyManagerImpl(); virtual void set_listener(PolicyListener* listener); PolicyListener* listener() const { return listener_; } virtual bool InitPT(const std::string& file_name); virtual bool LoadPT(const std::string& file, const BinaryMessage& pt_content); virtual bool ResetPT(const std::string& file_name); virtual void GetServiceUrls(const std::string& service_type, EndpointUrls& end_points); virtual std::string GetLockScreenIconUrl() const; virtual void RequestPTUpdate(); virtual void CheckPermissions(const PTString& device_id, const PTString& app_id, const PTString& hmi_level, const PTString& rpc, const RPCParams& rpc_params, CheckPermissionResult& result); virtual bool ResetUserConsent(); virtual void KmsChanged(int kilometers); virtual void IncrementIgnitionCycles(); virtual std::string ForcePTExchange(); virtual std::string GetPolicyTableStatus() const; virtual void ResetRetrySequence(); virtual int NextRetryTimeout(); virtual int TimeoutExchange(); virtual const std::vector<int> RetrySequenceDelaysSeconds(); virtual void OnExceededTimeout(); virtual void OnUpdateStarted(); virtual void PTUpdatedAt(int kilometers, int days_after_epoch); /** * Refresh data about retry sequence from policy table */ virtual void RefreshRetrySequence(); virtual DeviceConsent GetUserConsentForDevice(const std::string& device_id); virtual void GetUserConsentForApp( const std::string& device_id, const std::string& policy_app_id, std::vector<FunctionalGroupPermission>& permissions); virtual void SetUserConsentForDevice(const std::string& device_id, bool is_allowed); virtual bool ReactOnUserDevConsentForApp(const std::string app_id, bool is_device_allowed); virtual bool GetInitialAppData(const std::string& application_id, StringArray* nicknames = NULL, StringArray* app_hmi_types = NULL); virtual void SetDeviceInfo(const std::string& device_id, const DeviceInfo& device_info); virtual void SetUserConsentForApp(const PermissionConsent& permissions); virtual bool GetDefaultHmi(const std::string& policy_app_id, std::string* default_hmi); virtual bool GetPriority(const std::string& policy_app_id, std::string* priority); virtual std::vector<UserFriendlyMessage> GetUserFriendlyMessages( const std::vector<std::string>& message_code, const std::string& language); virtual bool IsApplicationRevoked(const std::string& app_id) const; virtual void GetPermissionsForApp( const std::string& device_id, const std::string& policy_app_id, std::vector<FunctionalGroupPermission>& permissions); virtual std::string& GetCurrentDeviceId(const std::string& policy_app_id); virtual void SetSystemLanguage(const std::string& language); virtual void SetSystemInfo(const std::string& ccpu_version, const std::string& wers_country_code, const std::string& language); virtual void OnSystemReady(); virtual uint32_t GetNotificationsNumber(const std::string& priority); virtual void SetVINValue(const std::string& value); // Interface StatisticsManager (begin) virtual void Increment(usage_statistics::GlobalCounterId type); virtual void Increment(const std::string& app_id, usage_statistics::AppCounterId type); virtual void Set(const std::string& app_id, usage_statistics::AppInfoId type, const std::string& value); virtual void Add(const std::string& app_id, usage_statistics::AppStopwatchId type, int32_t timespan_seconds); // Interface StatisticsManager (end) AppPermissions GetAppPermissionsChanges(const std::string& policy_app_id); void RemovePendingPermissionChanges(const std::string& app_id); void SendNotificationOnPermissionsUpdated(const std::string& device_id, const std::string& application_id); bool CleanupUnpairedDevices(); bool CanAppKeepContext(const std::string& app_id); bool CanAppStealFocus(const std::string& app_id); void MarkUnpairedDevice(const std::string& device_id); void AddApplication(const std::string& device_id, const std::string& application_id, const std::vector<int>& hmi_types); virtual void RemoveAppConsentForGroup(const std::string& app_id, const std::string& group_name); virtual uint16_t HeartBeatTimeout(const std::string& app_id) const; virtual void SaveUpdateStatusRequired(bool is_update_needed); virtual bool IsPredataPolicy(const std::string& policy_app_id); virtual bool GetHMITypes(const std::string& application_id, std::vector<int> *app_types); void set_cache_manager(CacheManagerInterface* cache_manager); virtual void OnAppsSearchStarted(); virtual void OnAppsSearchCompleted(); void OnAppRegisteredOnMobile(const std::string& device_id, const std::string& application_id); #ifdef SDL_REMOTE_CONTROL virtual TypeAccess CheckAccess(const PTString& device_id, const PTString& app_id, const SeatLocation& zone, const PTString& module, const PTString& rpc, const RemoteControlParams& params); virtual bool CheckModule(const PTString& app_id, const PTString& module); virtual void SetAccess(const PTString& dev_id, const PTString& app_id, const SeatLocation& zone, const PTString& module, bool allowed); virtual void ResetAccess(const PTString& dev_id, const PTString& app_id); virtual void ResetAccess(const SeatLocation& zone, const PTString& module); virtual void SetPrimaryDevice(const PTString& dev_id); virtual void ResetPrimaryDevice(); virtual PTString PrimaryDevice() const; virtual void SetDeviceZone(const PTString& dev_id, const SeatLocation& zone); virtual bool GetDeviceZone(const PTString& dev_id, SeatLocation* zone) const; virtual void SetRemoteControl(bool enabled); virtual bool GetRemoteControl() const; virtual void OnChangedPrimaryDevice(const std::string& device_id, const std::string& application_id); virtual void OnChangedRemoteControl(const std::string& device_id, const std::string& application_id); virtual void OnChangedDeviceZone(const std::string& device_id, const std::string& application_id); virtual void SendAppPermissionsChanged(const std::string& device_id, const std::string& application_id); virtual bool GetModuleTypes(const std::string& policy_app_id, std::vector<std::string>* modules) const; #endif // SDL_REMOTE_CONTROL protected: virtual utils::SharedPtr<policy_table::Table> Parse( const BinaryMessage& pt_content); private: void CheckTriggers(); /* * @brief Checks policy table update along with current data for any changes * in assigned functional group list of application * * @param Policy table update struct */ void CheckPermissionsChanges( const utils::SharedPtr<policy_table::Table> update, const utils::SharedPtr<policy_table::Table> snapshot); /** * @brief Fill structure to be sent with OnPermissionsChanged notification * * @param Policy table struct, which contains rpc functional groups data * @param List of rpc functional group names, which should be checked * @param group_permission User permissions for functional groups * @param Notification struct to be filled and sent */ void PrepareNotificationData( const policy_table::FunctionalGroupings& groups, const policy_table::Strings& group_names, const std::vector<FunctionalGroupPermission>& group_permission, Permissions& notification_data); /** * @brief Validate PermissionConsent structure according to currently * assigned groups * @param permissions PermissionConsent structure that should be validated. * @return PermissonConsent struct, which contains no foreign groups */ PermissionConsent EnsureCorrectPermissionConsent( const PermissionConsent& permissions_to_check); /** * @brief Allows to process case when added application is not present in * policy db. * @param policy application id. * @param cuuren consent for application's device. */ void AddNewApplication(const std::string& application_id, DeviceConsent device_consent); /** * @brief Allows to process case when added application is already * in policy db. * @param policy application id. * @param cuuren consent for application's device. */ void PromoteExistedApplication(const std::string& application_id, DeviceConsent device_consent); /** * @brief Check if certain application already in policy db. * @param policy application id. * @return true if application presents false otherwise. */ bool IsNewApplication(const std::string& application_id) const; /** * Checks existing and permissions of AppStorageFolder * @return true if AppStorageFolder exists and has permissions read/write */ bool CheckAppStorageFolder() const; /** * @brief Checks whether need ask the permission of users * @return true if user consent is needed */ virtual bool IsConsentNeeded(const std::string& app_id); /** * @brief Changes isConsentNeeded for app pending permissions, in case * user set permissions before app activation. * @param Unique app id * @param Current permissions for app */ void CheckPendingPermissionsChanges( const std::string& policy_app_id, const std::vector<FunctionalGroupPermission>& current_permissions); virtual void StartPTExchange(); virtual bool ExceededDays(); virtual bool ExceededIgnitionCycles(); bool IsPTValid(utils::SharedPtr<policy_table::Table> policy_table, policy_table::PolicyTableType type) const; private: void GetPermissions(const std::string device_id, const std::string application_id, Permissions* data); PolicyListener* listener_; UpdateStatusManager update_status_manager_; CacheManagerInterfaceSPtr cache_; #ifdef SDL_REMOTE_CONTROL TypeAccess CheckDriverConsent(const Subject& who, const Object& what, const std::string& rpc, const RemoteControlParams& params); void CheckPTUUpdatesChange( const utils::SharedPtr<policy_table::Table> pt_update, const utils::SharedPtr<policy_table::Table> snapshot); bool CheckPTURemoteCtrlChange( const utils::SharedPtr<policy_table::Table> pt_update, const utils::SharedPtr<policy_table::Table> snapshot); void CheckPTUZonesChange( const utils::SharedPtr<policy_table::Table> pt_update, const utils::SharedPtr<policy_table::Table> snapshot); void CheckRemoteGroupsChange( const utils::SharedPtr<policy_table::Table> pt_update, const utils::SharedPtr<policy_table::Table> snapshot); utils::SharedPtr<AccessRemote> access_remote_; void SendHMILevelChanged(const Subject& who); void UpdateDeviceRank(const Subject& who, const std::string& rank); void OnPrimaryGroupsChanged(const std::string& application_id); void OnNonPrimaryGroupsChanged(const std::string& application_id); #endif // SDL_REMOTE_CONTROL sync_primitives::Lock apps_registration_lock_; sync_primitives::Lock app_permissions_diff_lock_; std::map<std::string, AppPermissions> app_permissions_diff_; /** * Timeout to wait response with UpdatePT */ int retry_sequence_timeout_; /** * Seconds between retries to update PT */ std::vector<int> retry_sequence_seconds_; /** * Current index trying of retry sequence */ uint32_t retry_sequence_index_; /** * Lock for guarding retry sequence */ sync_primitives::Lock retry_sequence_lock_; /** * Lock for guarding recording statistics */ sync_primitives::Lock statistics_lock_; /** * @brief Device id, which is used during PTU handling for specific * application */ std::string last_device_id_; bool ignition_check; friend struct CheckAppPolicy; friend struct ProccessAppGroups; friend class PolicyManagerImplTest; }; } // namespace policy #endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_IMPL_H_
8b9b93ab88379a4958d0ff14aac54b2658ee1646
f9afa27efcfe23bc08ef1ab76fad1b0be6c98432
/monotonicRenumerationE.cpp
d39b96d1af3c98dfa7bf3722c18d3acaeec96fd3
[]
no_license
FABhishek/CodeforcesContests
c9686a8c1e1145fe399e5b950dbe9e3080b94884
854675e0d2d66098f2cb332c372604c753c13847
refs/heads/master
2023-06-02T06:46:47.435090
2021-06-15T16:59:58
2021-06-15T16:59:58
377,235,250
0
0
null
null
null
null
UTF-8
C++
false
false
1,752
cpp
monotonicRenumerationE.cpp
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; // Policy based data structure template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define ll long long int #define pii pair<ll,ll> #define rep(i,st,en) for(ll i=st;i<en;i++) #define vi vector<ll> #define vii vector<pii> #define all(x) x.begin(),x.end() #define rall(x) x.rbegin(),x.rend() #define eb emplace_back #define yes cout<<"YES"<<endl; return; #define no cout<<"NO"<<endl; return; #define flus fflush(stdout); #define gin(x) cerr<<#x<<" : "<<x<<" "; #define fin cerr<<endl; #define F first #define S second #define np next_permutation #define inf 1e18 #define mod 1000000007 #define N 200009 #define PI 3.14159265358979323846 #define minpq priority_queue <ll, vector<ll>, greater<ll>> #define maxpq priority_queue<ll> void sout(){ cout<<endl; } template <typename T,typename... Types> void sout(T var1,Types... var2){ cout<<var1<<" "; sout(var2...); } #define MOD 998244353 void solve(){ int n; scanf("%d", &n); vector<int> a(n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); map<int, int> lst; vector<int> last_pos(n); for(int i = n - 1; i >= 0; i--) { if(!lst.count(a[i])) lst[a[i]] = i; last_pos[i] = lst[a[i]]; } int ans = 1; int cur_max = -1; for(int i = 0; i < n-1 ; i++) { cur_max = max(cur_max, last_pos[i]); if(cur_max == i) ans = (2 * ans) % MOD; } printf("%d\n", ans); // return 0; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); clock_t t1=clock(); int t; // cin>>t; t=1; while(t--){ solve(); } cerr<<"Time elapsed: "<<(double)(clock()-t1)/1000<<" s"<<endl; }
215e80af0bc4cc5799000eb4538b9f8a9ee7de65
16a76b410f030732ccf0e625fb0af6fd283e7afc
/Insertion Sort/Insertion Sort.cpp
4abc3345e20764e15ad7e6d130563b81c8ca3a2f
[]
no_license
paperbody/CSE100
31e5a0540ae4fb0d28f22cf8f34b92ff228b902c
281fca5f16e0e32d3d9d6427f88f606e5b09f04a
refs/heads/master
2020-07-13T07:17:40.466363
2019-08-28T22:09:06
2019-08-28T22:09:06
205,030,125
0
0
null
null
null
null
UTF-8
C++
false
false
591
cpp
Insertion Sort.cpp
#include <iostream> using namespace std; void insertionSort(int array[],int size){ int i; int j; int key; for (j = 1;j < size; j++){ key = array[j]; i = j-1; while (i >= 0 && array[i] > key){ array[i+1] = array[i]; i = i-1; } array[i+1] = key; } } int main(){ int number; int size; cin >> size; int* array=new int[size]; for (int i = 0;i<size;i++){ cin>>array[i]; } //int array[]={5,2,1,7,8}; insertionSort(array,size); for (int i = size-1;i >= 0;i--){ cout<<array[i]<<";"; } return 0; }
ae813e8ac44079417548a72a4a3fa87362b4c883
669789a63bd5c01df2e68efa7931e74eb52c1742
/DDZ_AI/Range.h
66d83c21921da2adfdae1b0cc30344b938af5d99
[]
no_license
qq717337/ddzai
d47d4ab3c280a3832abbfd31cf26f8766b812c22
9e59e23a6e967ae3a91fb5d234d2bc782ea24eec
refs/heads/master
2020-03-21T02:26:56.805637
2018-03-26T13:39:47
2018-03-26T13:39:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
395
h
Range.h
#ifndef _RANGE_H_ #define _RANGE_H_ template<class Type> struct Range { public: Type Start; Type End; inline Type Length()const { _ASSERT(End >= Start); return End - Start + 1; } Range() { } Range(Type A, Type B) { Start = A; End = B; } bool operator==(const Range& rhs)const { return Start == rhs.Start&& End == rhs.End; } }; typedef Range<uint8_t> CardRange; #endif
e66cb1989d4f1f95800ab56c63b3ee0f4bcf6fcb
2800e49746e2119ae19596c9d6d3af029c7af60b
/common/gui/include/gui/MainWindow.h
f0a4aed5dfa8a612ee5003bd0e6f02919da65480
[]
no_license
krisukox/PCs-connector
8e37fae04ab57a215d606bca91f0608f3241e62a
37cc96b8ff50370474452cef1a35c6f3747596e5
refs/heads/master
2023-05-31T04:46:40.511309
2021-06-14T19:54:17
2021-06-14T19:54:17
184,431,378
0
0
null
2021-06-14T19:46:42
2019-05-01T14:48:16
C++
UTF-8
C++
false
false
916
h
MainWindow.h
#pragma once #include <QMainWindow> #include <memory> #include <thread> #include "gui/ScreenIndicator.h" #include "gui/ScreenResolutionMsg.h" namespace commons { class IApp; } QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget* parent = nullptr); ~MainWindow(); Ui::MainWindow* ui; private slots: void handleConnectButton(); void handleStartButton(); void handleScreenResolutionSet(const ScreenResolutionMsg&); void handleIdetifyScreensButton(); void borderScreenChanged(const int&); signals: void messageSent(const ScreenResolutionMsg&); private: void fillAvailableMonitors(); void showIndicators(); void addScreensToScene(const QSize&); std::unique_ptr<commons::IApp> app; std::vector<std::unique_ptr<Indicator>> indicators; QTimer* timer; };
eb0bd0480a34fa262c58607ecad22e6b8129af15
56d0f02555b098cd393f22dbe00cf85509b41596
/cpp/0638.cpp
14ed4a0da32b4512e33e8afc8fc1de53746a8eb7
[]
no_license
xfmeng17/leetcode
05cca36038d111f53d8f1d541607ea365ded2dfb
534ff8ef5617d230897d2bf0e1c0c7405bb309f9
refs/heads/master
2022-12-05T17:00:53.850397
2022-12-05T02:06:29
2022-12-05T02:06:29
121,209,775
0
0
null
2018-03-29T10:47:21
2018-02-12T06:37:18
C++
UTF-8
C++
false
false
1,503
cpp
0638.cpp
class Solution { public: int shoppingOffers(vector<int> &price, vector<vector<int>> &special, vector<int> &needs) { return func1(price, special, needs); } // ** straight forward DFS int func1(vector<int> &price, vector<vector<int>> &special, vector<int> &needs) { return helper1(price, special, 0, needs); } int helper1(vector<int> &price, vector<vector<int>> &special, int specialIndex, vector<int> &needs) { if (special.size() <= specialIndex) { int sum = 0; for (int i = 0; i < needs.size(); i++) { sum += needs[i] * price[i]; } return sum; } // ** do not use special int notSpecialCost = helper1(price, special, specialIndex + 1, needs); // ** use special int useSpecialCost = notSpecialCost; vector<int> &currSepcial = special[specialIndex]; bool canUseSpecial = true; int cnt = 1; while (canUseSpecial) { vector<int> auxNeeds(needs.begin(), needs.end()); for (int i = 0; i < auxNeeds.size(); i++) { auxNeeds[i] -= currSepcial[i] * cnt; if (auxNeeds[i] < 0) { canUseSpecial = false; break; } } if (canUseSpecial) { useSpecialCost = min(useSpecialCost, currSepcial[currSepcial.size() - 1] * cnt + helper1(price, special, specialIndex + 1, auxNeeds)); } cnt++; } return min(notSpecialCost, useSpecialCost); } };
daf0b3375263a9f7d0c53534433740f712d2f626
323dccba799a1b4ea3052d8b96ffaf9394baf52e
/ソースコード/gpsLibrary/gpsLibrary.ino
a7f13daa66bc186549b05ff8585f28df15975d7f
[]
no_license
100kinsat/seccamp2021-TeamA
16b23588758efc851a36eed2375a0e78399d2a66
ccede189b6dfd66683fac4582cb6098a2c4ef200
refs/heads/main
2023-07-17T11:43:42.202852
2021-09-04T16:49:30
2021-09-04T16:49:30
393,384,877
0
1
null
null
null
null
UTF-8
C++
false
false
440
ino
gpsLibrary.ino
#include "cansat_gps.hpp" Cansat_gps cansat_gps = Cansat_gps(); HardwareSerial ss(2); void setup() { Serial.begin(115200); ss.begin(9600); Serial.println("GPS start!"); } void loop() { char* temp; while(ss.available() > 0){ char c = ss.read(); // GPSセンサからの値を読み込み if(cansat_gps.gpsCsv(c, &temp) == true){ Serial.println(temp); } } delay(1000); }
7cbbd134c64296b4027139c77263efd6fc0d558b
b9b966952e88619c9c5d754fea0f0e25fdb1a219
/libcaf_core/caf/actor_system_config.hpp
5b0422e72b99359b9174d28182c329f9702d62a3
[]
permissive
actor-framework/actor-framework
7b152504b95b051db292696a803b2add6dbb484d
dd16d703c91e359ef421f04a848729f4fd652d08
refs/heads/master
2023-08-23T18:22:34.479331
2023-08-23T09:31:36
2023-08-23T09:31:36
1,439,738
2,842
630
BSD-3-Clause
2023-09-14T17:33:55
2011-03-04T14:59:50
C++
UTF-8
C++
false
false
13,774
hpp
actor_system_config.hpp
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include "caf/actor_factory.hpp" #include "caf/actor_profiler.hpp" #include "caf/config_option.hpp" #include "caf/config_option_adder.hpp" #include "caf/config_option_set.hpp" #include "caf/config_value.hpp" #include "caf/detail/core_export.hpp" #include "caf/detail/type_traits.hpp" #include "caf/dictionary.hpp" #include "caf/fwd.hpp" #include "caf/is_typed_actor.hpp" #include "caf/settings.hpp" #include "caf/thread_hook.hpp" #include <atomic> #include <functional> #include <memory> #include <string> #include <string_view> #include <type_traits> #include <typeindex> #include <unordered_map> namespace caf { /// Configures an `actor_system` on startup. class CAF_CORE_EXPORT actor_system_config { public: // -- friends ---------------------------------------------------------------- friend class actor_system; // -- member types ----------------------------------------------------------- using hook_factory = std::function<io::hook*(actor_system&)>; using hook_factory_vector = std::vector<hook_factory>; using thread_hooks = std::vector<std::unique_ptr<thread_hook>>; template <class K, class V> using hash_map = std::unordered_map<K, V>; using module_factory = std::function<actor_system::module*(actor_system&)>; using module_factory_vector = std::vector<module_factory>; using actor_factory_map = hash_map<std::string, actor_factory>; using portable_name_map = hash_map<std::type_index, std::string>; using group_module_factory = std::function<group_module*()>; using group_module_factory_vector = std::vector<group_module_factory>; using config_map = dictionary<config_value::dictionary>; using string_list = std::vector<std::string>; using opt_group = config_option_adder; // -- constructors, destructors, and assignment operators -------------------- virtual ~actor_system_config(); actor_system_config(); actor_system_config(actor_system_config&&) = default; actor_system_config(const actor_system_config&) = delete; actor_system_config& operator=(const actor_system_config&) = delete; // -- properties ------------------------------------------------------------- /// @private settings content; /// Extracts all parameters from the config, including entries with default /// values. virtual settings dump_content() const; /// Sets a config by using its name `config_name` to `config_value`. template <class T> actor_system_config& set(std::string_view name, T&& value) { return set_impl(name, config_value{std::forward<T>(value)}); } // -- modifiers -------------------------------------------------------------- /// Parses `args` as tuple of strings containing CLI options and `config` as /// configuration file. error parse(string_list args, std::istream& config); /// Parses `args` as CLI options and tries to locate a config file via /// `config_file_path` and `config_file_path_alternative` unless the user /// provides a config file path on the command line. error parse(string_list args); /// Parses the CLI options `{argc, argv}` and `config` as configuration file. error parse(int argc, char** argv, std::istream& config); /// Parses the CLI options `{argc, argv}` and tries to locate a config file /// via `config_file_path` and `config_file_path_alternative` unless the user /// provides a config file path on the command line. error parse(int argc, char** argv); /// Allows other nodes to spawn actors created by `fun` /// dynamically by using `name` as identifier. /// @experimental actor_system_config& add_actor_factory(std::string name, actor_factory fun); /// Allows other nodes to spawn actors of type `T` /// dynamically by using `name` as identifier. /// @experimental template <class T, class... Ts> actor_system_config& add_actor_type(std::string name) { using handle = infer_handle_from_class_t<T>; static_assert(detail::is_complete<type_id<handle>>); return add_actor_factory(std::move(name), make_actor_factory<T, Ts...>()); } /// Allows other nodes to spawn actors implemented by function `f` /// dynamically by using `name` as identifier. /// @experimental template <class F> actor_system_config& add_actor_type(std::string name, F f) { using handle = infer_handle_from_fun_t<F>; static_assert(detail::is_complete<type_id<handle>>); return add_actor_factory(std::move(name), make_actor_factory(std::move(f))); } /// Loads module `T` with optional template parameters `Ts...`. template <class T, class... Ts> actor_system_config& load() { T::add_module_options(*this); module_factories.push_back([](actor_system& sys) -> actor_system::module* { return T::make(sys, detail::type_list<Ts...>{}); }); return *this; } /// Adds a factory for a new hook type to the middleman (if loaded). template <class Factory> actor_system_config& add_hook_factory(Factory f) { hook_factories.push_back(f); return *this; } /// Adds a hook type to the middleman (if loaded). template <class Hook> actor_system_config& add_hook_type() { return add_hook_factory( [](actor_system& sys) -> Hook* { return new Hook(sys); }); } /// Adds a hook type to the scheduler. template <class Hook, class... Ts> actor_system_config& add_thread_hook(Ts&&... ts) { std::unique_ptr<thread_hook> hook{new Hook(std::forward<Ts>(ts)...)}; thread_hooks_.emplace_back(std::move(hook)); return *this; } // -- parser and CLI state --------------------------------------------------- /// Stores whether the help text was printed. If set to `true`, the /// application should not use this config to initialize an `actor_system` /// and instead return from `main` immediately. bool cli_helptext_printed; /// Stores the content of `argv[0]` from the arguments passed to `parse`. std::string program_name; /// Stores CLI arguments that were not consumed by CAF. string_list remainder; /// Returns the remainder including the program name (`argv[0]`) suitable for /// passing the returned pair of arguments to C-style functions that usually /// accept `(argc, argv)` input as passed to `main`. This function creates the /// necessary buffers lazily on first call. /// @note The returned pointer remains valid only as long as the /// `actor_system_config` object exists. std::pair<int, char**> c_args_remainder() const noexcept; // -- caf-run parameters ----------------------------------------------------- /// Stores whether this node was started in slave mode. bool slave_mode; /// Name of this node when started in slave mode. std::string slave_name; /// Credentials for connecting to the bootstrap node. std::string bootstrap_node; // -- OpenSSL parameters ----------------------------------------------------- std::string openssl_certificate; std::string openssl_key; std::string openssl_passphrase; std::string openssl_capath; std::string openssl_cafile; // -- factories -------------------------------------------------------------- actor_factory_map actor_factories; module_factory_vector module_factories; hook_factory_vector hook_factories; group_module_factory_vector group_module_factories; // -- hooks ------------------------------------------------------------------ thread_hooks thread_hooks_; /// Provides system-wide callbacks for several actor operations. /// @experimental /// @note Has no effect unless building CAF with CAF_ENABLE_ACTOR_PROFILER. actor_profiler* profiler = nullptr; /// Enables CAF to deserialize application-specific tracing information. /// @experimental /// @note Has no effect unless building CAF with CAF_ENABLE_ACTOR_PROFILER. tracing_data_factory* tracing_context = nullptr; // -- parsing parameters ----------------------------------------------------- /// Configures the default path of the configuration file. std::string config_file_path; /// Configures alternative paths for locating a config file when unable to /// open the default `config_file_path`. std::vector<std::string> config_file_path_alternatives; // -- utility for caf-run ---------------------------------------------------- int (*slave_mode_fun)(actor_system&, const actor_system_config&); // -- config file parsing ---------------------------------------------------- /// Tries to open `filename` and parses its content as CAF config file. /// @param filename Relative or absolute path to the config file. /// @returns A ::settings dictionary with the parsed content of `filename` on /// success, an ::error otherwise. static expected<settings> parse_config_file(const char* filename); /// Tries to open `filename` and parses its content as CAF config file. Also /// type-checks user-defined parameters in `opts`. /// @param filename Relative or absolute path to the config file. /// @param opts User-defined config options for type checking. /// @returns A ::settings dictionary with the parsed content of `filename` on /// success, an ::error otherwise. static expected<settings> parse_config_file(const char* filename, const config_option_set& opts); /// Tries to open `filename`, parses its content as CAF config file and /// stores all entries in `result` (overrides conflicting entries). Also /// type-checks user-defined parameters in `opts`. /// @param filename Relative or absolute path to the config file. /// @param opts User-defined config options for type checking. /// @param result Storage for parsed entries. Note that `result` will contain /// partial results if this function returns an error. /// @returns A default-constructed ::error on success, the error code of the /// parser otherwise. static error parse_config_file(const char* filename, const config_option_set& opts, settings& result); /// Parses the content of `source` using CAF's config format. /// @param source Character sequence in CAF's config format. /// @returns A ::settings dictionary with the parsed content of `source` on /// success, an ::error otherwise. static expected<settings> parse_config(std::istream& source); /// Parses the content of `source` using CAF's config format. Also /// type-checks user-defined parameters in `opts`. /// @param source Character sequence in CAF's config format. /// @param opts User-defined config options for type checking. /// @returns A ::settings dictionary with the parsed content of `source` on /// success, an ::error otherwise. static expected<settings> parse_config(std::istream& source, const config_option_set& opts); /// Parses the content of `source` using CAF's config format and stores all /// entries in `result` (overrides conflicting entries). Also type-checks /// user-defined parameters in `opts`. /// @param source Character sequence in CAF's config format. /// @param opts User-defined config options for type checking. /// @param result Storage for parsed entries. Note that `result` will contain /// partial results if this function returns an error. /// @returns A default-constructed ::error on success, the error code of the /// parser otherwise. static error parse_config(std::istream& source, const config_option_set& opts, settings& result); /// @private config_option_set& custom_options() { return custom_options_; } protected: config_option_set custom_options_; private: virtual detail::mailbox_factory* mailbox_factory(); void set_remainder(string_list args); mutable std::vector<char*> c_args_remainder_; std::vector<char> c_args_remainder_buf_; actor_system_config& set_impl(std::string_view name, config_value value); std::pair<error, std::string> extract_config_file_path(string_list& args); }; /// Returns all user-provided configuration parameters. CAF_CORE_EXPORT const settings& content(const actor_system_config& cfg); /// Returns whether `xs` associates a value of type `T` to `name`. /// @relates actor_system_config template <class T> bool holds_alternative(const actor_system_config& cfg, std::string_view name) { return holds_alternative<T>(content(cfg), name); } /// Tries to retrieve the value associated to `name` from `cfg`. /// @relates actor_system_config template <class T> auto get_if(const actor_system_config* cfg, std::string_view name) { return get_if<T>(&content(*cfg), name); } /// Retrieves the value associated to `name` from `cfg`. /// @relates actor_system_config template <class T> T get(const actor_system_config& cfg, std::string_view name) { return get<T>(content(cfg), name); } /// Retrieves the value associated to `name` from `cfg` or returns `fallback`. /// @relates actor_system_config template <class To = get_or_auto_deduce, class Fallback> auto get_or(const actor_system_config& cfg, std::string_view name, Fallback&& fallback) { return get_or<To>(content(cfg), name, std::forward<Fallback>(fallback)); } /// Tries to retrieve the value associated to `name` from `cfg` as an instance /// of type `T`. /// @relates actor_system_config template <class T> expected<T> get_as(const actor_system_config& cfg, std::string_view name) { return get_as<T>(content(cfg), name); } } // namespace caf
9f825d13f479a5147e9cc509296507c6c2d23768
1716936c6c29043a2af0b157b502fc041cf28cda
/1043.cpp
d0fdfd213cbef10b4210520f4a94fe625a2e93f4
[]
no_license
jiqc/PAT
d6c559fe3e7f196397a0773238ef619fa278a988
bd7ad0abfc41a301960f2ec538280c773c188ecf
refs/heads/master
2020-12-29T01:11:28.185141
2017-11-17T05:32:37
2017-11-17T05:32:37
53,915,553
11
2
null
2016-06-08T13:56:11
2016-03-15T04:49:36
null
UTF-8
C++
false
false
2,049
cpp
1043.cpp
#include<cstdio> #include<vector> using namespace std; struct node { int num; node * right; node * left; }; int N; vector<int> numin; bool mirror; bool judge(int pre, int pos) { if (pre + 2 >= pos) { return true; } int mid = numin[pre]; int index; pre++; if (mirror) { for (index = pre; index < pos; index++) { if (numin[index] < mid) { break; } } for (int i = index; i < pos; i++) { if (numin[i] >= mid) { return false; } } return judge(pre, index) && judge(index, pos); } else { for (index = pre; index < pos; index++) { if (numin[index] >= mid) { break; } } for (int i = index; i < pos; i++) { if (numin[i] < mid) { return false; } } return judge(pre, index) && judge(index, pos); } } node * insert(int m, node*T) { if (T == NULL) { T = new node; T->num = m; T->left = T->right = NULL; } else { if (mirror) { if (m >= T->num) { T->left = insert(m, T->left); } else { T->right = insert(m, T->right); } } else { if (m < T->num) { T->left = insert(m, T->left); } else { T->right = insert(m, T->right); } } } return T; } node * maketree(node * tree) { for (int i = 0; i < N; i++) { tree = insert(numin[i],tree); } return tree; } void postprint(node * t) { if (t == NULL) { return; } if (t->left != NULL) { postprint(t->left); printf(" "); } if (t->right != NULL) { postprint(t->right); printf(" "); } printf("%d", t->num); } int main() { bool isbft; node * tree; tree = NULL; scanf_s("%d", &N); numin.resize(N); for (int i = 0; i < N; i++) { scanf_s("%d", &numin[i]); } if (numin[0] <= numin[1]) { mirror = true; } else { mirror = false; } isbft = judge(0, N); if (isbft) { tree = maketree(tree); printf("YES\n"); postprint(tree); printf("\n"); } else { printf("NO\n"); } system("pause"); return 0; }
4161177a5683e269dba1ea95b2bc81e1b6498451
45246ec52b6002e2c07d4a9228d88a1cfbb4e632
/Technology Leverage/Summatives/Concurrency/GDE/Maths/FVector3.cpp
d31f81205ae467aa0bb0d435d892dddb74a7079b
[]
no_license
simplegsb/media-design-school
ec8015b22dc879d0df394666997b2d412cf27301
f2fbf7a9dabdeeffe22a09f5eea2519e3c668b63
refs/heads/master
2020-06-07T07:51:16.524820
2013-04-29T08:42:56
2013-04-29T08:42:56
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
15,813
cpp
FVector3.cpp
/** * @file GDE\Maths\FVector3.cpp * @brief * * Copyright() * Copyright © 2004-2011 Media Design School. All Rights Reserved. * *********************************************************************************************/ #include "GDE/Core/Core.h" #include "GDE/Core/Logger.h" #include "FVector3.h" #include "FVector2.h" #include "Matrix4x4.h" #include "MathConstants.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <xnamath.h> namespace GDE { const CFVec3 g_fv3ZERO = SFVec3( 0.0f, 0.0f, 0.0f ); SFVec3::operator const CFVec3 (void) const { CFVec3 RV; RV = *this; return RV; } CFVec3 CFVec3::Init( FLOAT32 fX, FLOAT32 fY, FLOAT32 fZ ) { CFVec3 RV; XMVECTOR& V = *reinterpret_cast<XMVECTOR*>(&RV); V = XMVectorSet(fX, fY, fZ, 0.0f); // note we don't care about w! return RV; } CFVec3& CFVec3::operator=( const SFVec3 &arg ) { XMVECTOR& V = *reinterpret_cast<XMVECTOR*>(this); V = XMLoadFloat3( (const XMFLOAT3*)&arg ); return *this; } /** * Print out to the debug stream with no carraige return. */ void CFVec3::DebugDump( void ) const { DbgPrint( "%0.2f, %0.2f, %0.2f", X(), Y(), Z() ); } /** * Print out to the debug stream with a carraige return. */ void CFVec3::DebugDumpCR( void ) const { DbgPrint( "%0.2f, %0.2f, %0.2f\n", X(), Y(), Z() ); } FLOAT32 CFVec3::X( void ) const { const XMVECTOR& V = *reinterpret_cast<const XMVECTOR*>(this); return XMVectorGetX( V ); } FLOAT32 CFVec3::Y( void ) const { const XMVECTOR& V = *reinterpret_cast<const XMVECTOR*>(this); return XMVectorGetY( V ); } FLOAT32 CFVec3::Z( void ) const { const XMVECTOR& V = *reinterpret_cast<const XMVECTOR*>(this); return XMVectorGetZ( V ); } //#ifndef _DONT_COMPILE_STUB_FVECTOR_FUNCS void CFVec3::X( FLOAT32 fVal ) { m_Vec.x = fVal; } void CFVec3::Y( FLOAT32 fVal ) { m_Vec.y = fVal; } void CFVec3::Z( FLOAT32 fVal ) { m_Vec.z = fVal; } void CFVec3::SetXY( CFVec2Arg fv2Source ) { m_Vec.x = fv2Source.X(); m_Vec.y = fv2Source.Y(); } void CFVec3::XAdd( FLOAT32 fVal ) { XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>(this); v3V = XMVectorSetX( v3V, XMVectorGetX( v3V ) + fVal ); } void CFVec3::YAdd( FLOAT32 fVal ) { XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>(this); v3V = XMVectorSetY( v3V, XMVectorGetY( v3V ) + fVal ); } void CFVec3::ZAdd( FLOAT32 fVal ) { XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>(this); v3V = XMVectorSetZ( v3V, XMVectorGetZ( v3V ) + fVal ); } ////////////////////////////////////////////////////////// // operator overloads bool CFVec3::operator == (CFVec3Arg vArg ) const { const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &vArg ); bool bSuccess = false; XMVector3Equal( v3V, v3V2 ) ? bSuccess = true : bSuccess = false; return bSuccess; } bool CFVec3::operator != (CFVec3Arg vArg ) const { const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &vArg ); bool bSuccess = false; XMVector3Equal( v3V, v3V2 ) ? bSuccess = false : bSuccess = true; return bSuccess; } // vector operations CFVec3 CFVec3::operator - ( void ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); //Negate v3Result = XMVectorNegate( v3V ); return v3Return; } CFVec3 CFVec3::operator - ( CFVec3Arg vArg ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &vArg ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVectorSubtract( v3V, v3V2 ); return v3Return; } CFVec3 CFVec3::operator + ( CFVec3Arg vArg ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &vArg ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVectorAdd( v3V, v3V2 ); return v3Return; } CFVec3 CFVec3::operator * ( CFVec3Arg vArg ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &vArg ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVectorMultiply( v3V, v3V2 ); return v3Return; } CFVec3& CFVec3::operator += ( CFVec3Arg vArg ) { XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &vArg ); v3V = XMVectorAdd( v3V, v3V2 ); return *this; } CFVec3& CFVec3::operator -= ( CFVec3Arg vArg ) { XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &vArg ); v3V = XMVectorSubtract( v3V, v3V2 ); return *this; } CFVec3& CFVec3::operator *= ( CFVec3Arg vArg ) { XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &vArg ); v3V = XMVectorMultiply( v3V, v3V2 ); return *this; } // scalar opertaors CFVec3& CFVec3::operator *= ( const FLOAT32 fArg ) { XMVECTOR v3Scaler; v3Scaler = XMVectorSet( fArg, fArg, fArg, 1.0f ); XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( this ); v3V = XMVectorMultiply( v3V, v3Scaler ); return *this; } CFVec3 CFVec3::operator * ( const FLOAT32 fArg ) const { CFVec3 v3Return; XMVECTOR v3Scaler; v3Scaler = XMVectorSet( fArg, fArg, fArg, 1.0f ); const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVectorMultiply( v3V, v3Scaler ); return v3Return; } CFVec3& CFVec3::operator /= ( const FLOAT32 fArg ) { FLOAT32 fDivisor = 1.0f / fArg; XMVECTOR v3Scaler; v3Scaler = XMVectorSet( fDivisor, fDivisor, fDivisor, 1.0f ); XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( this ); v3V = XMVectorMultiply( v3V, v3Scaler ); return *this; } CFVec3 CFVec3::operator / ( const FLOAT32 fArg ) const { CFVec3 v3Return; FLOAT32 fDivisor = 1.0f / fArg; XMVECTOR v3Scaler; v3Scaler = XMVectorSet( fDivisor, fDivisor, fDivisor, 1.0f ); const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVectorMultiply( v3V, v3Scaler ); return v3Return; } CFVec3 CFVec3::CrossProduct( CFVec3Arg vArg ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &vArg ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVector3Cross( v3V, v3V2 ); return v3Return; } FLOAT32 CFVec3::DotProduct( CFVec3Arg vArg ) const { const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &vArg ); return XMVectorGetX( XMVector3Dot( v3V, v3V2 ) ); } /** * @return A vector quantity with the scalar in each component. */ CFVec3 CFVec3::DotProductV( CFVec3Arg vArg ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &vArg ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVector3Dot( v3V, v3V2 ); return v3Return; } FLOAT32 CFVec3::SquareDistance( CFVec3Arg fv3To ) const { CFVec3 v3Temp; v3Temp = fv3To - *this; XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( &v3Temp ); return XMVectorGetX( XMVector3LengthSq( v3V ) ); } /** * @return A vector quantity with the scalar in each component. */ CFVec3 CFVec3::SquareDistanceV( CFVec3Arg fv3To ) const { CFVec3 v3Return; v3Return = fv3To - *this; XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3V = XMVector3LengthSq( v3V ); return v3Return; } FLOAT32 CFVec3::Distance( CFVec3Arg fv3To ) const { CFVec3 v3Temp; v3Temp = fv3To - *this; XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( &v3Temp ); return XMVectorGetX( XMVector3Length( v3V ) ); } /** * @return A vector quantity with the scalar in each component. */ CFVec3 CFVec3::DistanceV( CFVec3Arg fv3To ) const { CFVec3 v3Temp; v3Temp = fv3To - *this; XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( &v3Temp ); v3V = XMVector3Length( v3V ); return v3Temp; } FLOAT32 CFVec3::SquareMagnitude( void ) const { const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); return XMVectorGetX( XMVector3LengthSq( v3V ) ); } /** * @return A vector quantity with the scalar in each component. */ CFVec3 CFVec3::SquareMagnitudeV( void ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVector3LengthSq( v3V ); return v3Return; } FLOAT32 CFVec3::Magnitude( void ) const { const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); return XMVectorGetX( XMVector3Length( v3V ) ); } /** * @return A vector quantity with the scalar in each component. */ CFVec3 CFVec3::MagnitudeV( void ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVector3Length( v3V ); return v3Return; } void CFVec3::Normalise( void ) { XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( this ); v3V = XMVector3Normalize( v3V ); } void CFVec3::Normalise( FLOAT32 &fMagnitude ) { XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( this ); //TODO: Is there a cheaper way of doing this? fMagnitude = XMVectorGetX( XMVector3Length( v3V ) ); v3V = XMVector3Normalize( v3V ); } /** * @param vMagnitude Contains the scalar magnitude in each component. */ void CFVec3::Normalise( CFVec3 &vMagnitude ) { XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( this ); XMVECTOR& v3VMag = *reinterpret_cast<XMVECTOR*>( &vMagnitude ); //TODO: Is there a cheaper way of doing this? v3VMag = XMVector3Length( v3V ); v3V = XMVector3Normalize( v3V ); } CFVec3 CFVec3::GetNormal( void ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVector3Normalize( v3V ); return v3Return; } CFVec3 CFVec3::GetNormal( FLOAT32 &fMagnitude ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); //TODO: Is there a cheaper way of doing this? fMagnitude = XMVectorGetX( XMVector3Length( v3V ) ); v3Result = XMVector3Normalize( v3V ); return v3Return; } /** * @param vMagnitude Contains the scalar magnitude in each component. */ CFVec3 CFVec3::GetNormal( CFVec3 &vMagnitude ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); XMVECTOR& v3VMag = *reinterpret_cast<XMVECTOR*>( &vMagnitude ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); //TODO: Is there a cheaper way of doing this? v3VMag = XMVector3Length( v3V ); v3Result = XMVector3Normalize( v3V ); return v3Return; } bool CFVec3::IsNormal( void ) const { //const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); //TODO: Cheaper way of doing this? //Getting squared length is cheaper, and 1^2 is still 1. FLOAT32 fMag = SquareMagnitude();//= XMVectorGetX( XMVector3LengthSq( v3V ) ); bool bSuccess = false; //The GDE::fEPSILON value has too much precision for this.. FLOAT32 fEpsilon = 0.0000001f; fabsf( fMag - 1.0f ) <= fEpsilon ? bSuccess = true : bSuccess = false; return bSuccess; } void CFVec3::RotateX( FLOAT32 fRadians ) { CFMat4x4 matRotation; matRotation = CFMat4x4::CreateRotationX( fRadians ); *this = matRotation.TransformVec3( *this ); } void CFVec3::RotateY( FLOAT32 fRadians ) { CFMat4x4 matRotation; matRotation = CFMat4x4::CreateRotationY( fRadians ); *this = matRotation.TransformVec3( *this ); } void CFVec3::RotateZ( FLOAT32 fRadians ) { CFMat4x4 matRotation; matRotation = CFMat4x4::CreateRotationZ( fRadians ); *this = matRotation.TransformVec3( *this ); } //void CFVec3::RotateX( FLOAT32 fRadians ) //{ // const FLOAT32 fSin = sinf( -fRadians ); // const FLOAT32 fCos = cosf( -fRadians ); // const FLOAT32 fY = fCos*m_Vec.y + fSin*m_Vec.z; // m_Vec.z = -fSin*m_Vec.y + fCos*m_Vec.z; // m_Vec.y = fY; //} // //void CFVec3::RotateY( FLOAT32 fRadians ) //{ // const FLOAT32 fSin = sinf( -fRadians ); // const FLOAT32 fCos = cosf( -fRadians ); // const FLOAT32 fX = fCos*m_Vec.x + fSin*m_Vec.z; // m_Vec.z = -fSin*m_Vec.x + fCos*m_Vec.z; // m_Vec.x = fX; //} // //void CFVec3::RotateZ( FLOAT32 fRadians ) //{ // const FLOAT32 fSin = sinf( -fRadians ); // const FLOAT32 fCos = cosf( -fRadians ); // const FLOAT32 fX = fCos*m_Vec.x + fSin*m_Vec.y; // m_Vec.y = -fSin*m_Vec.x + fCos*m_Vec.y; // m_Vec.x = fX; //} /** * * Rotate vector using pitch, yaw and roll * Roll is applied first, then pitch, then yaw. * Angles are measured clockwise when looking along the rotation axis toward the origin. * * @param fPitch Pitch in radians. * @param fYaw Yaw in radians. * @param fRoll Roll in radians. */ void CFVec3::Rotate(FLOAT32 fPitch, FLOAT32 fYaw, FLOAT32 fRoll) { XMVECTOR& rThis = *reinterpret_cast<XMVECTOR*>(this); XMVECTOR qRotation = XMQuaternionRotationRollPitchYaw(fPitch, fYaw, fRoll); rThis = XMVector3Rotate(rThis, qRotation); } /** * If a direction vector - converting to Euler without roll, assuming Z is up. */ FLOAT32 CFVec3::GetHeading( void ) const { //atan2, return angle - ignore roll. //X and Z #pragma warnmsg( "stub function that needs implementation" ) assert_now( "stub function" ); return 0.0f; } FLOAT32 CFVec3::GetElevation( void ) const { #pragma warnmsg( "stub function that needs implementation" ) assert_now( "stub function" ); return 0.0f; } /** * Component wise set to minimum of this and other. */ CFVec3& CFVec3::MinimizeWith( CFVec3Arg fv3Other ) { XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &fv3Other ); v3V = XMVectorMin( v3V, v3V2 ); return *this; } CFVec3 CFVec3::GetMin( CFVec3Arg fv3Other ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &fv3Other ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVectorMin( v3V, v3V2 ); return v3Return; } /** * Component wise set to maximum of this and other. */ CFVec3& CFVec3::MaximizeWith( CFVec3Arg fv3Other ) { XMVECTOR& v3V = *reinterpret_cast<XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &fv3Other ); v3V = XMVectorMax( v3V, v3V2 ); return *this; } CFVec3 CFVec3::GetMax( CFVec3Arg fv3Other ) const { CFVec3 v3Return; const XMVECTOR& v3V = *reinterpret_cast<const XMVECTOR*>( this ); const XMVECTOR& v3V2 = *reinterpret_cast<const XMVECTOR*>( &fv3Other ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVectorMax( v3V, v3V2 ); return v3Return; } /** * Linearly interpolate two vectors. * * @param vTarget The destination vector. * @param fT The control time. * @return The resulting vector. */ CFVec3 CFVec3::Lerp( CFVec3Arg vTarget, GDE::FLOAT32 fT ) { CFVec3 v3Return; const XMVECTOR& v3VA = *reinterpret_cast<const XMVECTOR*>( this ); const XMVECTOR& v3VB = *reinterpret_cast<const XMVECTOR*>( &vTarget ); XMVECTOR& v3Result = *reinterpret_cast<XMVECTOR*>( &v3Return ); v3Result = XMVectorLerp( v3VA, v3VB, fT ); return v3Return; } } // end namespace GDE
b52c558b6ad137e1968e0cf939a9660c9e2be8cb
503360a78c49306e3a56b7aa5d846b4bea2a409f
/src/hook_manager.cc
bd83b976a46a4ab4ec2d9ea3e91a6ab631693738
[ "Unlicense" ]
permissive
naufraghi/kakoune
21f2b23d07153b520de1634532295acda6482ce5
439f16892828177dfea19f73f2e588071ed075e0
refs/heads/master
2021-01-17T06:21:53.191055
2016-07-05T18:21:15
2016-07-05T19:08:13
62,800,541
0
0
null
2016-07-07T11:05:21
2016-07-07T11:05:20
null
UTF-8
C++
false
false
3,204
cc
hook_manager.cc
#include "hook_manager.hh" #include "containers.hh" #include "context.hh" #include "buffer_utils.hh" #include "display_buffer.hh" #include "face_registry.hh" #include "regex.hh" #include <chrono> namespace Kakoune { void HookManager::add_hook(StringView hook_name, String group, HookFunc hook) { auto& hooks = m_hook[hook_name]; hooks.append({std::move(group), std::move(hook)}); } void HookManager::remove_hooks(StringView group) { if (group.empty()) throw runtime_error("invalid id"); for (auto& hooks : m_hook) hooks.value.remove_all(group); } CandidateList HookManager::complete_hook_group(StringView prefix, ByteCount pos_in_token) { CandidateList res; for (auto& list : m_hook) { auto container = list.value | transform(decltype(list.value)::get_id); for (auto& c : complete(prefix, pos_in_token, container)) { if (!contains(res, c)) res.push_back(c); } } return res; } void HookManager::run_hook(StringView hook_name, StringView param, Context& context) const { if (m_parent) m_parent->run_hook(hook_name, param, context); auto hook_list_it = m_hook.find(hook_name); if (hook_list_it == m_hook.end()) return; if (contains(m_running_hooks, std::make_pair(hook_name, param))) { auto error = format("recursive call of hook {}/{}, aborting", hook_name, param); write_to_debug_buffer(error); throw runtime_error(std::move(error)); } m_running_hooks.emplace_back(hook_name, param); auto pop_running_hook = on_scope_end([this]{ m_running_hooks.pop_back(); }); using Clock = std::chrono::steady_clock; using TimePoint = Clock::time_point; const DebugFlags debug_flags = context.options()["debug"].get<DebugFlags>(); const bool profile = debug_flags & DebugFlags::Profile; auto start_time = profile ? Clock::now() : TimePoint{}; auto& disabled_hooks = context.options()["disabled_hooks"].get<Regex>(); bool hook_error = false; for (auto& hook : hook_list_it->value) { if (not hook.key.empty() and not disabled_hooks.empty() and regex_match(hook.key.begin(), hook.key.end(), disabled_hooks)) continue; try { if (debug_flags & DebugFlags::Hooks) write_to_debug_buffer(format("hook {}/{}", hook_name, hook.key)); hook.value(param, context); } catch (runtime_error& err) { hook_error = true; write_to_debug_buffer(format("error running hook {}({})/{}: {}", hook_name, param, hook.key, err.what())); } } if (hook_error) context.print_status({ format("Error running hooks for '{}' '{}', see *debug* buffer", hook_name, param), get_face("Error") }); if (profile) { auto end_time = Clock::now(); auto full = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time); write_to_debug_buffer(format("hook '{}({})' took {} ms", hook_name, param, (size_t)full.count())); } } }
bdb7f225ef9d6d8b08b114cb42ab274cb3457f32
ca307d63901380ab11279e33a8a30eeaf5ad035a
/Code/DnaWNumRep.h
d4946a62e9e216f9d474453077afee998acd712b
[ "MIT" ]
permissive
Avramis/AlignmentByNumbers
33b6b6efad8ab0933ab4078a34838249b5e4c38e
8e2c028e688bc24ed741cfc44424edd12a301787
refs/heads/master
2020-05-03T22:10:11.119587
2019-04-01T11:05:27
2019-04-01T11:05:27
178,838,796
0
1
null
null
null
null
UTF-8
C++
false
false
1,009
h
DnaWNumRep.h
// // DnaWNumRep.h // Al_by_num_v2_array // // Created by Avraam_Tapinos on 19/02/2016. // Copyright (c) 2016 Avraam_Tapinos. All rights reserved. // #ifndef __Al_by_num_v2_array__DnaWNumRep__ #define __Al_by_num_v2_array__DnaWNumRep__ #include <stdio.h> #include <string> #include "Process2dArray.h" /* Geenrate a DNA-Walk representation for a nucleotide string */ class DnaWNumRep{ private: //Variables int Y = 2, X; public: //Destructor ~DnaWNumRep(); //Constractor DnaWNumRep(); //Create the double array using the Process2dArray class //generate the DNA-Walk representation void setRep(double** &rep, std::string read); //Return the X length (|------->)of the DNA-Walk representation int returnX(); // // ( ^ ) // ( | ) //Return the Y length ( | ) of the DNA-Walk representation int returnY(); }; #endif /* defined(__Al_by_num_v2_array__DnaWNumRep__) */
70469a95080e44534a05b6a6591fa2895b0a9b4a
fdc2804d9513a0547f9e470b3a70ad761104ddb0
/Applications/Utils/otbPixelValue.cxx
37a5a972b21139e07234ae05b334c25e686234da
[]
no_license
boussaffawalid/OTB
5244af9f3e4fd124e51da16be23e44dce58a42ab
876328788199bb14d66e32398724d422f5e614d3
refs/heads/master
2020-12-28T04:46:56.765449
2015-08-28T12:49:30
2015-08-28T12:49:30
38,159,731
0
0
null
2015-06-27T12:43:49
2015-06-27T12:43:48
null
UTF-8
C++
false
false
4,767
cxx
otbPixelValue.cxx
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbMultiChannelExtractROI.h" namespace otb { namespace Wrapper { class PixelInfo : public Application { public: /** Standard class typedefs. */ typedef PixelInfo Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; typedef otb::MultiChannelExtractROI<FloatVectorImageType::InternalPixelType, FloatVectorImageType::InternalPixelType> ExtractROIFilterType; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(PixelInfo, otb::Application); private: void DoInit() { SetName("PixelValue"); SetDescription("Get the value of a pixel."); // Documentation SetDocName("Pixel Value"); SetDocLongDescription("Get the value of a pixel.\nPay attention, index starts at 0."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag("Utilities"); AddDocTag("Coordinates"); AddDocTag("Raster"); AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription("in", "Input image"); AddParameter(ParameterType_Int,"coordx","Col index"); SetParameterDescription("coordx","Column index of the wanted pixel (starts at 0)."); SetMinimumParameterIntValue("coordx", 0); AddParameter(ParameterType_Int,"coordy","Line index"); SetParameterDescription("coordy","Line index of the wanted pixel (starts at 0)."); SetMinimumParameterIntValue("coordy", 0); AddParameter(ParameterType_ListView,"cl","Channels"); SetParameterDescription("cl","Displayed channels"); MandatoryOff("cl"); AddParameter(ParameterType_String,"value","Pixel Value"); SetParameterDescription("value", "Pixel radiometric value"); SetParameterRole("value", Role_Output); // Doc example parameter settings SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif"); SetDocExampleParameterValue("coordx", "50"); SetDocExampleParameterValue("coordy", "100"); SetDocExampleParameterValue("cl", "Channel1"); } void DoUpdateParameters() { if ( HasValue("in") ) { ExtractROIFilterType::InputImageType* inImage = GetParameterImage("in"); // Update the values of the channels to be selected unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel(); ClearChoices("cl"); for (unsigned int idx = 0; idx < nbComponents; ++idx) { std::ostringstream key, item; key<<"cl.channel"<<idx+1; item<<"Channel"<<idx+1; AddChoice(key.str(), item.str()); } ExtractROIFilterType::InputImageType::RegionType largestRegion = inImage->GetLargestPossibleRegion(); SetMaximumParameterIntValue("coordx", largestRegion.GetSize(0)-1); SetMaximumParameterIntValue("coordy", largestRegion.GetSize(1)-1); } } void DoExecute() { std::ostringstream ossOutput; FloatVectorImageType::Pointer inImage = GetParameterImage("in"); ExtractROIFilterType::Pointer extractor = ExtractROIFilterType::New(); extractor->SetInput(inImage); // Create the region FloatVectorImageType::IndexType id; id[0] = GetParameterInt("coordx"); id[1] = GetParameterInt("coordy"); FloatVectorImageType::SizeType size; size.Fill(0); FloatVectorImageType::RegionType region; region.SetSize(size); region.SetIndex(id); extractor->SetExtractionRegion(region); // Extract the channels if needed if ( GetParameterByKey("cl")->GetActive() ) { for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx) { extractor->SetChannel(GetSelectedItems("cl")[idx] + 1 ); } } extractor->Update(); // Display the pixel value id.Fill(0); std::ostringstream oss; oss << extractor->GetOutput()->GetPixel(id)<<std::endl; SetParameterString("value", oss.str()); //Display image informations in the dedicated logger otbAppLogINFO( << oss.str() ); } }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::PixelInfo)
c9c600b582edb2aa539eb6e04008e5898c771bbc
339ba3ab82e03576638779e7240812c3eccff894
/neo/Source/PainterForCurve.cpp
e01508fb6d77c74a58dac88a45ae6a7972f0fd3f
[]
no_license
Philosjay/OpenGL
070b44f44f83fc9f309cd005b2296c816e523631
31984ad2e383cd9900a8c3190d14857d5fc8f362
refs/heads/master
2021-05-08T05:19:56.166787
2017-12-05T07:23:03
2017-12-05T07:23:03
108,499,458
0
0
null
null
null
null
GB18030
C++
false
false
3,226
cpp
PainterForCurve.cpp
#include "../Include/PainterForCurve.h" #include "../Include/Window.h" #include "../Include/Graph.h" #include "../Include/Painter.h" #include "../Include/World.h" PainterForCurve::PainterForCurve(Application* targetApp, Window* targetWindow, World* targetWorld) : Painter(targetApp, targetWindow,targetWorld) { requiredClicks = 3; } PainterForCurve::PainterForCurve() { requiredClicks = 3; } void PainterForCurve::paint(int x, int y) { if (!mPainter->isStarted()) { start(x, y); } glutMouseFunc(mouseButton); glutMotionFunc(mouseMotion); } void PainterForCurve::start(int x, int y) { for (int i = 0; i < mPainter->getRequiredClicks()+1; i++) { mPainter->getTargetGraph()->setRefPoint( x, y, i); } mPainter->setStarted(); mPainter->getTargetGraph()->moveTo(mPainter->getCurPosX(), mPainter->getCurPosY()); mPainter->getTargetGraph()->setColor(mColor.r, mColor.g, mColor.b); mPainter->getTargetGraph()->setLineWidth(mPainter->getTargetWindow()->getActiveLineWidth()); mPainter->getTargetWorld()->addGraph(mPainter->getTargetGraph()); mPainter->setClicked(); } void PainterForCurve::mouseButton(int button, int state, int x, int y) { switch (button) { case GLUT_LEFT_BUTTON: switch (state) { case GLUT_DOWN: mPainter->setCurPos(x + 50, 770 - y); mPainter->getTargetWindow()->update(mPainter->getCurPosX(), mPainter->getCurPosY()); mPainter->setEndPos(mPainter->getCurPosX(), mPainter->getCurPosY()); if (mPainter->getTargetWindow()->isInPaper()) { //根据所选工具调用不同的方法 //更新当前图形所需点击数量 if (mPainter->isStarted()) { switch (mPainter->getRequiredClicks()) { case 2: mPainter->getTargetGraph()->setRefPoint( mPainter->getCurPosX(), mPainter->getCurPosY(), 1); break; case 1: mPainter->getTargetGraph()->setRefPoint( mPainter->getCurPosX(), mPainter->getCurPosY(), 2); break; default: break; } mPainter->setClicked(); } } break; case GLUT_UP: if (mPainter->getTargetWindow()->isInPaper()) { if (mPainter->getRequiredClicks() <= 0) { mPainter->quit(); } } // Pgrab = NULL; break; } break; case GLUT_RIGHT_BUTTON: switch (state) { case GLUT_DOWN: //点击右键结束绘图 mPainter->quit(); break; default: break; } break; case GLUT_MIDDLE_BUTTON: break; } mPainter->update(); } void PainterForCurve::mouseMotion(int x, int y) { //换算后的坐标 mPainter->setEndPos(x + 50, 770 - y); if (mPainter->getTargetWindow()->isInPaper()) { if (mPainter->getTargetGraph() != NULL) switch (mPainter ->getRequiredClicks()) { case 2: mPainter->getTargetGraph()->setRefPoint(mPainter->getEndPosX(), mPainter->getEndPosY(), 3); mPainter->getTargetGraph()->setRefPoint(mPainter->getEndPosX(), mPainter->getEndPosY(), 2); break; case 1: mPainter->getTargetGraph()->setRefPoint(mPainter->getEndPosX(), mPainter->getEndPosY(), 1); break; case 0: mPainter->getTargetGraph()->setRefPoint(mPainter->getEndPosX(), mPainter->getEndPosY(), 2); break; default: break; } } //更新当前操作状态 mPainter->update(); }
f7abcb3003981e29dd05cd7002ddc7c863991958
96479eb06ff3f4fbd470d48be308dfd6b9ef1975
/filesystem/include/png_utils.h
1085f00ef8b485e0c587eb3a13fead12e40d31ce
[]
no_license
AnatoliyYakimov/glassyrender
294febb498f3f36800877fd393000991a0e3561b
d4ba05965e2f4b0339f6d8f90aad04adad91b6ec
refs/heads/master
2020-08-12T12:46:59.508588
2020-04-20T15:05:05
2020-04-20T15:05:05
214,769,921
0
0
null
null
null
null
UTF-8
C++
false
false
1,794
h
png_utils.h
#ifndef GLASSYRENDER_PNG_UTILS_H #define GLASSYRENDER_PNG_UTILS_H #include <image.hpp> #include <memory> #include <basic_image.h> class png_utils { private: static constexpr uint8_t COLORS_8_BIT = 255; static constexpr uint16_t COLORS_16_BIT = 65535; public: static png::rgb_pixel to_rgb_pixel8(const rgb_pixel &pix) { uint8_t r = pix.r() * COLORS_8_BIT, g = pix.g() * COLORS_8_BIT, b = pix.b() * COLORS_8_BIT; return png::rgb_pixel{r, g, b}; } static png::rgb_pixel_16 to_rgb_pixel16(const rgb_pixel &pix) { uint16_t r = pix.r() * COLORS_16_BIT, g = pix.g() * COLORS_16_BIT, b = pix.b() * COLORS_16_BIT; return png::rgb_pixel_16{r, g, b}; } static std::shared_ptr<png::image<png::rgb_pixel>> to_8bit(const image_rgb &img) { int width = img.get_width(); int height = img.get_height(); auto data = img.get_data(); auto png = std::make_shared<png::image<png::rgb_pixel>>(width, height); auto &buf = png->get_pixbuf(); for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { buf[j][i] = to_rgb_pixel8(data[j + i * height]); } } return png; } static std::shared_ptr<png::image<png::rgb_pixel_16>> to_16bit(const image_rgb &img) { int width = img.get_width(); int height = img.get_height(); auto data = img.get_data(); auto png = std::make_shared<png::image<png::rgb_pixel_16>>(width, height); auto &buf = png->get_pixbuf(); for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { buf[j][i] = to_rgb_pixel16(data[j + i * height]); } } return png; } }; #endif //GLASSYRENDER_PNG_UTILS_H
83f6504f61a0493777b1f4267e9534a06b4d1b51
9ce9a01f05677f495fa244667bc77f4ebcac3509
/Tempest/Core/MemoryManagement/HeapManager.cpp
4ca36083e8cb1e2258eb1a7835445e3aa49a8f37
[]
no_license
Sumi-N/GameEngineProject
644c81eaf2c0b98f78dd35b2d80697a264606185
8f522021a3a1a50d44fc901b9402e2f10fde4a0e
refs/heads/master
2023-06-07T21:41:50.236576
2021-12-18T02:09:47
2021-12-18T02:09:47
225,953,189
0
0
null
2021-01-19T21:00:05
2019-12-04T20:41:50
HTML
UTF-8
C++
false
false
8,040
cpp
HeapManager.cpp
#include "HeapManager.h" void* _head; void* _current; void* _end; size_t _size; HeapManager::HeapManager() { DEBUG_PRINT("Heap Manager is created"); #ifdef ENABLE_CUSTOM_ALLOCATOR #ifdef ENGINE_PLATFORM_WINDOWS _head = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, HEAP_SIZE); Initialize(_head, HEAP_SIZE); #endif // ENGINE_PLATFORM_WINDOWS #endif // ENABLE_CUSTOM_ALLOCATOR is_heap_alive = true; } HeapManager::~HeapManager() { is_heap_alive = false; #ifdef ENABLE_CUSTOM_ALLOCATOR #ifdef ENGINE_PLATFORM_WINDOWS Finalize(); HeapFree(GetProcessHeap(), 0, _head); #endif // ENGINE_PLATFORM_WINDOWS DEBUG_PRINT("Heap Manager was destroyed"); #endif // ENABLE_CUSTOM_ALLOCATOR } void* HeapManager::Initialize(void* i_ptr, size_t i_size) { if (!i_ptr) { DEBUG_ASSERT(false); } _head = i_ptr; _current = i_ptr; _size = i_size; _end = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(_head) + i_size); if (_current >= _end) { return nullptr; } static_cast<Block*>(_head)->exist = false; static_cast<Block*>(_head)->size = i_size - sizeof(Block); return _current; } void HeapManager::Finalize(){ } void* HeapManager::Alloc(size_t i_size) { bool need_to_collect = false; Block* current_block = static_cast<Block*>(_current); //Check if there is a space to insert block while (!(current_block->exist == false && current_block->size >= i_size + sizeof(Block))) { #ifdef _DEBUG AccessViolationCheck(current_block); #endif _current = reinterpret_cast<void*> (reinterpret_cast<size_t>(_current) + current_block->size + sizeof(Block)); current_block = static_cast<Block*>(_current); if (reinterpret_cast<size_t>(_current) + sizeof(Block) >= reinterpret_cast<size_t>(_end)) { DEBUG_PRINT("Start collecting the heap since there is not enought memory to allocate"); need_to_collect = true; break; } } if (need_to_collect) { Collect(); _current = _head; current_block = static_cast<Block*>(_current); while (current_block->exist == true || current_block->size < i_size + sizeof(Block)) { #ifdef _DEBUG AccessViolationCheck(current_block); #endif _current = reinterpret_cast<void*> (reinterpret_cast<size_t>(_current) + current_block->size + sizeof(Block)); current_block = static_cast<Block*>(_current); if(reinterpret_cast<size_t>(_current) + sizeof(Block) >= reinterpret_cast<size_t>(_end)) { DEBUG_PRINT("There is not enough memory to allocate"); DEBUG_ASSERT(false); return nullptr; } } } #ifdef _DEBUG AccessViolationCheck(current_block); #endif //Now split the descriptor to two descriptors size_t available_space = current_block->size; current_block->exist = true; current_block->size = i_size; void* return_address = reinterpret_cast<void*>(reinterpret_cast<size_t>(_current) + sizeof(Block)); void * next = reinterpret_cast<void*> (reinterpret_cast<size_t>(_current) + sizeof(Block) + current_block->size); Block* next_block = static_cast<Block*>(next); next_block->exist = false; next_block->size = available_space - (i_size + sizeof(Block)); _current = next; //DEBUG_PRINT("The _current address is now at %zx", reinterpret_cast<size_t>(_current)); //DEBUG_PRINT("The _current empty space now at %zu", reinterpret_cast<size_t>(_end) - reinterpret_cast<size_t>(_current)); return return_address; } void* HeapManager::Realloc(void* i_ptr, size_t i_size) { if (!i_ptr) { DEBUG_ASSERT(false); } bool need_to_collect = false; Block* current_block = static_cast<Block*>(_current); //Check if there is a space to insert block while (!(current_block->exist == false && current_block->size >= i_size + sizeof(Block))) { #ifdef _DEBUG AccessViolationCheck(current_block); #endif _current = reinterpret_cast<void*> (reinterpret_cast<size_t>(_current) + current_block->size + sizeof(Block)); current_block = static_cast<Block*>(_current); if (reinterpret_cast<size_t>(_current) + sizeof(Block) >= reinterpret_cast<size_t>(_end)) { DEBUG_PRINT("Start collecting the heap since there is not enought memory to allocate"); need_to_collect = true; break; } } if (need_to_collect) { Collect(); _current = _head; current_block = static_cast<Block*>(_current); while (current_block->exist == true || current_block->size < i_size + sizeof(Block)) { _current = reinterpret_cast<void*> (reinterpret_cast<size_t>(_current) + current_block->size + sizeof(Block)); current_block = static_cast<Block*>(_current); if(reinterpret_cast<size_t>(_current) + sizeof(Block) >= reinterpret_cast<size_t>(_end)) { DEBUG_PRINT("There is not enough memory to allocate"); DEBUG_ASSERT(false); return nullptr; } } } #ifdef _DEBUG AccessViolationCheck(current_block); #endif //Now split the descriptor to two descriptors size_t available_space = current_block->size; current_block->exist = true; current_block->size = i_size; void* return_address = reinterpret_cast<void*>(reinterpret_cast<size_t>(_current) + sizeof(Block)); void* next = reinterpret_cast<void*> (reinterpret_cast<size_t>(_current) + sizeof(Block) + current_block->size); Block* next_block = static_cast<Block*>(next); next_block->exist = false; next_block->size = available_space - (i_size + sizeof(Block)); _current = next; memcpy(return_address, i_ptr, i_size); Free(i_ptr); //DEBUG_PRINT("The _current address is now at %zx", reinterpret_cast<size_t>(_current)); //DEBUG_PRINT("The _current empty space now at %zu", reinterpret_cast<size_t>(_end) - reinterpret_cast<size_t>(_current)); return return_address; } bool HeapManager::Free(void* i_ptr) { if (!i_ptr) { DEBUG_ASSERT(false); } void* freeing = reinterpret_cast<void*>(reinterpret_cast<size_t>(i_ptr) - sizeof(Block)); Block* freeing_block = static_cast<Block*>(freeing); if (!freeing_block->exist) { DEBUG_ASSERT(false); } freeing_block->exist = false; return true; } void HeapManager::Collect() { void* current_collecting = _head; Block* current_collecting_block = static_cast<Block*>(current_collecting); void* next_collecting = reinterpret_cast<void*>(reinterpret_cast<size_t>(current_collecting) + current_collecting_block->size + sizeof(Block)); Block* next_collecting_block = static_cast<Block*>(next_collecting); do { #ifdef _DEBUG AccessViolationCheck(current_collecting_block); AccessViolationCheck(next_collecting_block); #endif if (current_collecting_block->exist == false && next_collecting_block->exist == false) { current_collecting_block->size += (next_collecting_block->size + sizeof(Block)); next_collecting = reinterpret_cast<void*>(reinterpret_cast<size_t>(next_collecting) + next_collecting_block->size + sizeof(Block)); next_collecting_block = static_cast<Block*>(next_collecting); } else if(next_collecting_block->exist == false) { current_collecting = next_collecting; current_collecting_block = static_cast<Block*>(current_collecting); next_collecting = reinterpret_cast<void*>(reinterpret_cast<size_t>(next_collecting) + next_collecting_block->size + sizeof(Block)); next_collecting_block = static_cast<Block*>(next_collecting); } else { current_collecting = reinterpret_cast<void*>(reinterpret_cast<size_t>(next_collecting) + next_collecting_block->size + sizeof(Block)); current_collecting_block = static_cast<Block*>(current_collecting); next_collecting = reinterpret_cast<void*>(reinterpret_cast<size_t>(current_collecting) + current_collecting_block->size + sizeof(Block)); next_collecting_block = static_cast<Block*>(next_collecting); } } while (reinterpret_cast<size_t>(next_collecting) + next_collecting_block->size + sizeof(Block) <= reinterpret_cast<size_t>(_end)); return; } bool HeapManager::IsHeapAlive() { return is_heap_alive; } #ifdef _DEBUG void HeapManager::AccessViolationCheck(const Block* i_block) { if (i_block->headguardbanding != '\0' || i_block->tailguardbanding != '\0') { DEBUG_ASSERT(false); } return; } #endif
50fe5b97967eb94ba0863b5c22f65823fbdd1918
0875a3b39b8f6cc91bc64fd2d7ca7af1041d09f2
/src/design_pattern.hpp
21005e41218856ad66bfb6606aaf44ae73420dbc
[]
no_license
XuWensong/program
26d02094a3a44c473ef08f1584d991b5dcafcfa5
d079ab472c752782aac36cc67acb46a82c8beb7d
refs/heads/master
2021-06-26T15:06:39.667286
2020-12-17T08:25:37
2020-12-17T08:25:37
37,705,205
1
0
null
null
null
null
UTF-8
C++
false
false
789
hpp
design_pattern.hpp
#ifndef SONGZI_DESIGN_PATTERN_H #define SONGZI_DESIGN_PATTERN_H #include "op/op.hpp" #include "design_pattern/factory.hpp" #include "design_pattern/abstract_factory.hpp" #include "design_pattern/singleton.hpp" #include "design_pattern/prototype.hpp" #include "design_pattern/builder.hpp" #include "design_pattern/bridge.hpp" #include "design_pattern/adapter.hpp" class DesignPatternOp : public Op { private: void test_factory(); void test_abstract_factory(); void test_builder(); void test_prototype(); void test_singleton(); void test_bridge(); void test_adapter(); public: DesignPatternOp(Argument *argument):Op(argument, "dp", "test case of design pattern") { } ~DesignPatternOp(){} virtual void exec(); virtual void help(); }; #endif
b35173d52df445454005ec47919e6daa95bb0b03
b7d3d831804d4d52f3c5e0f234cd76808c114897
/20200625/test.cpp
2d7e10aec8ff4db8a6aaac0960806d864c76983a
[]
no_license
zhangxiaoyin0122/20200625
0df5d69562e2190bf0f998b7b7eae76a4a5428d3
1397f8634486dc24dc3aac6053852cd9387c27ce
refs/heads/master
2022-11-07T10:17:05.376743
2020-06-25T15:24:56
2020-06-25T15:24:56
274,953,013
0
0
null
null
null
null
GB18030
C++
false
false
2,326
cpp
test.cpp
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> using namespace std; //字符串拼接 class Solution1 { public: string reverseLeftWords(string s, int n) { string ret = ""; for (int i = n; i < s.size(); ++i) { ret += s[i]; } for (int i = 0; i < n; ++i) { ret += s[i]; } return ret; } }; // class String { public: //构造函数 String(const char* str) { _str = new char[strlen(str)+1]; strcpy(_str, str); _size = strlen(str); _capacity = _size; } //拷贝构造函数 /*String(const String& s) :_str(new char[s._capacity + 1]) , _size(s._size) , _capacity(s._capacity) { strcpy(_str, s._str); }*/ // void Swap( String& s) { swap(_str, s._str); swap(_size, s._size); swap(_capacity, s._capacity); } //拷贝构造函数:现代写法 String(const String& s) :_str(nullptr) , _size(0) , _capacity(0) { String tmp(s._str); Swap(tmp); } //赋值运算符 /*String& operator=(const String& s) { if (this != &s) { char* tmp = new char[s._size + 1]; strcpy(tmp, s._str); delete[]_str; _str = tmp; _size = s._size; _capacity = s._capacity; } return *this; }*/ //赋值运算符:现代写法 String& operator=(String s) { Swap(s); return *this; } //析构函数 ~String() { if (_str) { delete[]_str; _str = nullptr; _size = _capacity = 0; } } typedef char* iterator; typedef const char* const_iterator; iterator begin() { return _str; } iterator end() { return _str + _size; } const_iterator begin() const{ return _str; } const_iterator end()const { return _str + _size; } const char* c_str()const { return _str; } char& operator[](size_t pos) { if (pos < _size) { return _str[pos]; } } const char& operator[](size_t pos)const { if (pos < _size) { return _str[pos]; } } private: char* _str; size_t _size; size_t _capacity; }; void PrintString(String& s) { String::iterator it = s.begin(); while (it != s.end()) { cout << *it << " "; ++it; } cout << endl; String::const_iterator cit = s.begin(); while (cit != s.end()) { cout << *cit << " "; ++cit; } cout << endl; //范围for: for (auto e : s) { cout << e << " "; } cout << endl; } void test() { String s("987654321"); PrintString(s); } int main() { test(); return 0; }
f63b8ae634854cd77e60f21f256da8012ae8341b
66d1b8faa416a288da64e5d1488051ebac9e3f15
/ProtocolConnRules.cpp
6164785f330481c6e3dd9bd16ad95b786d56956b
[]
no_license
KouenSoftWare/Rano
c91194910a245f12ea55141d0bbb2c3a4b12bcce
c65c52992c4306bbbac27d5450c40726849ea6d3
refs/heads/master
2021-01-01T17:21:13.926242
2015-08-26T09:42:51
2015-08-26T09:42:51
39,719,146
0
0
null
null
null
null
UTF-8
C++
false
false
31
cpp
ProtocolConnRules.cpp
#include "ProtocolConnRules.h"
33db63d8a9b527678f3f0c0ff7eae9dfef0f42f2
96a7eb112e1484f2e06925eea799c938a824a217
/Algorithms/Graph Theory/C++ Implementations/bellmanford.cpp
a269748f6a72940ec47f973cdbb5c16e02c1d69e
[]
no_license
Thenuga12/Data-Structures-and-Algorithm
9b493d1bbcc88cf550acb2c22601e6f52b0e26bd
e2533f35fbc5abfbb1a888fee687bc513d81338e
refs/heads/master
2023-01-03T21:53:00.398426
2020-10-31T19:40:12
2020-10-31T19:40:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
814
cpp
bellmanford.cpp
/** Bellman ford shortest path algorithm... Time Complexity: O(V.E) ** @author: Arpan Pathak **/ #include <bits/stdc++.h> #define inf INT_MAX using namespace std; class Edge{ public: int u,v,weight; Edge(int u,int v,int weight): u(u), v(v), weight(weight) { } }; int main() { vector<Edge> G; vector<int> D; int n,v,e,u,w; cout<<"Enter number of vertices and edges="; cin>>n>>e; D.resize(n,inf); cout<<"Enter edges with weight u,v,w:\n"; while(e--) { cin>>u>>v>>w; G.push_back(Edge(u,v,w)); } cout<<"Enter source vertex="; cin>>u; D[u]=0; for(int i=1;i<=n-1;i++) for(int j=0;j<G.size();j++) if(D[G[j].u]!=inf && D[G[j].v] > D[G[j].u] + G[j].weight ) D[G[j].v] = D[G[j].u] + G[j].weight; for(int i: D) cout<<i<<" "; }
afed40ce49325df5e128dea49a542d09c8318da1
a9717ff2a1072d77b702f4447f57b9fe5f08ce90
/Game/Controllers/MonsterController.cpp
b7fa15350316b4ac9822ef3438edf160a3e63274
[]
no_license
singingsingh/Indra
e0685e45a33e0f39af943582d10f8043124523d5
7c6526af77dc1c435e3c3a8b66acdb26db5222e6
refs/heads/master
2020-03-26T18:47:42.139305
2017-01-22T20:05:57
2017-01-22T20:05:57
60,437,736
0
0
null
null
null
null
UTF-8
C++
false
false
3,885
cpp
MonsterController.cpp
#include <Game\Controllers\MonsterController.h> #include <Engine\Util\Assert.h> #include <Engine\Util\ConsolePrint.h> #include <Engine\Engine\PhysicsTickNotifier.h> #include <Engine\Engine\AIUpdateNotifier.h> #include <Engine\Engine\HitResult.h> #include <Engine\Core\Math\Vector2f.h> #include <time.h> namespace Game { MonsterController* MonsterController::_instance = nullptr; MonsterController::MonsterController() { Engine::PhysicsTickNotifier::RegisterPhysicsTick(this); Engine::AIUpdateNotifier::RegisterAIUpdate(this); runTime = 0.0f; srand((unsigned int)time(NULL)); } MonsterController::~MonsterController() { Engine::PhysicsTickNotifier::DeRegisterPhysicsTick(this); Engine::AIUpdateNotifier::DeRegisterAIUpdate(this); } void MonsterController::CreateMonsterController() { if (_instance == nullptr) { _instance = new Game::MonsterController(); } else { DEBUG_PRINT("Cannot create two instances of Player controller.\n"); } } MonsterController* MonsterController::GetMonsterController() { return _instance; } void MonsterController::DestroyMonsterController() { if (_instance) { delete _instance; _instance = nullptr; } } void MonsterController::setPhysicsInfo(Engine::SmartPtr<Engine::PhysicsInfo>& i_physicsInfo) { MessagedAssert(i_physicsInfo != nullptr, "Cannot set empty PhysicsInfo.\n"); _physicsInfo = i_physicsInfo; } void MonsterController::aiUpdate(double deltaTime) { runTime -= (float)deltaTime; if (runTime < 0) { runTime = 3000; Engine::Math::Vector2f force; force.x = ((float)(rand() % 2) / 50) + ((float)(rand() % 2) / 30); force.y = ((float)(rand() % 2) / 30) + ((float)(rand() % 2) / 50); if (rand() % 2 == 0) { force.x = -force.x; } if (rand() % 2 == 0) { force.y = -force.y; } Engine::Math::Vector2f offset; offset.x = (float)(rand() % 20) + (float)(rand() % 23); offset.y = (float)(rand() % 12) + (float)(rand() % 30); if (rand() % 2 == 0) { offset.x = -offset.x; } if (rand() % 2 == 0) { offset.y = -offset.y; } _physicsInfo->_gameObject->pos += offset; Engine::Math::Vector2f distance = _physicsInfo->_gameObject->pos; if (distance.length() > 300.0f) { distance.normalize(); distance = distance * 0.02f; distance.x = -distance.x; distance.y = -distance.y; applyForce(distance); } else { applyForce(force); } } } void MonsterController::preCollisionPhysicsTick(double i_deltaTime) { _physicsInfo->acceleration *= _physicsInfo->drag; Engine::Math::Vector2f newVelocity = _physicsInfo->acceleration * (float)i_deltaTime; _physicsInfo->potentialPos = _physicsInfo->_gameObject->pos; _physicsInfo->potentialPos += (_physicsInfo->velocity + newVelocity) * 0.5f * (float)i_deltaTime; _physicsInfo->velocity = newVelocity; } void MonsterController::postCollisionPhysicsTick(double i_deltaTime) { //law of conservation of momemtum if (_physicsInfo->hitResult->collision) { float m1 = _physicsInfo->mass; float m2 = _physicsInfo->hitResult->other->mass; Engine::Math::Vector2f v1 = _physicsInfo->velocity; Engine::Math::Vector2f v2 = _physicsInfo->hitResult->other->velocity; _physicsInfo->velocity = (((m1 - m2) / (m1 + m2)) * v1) + (((2 * m2) / (m1 + m2)) * v2); _physicsInfo->acceleration = _physicsInfo->velocity / (float)i_deltaTime; _physicsInfo->_gameObject->pos += _physicsInfo->velocity*(float)i_deltaTime; _physicsInfo->hitResult->collision = false; } else { _physicsInfo->_gameObject->pos = _physicsInfo->potentialPos; } // clean up _physicsInfo->hitResult->collision = false; _physicsInfo->hitResult->other = nullptr; } void MonsterController::applyForce( Engine::Math::Vector2f i_force ) { _physicsInfo->acceleration += i_force / _physicsInfo->mass; } }
4c99d2b615a8273114c4fad0b50c197a21344e86
b65cfd02fc0010e0bde6b5dda73a9765ffc1b19c
/Server/include/DamageBlock.h
b469d74f87f47c47271f8d0a789da3666e2c0935
[ "MIT" ]
permissive
ROLL-E/roll-e
58f5cf0b4c7f4a323b37784479af975c4e23e651
ddf7112ed7bf196616bafa9b9453df6b0b22ca38
refs/heads/master
2021-01-20T11:05:09.512796
2014-01-19T20:20:33
2014-01-19T20:20:33
14,613,510
1
0
null
2014-01-19T14:02:14
2013-11-22T09:19:40
C++
UTF-8
C++
false
false
855
h
DamageBlock.h
#ifndef DAMAGEBLOCK_H #define DAMAGEBLOCK_H #include "LogicBlock.h" #include <QString> class ValueBlock; class Character; class DamageBlock : public LogicBlock { private: Character* target{nullptr}; QString type; ValueBlock* valueblock{nullptr}; public: quint16 target_id; quint16 valueblock_id; DamageBlock() = default; DamageBlock(DamageBlock&); ~DamageBlock() = default; LogicBlock* execute() override; void set_target(Character*); Character* get_target() const; void set_valueblock(ValueBlock*); ValueBlock* get_valueblock() const; void set_type(const QString&); void populate_id_fields(QList<LogicBlock *> &, QList<Character *> &); void populate_pointer_fields(QList<LogicBlock *> &, QList<Character *> &); QDataStream& write_to_stream(QDataStream&); QDataStream& read_from_stream(QDataStream&); }; #endif
b37e9715c071584e82a5b4da09b6316f6da9bb61
8ff320e31e8ad83c75c93cd8f71347a38e718e71
/src/player/content/library/albumView.cpp
51654d792f6f64aafddb72d1fa44447312d8ee7c
[]
no_license
tavu/karakaxa
60ff6e3e79196f5a3e079c5dc1cc1c430d9ff1be
03f3df0f22a6a001438589d72c42c34a3f3dd519
refs/heads/master
2021-01-01T18:22:49.392260
2013-09-04T13:42:02
2013-09-04T13:42:02
4,357,814
2
0
null
null
null
null
UTF-8
C++
false
false
27,594
cpp
albumView.cpp
#include"albumView.h" #include <Basic/tagsTable.h> #include<QScrollBar> #include<QPainter> #include<QDebug> #include<QPaintEvent> #include <QHeaderView> #include"albumDelegate.h" #include<QApplication> #include<views/models/treeView.h> #include<views/decoration/decoration.h> #include<views/models/urlRole.h> #include<core/nowPlayList/nplaylist.h> #include<core/engine/engine.h> #include<views/models/urlRole.h> #define DECOR_SIZE QSize(80,80) #define HEADER_OFFSET albumOffset + albumWidth albumView::albumView(QString name,QWidget* parent): QAbstractItemView(parent) { rowHeight=20; albumOffset=20; albumWidth=80; albumMinHeight=100; albumInfoHeight=40; space=10; hashIsDirty=false; setMouseTracking(true); setSelectionBehavior(QAbstractItemView::SelectRows); header=new albumViewHeader(viewport() ); header->setVisible(false); // QRect r=viewportRectForRow(headerRect(-1)); readSettings(); columnResizeTimer.setInterval(500); columnResizeTimer.setSingleShot(true); // header->setGeometry(r); // header->move(r.topLeft()); // header->setFixedHeight(r.height()); // header->move(r.topLeft()); header->setNotHide(Basic::TITLE); header->setMovable(true); header->setClickable(true); header->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); setEditTriggers(QAbstractItemView::SelectedClicked); setSelectionMode(QAbstractItemView::ExtendedSelection); setDragDropMode(QAbstractItemView::DragOnly); verticalScrollBar()->setSingleStep(rowHeight); horizontalScrollBar()->setSingleStep(500); setItemDelegate(new albumDelegate(this) ); horizontalScrollBar()->setRange(0, 0); verticalScrollBar()->setRange(0, 0); setAutoFillBackground(true); verticalScrollBar()->setPageStep(rowHeight*10); horizontalScrollBar()->setPageStep(500); connect(horizontalScrollBar(),SIGNAL(valueChanged(int)),this,SLOT(hideHeader()) ); connect(verticalScrollBar(),SIGNAL(valueChanged(int)),this,SLOT(hideHeader()) ); connect(header,SIGNAL(geometriesChanged()),this,SLOT(columnsUpdated()) ); connect(header,SIGNAL(sectionResized(int,int,int)),this,SLOT(columnResized(int)) ); connect(header,SIGNAL(sectionMoved(int,int,int)),this,SLOT(columnsUpdated()) ); connect(header,SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)),this,SLOT(sortModel(int,Qt::SortOrder))); connect(&columnResizeTimer,SIGNAL(timeout()),this,SLOT(columnsUpdated()) ); connect(this,SIGNAL(doubleClicked(const QModelIndex&)),this,SLOT(doubleClickedSlot(const QModelIndex&))); setObjectName(name); } albumView::~albumView() { writeSettings(); } void albumView::setModel(QAbstractItemModel* m) { if(model()!=0) { disconnect(model()); _headerState=header->saveState(); } else { readSettings(); } hashIsDirty=true; QAbstractItemView::setModel(m); connect(m,SIGNAL(modelReset() ),this,SLOT(resetSlot()) ); connect(m,SIGNAL(layoutAboutToBeChanged()),this,SLOT(resetSlot()) ); header->setModel(m); header->restoreState(_headerState); // header->setResizeMode() header->stretchSectionCount(); QRect r=viewportRectForRow(headerRect(-1)); header->setGeometry(r); header->setStretchLastSection(false); columnsUpdated(); if(m->canFetchMore(QModelIndex() )) { m->fetchMore(QModelIndex()); } for(int row=0;row<m->rowCount();row++) { QModelIndex in=m->index(row,0); if(isExpanded(in)) { m->fetchMore(in); } } } int albumView::horizontalOffset() const { return horizontalScrollBar()->value(); } int albumView::verticalOffset() const { return verticalScrollBar()->value(); } QModelIndex albumView::indexAt(const QPoint& _point) const { if(model()==0) return QModelIndex(); QPoint point(_point); // int pos=point.rx(); point.rx() += horizontalScrollBar()->value(); point.ry() += verticalScrollBar()->value(); QRect rect; QHashIterator<int, QRect> i(albumRects); while (i.hasNext()) { i.next(); if (i.value().contains(point)) { rect=i.value(); break; } } if(rect.isNull()) { return QModelIndex(); } rect=itemsRect(i.key()); QModelIndex parent=model()->index(i.key(),0); if(!rect.contains(point)) { rect=albumRect(parent); if(rect.contains(point) ) { return parent; } return QModelIndex(); } int height=point.ry() -rect.topLeft().ry() ; int itemRow=height/rowHeight ; QPoint p=header->mapFromParent(_point); // QPoint p=header->mapFrom(viewport(),point); int k=header->logicalIndexAt(p); return model()->index(itemRow,k,parent); } bool albumView::isIndexHidden(const QModelIndex& index) const { if(index.parent().isValid() ) { if(!isExpanded(index.parent() ) ) { return true; } } return false; } QModelIndex albumView::moveCursor(QAbstractItemView::CursorAction cursorAction, Qt::KeyboardModifiers modifiers) { QModelIndex index = currentIndex(); return index; } void albumView::scrollTo(const QModelIndex& index, QAbstractItemView::ScrollHint hint) { return ; #if 0 QRect viewRect = viewport()->rect(); QRect itemRect = visualRect(index); if (itemRect.left() < viewRect.left()) horizontalScrollBar()->setValue(horizontalScrollBar()->value() + itemRect.left() - viewRect.left()); else if (itemRect.right() > viewRect.right()) horizontalScrollBar()->setValue(horizontalScrollBar()->value() + qMin(itemRect.right() - viewRect.right(), itemRect.left() - viewRect.left())); if (itemRect.top() < viewRect.top()) verticalScrollBar()->setValue(verticalScrollBar()->value() + itemRect.top() - viewRect.top()); else if (itemRect.bottom() > viewRect.bottom()) verticalScrollBar()->setValue(verticalScrollBar()->value() + qMin(itemRect.bottom() - viewRect.bottom(), itemRect.top() - viewRect.top())); viewport()->update(); #endif } void albumView::setSelection(const QRect& rect, QItemSelectionModel::SelectionFlags flags) { if (flags & QItemSelectionModel::Clear) selectionModel()->clear(); if(model()==0) return ; calculateRectsIfNecessary(); QPoint tl(qMin(rect.left(), rect.right()), qMin(rect.top(), rect.bottom())); QPoint br(qMax(rect.left(), rect.right()), qMax(rect.top(), rect.bottom())); QModelIndex topLeft = indexAt(tl); QModelIndex bottomRight = indexAt(br); if(topLeft.parent()!=bottomRight.parent()) return ; // if (!topLeft.isValid() || !bottomRight.isValid()) // return; /* if(isAlbum(topLeft) && !isExpanded(topLeft) ) { return ; }*/ QItemSelection selection(topLeft,bottomRight); selectionModel()->select(selection, flags); viewport()->update(); return ; } QRegion albumView::visualRegionForSelection(const QItemSelection& selection) const { QRegion region; QModelIndexList l=selection.indexes(); foreach(QModelIndex index,l) { region+=visualRect(index); } return region; } void albumView::calculateRectsIfNecessary() const { if (!hashIsDirty) return; if(model()==0) return ; int prevHeight = -10; for (int row = 0; row < model()->rowCount(); ++row) { int height=0; QModelIndex index=model()->index(row,0); if(expanded.contains(index.data(ID_ROLE).toInt())) { int rowCount=model()->rowCount(index); height=(rowCount+2)*rowHeight +albumInfoHeight;//one extra row for the header if(height<albumMinHeight) { height=albumMinHeight; } } else { height=albumMinHeight; } QRect albumR; //albuR is bellow the previous album albumR.setX(0); albumR.setY(prevHeight +albumOffset ); albumR.setWidth(qMax(viewport()->width(),header->length()+HEADER_OFFSET ) ); albumR.setHeight(height); albumRects[row]=albumR; prevHeight=albumR.y()+albumR.height(); } verticalScrollBar()->setRange(0, qMax(0, prevHeight -viewport()->height() ) ); // horizontalScrollBar()->setRange(0, width()); // updateScrollBars(); hashIsDirty=false; viewport()->update(); } QRect albumView::indexRect(const QModelIndex& index) const { QRect r; if (!index.isValid()) return r; if(isIndexHidden(index)) return r; calculateRectsIfNecessary(); if(isAlbum(index)) { r=albumRect(index); } else { r=itemRect(index); } return r; } QRect albumView::visualRect(const QModelIndex& index) const { return viewportRectForRow(indexRect(index) ); } QRect albumView::viewportRectForRow(QRect rect) const { if (!rect.isValid()) return rect; return QRect(rect.x() - horizontalScrollBar()->value(), rect.y() - verticalScrollBar()->value(), rect.width(), rect.height()); } QRect albumView::itemsRect(int parentRow) const { QModelIndex parentIndex=model()->index(parentRow,0); if(!isExpanded(parentIndex)) return QRect(); QRect r(albumRects[parentRow] ); r.setX(r.x() + albumOffset+albumWidth); r.setY(r.y()+albumInfoHeight + rowHeight); return r; } QRect albumView::headerRect(int row) const { // qDebug()<<"W "<<header->width(); if(row==-1) { QRect r; r.setX(r.x()+HEADER_OFFSET); r.setY(albumInfoHeight ); r.setHeight(rowHeight); // r.setWidth(r.width()); // r.setWidth(albumOffset + albumWidth+r.width()); // r.setWidth(header->sizeHint().width()); return r; } QModelIndex parentIndex=model()->index(row,0); if(!isExpanded(parentIndex)) return QRect(); QRect r(albumRects[row] ); r.setX(r.x() + albumOffset + albumWidth); r.setY(r.y()+albumInfoHeight ); r.setHeight(rowHeight); // r.setWidth(r.width()); // r.setWidth(albumOffset + albumWidth+r.width()); // r.setWidth(header->sizeHint().width()); // r.setWidth(header->sizeHint().width()); return r; } QRect albumView::itemRect(const QModelIndex& index) const { /* QRect r=itemsRect(index.parent().row() ); int width=header->sectionSize(index.column()); r.setY(r.y()+index.row()*rowHeight); r.setX(header->sectionViewportPosition(index.column()) +r.x() ); r.setHeight(rowHeight); r.setWidth(width); */ return itemRect(index.row(),index.column(),index.parent().row() ); } QRect albumView::itemRect(int row, int column, int parentR) const { QRect r=itemsRect(parentR); int width=header->sectionSize(column); r.setY(r.y()+row*rowHeight); r.setX(header->sectionViewportPosition(column) +r.x() ); r.setHeight(rowHeight); r.setWidth(width); return r; } QRect albumView::albumRect(const QModelIndex& index) const { QRect r=albumRects[index.row()]; if(!isExpanded(index) ) { return r; } r.setHeight(albumMinHeight); r.setWidth(albumMinHeight); return r; } void albumView::rowsInserted(const QModelIndex &parent, int start,int end) { QAbstractItemView::rowsInserted(parent,start,end); // return ; hashIsDirty = true; calculateRectsIfNecessary(); if(isAlbum(parent) && isExpanded(parent)) { for(int i=start;i<=end;i++) { QModelIndex index=model()->index(i,Basic::RATING,parent); openPersistentEditor(index); } } else { for(int i=start;i<=end;i++) { QModelIndex index=model()->index(i,0,parent); int id=index.data(ID_ROLE).toInt(); if(storeExpanded.contains(id) ) { setExpanded(index,true); } } } } void albumView::rowsAboutToBeRemoved(const QModelIndex &parent,int start, int end) { hashIsDirty = true; // expanded.clear(); if(!parent.isValid()) { for(int i=start;i<=end;i++) { QModelIndex index=model()->index(i,0); int id=index.data(ID_ROLE).toInt(); if(expanded.contains(id)) { expanded.remove(id); storeExpanded.insert(id); } } } QAbstractItemView::rowsAboutToBeRemoved(parent, start, end); } void albumView::paintEvent(QPaintEvent* e) { // qDebug()<<"PAINT"; calculateRectsIfNecessary(); mousePoint=viewport()-> mapFromGlobal(QCursor::pos()); hoverIndex=indexAt(mousePoint); QAbstractItemView::paintEvent(e); QPainter painter(viewport()); painter.setRenderHints(QPainter::Antialiasing|QPainter::TextAntialiasing); for (int row = 0; row < model()->rowCount(); ++row) { QModelIndex index = model()->index(row, 0); QStyleOptionViewItemV4 option = styleOptions(index); // itemDelegate()->paint(&painter, option, index); drawAlbum(&painter,option,index); drawChildren(index,&painter); } } void albumView::drawChildren(const QModelIndex& index, QPainter* p) { if(!isExpanded(index)) return ; for(int i=0;i<model()->columnCount(index); i++) { if(header->isSectionHidden(i)) continue; QRect r=itemRect(-1,i,index.row()); r=viewportRectForRow(r); paintHeader(p,r,i); } QRect r=headerRect(index.row()); r=viewportRectForRow(r); QStyleOptionFrameV3 option; option.lineWidth=r.width(); option.midLineWidth=r.width(); option.state |= QStyle::State_Sunken; r.setY(r.y()+r.height() ); option.rect=r; option.frameShape=QFrame::HLine; style()->drawControl(QStyle::CE_ShapedFrame,&option,p); for (int row = 0; row < model()->rowCount(index); ++row) { for(int j=0;j<model()->columnCount(index); j++) { if(header->isSectionHidden(j)) continue; QModelIndex in=model()->index(row,j,index); QStyleOptionViewItemV4 option = styleOptions(in); itemDelegate()->paint(p ,option,in); } } } void albumView::drawAlbum(QPainter* painter, QStyleOptionViewItemV4& option, const QModelIndex& index) const { painter->save(); if(option.state & QStyle::State_MouseOver ) { style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &option, painter ); } option.viewItemPosition = QStyleOptionViewItemV4::OnlyOne; QRect r=option.rect; r.setX(r.x()+space); r.setY(r.y()+space); QPixmap pic=views::decor->decorationPixmap(option,index); pic=pic.scaled(option.decorationSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); QRect shadowR=r; shadowR.setWidth(pic.width()); shadowR.setHeight(pic.height()); QPoint p=r.topLeft(); p.setX(p.x()+2); p.setY(p.y()+2); shadowR.moveTopLeft(p); QPainterPath shadowPath; shadowPath.addRoundedRect(shadowR,1,1); painter->setOpacity(0.5); painter->fillPath(shadowPath,Qt::black); painter->setOpacity(1); style()->drawItemPixmap(painter,r,Qt::AlignLeft|Qt::AlignTop,pic ); r.setX(r.x()+pic.width()+space +2); //draw text QString text=index.data(Qt::DisplayRole).toString(); if(text.isEmpty()) { text=tr("Unknown album"); painter->setOpacity(0.5); } painter->setFont(option.font); painter->drawText( r,option.displayAlignment, text); #if 0 int w=option.fontMetrics.boundingRect(text).width(); // r.setWidth(w+space); r.setHeight(rowHeight); option.rect=r; // option.rect.setX(r.x()-5); // option.rect.setY(r.y()-5); option.displayAlignment=Qt::AlignLeft|Qt::AlignTop; option.decorationAlignment=Qt::AlignRight|Qt::AlignTop; if(option.state & QStyle::State_Selected ) { // style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &option, painter ); } painter->setFont(option.font); painter->drawText( r,option.displayAlignment, text); r.setX(r.x()+w+20); r.setWidth(space); option.rect=r; painter->setOpacity(1); if(isExpanded(index)) style()->drawPrimitive(QStyle::PE_IndicatorArrowDown,&option,painter); else style()->drawPrimitive(QStyle::PE_IndicatorArrowRight,&option,painter); #endif painter->restore(); } void albumView::hideHeader() //this is a slot { header->setVisible(false); } void albumView::setExpanded(const QModelIndex& index, bool expanded) { if(model()==0 || !index.isValid()) return ; if(!model()->hasChildren(index) ) { return ; } if(isExpanded(index) == expanded ) return ; hashIsDirty=true; if(expanded) { this->expanded.insert(index.data(ID_ROLE).toInt()); if(model()->canFetchMore(index)) { model()->fetchMore(index); } } else { int id=index.data(ID_ROLE).toInt(); this->expanded.remove(id); storeExpanded.remove(id); } updateGeometries(); } void albumView::currentChanged(const QModelIndex& current, const QModelIndex& previous) { QAbstractItemView::currentChanged(current, previous); // setExpanded(current,true); } bool albumView::isExpanded(const QModelIndex& index) const { if(model()==0 || !index.isValid()) return false; if(!model()->hasChildren(index) ) return false; // calculateRectsIfNecessary(); return expanded.contains(index.data(ID_ROLE).toInt() ); } void albumView::updateGeometries() { calculateRectsIfNecessary(); QAbstractItemView::updateGeometries(); // updateScrollBars(); } void albumView::resizeEvent(QResizeEvent *e) { hashIsDirty = true; updateGeometries(); } void albumView::scrollContentsBy(int dx, int dy) { scrollDirtyRegion(dx, dy); viewport()->scroll(dx, dy); } QStyleOptionViewItemV4 albumView::styleOptions(const QModelIndex& index) const { QStyleOptionViewItemV4 opt = QStyleOptionViewItemV4(viewOptions() ); if(isAlbum(index)) { #if 0 if (selectionModel()->isSelected(index)) { opt.state |= QStyle::State_Selected; opt.showDecorationSelected=true; } #endif opt.viewItemPosition = QStyleOptionViewItemV4::OnlyOne; opt.rect= viewportRectForRow(albumRects[index.row()] ); // opt.rect = visualRect(index); if(hoverIndex==index ) { opt.state |= QStyle::State_MouseOver; } opt.displayAlignment=Qt::AlignLeft|Qt::AlignTop; opt.decorationSize=DECOR_SIZE; opt.font.setBold(true); } else { QModelIndex parent=index.parent(); int columns=header->count(); int pos=header->sectionPosition(index.column()); if(columns==1) { opt.viewItemPosition = QStyleOptionViewItemV4::OnlyOne; } else if(pos==columns ) { opt.viewItemPosition = QStyleOptionViewItemV4::End; } else if(pos==0) { opt.viewItemPosition = QStyleOptionViewItemV4::Beginning; } else { opt.viewItemPosition = QStyleOptionViewItemV4::Middle; } opt.rect = visualRect(index); if (selectionModel()->isSelected(index)) { opt.state |= QStyle::State_Selected; } else if(hoverIndex.isValid() && hoverIndex.row()==index.row() && hoverIndex.parent()==index.parent() ) { opt.state |= QStyle::State_MouseOver; } if(indexWidget(index)!=0) opt.features=QStyleOptionViewItemV2::None; else opt.features=QStyleOptionViewItemV2::HasDisplay; opt.displayAlignment=Qt::AlignLeft|Qt::AlignVCenter; } //we use pseudo-inactive role at the model from DISABLE_ROLE at index.data //Thus all the indexes are active opt.state & QStyle::State_Active; QPalette::ColorGroup cg=QPalette::Active; opt.palette.setCurrentColorGroup(cg); opt.fontMetrics=QFontMetrics(opt.font); return opt; } void albumView::resetSlot() { albumRects.clear(); // expanded.clear(); hashIsDirty=true; } void albumView::mouseMoveEvent(QMouseEvent* event) { QAbstractItemView::mouseMoveEvent(event); //TODO more efficient method if(model()==0) return; int i; for( i=0;i<model()->rowCount();i++) { QRect r=headerRect(i); r=viewportRectForRow(r); if(r.contains(event->pos()) ) { QModelIndex index=model()->index(i,0); headerRow=i; header->setRootIndex(index); header->setGeometry(r); // header->move(r.topLeft()); header->setVisible(true); update(); break; } } if(i==model()->rowCount() ) { header->setVisible(false); } viewport()->update(); return ; } void albumView::mousePressEvent(QMouseEvent *event) { QAbstractItemView::mousePressEvent(event); // setCurrentIndex(indexAt(event->pos())); } bool albumView::isAlbum(const QModelIndex& index) const { if(!index.isValid()) return false; return !index.parent().isValid(); } void albumView::columnsUpdated() { // qDebug()<<"IPPP "<<header->stretchSectionCount(); // header->setFixedWidth(header->sizeHint().width()); hashIsDirty=true; // calculateRectsIfNecessary(); updateGeometries (); updateScrollBars(); } void albumView::columnResized(int i) { hashIsDirty=true; columnResizeTimer.start(); } void albumView::updateScrollBars() const { horizontalScrollBar()->setRange(0, qMax(0, HEADER_OFFSET+header->length() -viewport()->width() ) ); // verticalScrollBar()->setRange(0, qMax(0, prevHeight -viewport()->height() ) ); } void albumView::paintHeader(QPainter *painter,QRect &rect, int logicalIndex) { painter->save(); rect.setX(rect.x()+2); if(logicalIndex==header->sortIndicatorSection() ) { rect.setWidth(rect.width()-20); } QString text=model()->headerData(logicalIndex,Qt::Horizontal).toString(); QFont f=painter->font(); f.setBold(true); painter->setFont(f); painter->drawText( rect,Qt::AlignLeft|Qt::AlignTop, text); painter->restore(); } QList< QUrl > albumView::getUrls(const QModelIndexList& list) const { QSet<QUrl> urlSet; foreach(QModelIndex index,list) { if(isAlbum(index)) { QSet<QUrl> l=getChildrenUrls(index); urlSet.unite(l); } else { QUrl u=index.data(URL_ROLE).toUrl(); if(u.isValid() ) { urlSet.insert(u); } } } return urlSet.toList(); } void albumView::startDrag(Qt::DropActions supportedActions) { QModelIndexList list=selectedIndexes(); QList<QUrl> urls; urls=getUrls(list); if(urls.isEmpty() ) { return ; } QMimeData *mimeData = new QMimeData; mimeData->setUrls(urls); QDrag *drag = new QDrag(this); drag->setMimeData(mimeData); drag->setPixmap(QPixmap(views::decor->tagIcon(-1).pixmap(48,48)) ); drag->exec(Qt::CopyAction|Qt::MoveAction); } void albumView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { QAbstractItemView::selectionChanged(selected, deselected); return ; #if 0 QModelIndexList l=selectionModel()->selectedIndexes(); foreach(QModelIndex index,l) { if(isAlbum(index) ) { // QModelIndex parent=topLeft; QModelIndex topLeft=model()->index(0,0,index); QModelIndex bottomRight=model()->index(model()->rowCount(index)-1,model()->columnCount(index)-1,index); QItemSelection selection(topLeft,bottomRight); selectionModel()->select(selection, QItemSelectionModel::Select); } } viewport()->update(); #endif } void albumView::mouseReleaseEvent(QMouseEvent* event) { QModelIndex current=currentIndex(); QAbstractItemView::mouseReleaseEvent(event); // return ; if(event->button()==Qt::LeftButton) { QModelIndex index=indexAt(event->pos()); if(!current.isValid() || current==index ) { setExpanded(index,!isExpanded(index)); } } } QSet<QUrl> albumView::getChildrenUrls(const QModelIndex& parent) const { QSet<QUrl> l; if(model()==0) return l; if(!model()->hasChildren(parent)) { return l; } if(model()->canFetchMore(parent) ) model()->fetchMore(parent); for(int i=0;i<model()->rowCount(parent);i++) { QModelIndex in=model()->index(i,0,parent); QUrl u=in.data(URL_ROLE).toUrl(); if(u.isValid() ) { l.insert(u); } } return l; } void albumView::doubleClickedSlot(const QModelIndex &index) { int row=0; QModelIndex parent; if(!isAlbum(index)) { parent=index.parent(); row=index.row(); } QList<QUrl> urls=getChildrenUrls(parent).toList(); core::nplList list; foreach(QUrl u,urls) { core::nplPointer t=core::nplTrack::getNplTrack(u); list<<t; } if(list.isEmpty() ) { return ; } core::npList()->clear(); core::npList()->insert(0,list); core::engine()->play(row ); } void albumView::sortModel(int logicalIndex, Qt::SortOrder order) { model()->sort(logicalIndex,order); } void albumView::writeSettings() { if (objectName().isEmpty() ) { return ; } KSharedConfigPtr config=core::config->configFile(); KConfigGroup group( config, objectName() ); group.writeEntry( "state", QVariant(header->saveState() )); group.config()->sync(); } void albumView::readSettings() { if(objectName().isEmpty()) return ; KSharedConfigPtr config=core::config->configFile(); KConfigGroup group( config, objectName() ); _headerState=group.readEntry( "state", QByteArray() ); } void albumView::contextMenuEvent(QContextMenuEvent *e) { QAbstractItemView::contextMenuEvent(e); emit showContextMenu(indexAt(e->pos() ),selectedIndexes() ); } void albumView::editCurrent() { edit( currentIndex() ); }
a533e1a87bf5e5d2983254d506474fbb0e2c9123
d00d604cbdea1d459a0b15a564d921d58b5f4276
/DnD/src/entity/Dragoon.cpp
94fac62b8bc11adcec107c983a30a2c79490fee8
[]
no_license
Iscandel/DnD
bc1fee8fe485dd1ca94ddd1c99a41a28f696a86d
82810a45ba3ba1b13ebbdd3de9961423e4a7719f
refs/heads/master
2020-06-23T17:44:33.079494
2019-07-25T00:21:08
2019-07-25T00:21:08
198,702,771
1
0
null
null
null
null
UTF-8
C++
false
false
5,158
cpp
Dragoon.cpp
#include "Dragoon.h" #include "game/Game.h" #include "game/GameEngine.h" #include "game/MessageBuilder.h" #include "gameState/serverState/SGameServer.h" Dragoon::Dragoon(int id, Game* game) :GraphicEntity(id) ,myGame(game) ,myIsAwake(false) { } Dragoon::~Dragoon() { } void Dragoon::update(GameState& state, const Game& game, unsigned int) { if (myGame->getCurrentIdTurn() != getId()) { myTimer.reset(); return; } if (myTimer.elapsedTime() < 1.5) return; myTimer.reset(); //EntityStates could be used here (sleeping, chasing...)) if (isAwake()) { Player::ptr target = chooseTarget(); if (target) moveToChoosenPlayer(state, target); else returnToTreasureRoom(state); } } bool Dragoon::onMoved(SGameServer& state) { bool handled = false; std::vector<Player::ptr> players = myGame->getPlayers(); Player::ptr player = getWeakestPlayerOnDragoonCell(); if (player) { handled = player->onArrivedOnCell(state, *this); if (handled) player->resetStepsRemaining(); } else { for (Player::ptr player : players) { bool res = player->onArrivedOnCell(state, *this); //Choose best player if they are both on the same cell if (res) { player->resetStepsRemaining(); //while (player->hasStepsRemaining()) // player->doStep(); } handled |= res; } } return handled; } Player::ptr Dragoon::getWeakestPlayerOnDragoonCell() { bool handled = false; std::vector<Player::ptr> players = myGame->getPlayers(); int minStrength = 1e6; Player::ptr res; std::vector<Player::ptr> candidates; for (Player::ptr player : players) { if (player->getAbstractPos() == getAbstractPos()) { candidates.push_back(player); } } if (candidates.size() == 0) return res; res = candidates[0]; minStrength = res->getStrength(); for (unsigned int i = 1; i < candidates.size(); i++) { if (candidates[i]->getStrength() < minStrength) { minStrength = candidates[i]->getStrength(); res = candidates[i]; } } return res; } bool Dragoon::awakeIfSucceed(const Point<int>& pos) { int sum = getDistanceTo(pos); //int sum = std::abs(pos.x - getAbstractX()) + std::abs(pos.y - getAbstractY()); if (sum == 3) { int value = myRng.random(1, 100); if (value <= 50) { awake(); return true; } } else if (sum == 2) { awake(); return true; } return false; } Player::ptr Dragoon::chooseTarget() { Player::ptr res; std::vector<Player::ptr> players = myGame->getPlayers(); double minDist = 1e6; for (Player::ptr player : players) { if (player->hasTreasure()) return player; double tmp = getEuclideanDistanceTo(player->getAbstractPos()); if (tmp < minDist && !player->isInSecretRoom()) { minDist = tmp; res = player; } } return res; } int Dragoon::getDistanceTo(const Point<int>& pos) { return std::abs(pos.x - getAbstractX()) + std::abs(pos.y - getAbstractY()); } double Dragoon::getEuclideanDistanceTo(const Point<int>& pos) { return std::sqrt(std::pow(pos.x - getAbstractX(), 2) + std::pow(pos.y - getAbstractY(), 2)); } void Dragoon::moveToChoosenPlayer(GameState& state, Player::ptr player) { int diffX = getAbstractX() - player->getAbstractX(); int diffY = getAbstractY() - player->getAbstractY(); Direction vert = diffY > 0 ? Direction::NORTH : diffY == 0 ?Direction::NONE : Direction::SOUTH; Direction horiz = diffX > 0 ? Direction::WEST : diffX == 0 ? Direction::NONE : Direction::EAST; Message msg = MessageBuilder::clDragoonMoves(vert, horiz); //state.getGameEngine()->processMessage(msg); state.sendMessage(msg, getId()); } void Dragoon::returnToTreasureRoom(GameState& state) { Treasure::ptr treasure = myGame->getTreasure(); int diffX = getAbstractX() - treasure->getAbstractX(); int diffY = getAbstractY() - treasure->getAbstractY(); Direction vert = diffY > 0 ? Direction::NORTH : diffY == 0 ? Direction::NONE : Direction::SOUTH; Direction horiz = diffX > 0 ? Direction::WEST : diffX == 0 ? Direction::NONE : Direction::EAST; Message msg = MessageBuilder::clDragoonMoves(vert, horiz); //state.getGameEngine()->processMessage(msg); state.sendMessage(msg, getId()); } //Dragoon receives player that just moved bool Dragoon::onArrivedOnCell(SGameServer& state, Player& player) { if (!isAwake()) { if (awakeIfSucceed(player.getAbstractPos())) { Message msg = MessageBuilder::clDragonAwakes(); state.processMessage(msg); return true; } } else { if (isReadyToAttack(player.getAbstractPos())) { attack(state, player); return true; } } return false; } bool Dragoon::onArrivedOnCell(SGameServer&, Dragoon&) { return false; } bool Dragoon::isReadyToAttack(const Point<int>& pos) { if (pos == getAbstractPos()) return true; return false; } void Dragoon::attack(SGameServer& state, Player& target) { if (target.hasTreasure()) { Game& game = state.getGameEngine()->getGame(); Treasure::ptr treasure = game.getTreasure(); treasure->setTaken(false); Message msg = MessageBuilder::clPlayerLooses(target.getId()); state.processMessage(msg); } else { Message msg = MessageBuilder::clPlayerWounded(target.getId()); state.processMessage(msg); } }
6a465ea2280a93837a1c5c16b02fdba82046cade
86786a0141a3d5afa3974d6e87c13987215b1f67
/5_more_struct.cpp
8d57307ecab982d35ee601c6504a8beb5476f97a
[]
no_license
ZhangKangK/C-PlusPlus
6d4c35804d9409d61fd988ceb62ede6c2aa0405a
1d3bde40b998b8c56c1593b3cdb859eebe849464
refs/heads/master
2021-08-19T13:41:39.164932
2017-11-26T12:41:01
2017-11-26T12:41:01
112,079,481
0
0
null
null
null
null
GB18030
C++
false
false
347
cpp
5_more_struct.cpp
#include <iostream> using namespace std; struct Student { int id; char name[20]; }; int main() { // C++中的结构体是一种新的数据类型,可以直接拿来定义变量,不需要再加 struct 关键字 Student stu = {10, "wang"}; cout << "id = " << stu.id << ", name = " << stu.name << endl; return 0; }
c541dd05fb442ab21a1670f5824fff7cfb24235e
b70d6567f266bd4ec60b6ea292344f8e71127c54
/labworks/lw04/Guskova/OC_lab4/lab4_41/main.cpp
907b3bc46c3d5642aaf6b8b8951684e721f3b781
[]
no_license
vladdy-moses/ulstu-ivk-os-2019
3766e15d1a0a6b64e9c1ce5dba86d786296abd6d
26727bd7961a57f9a6256033a1d95de61703762e
refs/heads/master
2020-04-28T02:52:26.347851
2019-06-13T09:42:54
2019-06-13T09:42:54
174,914,608
1
34
null
2019-06-13T09:42:55
2019-03-11T02:52:56
C
WINDOWS-1251
C++
false
false
1,678
cpp
main.cpp
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <string.h> //Лабораторная работа №4.4.1 //Межпроцессное взаимодействие через канал FIFO. //Выполнила студентка гр.ИСТбд-22 Гуськова Ю.А. int main() { printf("Лабораторная работа №4.4.1\n"); printf("Межпроцессное взаймодействие через канал FIFO\n"); printf("Выполнила студентка гр.ИСТбд-22 Гуськова Ю.А.\n"); printf("Задание: напишите на базе предыдущего примера две программы, одна\ из которых пишет информацию в FIFO, а вторая – читает из него, так чтобы между ними не было\ ярко выраженных родственных связей (т.е. чтобы ни одна из них не была потомком другой).\n"); int fd; size_t size; char result[1024]; printf("Открываем FIFO на чтение...\n"); fd = open("/home/student/Documents/OC_lab4/lab4_4/fifo", O_RDONLY); printf("Начало чтения...\n"); char *s = result;// считываемый символ do { size = read(fd, s, 1); s++; } while (size != 0);//считоваем по одному символу пока они не закончатся printf("Данные прочитаны\n"); printf("Результат: %s\n", result); close(fd); return 0; }
d01da45421477beb68dc4636f803504f1d54fd48
cb49c2c846eb29252ed37a885b7b3a546168c998
/src/affinetransform.cpp
498c756d85b67c9bf337cc928f02093cbcb02dc6
[ "curl", "MIT", "BSL-1.0" ]
permissive
appelmar/scidb4gdal
60dba13b18fb7a4cb9f054cecff13ac6c2a17305
d040fe41761ab72a2cf1169b002df2c413e9ffad
refs/heads/master
2021-06-14T05:05:46.595161
2017-04-13T06:44:44
2017-04-13T06:44:44
31,667,264
10
4
null
2017-04-13T06:44:45
2015-03-04T16:31:43
C++
UTF-8
C++
false
false
7,950
cpp
affinetransform.cpp
/* Copyright (c) 2016 Marius Appel <marius.appel@uni-muenster.de> This file is part of scidb4gdal. scidb4gdal is licensed under the MIT license. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -----------------------------------------------------------------------------*/ #include "affinetransform.h" #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <sstream> #include <vector> #include <iomanip> #include <limits> #include "utils.h" namespace scidb4gdal { using namespace std; AffineTransform::AffineTransform() : _x0(0), _y0(0), _a11(1), _a22(1), _a12(0), _a21(0), _inv(NULL) {} AffineTransform::AffineTransform(double x0, double y0) : _x0(x0), _y0(y0), _a11(1), _a22(1), _a12(0), _a21(0), _inv(NULL) {} AffineTransform::AffineTransform(double x0, double y0, double a11, double a22) : _x0(x0), _y0(y0), _a11(a11), _a22(a22), _a12(0), _a21(0), _inv(NULL) {} AffineTransform::AffineTransform(double x0, double y0, double a11, double a22, double a12, double a21) : _x0(x0), _y0(y0), _a11(a11), _a22(a22), _a12(a12), _a21(a21), _inv(NULL) { } AffineTransform::AffineTransform(const string& astr) : _x0(0), _y0(0), _a11(1), _a22(1), _a12(0), _a21(0), _inv(NULL) { vector<string> parts; boost::split(parts, astr, boost::is_any_of(",; ")); for (vector<string>::iterator it = parts.begin(); it != parts.end(); ++it) { vector<string> kv; boost::split(kv, *it, boost::is_any_of("=:")); if (kv.size() != 2) { stringstream serr; serr << "Cannot read affine transformation string '" << astr << "'"; Utils::error(serr.str()); break; } else { if (kv[0].compare("x0") == 0) _x0 = boost::lexical_cast<double>(kv[1]); else if (kv[0].compare("y0") == 0) _y0 = boost::lexical_cast<double>(kv[1]); else if (kv[0].compare("a11") == 0) _a11 = boost::lexical_cast<double>(kv[1]); else if (kv[0].compare("a22") == 0) _a22 = boost::lexical_cast<double>(kv[1]); else if (kv[0].compare("a12") == 0) _a12 = boost::lexical_cast<double>(kv[1]); else if (kv[0].compare("a21") == 0) _a21 = boost::lexical_cast<double>(kv[1]); else { stringstream serr; serr << "Unknown affine transformation parameter '" + kv[0] + "' will be ignored "; Utils::warn(serr.str()); } } } } AffineTransform::~AffineTransform() { if (_inv) { _inv->_inv = NULL; // No recursive deletes!!! delete _inv; _inv = NULL; } } string AffineTransform::toString() { stringstream sstr; sstr << setprecision(numeric_limits<double>::digits10) << "x0" << "=" << _x0 << " " << "y0" << "=" << _y0 << " " << "a11" << "=" << _a11 << " " << "a22" << "=" << _a22 << " " << "a12" << "=" << _a12 << " " << "a21" << "=" << _a21; return sstr.str(); } bool AffineTransform::isIdentity() { return (_a11 == 1 && _a12 == 0 && _a21 == 0 && _a22 == 1 && _x0 == 0 && _y0 == 0); } AffineTransform::double2 AffineTransform::f(const double2& v) { double2 result; result.x = _x0 + _a11 * v.x + _a12 * v.y; result.y = _y0 + _a21 * v.x + _a22 * v.y; return result; } void AffineTransform::f(const AffineTransform::double2& v_in, AffineTransform::double2& v_out) { v_out.x = _x0 + _a11 * v_in.x + _a12 * v_in.y; v_out.y = _y0 + _a21 * v_in.x + _a22 * v_in.y; } void AffineTransform::f(AffineTransform::double2& v) { double x = v.x; v.x = _x0 + _a11 * v.x + _a12 * v.y; v.y = _y0 + _a21 * x + _a22 * v.y; } AffineTransform::double2 AffineTransform::fInv(const double2& v) { if (_inv == NULL) { double d = det(); if (fabs(d) < DBL_EPSILON) { Utils::error("Affine transformation not invertible, det=0"); } double d1 = 1 / d; double inv_a11 = d1 * _a22; double inv_a12 = d1 * (-_a12); double inv_a21 = d1 * (-_a21); double inv_a22 = d1 * _a11; double inv_x0 = -inv_a11 * _x0 + inv_a12 * _y0; double inv_y0 = inv_a21 * _x0 - inv_a22 * _y0; _inv = new AffineTransform(inv_x0, inv_y0, inv_a11, inv_a22, inv_a12, inv_a21); _inv->_inv = this; // Prevent repreated computations of f, f-1, f, f-1, ... // This is dangerous in destruction... } return _inv->f(v); } void AffineTransform::fInv(const AffineTransform::double2& v_in, AffineTransform::double2& v_out) { if (_inv == NULL) { double d = det(); if (fabs(d) < DBL_EPSILON) { Utils::error("Affine transformation not invertible, det=0"); } double d1 = 1 / d; double inv_a11 = d1 * _a22; double inv_a12 = d1 * (-_a12); double inv_a21 = d1 * (-_a21); double inv_a22 = d1 * _a11; double inv_x0 = -inv_a11 * _x0 + inv_a12 * _y0; double inv_y0 = inv_a21 * _x0 - inv_a22 * _y0; _inv = new AffineTransform(inv_x0, inv_y0, inv_a11, inv_a22, inv_a12, inv_a21); _inv->_inv = this; // Prevent repreated computations of f, f-1, f, f-1, ... // This is dangerous in destruction... } _inv->f(v_in, v_out); } void AffineTransform::fInv(AffineTransform::double2& v) { if (_inv == NULL) { double d = det(); if (fabs(d) < DBL_EPSILON) { Utils::error("Affine transformation not invertible, det=0"); } double d1 = 1 / d; double inv_a11 = d1 * _a22; double inv_a12 = d1 * (-_a12); double inv_a21 = d1 * (-_a21); double inv_a22 = d1 * _a11; double inv_x0 = -inv_a11 * _x0 + inv_a12 * _y0; double inv_y0 = inv_a21 * _x0 - inv_a22 * _y0; _inv = new AffineTransform(inv_x0, inv_y0, inv_a11, inv_a22, inv_a12, inv_a21); _inv->_inv = this; // Prevent recursive computations of f, f-1, f, f-1, ... This is dangerous in destruction... } _inv->f(v); } double AffineTransform::det() { return _a11 * _a22 - _a12 * _a21; } }
fd1a9730bdfdaa2b04ce9b0837fc103882b3f86b
01e1525dba795c49d403ab7c513bd896c2d96c4b
/牛客/third-A.cpp
5070600e466f1cb23ddcd0d49540399edbd9b367
[]
no_license
Dyryamo/algorithm
c24bc3b92fa280af258966cbd149c4ad734c5480
0100f2d4e6cc69caa268a910adebb95cebda6ce0
refs/heads/master
2021-04-26T04:00:21.969733
2018-03-08T05:12:18
2018-03-08T05:12:18
103,379,896
0
0
null
null
null
null
UTF-8
C++
false
false
404
cpp
third-A.cpp
#include<iostream> #include<cstdio> #include<cstring> #include<math.h> #include<algorithm> using namespace std; #define PI 3.1615926535 double log8=log(8); double f(int n){ return (0.5*log(2)+0.572364929+0.5*log(n)+n*log(n)-n)/log8; } int main(){ int T; scanf("%d",&T); while(T--){ int n; scanf("%d",&n); if(n==1||n==0){ printf("1\n"); } else { printf("%d\n",(int)(f(n))+1); } } }
71c4b2a6ad1354d71eb98ff194de72dea2a9bb3d
ae936fb07d9478152cb998e94b9937d625f5c3dd
/UVA/11624.cpp
5c9a182f7e07607c001f6988ece0112307f60c98
[]
no_license
Jorgefiestas/CompetitiveProgramming
f035978fd2d3951dbd1ffd14d60236ef548a1974
b35405d6be5adf87e9a257be2fa0b14f5eba3c83
refs/heads/master
2021-06-12T06:28:20.878137
2021-04-21T01:32:37
2021-04-21T01:32:37
164,651,348
0
0
null
null
null
null
UTF-8
C++
false
false
1,298
cpp
11624.cpp
#include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; int t, n, m; string maze[1000]; int dx[4] = {-1, 0, 0, 1}; int dy[4] = {0, -1, 1, 0}; int solve() { cin >> n >> m; for (int i = 0; i < n; i++) { cin >> maze[i]; } int r[1000][1000]; queue<pii> pq; queue<bool> tq; pii J; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (maze[i][j] == 'J') { J = {i, j}; r[i][j] = 0; } else if (maze[i][j] == 'F') { pq.push({i, j}); tq.push(false); r[i][j] = 0; } } } pq.push(J); tq.push(true); while (!pq.empty()) { pii v = pq.front(); bool state = tq.front(); pq.pop(); tq.pop(); for (int i = 0; i < 4; i++) { int nx = v.first + dx[i]; int ny = v.second + dy[i]; char tile = maze[nx][ny]; if (nx >= n || nx < 0 || ny >= m || ny < 0) { if (state) { return r[v.first][v.second] + 1; } continue; } if (tile == '.') { pq.push({nx, ny}); tq.push(state); maze[nx][ny] = 'F'; r[nx][ny] = r[v.first][v.second] + 1; } } } return -1; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> t; while (t--) { int ans = solve(); if (ans != -1) { cout << ans << endl; } else { cout << "IMPOSSIBLE" << endl; } } return 0; }
7b53e6c8cd7f919b30cc8f16773640aed4debaab
019ad59225930e297336939183b652c7c7a1aa6e
/http/httpParser.h
883c4430bdec08c9d79819f0fdec3b8bd78e9cc1
[]
no_license
Yeonon-Wyy/budd
c8b7fbfc8fe9e039bb11f68ccf8bd0372e6a594c
d6771f02977cb4ef38d100dde0ed4113b5389b7a
refs/heads/master
2023-07-24T23:25:36.017330
2020-10-11T12:31:12
2020-10-11T12:31:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
884
h
httpParser.h
#ifndef HTTPPARSER #define HTTPPARSER #include <memory> #include "base/buffer.h" namespace budd { namespace http { class HttpContext; class HttpRequest; class HttpParser { public: HttpParser() : m_state(EXPECTSTARTLINE) { } bool parse(base::Buffer *buffer, std::shared_ptr<HttpContext> context); private: bool parseStartLine(const char *start, const char *end, HttpRequest *request); bool parseHeaderLine(const char *start, const char *end, HttpRequest *request); bool parseQueryParam(const char *start, const char *end, HttpRequest *request); bool parseFormBody(const char *start, const char *end, HttpRequest *request); enum HttpParseState { EXPECTSTARTLINE, EXPECTHEADERLINE, EXPECTBODY, INVALID, FINISH, }; HttpParseState m_state; }; } //namespace budd } //namespace http #endif
d4526ec1d5d633b0d1e0f68563ac6079d43a8dd6
67d616bdde1b978f6d43a0d540471ec111a93827
/cpp/inheritance_review/Review-06-CPP-Shapes/Example-3/source/ShapeCollection.cpp
f346492d117de3c7da1565a0d2b907ecacb271fb
[]
no_license
Crusaton/cs330fall2020
6efad5dcd0d14bca6a2bba00129c9a43e3964769
282827769eb4f737b6c12ac730cee90f73a2ff45
refs/heads/main
2023-01-30T11:19:04.390813
2020-12-08T01:13:28
2020-12-08T01:13:28
314,138,571
0
0
null
null
null
null
UTF-8
C++
false
false
1,555
cpp
ShapeCollection.cpp
#include <utility> #include <algorithm> #include "ShapeCollection.h" //------------------------------------------------------------------------------ ShapeCollection::ShapeCollection() :shapes() // Is this necessary? { } //------------------------------------------------------------------------------ ShapeCollection::ShapeCollection(int n) { shapes.reserve(n); } //------------------------------------------------------------------------------ ShapeCollection::ShapeCollection(const ShapeCollection& src) { for (const Shape* s : src.shapes) { shapes.push_back(s->clone()); } } //------------------------------------------------------------------------------ ShapeCollection::~ShapeCollection() { for (Shape* s : this->shapes) { delete s; } } //------------------------------------------------------------------------------ bool ShapeCollection::addShape(Shape* toAdd) { if (toAdd == nullptr) { return false; } shapes.push_back(toAdd); return true; } //------------------------------------------------------------------------------ ShapeCollection& ShapeCollection::operator=(ShapeCollection rhs) { std::swap(*this, rhs); return *this; } //------------------------------------------------------------------------------ void ShapeCollection::display(std::ostream& outs) const { for (const Shape* s : this->shapes) { outs << *s << "\n"; } } void swap(ShapeCollection& lhs, ShapeCollection& rhs) { using std::swap; swap(lhs.shapes, rhs.shapes); }
87b9b41463a320288afcdedc04f960136d7a785b
8fb8ddf3d5f310ae94c61dd72467a644ce3f8ad1
/libraries/shifter_example2/shifter_example2.ino/shifter_example2.ino.ino
5321e7b41a085c0c1191f574d5a72b25990a64d3
[ "MIT" ]
permissive
scarybeard/Pinball_01
4340174bc7f9c21984c35fc0f0a872113228566c
e6c1a835d5c65a121e7c6c1aa6890844d0642b5c
refs/heads/master
2020-04-02T03:31:51.195405
2016-07-09T21:07:37
2016-07-09T21:07:37
60,320,949
0
0
null
null
null
null
UTF-8
C++
false
false
1,303
ino
shifter_example2.ino.ino
#include <Shifter.h> #define SER_Pin 7 //SER_IN #define RCLK_Pin 6 //L_CLOCK #define SRCLK_Pin 8 //CLOCK #define NUM_REGISTERS 2 //how many registers are in the chain //initaize shifter using the Shifter library Shifter shifter(SER_Pin, RCLK_Pin, SRCLK_Pin, NUM_REGISTERS); const int redLight = 12; const int button0 = A0; const int button1 = A1; boolean lastReadButton0; boolean lastReadButton1; int buttonState = 0; int score_1 = 0; void setup(){ pinMode(redLight, OUTPUT); pinMode(button0, INPUT); pinMode(button1, INPUT); } void loop(){ shifter.setPin(2, HIGH); shifter.setPin(3, HIGH); shifter.setPin(4, HIGH); shifter.setPin(5, HIGH); shifter.setPin(6, HIGH); shifter.setPin(7, HIGH); shifter.write(); ///SCORE a 100 PTS////////////////////////////////////////////// boolean readButton0 = digitalRead(button0); if (readButton0 == LOW and lastReadButton0 == HIGH) { shifter.setPin(1, HIGH); shifter.write(); } lastReadButton0 = readButton0; ///SCORE a 100 PTS////////////////////////////////////////////// boolean readButton1 = digitalRead(button1); if (readButton1 == LOW and lastReadButton1 == HIGH) { shifter.setPin(1, LOW); shifter.write(); } lastReadButton1 = readButton1; }
ea628a242c0ab3a6cd03f03040b2bb9adab50e8b
291401bb1fa7f07e906f5d3551585101afbd848a
/SimulationControl.cpp
484b67d81105a82ffb82018ce34cfc78ecbb1358
[]
no_license
ljmotta/2019_2022_GenESyS
65c1dad3ab077bcfa1f4f2ac92203362cf4b5841
2d3331ec1998c9ac0cd88b2a826472fcff48e795
refs/heads/master
2023-04-12T14:41:39.638474
2021-04-24T12:34:32
2021-04-24T12:34:32
350,146,492
1
0
null
2021-04-09T17:39:11
2021-03-21T23:28:32
C++
UTF-8
C++
false
false
800
cpp
SimulationControl.cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: SimulationControl.cpp * Author: rafael.luiz.cancian * * Created on 10 de Outubro de 2018, 18:01 */ #include "SimulationControl.h" //using namespace GenesysKernel; SimulationControl::SimulationControl(std::string type, std::string name, GetterMember getterMember, SetterMember setterMember) : SimulationResponse(type, name, getterMember) { this->_type = type; this->_setMemberFunction = setterMember; } std::string SimulationControl::show() { return "name=" + this->_name + ", type=" + this->_type; } void SimulationControl::setValue(double value) { this->_setMemberFunction(value); }
84527f2c68c548b0022803a481d44d694df4d351
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/collectd/gumtree/collectd_repos_function_2250_collectd-5.6.1.cpp
5b41b77fd5fb211b9c2dcc09e823019a24303ae5
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
80
cpp
collectd_repos_function_2250_collectd-5.6.1.cpp
void oconfig_free (oconfig_item_t *ci) { oconfig_free_all (ci); free (ci); }
b45389eb6b4ec03f95d1583bb716bbcda1bfa493
d867e76750cfaf6aec301a6c104bee9121f03655
/src/Rendu/Map.cpp
e15fa024511e0ffd266c0f74f3177107ca079159
[]
no_license
AnaisVincent/DuelMaster
778ce6c24cc9740486a0723665eac186879979f0
505d0c53c77cb2e0969722ad36c2e1b06ca347b7
refs/heads/master
2021-03-12T20:04:24.021434
2016-01-14T19:31:26
2016-01-14T19:31:26
42,943,504
0
0
null
null
null
null
UTF-8
C++
false
false
5,068
cpp
Map.cpp
#include "../Rendu_headers/Moteur_de_Rendu.hpp" using namespace Moteur_de_Rendu; Map::Map() { } Map::~Map() { } void Map::levelMap() { w = 48; h = 24; level = { 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 70, 20, 21, 21, 21, 21, 21, 21, 21, 21, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 70, 20, 21, 21, 21, 40, 21, 21, 01, 01, 01, 01, 01, 01, 01, 21, 21, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 25, 25, 26, 21, 21, 21, 28, 25, 25, 25, 25, 26, 21, 21, 21, 28, 25, 25, 70, 20, 21, 21, 40, 40, 21, 21, 21, 01, 01, 01, 01, 21, 21, 21, 21, 21, 21, 01, 01, 01, 40, 40, 40, 40, 01, 01, 01, 01, 25, 26, 21, 21, 21, 21, 21, 21, 28, 25, 26, 21, 21, 21, 21, 21, 21, 28, 25, 26, 21, 21, 21, 21, 21, 21, 21, 21, 01, 01, 21, 21, 21, 21, 21, 21, 21, 21, 21, 40, 40, 21, 40, 40, 40, 01, 01, 01, 25, 26, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 01, 21, 21, 21, 28, 70, 20, 21, 21, 21, 21, 21, 21, 21, 21, 01, 01, 21, 21, 01, 01, 01, 21, 21, 21, 21, 21, 21, 21, 21, 40, 40, 40, 01, 25, 26, 21, 21, 40, 40, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 40, 40, 21, 28, 70, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 01, 01, 01, 01, 21, 21, 01, 01, 21, 21, 21, 40, 40, 01, 25, 26, 21, 21, 21, 21, 40, 21, 21, 41, 41, 41, 41, 41, 41, 21, 21, 40, 21, 21, 28, 26, 21, 21, 41, 41, 41, 41, 41, 41, 41, 41, 41, 21, 21, 21, 01, 21, 21, 21, 21, 01, 01, 21, 21, 21, 40, 01, 25, 26, 21, 21, 21, 21, 01, 01, 21, 41, 21, 21, 21, 21, 41, 41, 41, 21, 21, 21, 21, 21, 21, 41, 41, 21, 21, 01, 01, 21, 21, 21, 41, 41, 41, 41, 41, 21, 21, 21, 21, 21, 21, 21, 21, 21, 40, 01, 25, 70, 20, 21, 21, 21, 21, 21, 41, 41, 21, 01, 21, 40, 21, 21, 41, 41, 41, 41, 41, 41, 41, 41, 21, 21, 21, 21, 01, 01, 01, 21, 01, 01, 01, 01, 41, 41, 41, 41, 21, 21, 21, 21, 21, 40, 01, 01, 28, 25, 70, 20, 21, 21, 21, 21, 41, 21, 21, 21, 21, 21, 21, 21, 21, 40, 18, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 01, 01, 01, 01, 01, 40, 40, 40, 41, 21, 21, 21, 21, 21, 40, 40, 01, 01, 01, 21, 28, 25, 26, 21, 21, 21, 21, 41, 21, 21, 21, 21, 21, 21, 18, 19, 19, 24, 26, 21, 21, 21, 21, 21, 40, 21, 21, 01, 01, 01, 01, 01, 40, 21, 21, 41, 41, 21, 21, 01, 01, 01, 01, 01, 01, 01, 01, 21, 40, 28, 70, 19, 20, 21, 21, 41, 21, 18, 20, 40, 18, 19, 24, 25, 25, 26, 21, 21, 40, 21, 21, 40, 21, 21, 21, 21, 01, 01, 01, 01, 21, 21, 21, 41, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 01, 21, 21, 21, 28, 25, 26, 40, 41, 41, 21, 28, 70, 19, 24, 25, 25, 25, 26, 21, 21, 40, 40, 21, 21, 21, 21, 21, 21, 21, 21, 21, 40, 40, 21, 21, 21, 41, 21, 01, 01, 01, 01, 01, 40, 40, 21, 21, 21, 40, 21, 21, 40, 28, 26, 21, 41, 21, 21, 28, 25, 25, 25, 25, 25, 26, 21, 21, 21, 40, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 41, 21, 40, 40, 01, 01, 21, 21, 21, 21, 21, 21, 52, 40, 21, 18, 24, 26, 21, 41, 21, 21, 28, 25, 25, 25, 25, 25, 26, 21, 21, 21, 21, 41, 41, 41, 41, 41, 21, 21, 21, 21, 21, 21, 21, 40, 40, 21, 41, 21, 21, 21, 21, 21, 21, 21, 21, 21, 40, 21, 40, 21, 21, 28, 26, 21, 21, 41, 40, 40, 21, 21, 21, 40, 28, 25, 70, 20, 21, 21, 21, 41, 21, 21, 21, 41, 41, 41, 41, 41, 21, 21, 21, 21, 21, 21, 41, 21, 21, 21, 33, 21, 21, 21, 21, 21, 21, 21, 21, 21, 18, 24, 26, 21, 41, 41, 21, 21, 40, 40, 21, 21, 40, 28, 25, 26, 21, 21, 41, 41, 21, 40, 21, 21, 21, 21, 21, 41, 41, 41, 41, 21, 21, 21, 41, 21, 21, 21, 21, 21, 40, 21, 21, 21, 33, 33, 21, 21, 28, 26, 40, 21, 41, 01, 21, 52, 40, 21, 21, 21, 21, 21, 28, 26, 21, 21, 41, 21, 40, 40, 01, 21, 21, 21, 40, 40, 40, 21, 41, 41, 41, 41, 41, 21, 21, 21, 21, 21, 21, 21, 33, 33, 33, 52, 21, 21, 21, 21, 40, 21, 41, 21, 21, 21, 21, 01, 52, 21, 21, 21, 21, 21, 21, 21, 41, 21, 40, 01, 01, 40, 40, 01, 01, 01, 01, 40, 40, 21, 21, 21, 41, 41, 41, 21, 21, 21, 33, 33, 33, 33, 33, 33, 40, 40, 21, 21, 21, 21, 41, 41, 41, 41, 21, 40, 40, 40, 01, 21, 21, 41, 41, 41, 41, 21, 40, 40, 01, 01, 01, 01, 40, 40, 40, 21, 21, 21, 33, 21, 21, 21, 41, 41, 41, 33, 33, 52, 33, 33, 33, 33, 40, 21, 21, 21, 21, 21, 21, 21, 21, 41, 41, 41, 41, 41, 41, 41, 41, 41, 21, 21, 21, 21, 21, 40, 01, 01, 01, 40, 21, 21, 21, 21, 33, 21, 21, 21, 21, 21, 21, 21, 41, 33, 33, 33, 33, 33, 33, 33, 40, 40, 21, 21, 21, 40, 40, 40, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 40, 40, 21, 01, 01, 01, 40, 40, 21, 21, 21, 33, 52, 33, 21, 21, 21, 21, 33, 33, 41, 41, 41, 33, 33, 52, 33, 33, 40, 40, 40, 21, 40, 40, 52, 40, 40, 40, 40, 40, 21, 21, 21, 21, 21, 40, 40, 40, 40, 01, 40, 40, 01, 01, 01, 01, 21, 21, 21, 21, 21, 33, 21, 21, 21, 33, 52, 33, 33, 33, 33, 33, 33, 33, 33, 33, 52, 40, 40, 40, 40, 40, 40, 40, 01, 40, 40, 40, 52, 40, 40, 01, 40, 40, 01, 52, 01, 40, 40, 01, 01, 01, 01, 01, 01, 21, 21, 21, 21, 21, 21, 21, 33, 33, 33, 33, 33, 33, 52, 33, 33, 33, 33, 33, }; } void Map::levelDuel() { } std::vector<int> Map::getlevel() { return level; } const int Map::getnumber(int x, int y) { return level[x + (y * w)]; } const int Map::getheight() { return h; } const int Map::getwidth() { return w; }
58b89ab97a836af9ebd95977511fdc6e8def813c
0d4b07303fe9facd5ab1464ceec12d69316f1773
/src/ProgramSegment.cpp
24edf8703f2f4c52920276c58d147b701f1528f3
[]
no_license
ricardobg/EventSimulator
9d8b0850775a66e5f8d2da5ce526a4524b7231d3
a704f0ebf4f62b6357232c8447b3ce3abbc99093
refs/heads/master
2021-01-15T08:49:25.102380
2015-08-01T13:09:20
2015-08-01T13:09:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,308
cpp
ProgramSegment.cpp
/* * ProgramSegment.cpp * * Created on: 06/06/2015 * Author: Ricardo */ #include "include/Job.h" #include "include/ProgramSegment.h" #include "include/MemorySegment.h" #include "include/Debug.h" ProgramSegment::ProgramSegment(int64_t segment_number, int64_t size, ProgramSegment* parent) : _segment_number(segment_number), _size(size), _parent(parent) { _memory = nullptr; } const Job* ProgramSegment::SegmentJob() const { return _job; } void ProgramSegment::SegmentJob(Job* job) { _job = job; } ProgramSegment& ProgramSegment::AddChild(const ProgramSegment& child) { std::set<ProgramSegment>::iterator it = _children.insert(child).first; ProgramSegment& ret = const_cast<ProgramSegment&>(*it); ret._parent = this; ret._job = _job; return ret; } ProgramSegment* ProgramSegment::Parent() { return _parent; } const std::set<ProgramSegment>& ProgramSegment::Children() const { return _children; } int64_t ProgramSegment::Size() const { return _size; } int64_t ProgramSegment::Number() const { return _segment_number; } bool ProgramSegment::operator<(const ProgramSegment& other) const { return _segment_number < other._segment_number; } void ProgramSegment::Memory(MemorySegment* memory) { _memory = memory; } MemorySegment* ProgramSegment::Memory() { return _memory; }
e762130d1df79d0675c646c7f3de5104fac7bea8
e753f8ab10eb6732f272217169e48ab4754295ee
/devel/boost-libs/dragonfly/patch-boost_system_config.hpp
690b7684d710d1fc7089efdf003db66f4a00afa4
[ "BSD-2-Clause" ]
permissive
DragonFlyBSD/DPorts
dd2e68f0c11a5359bf1b3e456ab21cbcd9529e1c
4b77fb40db21fdbd8de66d1a2756ac1aad04d505
refs/heads/master
2023-08-12T13:54:46.709702
2023-07-28T09:53:12
2023-07-28T09:53:12
6,439,865
78
52
NOASSERTION
2023-09-02T06:27:16
2012-10-29T11:59:35
null
UTF-8
C++
false
false
595
hpp
patch-boost_system_config.hpp
No push, lets try to reduce deprecated support in this. Keep NEEDS just in case. --- boost/system/config.hpp.orig 2016-09-21 17:33:27.000000000 +0300 +++ boost/system/config.hpp @@ -10,6 +10,12 @@ #ifndef BOOST_SYSTEM_CONFIG_HPP #define BOOST_SYSTEM_CONFIG_HPP +#if defined(__DragonFly__) && !defined(BOOST_SYSTEM_NEEDS_DEPRECATED) +#ifndef BOOST_SYSTEM_NO_DEPRECATED +#define BOOST_SYSTEM_NO_DEPRECATED +#endif +#endif + #include <boost/config.hpp> #include <boost/predef/platform.h> #include <boost/system/api_config.hpp> // for BOOST_POSIX_API or BOOST_WINDOWS_API
e66440dc8effb0397cc704d06765082e1f42bd61
e86fcbd73260f184a678bac683bb4ed687649355
/src/opendnp3/gen/StaticFrozenCounterVariation.h
25af5ef8f5db3b2fd7ad20304e4f0689eff97f15
[]
no_license
kyle8615/ddd
5b725b438e004e5670c62cf3d82417e05dc743fa
fa891318224af1d69f248d2fbcf1819d6e230133
refs/heads/master
2023-04-09T15:44:32.350679
2020-04-29T15:16:25
2020-04-29T15:16:25
258,099,556
0
0
null
2021-04-20T19:49:04
2020-04-23T05:04:17
C++
UTF-8
C++
false
false
1,028
h
StaticFrozenCounterVariation.h
#ifndef PYDNP3_OPENDNP3_GEN_STATICFROZENCOUNTERVARIATION_H #define PYDNP3_OPENDNP3_GEN_STATICFROZENCOUNTERVARIATION_H #include <Python.h> #include <pybind11/pybind11.h> #include <opendnp3/gen/StaticFrozenCounterVariation.h> #ifdef PYDNP3_OPENDNP3 namespace py = pybind11; using namespace std; void bind_StaticFrozenCounterVariation(py::module& m) { // ----- enum class: opendnp3::StaticFrozenCounterVariation py::enum_<opendnp3::StaticFrozenCounterVariation>(m, "StaticFrozenCounterVariation") .value("Group21Var1", opendnp3::StaticFrozenCounterVariation::Group21Var1) .value("Group21Var2", opendnp3::StaticFrozenCounterVariation::Group21Var2) .value("Group21Var5", opendnp3::StaticFrozenCounterVariation::Group21Var5) .value("Group21Var6", opendnp3::StaticFrozenCounterVariation::Group21Var6) .value("Group21Var9", opendnp3::StaticFrozenCounterVariation::Group21Var9) .value("Group21Var10", opendnp3::StaticFrozenCounterVariation::Group21Var10); } #endif // PYDNP3_OPENDNP3 #endif
e5c8f02259dcd9e015268301e8c89e9638cd9069
cab800f3e7fd25c30483065256c014957dc2ad76
/CppProject5_3D/CppProject5/src/renderEngine/SelectionRenderer.h
5102d3d7fbc3d55f224616ca6ff22e393655f56e
[ "MIT" ]
permissive
Damoy/Cpp-3D-game-engine
461fefd19a56ee30d97e3e25412ac300e7d42fd0
a6f1ec9fd5e7c26ade5528828cc576f5ed45394a
refs/heads/master
2021-09-01T07:59:43.068557
2017-12-25T22:00:47
2017-12-25T22:00:47
115,257,370
1
0
null
null
null
null
UTF-8
C++
false
false
1,151
h
SelectionRenderer.h
#pragma once #include <sstream> #include "Renderer.h" #include "entities\graphics\Camera.h" #include "shaders\SelectionShader.h" #include "models\TexturedModel.h" #include "input\InputController.h" #include "loaders\ModelLoader.h" #include "world\World.h" #include "TextRenderer.h" /* The player mouse map collision tile selection information rendering. (Hurgh, quite a long sentence) Renders the flat quad indicating where your selection is. */ class SelectionRenderer : public Renderer { private: Camera* playerCamera; Light* light; World* world; // different models used according to the currentselection TexturedModel* currentModel; TexturedModel* baseSelectionModel; TexturedModel* sampleTowerSelectionModel; TexturedModel* intelligentTowerSelectionModel; glm::mat4 projectionMatrix; // prepare the rendering void prepare() const; // render the selection void renderSelection() const; public: SelectionRenderer(SelectionShader* shader, World* world, glm::mat4 proj, Camera* playerCamera, Light* light); ~SelectionRenderer(); // renders void render() const; // model getter TexturedModel* getCurrentModel() const; };
9a96a47c647d32e87b0d380413d401b893c32e73
1b90be9561c10508eea59cb36c1f1665d0ef947f
/stan/math/prim/fun/sort_desc.hpp
4c8d7307d97ad1f455e30f52fdd5505c2015417b
[ "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0" ]
permissive
stan-dev/math
473e7c1eaf11f84eaf2032c2455e12ba65feef39
bdf281f4e7f8034f47974d14dea7f09e600ac02a
refs/heads/develop
2023-08-31T09:02:59.224115
2023-08-29T15:17:01
2023-08-29T15:17:01
38,388,440
732
240
BSD-3-Clause
2023-09-14T19:44:20
2015-07-01T18:40:54
C++
UTF-8
C++
false
false
1,358
hpp
sort_desc.hpp
#ifndef STAN_MATH_PRIM_FUN_SORT_DESC_HPP #define STAN_MATH_PRIM_FUN_SORT_DESC_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <algorithm> #include <functional> #include <vector> namespace stan { namespace math { /** * Return the specified standard vector in descending order. * * @tparam T Type of elements contained in vector. * @param xs Vector to order. * @return Vector in descending order. * @throw std::domain_error If any of the values are NaN. */ template <typename T> inline std::vector<T> sort_desc(std::vector<T> xs) { check_not_nan("sort_asc", "container argument", xs); std::sort(xs.begin(), xs.end(), std::greater<T>()); return xs; } /** * Return the specified vector in descending order. * * @tparam EigVec type of the vector * * @param xs Vector to order. * @return Vector in descending order. * @throw std::domain_error If any of the values are NaN. */ template <typename EigVec, require_eigen_vector_t<EigVec>* = nullptr> inline plain_type_t<EigVec> sort_desc(EigVec&& xs) { plain_type_t<EigVec> x = std::forward<EigVec>(xs); check_not_nan("sort_asc", "container argument", x); std::sort(x.data(), x.data() + x.size(), std::greater<value_type_t<EigVec>>()); return x; } } // namespace math } // namespace stan #endif
8f67c97b96715ff0a91ed726ed5b49f14891de8e
24e804a369d507b177cd6ba44d44b2278f1bbd97
/Trabalho 2/AVL.cpp
587573ca9342d7c999e0a831815fce2ab5e6ff45
[]
no_license
techmarktm/trabalhoED2
e9fadb4d47177a7ac32a23768da87fe46e21aee4
6be60f3e070fc58f4becc30c4fe017dfb08bd443
refs/heads/master
2021-08-23T09:10:30.444280
2017-12-04T12:46:53
2017-12-04T12:46:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,705
cpp
AVL.cpp
/*--------------------------------------- TRABALHO DE ESTRUTURA DE DADOS 2 GRUPO: Bruno Carvalho Diogo Destefano Rafael Terra Pedro Bellotti --------------------------------------*/ #include "AVL.h" //construtor e destrutor AVL::AVL() { raiz = NULL; numCompar = 0; numCopias = 0; tempoGastoInsercao = 0; tempoGastoRemocao = 0; tempoGastoBusca = 0; } AVL::~AVL() { destrutorAux(raiz); } void AVL::destrutorAux(No *no) { if (no != NULL) { destrutorAux(no->getEsq()); destrutorAux(no->getDir()); delete no; } } //rotacoes No *AVL::rotR(No *no) //rotacao direita { No *noAux = no->getEsq(); numCopias++; no->setEsq(noAux->getDir()); noAux->setDir(no); return noAux; } No *AVL::rotRR(No *no) //rotacao dupla direita { no->setEsq(rotL(no->getEsq())); No *noAux = rotR(no); numCopias++; return noAux; } No *AVL::rotL(No *no) //rotacao esquerda { No *noAux = no->getDir(); No *noAux2 = noAux->getEsq(); numCopias++; numCopias++; no->setDir(noAux2); noAux->setEsq(no); return noAux; } No *AVL::rotLL(No *no) //rotacao dupla esquerda { no->setDir(rotR(no->getDir())); No *noAux = rotL(no); numCopias++; return noAux; } //Buscas bool AVL::busca(int tweetId) { return buscaAuxiliar(tweetId, raiz); } bool AVL::buscaAuxiliar(int tweetId, No *no) { clock_t relogio; relogio = clock(); if (no == NULL) { numCompar++; tempoGastoBusca += (clock() - relogio) / (double)CLOCKS_PER_SEC; return false; } else if (no->getChave()->getTweetID() == tweetId) { numCompar++; tempoGastoBusca += (clock() - relogio) / (double)CLOCKS_PER_SEC; return true; } else if (no->getChave()->getTweetID() != tweetId) { if (no->getEsq() != NULL && no->getChave()->getTweetID() < tweetId) { numCompar++; return buscaAuxiliar(tweetId, no->getEsq()); } else if (no->getDir() != NULL && no->getChave()->getTweetID() > tweetId) { numCompar++; return buscaAuxiliar(tweetId, no->getDir()); } else if (no->getEsq() == NULL && no->getDir() == NULL) { numCompar++; tempoGastoBusca += (clock() - relogio) / (double)CLOCKS_PER_SEC; return false; } } } //Manipulacao da arvore void AVL::inserir(Tweet *tw) { clock_t relogio; relogio = clock(); raiz = inserirAuxiliar(tw, raiz); raiz = balanceia(raiz); setFB(raiz); tempoGastoInsercao += (clock() - relogio) / (double)CLOCKS_PER_SEC; } void AVL::remover(Tweet *tw) { clock_t relogio; relogio = clock(); raiz = removerAux(raiz, tw); raiz = balanceia(raiz); setFB(raiz); tempoGastoRemocao += (clock() - relogio) / (double)CLOCKS_PER_SEC; } No *AVL::removerAux2(No *no) { No *noAux; No *noAuxPai = new No(); if ((no->getEsq() == NULL) && (no->getDir() == NULL)) { numCompar++; delete no; return NULL; } else if ((no->getEsq() == NULL) && (no->getDir() != NULL)) { numCompar++; noAux = no->getEsq(); numCopias++; delete no; return noAux; } else if ((no->getEsq() != NULL) && (no->getDir() == NULL)) { numCompar++; noAux = no->getDir(); numCopias++; delete no; return noAux; } else { if (no->getEsq()->getDir() == NULL) { numCompar++; noAux = no->getEsq(); numCopias++; no->getEsq()->setDir(no->getDir()); delete no; delete noAux; } else { noAux = no->getEsq(); numCopias++; while (noAux->getDir() != NULL) { noAuxPai = noAux; numCopias++; noAux = noAux->getDir(); numCopias++; } if (noAux->getEsq() != NULL) { numCompar++; noAuxPai->setDir(noAux->getEsq()); } else { noAuxPai->setDir(NULL); } noAux->setDir(no->getDir()); noAux->setEsq(no->getEsq()); delete no; return noAux; } } return NULL; } No *AVL::removerAux(No *no, Tweet *tw) { No *noAux = no; numCopias++; No *noPai = new No(); bool bdir = false; if(no!=NULL) { if (tw->getTweetID() == no->getChave()->getTweetID()) { numCompar++; return removerAux2(noAux); } while (noAux != NULL) { if (tw->getTweetID() == noAux->getChave()->getTweetID()) { numCompar++; if (bdir) noPai->setDir(removerAux2(noAux)); else noPai->setEsq(removerAux2(noAux)); return no; } else { if (tw->getTweetID() > noAux->getChave()->getTweetID()) { numCompar++; bdir = false; noPai = noAux; numCopias++; noAux = noAux->getEsq(); numCopias++; } else { numCompar++; bdir = true; noPai = noAux; numCopias++; noAux = noAux->getDir(); numCopias++; } } } } return no; } void AVL::setFB(No* no) { if(no!=NULL) { no->setFB(calculaAltura(no->getEsq()) - calculaAltura(no->getDir())); setFB(no->getEsq()); setFB(no->getDir()); } } No* AVL::inserirAuxiliar(Tweet *tw, No *no) { if (no == NULL) { numCompar++; no = new No(); no->setChave(tw); no->setFB(0); numCopias++; } else { if (tw->getTweetID() < no->getChave()->getTweetID()) { numCompar++; no->setEsq(inserirAuxiliar(tw, no->getEsq())); } else if (tw->getTweetID() > no->getChave()->getTweetID()) { numCompar++; no->setDir(inserirAuxiliar(tw, no->getDir())); } } return no; } void AVL::limpaDados() { numCompar = 0; numCopias = 0; tempoGastoInsercao = 0; tempoGastoRemocao = 0; } //Outras funcoes int AVL::calculaFB(No *no) { if (no != NULL) { return (((calculaAltura(no->getEsq())) - (calculaAltura(no->getDir())))); numCompar++; } else return 0; } int AVL::calculaAltura(No *no) { int altEsq, altDir; if (no == NULL) { numCompar++; return 0; } else { altEsq = calculaAltura(no->getEsq()); altDir = calculaAltura(no->getDir()); if (altEsq > altDir) { numCompar++; return (1 + altEsq); } else { numCompar++; return (1 + altDir); } } } No *AVL::balanceia(No *no) { if (no != NULL) { no->setFB(calculaFB(no)); if (no->getFB() == 2) { numCompar++; no->getEsq()->setFB(calculaFB(no->getEsq())); if (no->getEsq()->getFB() > 0) { numCompar++; no = rotR(no); numCopias++; } else { numCompar++; no = rotRR(no); numCopias++; } } else if (no->getFB() == -2) { no->getDir()->setFB(calculaFB(no->getDir())); if (no->getDir()->getFB() < 0) { numCompar++; no = rotL(no); numCopias++; } else { no = rotLL(no); numCompar++; numCopias++; } } no->setEsq(balanceia(no->getEsq())); no->setDir(balanceia(no->getDir())); } return no; } void AVL::imprimir() { imprimirAux(raiz); } void AVL::imprimirAux(No *no) { if (no != NULL) { cout << "Chave: " << no->getChave()->getTweetID() << endl; if (no->getEsq() != NULL) cout << "Esquerda: " << no->getEsq()->getChave()->getTweetID() << endl; else cout << "Esquerda: NULL" << endl; if (no->getDir() != NULL) cout << "Direita: " << no->getDir()->getChave()->getTweetID() << endl; else cout << "Direita: NULL" << endl; cout << endl; imprimirAux(no->getEsq()); imprimirAux(no->getDir()); } else if(no==raiz) { cout << "Arvore vazia!" << endl; } } long int AVL::getNumCompar() { return numCompar; } long int AVL::getNumCopias() { return numCopias; } double AVL::getTempoInsercao() { return tempoGastoInsercao; } double AVL::getTempoRemocao() { return tempoGastoRemocao; } double AVL::getTempoBusca() { return tempoGastoBusca; }
42ee4f8514354f3ee6517a781d11df32621f6c02
6a2d97622c4d5d504611d774119d8c2cfb49ff65
/src/entities/Entity.cpp
585f463c10e99fd1b2a6844a8e932f0c71ff0ff3
[]
no_license
SemvdH/SDBA
50e63b9fd4b7f46f3eb8f5faf6ee82000c2d643d
85f341e576bcbace04386eaf413a3cfba1ff9bcc
refs/heads/main
2023-05-29T02:05:46.688068
2021-06-18T15:56:41
2021-06-18T15:56:41
368,453,279
1
0
null
2021-06-18T15:56:42
2021-05-18T08:18:27
C++
UTF-8
C++
false
false
565
cpp
Entity.cpp
#include "entity.h" namespace entities { Entity::Entity(const models::TexturedModel& model, const glm::vec3& position, const glm::vec3& rotation, float scale) : model(model), position(position), rotation(rotation), scale(scale) { } void Entity::IncreasePosition(const glm::vec3& distance) { position.x += distance.x; position.y += distance.y; position.z += distance.z; } void Entity::IncreaseRotation(const glm::vec3& rotation) { this->rotation.x += rotation.x; this->rotation.y += rotation.y; this->rotation.z += rotation.z; } }
217105f848de2efa4d73d071db857543588a870a
0e5ea03c2455b34a2f416c6c94c1669d7fe26e37
/_2018_03_20 BattleShip 1/stdafx.h
427f30cffd128c1790b92a468e13b12230fd3b17
[]
no_license
Arroria/__old_project
8682652fac9a95898b41eff5b4fdfab023cda699
efb655b2356bd95744ba19093f25ab266a625722
refs/heads/master
2020-09-05T08:02:44.806509
2019-11-06T18:01:23
2019-11-06T18:01:23
220,033,980
1
1
null
null
null
null
UTF-8
C++
false
false
506
h
stdafx.h
#pragma once #include <vector> #include <map> #include <list> #include <string> #include <array> #include <iostream> using std::cout; using std::endl; #include <windowsx.h> #define DEVICE (DXUTGetD3D9Device()) #define CONSTEXPR #include "SoundManager.h" #include "TextureManager.h" #include "InputManager.h" #include "ASEManager.h" #include "SceneManager.h" #include "Sprite.h" #include "Plane.h" #include "Camera.h" #include "Skybox.h" #include "WhiteMtrl.h" #include "Fader.h" #include "Score.h"
1a42ea38d2edec80de61a2e7d3432a474a9cf4bb
e93a80168efe321e3586118ee7097f5192a284ec
/src/OpenCvSharpExtern/features2d.h
724c72e4ae1e4346510f77160bb1cf42b9a60c1e
[ "BSD-3-Clause" ]
permissive
TWhidden/opencvsharp
bc2d5120bb53ca393493bcaf4dcf31e0a493fc71
b88305b021c88775a0da8ada237778f4ed90dc41
refs/heads/master
2021-07-11T05:06:32.867687
2020-11-29T18:44:38
2020-11-29T18:44:38
222,134,723
2
0
BSD-3-Clause
2019-11-16T17:26:55
2019-11-16T17:26:54
null
UTF-8
C++
false
false
6,682
h
features2d.h
#ifndef _CPP_FEATURES2D_H_ #define _CPP_FEATURES2D_H_ #include "include_opencv.h" CVAPI(ExceptionStatus) features2d_drawKeypoints(cv::_InputArray *image, cv::KeyPoint *keypoints, int keypointsLength, cv::_InputOutputArray *outImage, MyCvScalar color, int flags) { BEGIN_WRAP const std::vector<cv::KeyPoint> keypointsVec(keypoints, keypoints + keypointsLength); cv::drawKeypoints(*image, keypointsVec, *outImage, cpp(color), static_cast<cv::DrawMatchesFlags>(flags)); END_WRAP } CVAPI(ExceptionStatus) features2d_drawMatches(cv::Mat *img1, cv::KeyPoint *keypoints1, int keypoints1Length, cv::Mat *img2, cv::KeyPoint *keypoints2, int keypoints2Length, cv::DMatch *matches1to2, int matches1to2Length, cv::Mat *outImg, MyCvScalar matchColor, MyCvScalar singlePointColor, char *matchesMask, int matchesMaskLength, int flags) { BEGIN_WRAP const std::vector<cv::KeyPoint> keypoints1Vec(keypoints1, keypoints1 + keypoints1Length); const std::vector<cv::KeyPoint> keypoints2Vec(keypoints2, keypoints2 + keypoints2Length); const std::vector<cv::DMatch> matches1to2Vec(matches1to2, matches1to2 + matches1to2Length); std::vector<char> matchesMaskVec; if (matchesMask != nullptr) matchesMaskVec = std::vector<char>(matchesMask, matchesMask + matchesMaskLength); cv::drawMatches(*img1, keypoints1Vec, *img2, keypoints2Vec, matches1to2Vec, *outImg, cpp(matchColor), cpp(singlePointColor), matchesMaskVec, static_cast<cv::DrawMatchesFlags>(flags)); END_WRAP } CVAPI(ExceptionStatus) features2d_drawMatchesKnn(cv::Mat *img1, cv::KeyPoint *keypoints1, int keypoints1Length, cv::Mat *img2, cv::KeyPoint *keypoints2, int keypoints2Length, cv::DMatch **matches1to2, int matches1to2Size1, int *matches1to2Size2, cv::Mat *outImg, MyCvScalar matchColor, MyCvScalar singlePointColor, char **matchesMask, int matchesMaskSize1, int *matchesMaskSize2, int flags) { BEGIN_WRAP const std::vector<cv::KeyPoint> keypoints1Vec(keypoints1, keypoints1 + keypoints1Length); const std::vector<cv::KeyPoint> keypoints2Vec(keypoints2, keypoints2 + keypoints2Length); std::vector<std::vector<cv::DMatch> > matches1to2Vec(matches1to2Size1); for (int i = 0; i < matches1to2Size1; i++) { cv::DMatch *p = matches1to2[i]; matches1to2Vec[i] = std::vector<cv::DMatch>(p, p + matches1to2Size2[i]); } std::vector<std::vector<char> > matchesMaskVec; if (matchesMask != nullptr) { matchesMaskVec = std::vector<std::vector<char> >(matchesMaskSize1); for (int i = 0; i < matchesMaskSize1; i++) { char *p = matchesMask[i]; matchesMaskVec[i] = std::vector<char>(p, p + matchesMaskSize2[i]); } } cv::drawMatches(*img1, keypoints1Vec, *img2, keypoints2Vec, matches1to2Vec, *outImg, cpp(matchColor), cpp(singlePointColor), matchesMaskVec, static_cast<cv::DrawMatchesFlags>(flags)); END_WRAP } CVAPI(ExceptionStatus) features2d_evaluateFeatureDetector( cv::Mat *img1, cv::Mat *img2, cv::Mat *H1to2, std::vector<cv::KeyPoint> *keypoints1, std::vector<cv::KeyPoint> *keypoints2, float *repeatability, int *correspCount/*, const Ptr<FeatureDetector>& fdetector = Ptr<FeatureDetector>()*/) { BEGIN_WRAP cv::evaluateFeatureDetector( *img1, *img2, *H1to2, keypoints1, keypoints2, *repeatability, *correspCount); END_WRAP } CVAPI(ExceptionStatus) features2d_computeRecallPrecisionCurve( cv::DMatch **matches1to2, int matches1to2Size1, int *matches1to2Size2, uchar **correctMatches1to2Mask, int correctMatches1to2MaskSize1, int *correctMatches1to2MaskSize2, std::vector<cv::Point2f> *recallPrecisionCurve) { BEGIN_WRAP std::vector<std::vector<cv::DMatch> > matches1to2Vec; std::vector<std::vector<uchar> > correctMatches1to2MaskVec; matches1to2Vec.reserve(matches1to2Size1); for (int i = 0; i < matches1to2Size1; i++) { matches1to2Vec.emplace_back(matches1to2[i], matches1to2[i] + matches1to2Size2[i]); } correctMatches1to2MaskVec.reserve(correctMatches1to2MaskSize1); for (int i = 0; i < correctMatches1to2MaskSize1; i++) { correctMatches1to2MaskVec.emplace_back(correctMatches1to2Mask[i], correctMatches1to2Mask[i] + correctMatches1to2MaskSize2[i]); } cv::computeRecallPrecisionCurve( matches1to2Vec, correctMatches1to2MaskVec, *recallPrecisionCurve); END_WRAP } CVAPI(ExceptionStatus) features2d_getRecall( cv::Point2f *recallPrecisionCurve, int recallPrecisionCurveSize, float l_precision, float *returnValue) { BEGIN_WRAP const std::vector<cv::Point2f> recallPrecisionCurveVec( recallPrecisionCurve, recallPrecisionCurve + recallPrecisionCurveSize); *returnValue = cv::getRecall(recallPrecisionCurveVec, l_precision); END_WRAP } CVAPI(ExceptionStatus) features2d_getNearestPoint( cv::Point2f *recallPrecisionCurve, int recallPrecisionCurveSize, float l_precision, int *returnValue) { BEGIN_WRAP const std::vector<cv::Point2f> recallPrecisionCurveVec( recallPrecisionCurve, recallPrecisionCurve + recallPrecisionCurveSize); *returnValue = cv::getNearestPoint(recallPrecisionCurveVec, l_precision); END_WRAP } #pragma region KeyPointsFilter CVAPI(ExceptionStatus) features2d_KeyPointsFilter_runByImageBorder( std::vector<cv::KeyPoint> *keypoints, MyCvSize imageSize, int borderSize) { BEGIN_WRAP cv::KeyPointsFilter::runByImageBorder(*keypoints, cpp(imageSize), borderSize); END_WRAP } CVAPI(ExceptionStatus) features2d_KeyPointsFilter_runByKeypointSize( std::vector<cv::KeyPoint> *keypoints, float minSize, float maxSize) { BEGIN_WRAP cv::KeyPointsFilter::runByKeypointSize(*keypoints, minSize, maxSize); END_WRAP } CVAPI(ExceptionStatus) features2d_KeyPointsFilter_runByPixelsMask( std::vector<cv::KeyPoint> *keypoints, cv::Mat *mask) { BEGIN_WRAP cv::KeyPointsFilter::runByPixelsMask(*keypoints, *mask); END_WRAP } CVAPI(ExceptionStatus) features2d_KeyPointsFilter_removeDuplicated( std::vector<cv::KeyPoint> *keypoints) { BEGIN_WRAP cv::KeyPointsFilter::removeDuplicated(*keypoints); END_WRAP } CVAPI(ExceptionStatus) features2d_KeyPointsFilter_removeDuplicatedSorted( std::vector<cv::KeyPoint> *keypoints) { BEGIN_WRAP cv::KeyPointsFilter::removeDuplicatedSorted(*keypoints); END_WRAP } CVAPI(ExceptionStatus) features2d_KeyPointsFilter_retainBest( std::vector<cv::KeyPoint> *keypoints, int nPoints) { BEGIN_WRAP cv::KeyPointsFilter::retainBest(*keypoints, nPoints); END_WRAP } #pragma endregion #endif
a1b120b00ed7d0c607d26ca237eaf186c6c538e9
702191129549fb9e28ed327b9eed344218e82496
/Problems/1021/1021회전하는큐.cpp
57441b351936a0bba3cf7c356f3fa62831fa9304
[]
no_license
Sunjae95/BOJ-Algorithm-Study
219997490c5098a34e7b9d008070e0799345ac92
8154101bd1c4b2ab0cea957f8bd7594d569cb517
refs/heads/master
2022-12-30T17:47:10.473181
2020-10-20T15:34:11
2020-10-20T15:34:11
null
0
0
null
null
null
null
UHC
C++
false
false
1,134
cpp
1021회전하는큐.cpp
#include<iostream> #include<algorithm> #include<queue> #include<vector> using namespace std; int n, m; int ans = 0; deque<int> q; void moveLeft(deque<int> &q) { // 2번 연산 q.push_back(q.front()); q.pop_front(); } void moveRight(deque<int> &q) { // 3번 연산 q.push_front(q.back()); q.pop_back(); } int main(void) { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> n >> m; vector<int> v(m); for (int i = 0; i < m; i++) cin >> v[i]; for (int i = 1; i <= n; i++) q.push_back(i); for (int i = 0; i < m; i++) { if (q.front() == v[i]) { q.pop_front(); } else { int cntLeft = 0; deque<int> tmpDq = q; while (tmpDq.front() != v[i]) { moveLeft(tmpDq); cntLeft++; } tmpDq = q; int cntRight = 0; while (tmpDq.front() != v[i]) { moveRight(tmpDq); cntRight++; } if (cntLeft > cntRight) { ans += cntRight; while (q.front() != v[i]) { moveRight(q); } q.pop_front(); } else { ans += cntLeft; while (q.front() != v[i]) { moveLeft(q); } q.pop_front(); } } } cout << ans << '\n'; }
98e800b6ad0c34e3726dbf0adba5382595c0610f
0fba32eabcf1a4b22bee010b4dbf79503c6050c9
/include/cmdlime/simpleconfig.h
c6cedd0a24b2e52f2b3b4b990acb5d811664f392
[ "MS-PL", "MIT" ]
permissive
lineCode/cmdlime
a7a3b0da132525352bfa3d442232a47ecc68fc25
1f99cf7cb79ccb113007ad175728d6385f91a03d
refs/heads/master
2023-05-04T13:28:29.088463
2021-05-21T14:30:32
2021-05-21T14:30:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
261
h
simpleconfig.h
#pragma once #include "customnames.h" #include "configreader.h" #include "detail/config.h" #include "detail/configmacro.h" #include "detail/simpleformat.h" namespace cmdlime{ using SimpleConfig = cmdlime::detail::Config<cmdlime::detail::FormatType::Simple>; }
0a674e4f7ebccaf96c25030bb7fa33fb70e8cdb0
12d2d105d55ac0061bbbd1a29122c165e79c4b0a
/Scheduler/src/Scheduler.h
cf65275d4be941e0a852b210be5f972ad1263531
[]
no_license
giulianoc/CatraLibraries
75d3f22f7636ae001d4bd2cc4e83648664e0734e
928730f656290b0f9907e7794935f96d2a895df1
refs/heads/master
2023-03-03T11:28:54.408320
2023-02-26T11:13:30
2023-02-26T11:13:30
29,320,791
4
2
null
null
null
null
UTF-8
C++
false
false
6,892
h
Scheduler.h
/* Copyright (C) Giuliano Catrambone (giuliano.catrambone@catrasoftware.it) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Commercial use other than under the terms of the GNU General Public License is allowed only after express negotiation of conditions with the authors. */ #ifndef Scheduler_h #define Scheduler_h #ifdef WIN32 #include "WinThread.h" #else #include "PosixThread.h" #endif #include "PMutex.h" #include "SchedulerErrors.h" #include "Times.h" /** La libreria Scheduler gestisce la schedulazione di attivita'. Ogni schedulazione viene incapsulata all'interno di un oggetto di tipo Times che e' un componente passivo: infatti esso viene attivato da un oggetto di tipo Scheduler che costituisce il motore dello scheduler. La classe Scheduler eredita dalla classe PosixThread e rappresenta uno scheduler. Essa gestisce gli eventuali timeouts di oggetti di tipo Times. Un oggetto di tipo Times puo' essere pensato come un orologio cui possono essere inseriti allarmi (timeouts). L'attivita' dello scheduler consiste nel controllare periodicamente gli oggetti di tipo Times e, nel momento in cui viene riscontrato un timeout, invocare il metodo handleTimeout dell'oggetto Times. Per la gestione del cambio ora legale da parte degli oggetti di tipo Times vedi la descrizione della classe Times. Il tipo Times e' una classe astratta in quanto possiede il metodo virtuale puro handleTimeOut che deve essere ridefinito dall'utente in modo che esso possa realizzare le operazioni da eseguire quando si verifica un timeout. L'utente della libreria deve semplicemente creare una classe per ogni Times personalizzato che eredita dalla classe Times e ridefinire il metodo handleTimeout. E' lo scheduler che automaticamente si preoccupa di gestire gli oggetti di tipo Times e chiamare il metodo handleTimeout ogni qual volta si verifica un timeout. Gli esempi che si trovano nella directory examples chiariranno l'uso di questa libreria. */ #ifdef WIN32 typedef class Scheduler: public WinThread #else typedef class Scheduler: public PosixThread #endif { private: typedef enum SchedulerStatus { SCHEDULER_BUILDED, SCHEDULER_INITIALIZED, SCHEDULER_STARTED, SCHEDULER_SUSPENDED } SchedulerStatus_t, *SchedulerStatus_p; private: unsigned long _ulThreadSleepInMilliSecs; SchedulerStatus_t _schedulerStatus; unsigned long _ulTimesPointerToAllocOnOverflow; unsigned long _ulAllocatedTimesPointerNumber; Error getTimesPointerIndex (Times_p pTimes, long *plTimesPointerIndex); protected: // mutex for the private and protected variables PMutex_t _mtSchedulerMutex; Times_p *_pTimesList; unsigned long _ulTimesPointerNumber; Scheduler (const Scheduler &); /** In questo metodo viene realizzato il corpo principale dello scheduler. Esso chiama il metodo handleTimes per la gestione degli eventi. */ Error run (void); /** Il metodo gestisce tutti i Times attivati all'interno dello scheduler ed in particolare, per ogni Times, l'algoritmo che il metodo esegue risulta essere il seguente: se il Times e' in stato STARTED se il timeout del Times e' scaduto chiama il metodo handleTimeout se il periodo del Times e' 0 chiama il metodo deactiveTimes per quel Times altrimenti chiama il metodo updateNextExpirationDateTime al Times */ virtual Error handleTimes (void); public: /** Costruttore */ Scheduler (void); /** Distruttore */ ~Scheduler (void); /** Inizializza lo scheduler. Il parametro ulThreadSleepInMilliSecs indica il periodo espresso in milli-secondi tra un controllo dei Times e l'altro. L'oggetto Scheduler conterra' i puntatori ad oggetti di tipo Times all'interno di un vettore. Il parametro lTimesPointerToAllocOnOverflow indica che il vettore sara' inizialmente dimensionato per 20 puntatori ai Times. Ogni qual volta si supera questa soglia saranno eseguite le seguenti operazioni: 1. sara' allocato un vettore avente la dimensione precedente + 20 2. saranno copiati i precedenti puntatori ai Times nel nuovo vettore 3. sara' deallocato il precedente vettore */ Error init (unsigned long ulThreadSleepInMilliSecs = 1000, unsigned long ulTimesPointerToAllocOnOverflow = 20); /** Finish the object freeing his internal list from any Times object. If bDestroyTimes is true it performs also the following actions: - call the finish method to each Times object - delete each Times object */ Error finish (Boolean_t bDestroyTimes); /** Il metodo attiva lo scheduler thread. Vedi PosixThread:: start. */ Error start (void); /** Sospende il funzionamento dello scheduler. Il thread non viene interrotto. */ Error suspend (void); /** Viene chiamato per riattivare lo scheduler dopo che sia stato interrotto dal metodo suspend. */ Error resume (void); /** Interrompe l'esecuzione del thread. Vedi PosixThread:: cancel. */ Error cancel (void); /** Viene dato allo scheduler un ulteriore Times da gestire. */ Error activeTimes (Times_p pTimes); /** Il metodo permette di disattivare un Times attivato dal metodo activeTimes. */ Error deactiveTimes (Times_p pTimes); /** Il metodo permette di disattivare un Times attivato dal metodo activeTimes. */ Error deactiveTimes (long lTimesPointerIndex); /** Ritorna il numero di Times correntemente gestiti dallo scheduler. */ Error getTimesNumber (unsigned long *pulTimesNumber); /** I Times gestiti dallo scheduler sono inseriti in un vettore le cui dimensioni cambiano dinamicamente. Il metodo ritorna il puntatore al Times che correntemente occupa la posizione indicata dal parametro lTimesIndex. */ Error getTimes (unsigned long ulTimesIndex, Times_p *pTimes); /** Ritorna lo stato dello scheduler. */ Error getSchedulerStatus (SchedulerStatus_p pssSchedulerStatus); } Scheduler_t, *Scheduler_p; #endif
90c7091670dafea28a2d937f5ba0f9f4247eb910
be6e6f384fa5eb61f14eb2a418541efb9ddbaed1
/daemonsofchaosslaaneshfaction.cpp
2699c11380d0724d0f3ca8c6593baa8243a4e81d
[]
no_license
mehoggan/ArmyBalancer
fdc9ccb12cb1a0139486a76124f493788bd37101
b1a3698e3bdb38cc25281ea203f2642ff5a08725
refs/heads/master
2021-06-06T08:14:39.542664
2019-11-29T18:56:32
2019-11-29T18:57:46
39,392,631
0
0
null
null
null
null
UTF-8
C++
false
false
18,444
cpp
daemonsofchaosslaaneshfaction.cpp
#include "daemonsofchaosslaaneshfaction.h" namespace WarScrollGeneration { WarScroll Keeper_of_Secrets(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(14, 10, 10, 4); ws.addWeapon(WarScroll::Weapon("Razor-sharp Claws", 2, 6, 3, 3, 1, 2)); ws.addWeapon(WarScroll::Weapon("Elegant Greatblade", 2, 2, 3, 2, 2, 3)); ws.addAbility(WarScroll::Ability("Dark Temptations", 2)); ws.addAbility(WarScroll::Ability("Delicate Precision", 1)); ws.addAbility(WarScroll::Ability("Excess of Violence", 2, true)); ws.addArcaneBolt(); ws.addMysticShield(); ws.addSpell(WarScroll::Spell("Summon Daemons"), 7, 3); ws.addSpell(WarScroll::Spell("Cacophonic Choir"), 6, 2); ws.addKeyWords({"CHAOS", "DAEMON", "SLAANESH", "MONSTER", "HERO", "WIZARD", "KEEPER OF SECRETS"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); ws.addKeyWordConnection(WarScroll::KeyWordConnection("HERO", WarScroll::s_MaxDistance, WarScroll::Ability("Dark Temptations", 2), 1, WarScroll::KeyWordConnection::ConnectionAffectType::eEnemy, WarScroll::Spell())); { WarScroll::KeyWordConnection connection("SLAANESH and DAEMON", 12, WarScroll::Ability("Excess of Violence", 2, true), 1, WarScroll::KeyWordConnection::ConnectionAffectType::eFriendly, WarScroll::Spell()); connection.setMaxConnections(1); ws.addKeyWordConnection(connection); } WarScroll::addSummonable(ws, name, 9, 3, 12, 1, {"CHAOS", "WIZARD"}); return ws; } WarScroll The_Masque_of_Slaanesh(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(10, 5, 10, 4); ws.addWeapon(WarScroll::Weapon("Serrated Claws", 1, 6, 3, 4, 1, 1)); ws.addWeapon(WarScroll::Weapon("Staff of Masks", 1, 1, 3, 5, 0, 1)); ws.addAbility(WarScroll::Ability("Unnatural Reflexes", 2)); ws.addAbility(WarScroll::Ability("The Endless Dance", 1)); ws.addAbility(WarScroll::Ability("Infernal Choreographer", 1)); ws.addKeyWords({"CHAOS", "DAEMON", "DAEMONETTE", "SLAANESH", "HERO", "THE MASQUE"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); return ws; } WarScroll Herald_of_Slaanesh(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(6, 5, 10, 5); ws.addWeapon(WarScroll::Weapon("Ravaging Claws", 1, 6, 3, 4, 1, 1)); WarScroll::UnitUpgrade steedUpgrade("Steed of Slaanesh", WarScroll::UnitUpgrade::UnitUpgradeType::eMount, 1); steedUpgrade.registerCharacteristicToIncrease("Move", 6); steedUpgrade.addWeapon(WarScroll::Weapon("Steed's Poisoned Tongue", 1, 2, 4, 4, 0, 1)); ws.registerUnitUpgrade(steedUpgrade); ws.addAbility(WarScroll::Ability("Deadly Grace", 1)); ws.addAbility(WarScroll::Ability("Quicksilver Dodge", 1)); ws.addKeyWords({"CHAOS", "DAEMON", "DAEMONETTE", "SLAANESH", "HERO", "HERALD OF SLAANESH"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); ws.addSummonable(ws, name, 5, 3, 12, 1, {"CHAOS", "WIZARD"}); return ws; } WarScroll Herald_of_Slaanesh_on_Seeker_Chariot(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(12, 5, 10, 5); ws.addWeapon(WarScroll::Weapon("Herald's Flensing Whips", 2, 6, 3, 4, 0, 1)); ws.addWeapon(WarScroll::Weapon("Daemonette's Piercing Claws", 1, 2, 4, 4, 1, 1)); ws.addWeapon(WarScroll::Weapon("Steeds' Poisoned Tongues", 1, 4, 4, 4, 0, 1)); ws.addAbility(WarScroll::Ability("Deadly Grace", 1)); ws.addAbility(WarScroll::Ability("Impossibly Quick", 2)); ws.addAbility(WarScroll::Ability("Excess of Blades", 1)); ws.addAbility(WarScroll::Ability("Disturbing Beauty", 1)); ws.addKeyWords({"CHAOS", "DAEMON", "DAEMONETTE", "SLAANESH", "HERO", "SEEKER", "CHARIOT"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); ws.addKeyWordConnection(WarScroll::KeyWordConnection("HERO", WarScroll::s_MaxDistance, WarScroll::Ability("Disturbing Beauty", 1), 1, WarScroll::KeyWordConnection::ConnectionAffectType::eEnemy, WarScroll::Spell())); WarScroll::addSummonable(ws, name, 7, 3, 12, 1, {"CHAOS and WIZARD"}); return ws; } WarScroll Herald_of_Slaanesh_on_Exalted_Seeker_Chariot( const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(12, 9, 10, 5); ws.addWeapon(WarScroll::Weapon("Herald's Flensing Whips", 2, 6, 3, 4, 0, 1)); ws.addWeapon(WarScroll::Weapon("Daemonettes' Piercing Claws", 1, 6, 4, 4, 1, 1)); ws.addWeapon(WarScroll::Weapon("Steeds' Poisoned Tongues", 1, 8, 4, 4, 0, 1)); ws.addAbility(WarScroll::Ability("Swirling Shapes and Unholy Hues", 1)); ws.addAbility(WarScroll::Ability("Exalted Excess of Blades", 1)); ws.addAbility(WarScroll::Ability("Deadly Grace", 1)); ws.addAbility(WarScroll::Ability("Disturbing Beauty", 1)); ws.addKeyWords({"CHAOS", "DAEMON", "DAEMONETTE", "SLAANESH", "HERO", "EXALTED SEEKER CHARIOT"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); ws.addKeyWordConnection(WarScroll::KeyWordConnection("HERO", WarScroll::s_MaxDistance, WarScroll::Ability("Disturbing Beauty", 1), 1, WarScroll::KeyWordConnection::ConnectionAffectType::eEnemy, WarScroll::Spell())); WarScroll::addSummonable(ws, name, 7, 3, 12, 1, {"CHAOS and WIZARD"}); return ws; } WarScroll Daemonettes_of_Slaanesh(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(6, 1, 10, 5); ws.addWeapon(WarScroll::Weapon("Piercing Claws", 1, 2, 4, 4, 1, 1)); ws.setMinMaxUnitCount(10, IFaction::s_MaxUnitSize); ws.registerUnitUpgrade(WarScroll::UnitUpgrade("Alluress", WarScroll::UnitUpgrade::UnitUpgradeType::eChampion, 1)); ws.registerUnitUpgrade(WarScroll::UnitUpgrade("Icon Bearer", WarScroll::UnitUpgrade::UnitUpgradeType::eBannerBearer, 2)); ws.registerUnitUpgrade(WarScroll::UnitUpgrade("Hornblower", WarScroll::UnitUpgrade::UnitUpgradeType::eMusician, 1)); ws.addAbility(WarScroll::Ability("Lith and Swift", 2)); ws.addAbility(WarScroll::Ability("Graceful Killers", 1)); ws.addAbility(WarScroll::Ability("Locus of Beguilement", 1)); ws.addKeyWords({"CHAOS", "DAEMON", "SLAANESH", "DAEMONETTES"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); ws.addKeyWordConnection(WarScroll::KeyWordConnection("DAEMONETTE and HERO", 6, WarScroll::Ability("Locus of Beguilement", 1), 1, WarScroll::KeyWordConnection::ConnectionAffectType::eFriendly, WarScroll::Spell())); WarScroll::addSummonable(ws, name, 6, 3, 12, 10, {"CHAOS", "WIZARD"}); return ws; } WarScroll Seekers_of_Slaanesh(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(14, 2, 10, 5); ws.addWeapon(WarScroll::Weapon("Piercing Claws", 1, 2, 4, 4, 1, 1)); ws.addWeapon(WarScroll::Weapon("Poisoned Tongue", 1, 2, 4, 4, 0, 1)); ws.setMinMaxUnitCount(5, IFaction::s_MaxUnitSize); ws.registerUnitUpgrade(WarScroll::UnitUpgrade("Heartseeker", WarScroll::UnitUpgrade::UnitUpgradeType::eChampion, 1)); ws.registerUnitUpgrade(WarScroll::UnitUpgrade("Icon Bearer", WarScroll::UnitUpgrade::UnitUpgradeType::eBannerBearer, 2)); ws.registerUnitUpgrade(WarScroll::UnitUpgrade("Hornblower", WarScroll::UnitUpgrade::UnitUpgradeType::eMusician, 1)); ws.addAbility(WarScroll::Ability("Graceful Killers", 1)); ws.addAbility(WarScroll::Ability("Quicksilver Speed", 2)); ws.addAbility(WarScroll::Ability("Locus of Swiftness", 1)); ws.addKeyWords({"CHAOS", "DAEMON", "DAEMONETTE", "SLAANESH", "SEEKERS"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); ws.addKeyWordConnection(WarScroll::KeyWordConnection("DAEMONETTE and HERO", 12, WarScroll::Ability("Locus of Swiftness", 1), 1, WarScroll::KeyWordConnection::ConnectionAffectType::eFriendly, WarScroll::Spell())); WarScroll::addSummonable(ws, name, 5, 3, 12, 5, {"CHAOS", "WIZARD"}); return ws; } WarScroll Fiends_of_Slaanesh(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(12, 4, 10, 5); ws.addWeapon(WarScroll::Weapon("Deadly Pincers", 1, 4, 4, 4, 0, 1)); ws.addWeapon(WarScroll::Weapon("Barbed Stinger", 2, 1, 4, 3, 1, 3)); ws.setMinMaxUnitCount(1, IFaction::s_MaxUnitSize); ws.addAbility(WarScroll::Ability("Vicious Pincers", 1)); ws.addAbility(WarScroll::Ability("Soporific Musk", 1)); ws.addAbility(WarScroll::Ability("Locus of Grace", 1)); ws.addKeyWords({"CHAOS", "DAEMON", "SLAANESH", "FIENDS"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); ws.addKeyWordConnection(WarScroll::KeyWordConnection("DAEMONETTE and HERO", 6, WarScroll::Ability("Locus of Grace", 1), 1, WarScroll::KeyWordConnection::ConnectionAffectType::eFriendly, WarScroll::Spell())); WarScroll::addSummonable(ws, name, 6, 3, 12, 1, {"CHAOS", "WIZARD"}); return ws; } WarScroll Seeker_Chariots_of_Slaanesh(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(12, 6, 10, 5); ws.addWeapon(WarScroll::Weapon("Alluress' Flensing Whips", 2, 3, 4, 4, 0, 1)); ws.addWeapon(WarScroll::Weapon("Daemonette's Piercing Claws", 1, 2, 4, 4, 1, 1)); ws.addWeapon(WarScroll::Weapon("Steeds' Poisoned Tongues", 1, 4, 4, 4, 0, 1)); ws.setMinMaxUnitCount(1, IFaction::s_MaxUnitSize); ws.addAbility(WarScroll::Ability("Impossibly Quick", 3)); ws.addAbility(WarScroll::Ability("Exenterating Blades", 1)); ws.addAbility(WarScroll::Ability("Deadly Grace", 1)); ws.addKeyWords({"CHAOS", "DAEMON", "DAEMONETTE", "SLAANESH", "SEEKER CHARIOTS"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); WarScroll::addSummonable(ws, name, 7, 3, 12, 1, {"CHAOS", "WIZARD"}); return ws; } WarScroll Exalted_Seeker_Chariots_of_Slaanesh(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(12, 9, 10, 5); ws.addWeapon(WarScroll::Weapon("Alluress' Flensing Whips", 2, 3, 4, 4, 0, 1)); ws.addWeapon(WarScroll::Weapon("Daemonettes' Piercing Claws", 1, 6, 4, 4, 1, 1)); ws.addWeapon(WarScroll::Weapon("Steeds' Poisoned Tongues", 1, 8, 4, 4, 0, 1)); ws.setMinMaxUnitCount(1, IFaction::s_MaxUnitSize); ws.addAbility(WarScroll::Ability("Swirling Shapes and Unholy Hues", 1)); ws.addAbility(WarScroll::Ability("Exalted Excess of Blades", 1)); ws.addAbility(WarScroll::Ability("Deadly Grace", 1)); ws.addKeyWords({"CHAOS", "DAEMON", "DAEMONETTE", "SLAANESH", "EXALTED SEEKER CHARIOTS"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); WarScroll::addSummonable(ws, name, 8, 3, 12, 1, {"CHAOS", "WIZARD"}); return ws; } WarScroll Hellflayers_of_Slaanesh(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(12, 6, 10, 5); ws.addWeapon(WarScroll::Weapon("Alluress' Piercing Claws", 1, 3, 4, 4, 1, 1)); ws.addWeapon(WarScroll::Weapon("Daemonettes' Flensing Whips", 2, 4, 4, 4, 0, 1)); ws.addWeapon(WarScroll::Weapon("Steeds' Poisoned Tongues", 1, 4, 4, 4, 0, 1)); ws.setMinMaxUnitCount(1, IFaction::s_MaxUnitSize); ws.addAbility(WarScroll::Ability("Deadly Grace", 1)); ws.addAbility(WarScroll::Ability("Soulscent", 1)); ws.addKeyWords({"CHAOS", "DAEMON", "DAEMONETTE", "SLAANESH", "HELLFLAYERS"}); WarScroll::addSummonable(ws, name, 7, 3, 12, 1, {"CHAOS", "WIZARD"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); return ws; } WarScroll Daemon_Prince_in_Slaanesh(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(8, 8, 10, 4); ws.addWeapon(WarScroll::Weapon("Malefic Talons", 1, 3, 4, 3, 0, 2)); ws.addAbility(WarScroll::Ability("Immortal Champion", 1)); ws.addAbility(WarScroll::Ability("Nurgle", 2)); ws.addWeaponUpgrade(WarScroll::WeaponUpgrade( WarScroll::Weapon("Daemonic Axe", 2, 4, 4, 3, 2, 3), WarScroll::Ability())); ws.addWeaponUpgrade(WarScroll::WeaponUpgrade( WarScroll::Weapon("Hellforged Sword", 2, 4, 3, 3, 1, 3), WarScroll::Ability())); WarScroll::MountUpgrade wingsUpgrade("Wings", true); wingsUpgrade.registerCharacteristicToIncrease("Move", 4); ws.registerMountUpgrade(wingsUpgrade); ws.addKeyWords({"CHAOS", "DAEMON", "SLAANESH", "MONSTER", "HERO", "DAEMON PRINCE"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); WarScroll::addSummonable(ws, name, 8, 3, 16, 1, {"CHAOS", "WIZARD"}); return ws; } WarScroll Furies_in_Slaanesh(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(12, 1, 10, 5); ws.setMinMaxUnitCount(1, IFaction::s_MaxUnitSize); ws.setCanFly(true); ws.addWeapon(WarScroll::Weapon("Hooked Claws", 1, 2, 4, 4, 0, 1)); ws.addAbility(WarScroll::Ability("Shadows of the Dark Gods", 1)); ws.addAbility(WarScroll::Ability("Prey Upon Terror", 1)); ws.addKeyWords({"CHAOS", "DAEMON", "FURIES", "SLAANESH"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); WarScroll::addSummonable(ws, name, 8, 3, 16, 1, {"CHAOS", "WIZARD"}); return ws; } WarScroll Soul_Grinder_in_Slaanesh(const std::string &name) { WarScroll ws; ws.setTitle(name); ws.setCharacteristics(12, 16, 10, 4); ws.addWeapon(WarScroll::Weapon("Harvester Cannon", 16, 6, 4, 3, 1, 1)); ws.addWeapon(WarScroll::Weapon("Phlegm Bombardment", 20, 1, 4, 3, 2, 3)); ws.addWeapon(WarScroll::Weapon("Piston-driven Legs", 1, 6, 4, 3, 1, 1)); ws.addWeapon(WarScroll::Weapon("Hellforged Claw", 2, 1, 4, 3, 2, 6)); ws.addAbility(WarScroll::Ability("Daemon Engine of the Dark God", 1)); ws.addAbility(WarScroll::Ability("Implacable Advance", 3)); ws.addAbility(WarScroll::Ability("Caught by the Claw", 2)); ws.addWeaponUpgrade(WarScroll::WeaponUpgrade( WarScroll::Weapon("No Additional Weapon", 0, 0, 7, 7, 0, 0), WarScroll::Ability())); ws.addWeaponUpgrade(WarScroll::WeaponUpgrade( WarScroll::Weapon("Warpmetal Blade", 2, 2, 4, 3, 2, 3), WarScroll::Ability())); ws.addWeaponUpgrade(WarScroll::WeaponUpgrade( WarScroll::Weapon("Daemonbone Talon", 2, 4, 3, 3, 1, 3), WarScroll::Ability())); ws.addKeyWords({"CHAOS", "DAEMON", "MONSTER", "SOUL GRINDER", "SLAANESH"}); ws.setGrandAllianceType(WarScroll::GrandAllianceType::eChaos); ws.addKeyWordConnection(WarScroll::KeyWordConnection("HERO or MONSTER", 2, WarScroll::Ability("Caught by the Claw", 2), 1, WarScroll::KeyWordConnection::ConnectionAffectType::eEnemy, WarScroll::Spell())); ws.addSummonable(ws, name, 10, 3, 16, 1, {"CHAOS", "WIZARD"}); return ws; } } DaemonsOfChaosSlaaneshFaction::DaemonsOfChaosSlaaneshFaction() : IFaction() { m_Units.push_back(""); m_Units.push_back("Keeper of Secrets"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Keeper_of_Secrets, m_Units.back()))); m_Units.push_back("The Masque of Slaanesh"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::The_Masque_of_Slaanesh, m_Units.back()))); m_Units.push_back("Herald of Slaanesh"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Herald_of_Slaanesh, m_Units.back()))); m_Units.push_back("Herald of Slaanesh on Seeker Chariot"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Herald_of_Slaanesh_on_Seeker_Chariot, m_Units.back()))); m_Units.push_back("Herald of Slaanesh on Exalted Seeker Chariot"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind( &WarScrollGeneration::Herald_of_Slaanesh_on_Exalted_Seeker_Chariot, m_Units.back()))); m_Units.push_back("Daemonettes of Slaanesh"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Daemonettes_of_Slaanesh, m_Units.back()))); m_Units.push_back("Seekers of Slaanesh"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Seekers_of_Slaanesh, m_Units.back()))); m_Units.push_back("Fiends of Slaanesh"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Fiends_of_Slaanesh, m_Units.back()))); m_Units.push_back("Seeker Chariots of Slaanesh"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Seeker_Chariots_of_Slaanesh, m_Units.back()))); m_Units.push_back("Exalted Seeker Chariots of Slaanesh"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Exalted_Seeker_Chariots_of_Slaanesh, m_Units.back()))); m_Units.push_back("Hellflayers of Slaanesh"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Hellflayers_of_Slaanesh, m_Units.back()))); m_Units.push_back("Daemon Prince"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Daemon_Prince_in_Slaanesh, m_Units.back()))); m_Units.push_back("Furies"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Furies_in_Slaanesh, m_Units.back()))); m_Units.push_back("Soul Grinder"); m_NameToWarScroll.insert(std::make_pair(m_Units.back(), std::bind(&WarScrollGeneration::Soul_Grinder_in_Slaanesh, m_Units.back()))); std::sort(m_Units.begin(), m_Units.end()); } const std::vector<std::string> &DaemonsOfChaosSlaaneshFaction::getUnits() const { return m_Units; } void DaemonsOfChaosSlaaneshFaction::getWarScrolls( std::list<WarScroll>& warScrolls) { for (const std::string &unit : m_Units) { if (unit.empty()) { continue; } WarScroll ws = m_NameToWarScroll[unit](unit); warScrolls.push_back(ws); } }
c39ebce86392695a6285f487d21aadd758123af9
41b3dc19df92c63a34ac4d0965557f8bc8e11b3c
/Data Structures/Arrays/WaveArray.cpp
9b5ac9b9f8f6a2f04c6a10ecd58e7e3cb40cafca
[]
no_license
AyushSri19-777/Coding-2020
6153228dad129f8bdbb8923bfe4c9ffacafb2e98
8585c2ec2573871a182c72183f372416039019e7
refs/heads/master
2022-12-24T20:46:49.235973
2020-10-01T18:39:33
2020-10-01T18:39:33
259,876,021
0
3
null
2020-10-01T18:39:34
2020-04-29T09:02:41
C++
UTF-8
C++
false
false
690
cpp
WaveArray.cpp
#include<bits/stdc++.h> using namespace std; int main() { int n; cout<<"Enter the number of array elements\n"; cin>>n; int arr[n]; cout<<"Enter array elements\n"; for(int i=0;i<n;i++) cin>>arr[i]; for(int i=0;i<n;i+=2) { if(i-1>0&&arr[i-1]>arr[i]) { arr[i-1]=arr[i-1]^arr[i]; arr[i]=arr[i]^arr[i-1]; arr[i-1]=arr[i-1]^arr[i]; } if(arr[i+1]>arr[i]) { arr[i+1]=arr[i+1]^arr[i]; arr[i]=arr[i]^arr[i+1]; arr[i+1]=arr[i+1]^arr[i]; } } cout<<"The wave form array\n"; for(int i=0;i<n;i++) cout<<arr[i]<<"\t"; }
841624df19dc0845bba62d4181324bd7aac44bb4
ccd40b971ef0ad5bec9e12fcaa81a7e63d74c551
/src/primitives.cpp
d5aa866f70bcb1721235e2c4296370e7d2eb95a8
[ "MIT" ]
permissive
Sindisil/ray-tracer-challenge-cpp
dd43ac7d89155f26c977111127838dd2f2efa18d
7588a28171f4546843d4fb97a9aad22b9a62b539
refs/heads/main
2023-02-28T05:20:10.983465
2021-02-04T06:54:07
2021-02-04T06:54:07
311,523,414
0
0
null
null
null
null
UTF-8
C++
false
false
513
cpp
primitives.cpp
#include "primitives.h" #include <ostream> namespace raytrace { auto Vector3::reflect(Vector3 normal) const -> Vector3 { return *this - normal * 2 * this->dot(normal); } auto operator<<(std::ostream &os, Vector3 const &val) -> std::ostream & { os << "Vec3(" << val.x << ", " << val.y << ", " << val.z << ")"; return os; } auto operator<<(std::ostream &os, Point const &val) -> std::ostream & { os << "Point(" << val.x << ", " << val.y << ", " << val.z << ")"; return os; } } // namespace raytrace
c3488b2f3e1d0ada5ef837f957b40608053c7234
b3cc0105d9cc7b25a6de5a637047872b6a87a0e1
/Trabalho2/Exercicio5/Exercicio5/Exercicio5.cpp
ccde9f1ab89597d0c63f9243cab439d2f40818ae
[]
no_license
joseeduardoleite/trabalhos-faculdade
300761cfe90d19fbf80dea3104a36f0b1330476c
8f21727d9616c54c5e8145e0d9bdad7871b336a6
refs/heads/main
2023-01-05T14:18:59.079896
2020-11-06T02:26:07
2020-11-06T02:26:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,348
cpp
Exercicio5.cpp
#include <iostream> #include <stdio.h> #include <stdint.h> #include <string.h> #include <math.h> //criação das structs struct ponto2d { int x, y; //atributos }; //estruturas struct ponto2d ponto_inicial; struct ponto2d ponto_final; int main() { int resposta = 0; //variavel para verificação de qual opcao o usuario irá querer double distancia; //variavel que fará o calculo da distancia while (true) //laço de repetição para sempre mostrar o menu { //menu das opcoes system("cls"); printf("[1] - Digitar os valores do primeiro ponto\n"); printf("[2] - Digitar os valores do segundo ponto\n"); printf("[3] - Mostrar a distância entre os pontos\n"); printf("[4] - Sair\n"); printf("\nDigite sua opcao: "); scanf_s("%d", &resposta); //lendo qual a opcao system("cls"); switch (resposta) //fazendo um switch case para cada pedido do usuario { case 1: //ler e armazenar os pontos iniciais system("cls"); printf("Digite o valor de x1:\n"); scanf_s("%d", &ponto_inicial.x); printf("Digite o valor de y1:\n"); scanf_s("%d", &ponto_inicial.y); break; case 2: //ler e armazenar os pontos finais system("cls"); printf("Digite o valor de x2:\n"); scanf_s("%d", &ponto_final.x); printf("Digite o valor de y2:\n"); scanf_s("%d", &ponto_final.y); break; case 3: //efetuar o calculo e mostrar ao usuario system("cls"); //fiz um sqrt para pegar a raiz e o pow para elevar ao quadrado o ponto inicial menos o ponto final distancia = sqrt(pow(ponto_inicial.x - ponto_final.x, 2) + pow(ponto_inicial.y - ponto_final.y, 2)); printf("A distancia entre os pontos e:\n"); printf("%.2f\n", distancia); system("pause"); break; case 4: //despedida system("cls"); printf("Obrigado e ate mais...\n"); system("pause"); return 0; default: //por default exibirá esta mensagem e voltará ao menu principal printf("Voce digitou o numero errado!"); } } }
756906e85db1875f930d853548c2fd70948fe984
0253211cf030ee20f34894442e8ef222c0aebb25
/Pr03a-Patient-maharjan-pratistha (1).cpp
b31a80ecc2cff86c24a19c3bf5eba5ffbd4d6af5
[]
no_license
Pratistha98/Comsc-110
bb27bb968bdc0ef749863f07abe47780abb81488
b158ed29dc9e8c6ebb4f9a711807a2c109d4954f
refs/heads/master
2020-06-29T17:42:10.939540
2019-08-05T04:30:51
2019-08-05T04:30:51
200,582,188
0
0
null
null
null
null
UTF-8
C++
false
false
1,180
cpp
Pr03a-Patient-maharjan-pratistha (1).cpp
/* School: Diablo Valley College Term : 2017 Fall Course: ComSc-110-3120, Introduction to Programming (With C++) Chapter: 3 Program: Pr03a-Patient-maharjan-pratistha.cpp Author : Maharjan, Pratistha Date : Aug.24,2017 Purpose: Get familiar with: -- declaring variables of different types -- assigning values to variables -- outputting labels and variables values -- coding conventionns( see a seperate document on the course web site) */ #include <iostream> #include <string> using namespace std; int main() { //Declare variables string name; //Patient name (last, First) char gender; //Patient gender (M or F) int age; //Patient age (years) int height; //Patient height (inches) //Assign values to variables for patient 1 name = "Washington, Goerge"; gender ='M'; age = 57; height = 74; //To the console, output labels and //output values for patient 1 variables cout << endl; cout << "Name : " << name << endl; cout << "Gender: " << gender << endl; cout << "Age : " << age << endl; cout << "Height: " << height << endl; }
52015e6e13232889de88a41f20067d5ebfa93988
76270c3a731e8f4906153a897fbbcf2e3ef63711
/src/Parser.cpp
9cbd365e5234dece18b94fa477369d1c355d7312
[ "BSD-2-Clause" ]
permissive
wrighteagle2d/wrighteaglebase
c16c5f0e5e15dace3bf3bbf9464017fd6b495487
758b7fc3ef2166e33b4e1a91a9bd799e26aefa6b
refs/heads/master
2022-09-23T20:54:56.466493
2022-09-19T05:53:44
2022-09-19T05:53:44
42,196,878
96
46
null
null
null
null
UTF-8
C++
false
false
65,641
cpp
Parser.cpp
/************************************************************************************ * WrightEagle (Soccer Simulation League 2D) * BASE SOURCE CODE RELEASE 2016 * * Copyright (c) 1998-2016 WrightEagle 2D Soccer Simulation Team, * Multi-Agent *Systems Lab., * School of Computer Science and *Technology, * University of Science and Technology of China * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * Neither the name of the WrightEagle 2D Soccer Simulation Team 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 WrightEagle 2D Soccer *Simulation Team BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, *PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR *PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF *LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING *NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, *EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ************************************************************************************/ #include "Parser.h" #include "DynamicDebug.h" #include "Logger.h" #include "NetworkTest.h" #include "Observer.h" #include "PlayerParam.h" #include "ServerParam.h" #include "Thread.h" #include "TimeTest.h" #include "UDPSocket.h" #include <limits> char Parser::mBuf[MAX_MESSAGE]; bool Parser::mIsPlayerTypesReady = false; const double Parser::INVALID_VALUE = std::numeric_limits<double>::max(); #ifdef _Debug #define PARSE_ERROR(x) PRINT_ERROR((x)) #else #define PARSE_ERROR(x) #endif Parser::Parser(Observer *p_observer) { mpObserver = p_observer; mConnectServerOk = false; mHalfTime = 0; mClangOk = false; mSynchOk = false; mEyeOnOk = false; mEarOnOk = false; mLastServerPlayMode = SPM_Null; ServerPlayModeMap::instance(); if (PlayerParam::instance().isCoach()) { UDPSocket::instance().Initial(ServerParam::instance().serverHost().c_str(), ServerParam::instance().onlineCoachPort()); } else if (PlayerParam::instance().isTrainer()) { UDPSocket::instance().Initial(ServerParam::instance().serverHost().c_str(), ServerParam::instance().offlineCoachPort()); } else { UDPSocket::instance().Initial(ServerParam::instance().serverHost().c_str(), ServerParam::instance().playerPort()); } } Parser::~Parser() {} void Parser::StartRoutine() { ConnectToServer(); while (true) { if (UDPSocket::instance().Receive(mBuf) > 0) { NetworkTest::instance().AddParserBegin(); DynamicDebug::instance().AddMessage(mBuf, MT_Parse); // 动态调试记录Parser信息 mpObserver->Lock(); // parse时禁止WorldState更新 Parse(mBuf); mpObserver->UnLock(); NetworkTest::instance().AddParserEnd(mpObserver->CurrentTime()); } } } void Parser::ConnectToServer() { mOkMutex.Lock(); mConnectServerOk = false; mOkMutex.UnLock(); SendInitialLizeMsg(); do { UDPSocket::instance().Receive(mBuf); } while (!ParseInitializeMsg(mBuf)); mOkMutex.Lock(); mConnectServerOk = true; mOkMutex.UnLock(); DynamicDebug::instance().Initial( mpObserver); // 动态调试的初始化,知道自己是哪边了才能初始化,位置不能动 DynamicDebug::instance().AddMessage(mBuf, MT_Parse); // 动态调试记录Parse信息 // Logger::instance().GetTextLogger("msg-text") << mBuf << std::endl; } void Parser::SendInitialLizeMsg() { // TODO: how about reconnect std::ostringstream init_string; if (PlayerParam::instance().isCoach()) { init_string << "(init " << PlayerParam::instance().teamName() << " (version " << PlayerParam::instance().coachVersion() << "))"; } else if (PlayerParam::instance().isGoalie()) { init_string << "(init " << PlayerParam::instance().teamName() << " (version " << PlayerParam::instance().playerVersion() << ") (goalie))"; } else if (PlayerParam::instance().isTrainer()) { init_string << "(init " << " (version " << PlayerParam::instance().playerVersion() << "))"; } else { init_string << "(init " << PlayerParam::instance().teamName() << " (version " << PlayerParam::instance().playerVersion() << "))"; } if (UDPSocket::instance().Send(init_string.str().c_str()) < 0) { PRINT_ERROR("send_initialize_message failed"); } } bool Parser::ParseInitializeMsg(const char *msg) { char play_mode[128]; char my_side = '?'; Unum my_unum = 0; // TODO: how about reconnect if (PlayerParam::instance().isCoach()) { if (!(strncmp(msg, "(init", 4))) { // initialize message sscanf(msg, "(init %c %[^)]", &my_side, play_mode); } else { return false; } } else if (PlayerParam::instance().isTrainer()) { if (!(strcmp(msg, "(init ok)"))) { // initialize message //初始信息没有我们的信息,Trainer是全局的 } else { return false; } my_side = 'l'; //设定trainer是我方的 my_unum = TRAINER_UNUM; //设定trainer的号码为12号 play_mode[0] = 'b'; } else { if (!(strncmp(msg, "(init", 4))) { // initialize message sscanf(msg, "(init %c %d %[^)]", &my_side, &my_unum, play_mode); } else { return false; } } mpObserver->SetOurInitSide(my_side); mpObserver->SetOurSide(my_side); mpObserver->SetSelfUnum(my_unum); ++mHalfTime; if (play_mode[0] == 'b' || PlayerParam::instance().isCoach()) { /* Before_kick_off */ mpObserver->SetPlayMode(PM_Before_Kick_Off); mpObserver->SetServerPlayMode(SPM_BeforeKickOff); if (mpObserver->OurInitSide() == 'l') mpObserver->SetKickOffMode(KO_Ours); else mpObserver->SetKickOffMode(KO_Opps); } else { mpObserver->SetPlayMode(PM_Play_On); mpObserver->SetServerPlayMode(SPM_PlayOn); } mpObserver->Initialize(); //必须知道自己是哪边的才能初始化 TimeTest::instance().SetUnum(my_unum); // TimeTest的记录文件名会用到 NetworkTest::instance().SetUnum(my_unum); return true; } void Parser::Parse(char *msg) { ServerMsgType msg_type = None_Msg; switch (msg[1]) { case 'i': msg_type = Initialize_Msg; break; /* ( i nit */ case 'c': switch (msg[2]) { case 'h': msg_type = ChangePlayerType_Msg; break; /* ( c h ange */ case 'l': msg_type = Clang_Msg; break; /* ( c l ang */ } break; case 'd': msg_type = Disp_Msg; break; /* (d isp */ case 'e': msg_type = Error_Msg; break; /* ( e rror */ case 'f': msg_type = Fullstate_Msg; break; /* ( f ullstate */ case 'h': msg_type = Hear_Msg; break; /* ( h ear */ case 'o': msg_type = Ok_Msg; break; /* ( o k */ case 'p': switch (msg[8]) { case 'p': msg_type = PlayerParam_Msg; break; /* (p layer_ p ram */ case 't': msg_type = PlayerType_Msg; break; /* ( p layer_ t ype */ default: msg_type = None_Msg; break; } break; case 's': switch (msg[3]) { case 'o': msg_type = Score_Msg; break; /* ( s c o re */ case 'e': switch (msg[4]) { case ' ': msg_type = Sight_Msg; break; /* ( s e e */ case '_': msg_type = CoachSight_Msg; break; /* ( s e e _global */ default: msg_type = None_Msg; break; } break; case 'n': msg_type = Sense_Msg; break; /* ( s e n se_body */ case 'r': msg_type = ServerParam_Msg; break; /* ( s e r ver_param */ default: msg_type = None_Msg; break; } break; case 't': msg_type = Think_Msg; break; /* (t hink */ default: msg_type = None_Msg; break; } char *time_end = 0; switch (msg_type) { case Sight_Msg: ParseTime(msg, &time_end, false); ParseSight(time_end); mpObserver->SetNewSight(); break; case CoachSight_Msg: ParseTime(msg, &time_end, true); ParseSight_Coach(time_end); mpObserver->SetNewSight(); break; case Sense_Msg: ParseTime(msg, &time_end, true); ParseSense(time_end); mpObserver->SetNewSense(); break; case Hear_Msg: if (!ParseForTrainer(msg)) { ParseTime(msg, &time_end, true); ParseSound(time_end); } break; case PlayerParam_Msg: ParsePlayerParam(msg); break; case ServerParam_Msg: ParseServerParam(msg); break; case Disp_Msg: /*TODO: process disp message */ break; case Fullstate_Msg: ParseFullstateMsg(msg); break; case ChangePlayerType_Msg: ParseChangePlayerType(msg); break; case Clang_Msg: /*TODO: process clang message*/ break; case PlayerType_Msg: ParsePlayerType(msg); break; case Score_Msg: /*TODO: process score message*/ break; case Ok_Msg: ParseOkMsg(msg); break; case Initialize_Msg: ParseInitializeMsg(msg); break; case Error_Msg: std::cout << mpObserver->SelfUnum() << "@" << mpObserver->CurrentTime() << ": " << msg << std::endl; break; case Think_Msg: mpObserver->SetNewThink(); break; case None_Msg: PRINT_ERROR(mpObserver->CurrentTime() << msg); break; } } void Parser::ParseFullstateMsg(char *msg) { //(fullstate 336 (pmode goal_l) (vmode high narrow) (count 0 0 313 0 1 290 8 //743) (arm (movable 0) (expires 0) (target 0 0) (count 0)) (score 1 0) //((b) 52.6578 -4.41664 0 0) //((p l 1 g 8) -47.5 0 0 0 -66.8915 -80 (stamina 8000 0.829636 1 130600)) //((p l 2 4) -25 -13 7.7863e-25 4.77769e-24 151.664 34 (stamina 8000 0.974746 //1 123249)) //((p l 3 12) -5.00073 -8.01793 -1.54512e-19 -8.12881e-18 -25.8413 -66 //(stamina 7621.08 0.985774 1 111028)) //... //((p r 11 14) 0.385 -7.01275e-12 -1.15337e-23 -8.33192e-24 46.129 0 (stamina //8000 0.933173 1 124249))) int time = parser::get_int(&msg); if (time != mpObserver->CurrentTime().T()) { mpObserver->SetCurrentTime(Time(time, mpObserver->CurrentTime().S())); } parser::get_word(&msg); parser::get_next_word(&msg); // skip 'pmode' parser::get_word(&msg); { static char buffer[MAX_MESSAGE]; char *end = msg; while (*end != ')') end++; int n = end - msg; strncpy(buffer, msg, n * sizeof(char)); buffer[n] = '\0'; ParsePlayMode(buffer); msg = end; } parser::get_next_word(&msg); // skip 'vmode' parser::get_next_word(&msg); // skip not used view quality ViewWidth view_width = VW_None; switch (msg[1]) { case 'o': view_width = VW_Normal; break; /* normal */ case 'a': view_width = VW_Narrow; break; /* narrow */ case 'i': view_width = VW_Wide; break; /* wide */ default: PARSE_ERROR("Unknown view quality"); break; } int kicks = parser::get_int(&msg); int dashes = parser::get_int(&msg); int turns = parser::get_int(&msg); int catchs = parser::get_int(&msg); int moves = parser::get_int(&msg); int turn_necks = parser::get_int(&msg); int change_views = parser::get_int(&msg); int says = parser::get_int(&msg); int arm_movable_ban = parser::get_int(&msg); // 直到下次手臂能动的剩余周期数 int arm_expires = parser::get_int(&msg); // 直到手臂动作失效剩余的周期数 double arm_target_dist = parser::get_double(&msg); // 指向的目标的距离 AngleDeg arm_target_dir = parser::get_double(&msg); // 指向的目标的方向 int arm_count = parser::get_int(&msg); // point count mpObserver->SetSensePartialBody( view_width, kicks, dashes, turns, says, turn_necks, catchs, moves, change_views, arm_movable_ban, arm_expires, arm_target_dist, arm_target_dir, arm_count, mpObserver->CurrentTime()); for (int i = 1; i <= TEAMSIZE; ++i) { mpObserver->Teammate_Fullstate(i).SetIsAlive(false); mpObserver->Opponent_Fullstate(i).SetIsAlive(false); } msg = strstr(msg, "(("); while (msg != 0) { // 直到没有object为止 msg += 2; // 跳过 (( ObjType obj = ParseObjType_Fullstate(msg); // 获得object的类型 msg = strchr(msg, ')'); ObjProperty_Fullstate prop = ParseObjProperty_Fullstate(msg + 1); // 获得object的属性 switch (obj.type) { case OBJ_Ball: mpObserver->Ball_Fullstate().UpdatePos(Vector(prop.x, prop.y), 0, 1.0); mpObserver->Ball_Fullstate().UpdateVel(Vector(prop.vx, prop.vy), 0, 1.0); break; case OBJ_Player: if (obj.side == mpObserver->OurSide()) { mpObserver->Teammate_Fullstate(obj.num).UpdatePlayerType( obj.player_type); mpObserver->Teammate_Fullstate(obj.num).SetIsAlive(true); mpObserver->Teammate_Fullstate(obj.num).UpdatePos( Vector(prop.x, prop.y), 0, 1.0); mpObserver->Teammate_Fullstate(obj.num).UpdateVel( Vector(prop.vx, prop.vy), 0, 1.0); mpObserver->Teammate_Fullstate(obj.num).UpdateBodyDir(prop.body_dir, 0, 1.0); mpObserver->Teammate_Fullstate(obj.num).UpdateNeckDir(prop.head_dir, 0, 1.0); mpObserver->Teammate_Fullstate(obj.num).UpdateStamina(prop.stamina); mpObserver->Teammate_Fullstate(obj.num).UpdateEffort(prop.effort); mpObserver->Teammate_Fullstate(obj.num).UpdateRecovery(prop.recovery); mpObserver->Teammate_Fullstate(obj.num).UpdateCapacity(prop.capacity); mpObserver->Teammate_Fullstate(obj.num).UpdateCardType(prop.card_type); if (prop.pointing) { mpObserver->Teammate_Fullstate(obj.num).UpdateArmPoint( prop.point_dir, 0, 1.0, 0.0, 0, 0); // TODO: // 这个接口不好,因为是看不到dist,ban等信息的,这些要自己算然后维护 } if (prop.tackling) { if (mpObserver->Teammate_Fullstate(obj.num).GetTackleBan() == 0) { mpObserver->Teammate_Fullstate(obj.num).UpdateTackleBan( ServerParam::instance().tackleCycles() - 1); } } else { mpObserver->Teammate_Fullstate(obj.num).UpdateTackleBan(0); } if (prop.lying) { if (mpObserver->Teammate_Fullstate(obj.num).GetFoulChargedCycle() == 0) { mpObserver->Teammate_Fullstate(obj.num).UpdateFoulChargedCycle( ServerParam::instance().foulCycles() - 1); } } else { mpObserver->Teammate_Fullstate(obj.num).UpdateFoulChargedCycle(0); } } else { mpObserver->Opponent_Fullstate(obj.num).UpdatePlayerType( obj.player_type); mpObserver->Opponent_Fullstate(obj.num).SetIsAlive(true); mpObserver->Opponent_Fullstate(obj.num).UpdatePos( Vector(prop.x, prop.y), 0, 1.0); mpObserver->Opponent_Fullstate(obj.num).UpdateVel( Vector(prop.vx, prop.vy), 0, 1.0); mpObserver->Opponent_Fullstate(obj.num).UpdateBodyDir(prop.body_dir, 0, 1.0); mpObserver->Opponent_Fullstate(obj.num).UpdateNeckDir(prop.head_dir, 0, 1.0); mpObserver->Opponent_Fullstate(obj.num).UpdateStamina(prop.stamina); mpObserver->Opponent_Fullstate(obj.num).UpdateEffort(prop.effort); mpObserver->Opponent_Fullstate(obj.num).UpdateRecovery(prop.recovery); mpObserver->Opponent_Fullstate(obj.num).UpdateCapacity(prop.capacity); mpObserver->Opponent_Fullstate(obj.num).UpdateCardType(prop.card_type); if (prop.pointing) { mpObserver->Opponent_Fullstate(obj.num).UpdateArmPoint( prop.point_dir, 0, 1.0, 0.0, 0, 0); // TODO: // 这个接口不好,因为是看不到dist,ban等信息的,这些要自己算然后维护 } if (prop.tackling) { if (mpObserver->Opponent_Fullstate(obj.num).GetTackleBan() == 0) { mpObserver->Opponent_Fullstate(obj.num).UpdateTackleBan( ServerParam::instance().tackleCycles() - 1); } } else { mpObserver->Opponent_Fullstate(obj.num).UpdateTackleBan(0); } if (prop.lying) { if (mpObserver->Opponent_Fullstate(obj.num).GetFoulChargedCycle() == 0) { mpObserver->Opponent_Fullstate(obj.num).UpdateFoulChargedCycle( ServerParam::instance().foulCycles() - 1); } } else { mpObserver->Opponent_Fullstate(obj.num).UpdateFoulChargedCycle(0); } } break; default: break; } msg = strstr(msg, "(("); // 下一个object } mpObserver->mReceiveFullstateMsg = true; } void Parser::ParseTime(char *msg, char **end_ptr, bool is_new_cycle) { while (!isspace(*msg)) msg++; *end_ptr = msg; int time = parser::get_int(end_ptr); RealTime real_time = GetRealTimeParser(); /* if (mpObserver->IsPlanned()) { // -- 决策完了,才收到信息 std::cerr << "# " << mpObserver->SelfUnum() << " @ " << mpObserver->CurrentTime() << " got a deprecated message" << std::endl; }*/ if (is_new_cycle == true) { /** player: sense msg & hear msg */ /** coach: sight msg & hear msg */ if (time > mpObserver->CurrentTime().T()) // new cycle { mpObserver->SetCurrentTime(Time(time, 0)); mpObserver->SetLastCycleBeginRealTime(real_time); } else { if (real_time - mpObserver->GetLastCycleBeginRealTime() > ServerParam::instance().simStep() * 0.7) // stoppage time, add some buffer { mpObserver->SetCurrentTime( Time(time, mpObserver->CurrentTime().S() + 1)); mpObserver->SetLastCycleBeginRealTime(real_time); } else { // the current time has been set by another msg just now } } } else { /** player: sight msg */ if (time != mpObserver->CurrentTime().T()) // new cycle -- miss a sense { mpObserver->SetCurrentTime(Time(time, 0)); mpObserver->SetLastCycleBeginRealTime( real_time - ServerParam::instance().synchOffset()); PRINT_ERROR("Player " << mpObserver->SelfUnum() << " miss a sense at " << mpObserver->CurrentTime()); } } } void Parser::ParsePlayerParam(char *msg) { Logger::instance().InitSightLogger(PlayerParam_Msg, msg); msg += 13; // 去掉"(player_param" PlayerParam::instance().ParseFromServerMsg(msg); PlayerParam::instance().MaintainConsistency(); } void Parser::ParseServerParam(char *msg) { Logger::instance().InitSightLogger(ServerParam_Msg, msg); msg += 13; // 去掉"(server_param" ServerParam::instance().ParseFromServerMsg(msg); ServerParam::instance().MaintainConsistency(); } void Parser::ParsePlayerType(char *msg) { Logger::instance().InitSightLogger(PlayerType_Msg, msg); char *p = msg; while (!isspace(*p)) p++; while (isspace(*p)) p++; char *line = p; while (!isspace(*p)) p++; int type = parser::get_int(p); PlayerParam::instance().AddPlayerType(type, line); if (type >= PlayerParam::instance().playerTypes() - 1) { mIsPlayerTypesReady = true; } } void Parser::ParseChangePlayerType(char *msg) { int player = parser::get_int(&msg); if (*msg != ')') { int type = parser::get_int(msg); mpObserver->SetTeammateType(player, type); } else { mpObserver->AddOpponentTypeChangedCount(player); } } void Parser::ParseSight(char *msg) { NetworkTest::instance().End("Sense", "Sight"); mpObserver->SetLastSightRealTime( GetRealTimeParser()); // set the last sight time mpObserver->SetLatestSightTime(mpObserver->CurrentTime()); msg = strstr(msg, "(("); while (msg != 0) { // 直到没有object为止 msg += 2; // 跳过 (( ObjType obj = ParseObjType(msg); // 获得object的类型 msg = strchr(msg, ')'); ObjProperty prop = ParseObjProperty(msg + 1); // 获得object的属性 switch (obj.type) { case OBJ_Marker: case OBJ_Marker_Behind: if (obj.marker == FLAG_NONE) { if (obj.type != OBJ_Marker_Behind) { PARSE_ERROR("Should know the marker"); } break; } if (InvalidValue(prop.dir_chg)) { mpObserver->SeeMarker(obj.marker, prop.dist, prop.dir); } else { /* know direction*/ mpObserver->SeeMarker(obj.marker, prop.dist, prop.dir, prop.dist_chg, prop.dir_chg); } break; case OBJ_Line: mpObserver->SeeLine(obj.line, prop.dist, prop.dir); break; case OBJ_Ball: if (InvalidValue(prop.dir_chg)) { /* high quality */ mpObserver->SeeBall(prop.dist, prop.dir); } else { /* know direction*/ mpObserver->SeeBall(prop.dist, prop.dir, prop.dist_chg, prop.dir_chg); } break; case OBJ_Player: if (obj.side == '?') { /* Too far for team or num */ if (InvalidValue(prop.dir_chg)) { /* high quality */ mpObserver->SeePlayer(prop.dist, prop.dir); } else { /* know direction*/ PARSE_ERROR("Shouldn't know dirChng when the player's far"); } } else { // 知道是哪边的 if (obj.num == 0) { /* Too far for number */ if (InvalidValue(prop.dir_chg)) { /* high quality */ mpObserver->SeePlayer(obj.side, prop.dist, prop.dir, prop.tackling, prop.kicked, prop.lying, prop.card_type); } else { /* know direction*/ PARSE_ERROR("Shouldn't know dirChng when the team Member's far"); } } else { /* Know side AND number */ if (InvalidValue(prop.dir_chg)) { /* high quality */ mpObserver->SeePlayer(obj.side, obj.num, prop.dist, prop.dir, prop.pointing, prop.point_dir, prop.tackling, prop.kicked, prop.lying, prop.card_type); } else { /* know direction*/ mpObserver->SeePlayer(obj.side, obj.num, prop.dist, prop.dir, prop.dist_chg, prop.dir_chg, prop.body_dir, prop.head_dir, prop.pointing, prop.point_dir, prop.tackling, prop.kicked, prop.lying, prop.card_type); } } } break; default: break; } msg = strstr(msg, "(("); // 下一个object } } Parser::ObjType Parser::ParseObjType_Fullstate(char *msg) { switch (*msg) { case 'p': case 'P': return ParsePlayer_Fullstate(msg); case 'b': case 'B': return ParseBall(msg); default: PARSE_ERROR("unknown object"); break; } ObjType result; result.type = OBJ_None; return result; } Parser::ObjType Parser::ParseObjType(char *msg) { switch (*msg) { case 'g': case 'G': return ParseGoal(msg); case 'f': case 'F': return ParseMarker(msg); case 'l': return ParseLine(msg); case 'p': case 'P': return ParsePlayer(msg); case 'b': case 'B': return ParseBall(msg); default: PARSE_ERROR("unknown object"); break; } ObjType result; result.type = OBJ_None; return result; } Parser::ObjType Parser::ParseGoal(char *msg) { ObjType result; if (*msg == 'g') { // goal result.type = OBJ_Marker; msg += 2; // 'g ' if (*msg == 'r') { result.marker = Goal_R; } else if (*msg == 'l') { result.marker = Goal_L; } else { PARSE_ERROR("goal ?"); } } else if (*msg == 'G') { // goal behind result.type = OBJ_Marker_Behind; // result.marker = _pMem->ClosestGoal(); TODO: how to process? } return result; } Parser::ObjType Parser::ParseMarker(char *msg) { ObjType result; if (*msg == 'f') { // flag result.type = OBJ_Marker; msg += 2; // 'f ' if (*msg == 'r') { msg += 2; // 'r' if (*msg == '0') { result.marker = Flag_R0; } else if (*msg == 'b') { msg += 1; if (*msg == ')') { result.marker = Flag_RB; } else { // flag r b msg += 1; // skip space if (*msg == '1') { result.marker = Flag_RB10; } else if (*msg == '2') { result.marker = Flag_RB20; } else if (*msg == '3') { result.marker = Flag_RB30; } else { PARSE_ERROR("flag r b ?"); } } } else if (*msg == 't') { msg += 1; if (*msg == ')') { result.marker = Flag_RT; } else { // flag r t msg += 1; if (*msg == '1') { result.marker = Flag_RT10; } else if (*msg == '2') { result.marker = Flag_RT20; } else if (*msg == '3') { result.marker = Flag_RT30; } else { PARSE_ERROR("flag r t ?"); } } } else { PARSE_ERROR("flag r ?"); } } else if (*msg == 'l') { // flag l msg += 2; // 'l ' if (*msg == '0') { result.marker = Flag_L0; } else if (*msg == 'b') { // flag l b msg += 1; if (*msg == ')') { result.marker = Flag_LB; } else { msg += 1; if (*msg == '1') { result.marker = Flag_LB10; } else if (*msg == '2') { result.marker = Flag_LB20; } else if (*msg == '3') { result.marker = Flag_LB30; } else { PARSE_ERROR("flag l b ?"); } } } else if (*msg == 't') { // flag l t msg += 1; if (*msg == ')') { result.marker = Flag_LT; } else { msg += 1; if (*msg == '1') { result.marker = Flag_LT10; } else if (*msg == '2') { result.marker = Flag_LT20; } else if (*msg == '3') { result.marker = Flag_LT30; } else { PARSE_ERROR("flag l t ?"); } } } else { PARSE_ERROR("flag l ?"); } } else if (*msg == 't') { // flag t msg += 2; if (*msg == '0') { result.marker = Flag_T0; } else if (*msg == 'l') { msg += 2; if (*msg == '1') { result.marker = Flag_TL10; } else if (*msg == '2') { result.marker = Flag_TL20; } else if (*msg == '3') { result.marker = Flag_TL30; } else if (*msg == '4') { result.marker = Flag_TL40; } else if (*msg == '5') { result.marker = Flag_TL50; } else { PARSE_ERROR("flag t l ?"); } } else if (*msg == 'r') { msg += 2; if (*msg == '1') { result.marker = Flag_TR10; } else if (*msg == '2') { result.marker = Flag_TR20; } else if (*msg == '3') { result.marker = Flag_TR30; } else if (*msg == '4') { result.marker = Flag_TR40; } else if (*msg == '5') { result.marker = Flag_TR50; } else { PARSE_ERROR("flag t r ?"); } } else { PARSE_ERROR("flag t ?"); } } else if (*msg == 'b') { msg += 2; if (*msg == '0') { result.marker = Flag_B0; } else if (*msg == 'l') { msg += 2; if (*msg == '1') { result.marker = Flag_BL10; } else if (*msg == '2') { result.marker = Flag_BL20; } else if (*msg == '3') { result.marker = Flag_BL30; } else if (*msg == '4') { result.marker = Flag_BL40; } else if (*msg == '5') { result.marker = Flag_BL50; } else { PARSE_ERROR("flag b l ?"); } } else if (*msg == 'r') { msg += 2; if (*msg == '1') { result.marker = Flag_BR10; } else if (*msg == '2') { result.marker = Flag_BR20; } else if (*msg == '3') { result.marker = Flag_BR30; } else if (*msg == '4') { result.marker = Flag_BR40; } else if (*msg == '5') { result.marker = Flag_BR50; } else { PARSE_ERROR("flag b r ?"); } } else { PARSE_ERROR("flag b ?"); } } else if (*msg == 'c') { msg += 1; if (*msg == ')') { result.marker = Flag_C; } else { msg += 1; if (*msg == 'b') { result.marker = Flag_CB; } else if (*msg == 't') { result.marker = Flag_CT; } else { PARSE_ERROR("flag c ?"); } } } else if (*msg == 'p') { msg += 2; if (*msg == 'r') { msg += 2; if (*msg == 't') { result.marker = Flag_PRT; } else if (*msg == 'c') { result.marker = Flag_PRC; } else if (*msg == 'b') { result.marker = Flag_PRB; } else { PARSE_ERROR("flag p r ?"); } } else if (*msg == 'l') { msg += 2; if (*msg == 't') { result.marker = Flag_PLT; } else if (*msg == 'c') { result.marker = Flag_PLC; } else if (*msg == 'b') { result.marker = Flag_PLB; } else { PARSE_ERROR("flag p l ?"); } } else { PARSE_ERROR("flag p ?"); } } else if (*msg == 'g') { msg += 2; if (*msg == 'l') { msg += 2; if (*msg == 't') { result.marker = Flag_GLT; } else if (*msg == 'b') { result.marker = Flag_GLB; } else { PARSE_ERROR("flag g l ?"); } } else if (*msg == 'r') { msg += 2; if (*msg == 't') { result.marker = Flag_GRT; } else if (*msg == 'b') { result.marker = Flag_GRB; } else { PARSE_ERROR("flag g r ?"); } } else { PARSE_ERROR("flag g ?"); } } else { PARSE_ERROR("flag ?"); } } else if (*msg == 'F') { // Flag behind result.type = OBJ_Marker_Behind; // result.marker = _pMem->ClosestFlagTo(); /*TODO: could be No_Marker */ } return result; } Parser::ObjType Parser::ParseLine(char *msg) { ObjType result; result.type = OBJ_Line; msg += 2; // 'l' if (*msg == 'r') { result.line = SL_Right; } else if (*msg == 'l') { result.line = SL_Left; } else if (*msg == 't') { result.line = SL_Top; } else if (*msg == 'b') { result.line = SL_Bottom; } else { PARSE_ERROR("line ?"); } return result; } Parser::ObjType Parser::ParsePlayer_Fullstate(char *msg) { //((p l 1 g 8) -47.5 0 0 0 -66.8915 -80 (stamina 8000 0.829636 1 130600)) //((p r 11 14) 0.385 -7.01275e-12 -1.15337e-23 -8.33192e-24 46.129 0 (stamina //8000 0.933173 1 124249))) ObjType result; result.type = OBJ_Player; msg += 2; // 'p ' result.side = *msg; result.num = parser::get_int(&msg); msg += 1; if (*msg == 'g') { if (result.side != mpObserver->OurInitSide()) { mpObserver->SeeOppGoalie(result.num); } } result.player_type = parser::get_int(&msg); return result; } Parser::ObjType Parser::ParsePlayer(char *msg) { ObjType result; const char *team_name = PlayerParam::instance().teamName().c_str(); int team_name_len = PlayerParam::instance().teamNameLen(); result.type = OBJ_Player; msg += 1; // 'p' if (*msg == ' ') { /* there's a team */ msg += 2; // skip space and " if (msg[team_name_len] == '"' && !strncmp(msg, team_name, team_name_len)) { /* 一定要比较到双引号("),防止出现一个队名包含另一个的问题 */ result.side = mpObserver->OurSide(); } else { if (PlayerParam::instance().opponentTeamName().empty()) { int a = 0; char tmp[256]; while (*msg != '"') { tmp[a++] = *msg++; } tmp[a] = '\0'; PlayerParam::instance().setOpponentTeamName(tmp); } result.side = mpObserver->OppSide(); } while (*msg != ' ' && *msg != ')') { msg++; } /* advance past team name */ if (*msg == ' ') { /* there's a number */ result.num = parser::get_int(&msg); } if (*msg == ' ') { // will be goalie msg += 1; if (!strncmp(msg, "goalie", 6)) { // there's goalie if (result.side == mpObserver->OurInitSide()) { // our goalie unum is no need to set } else { mpObserver->SeeOppGoalie(result.num); } } while (*msg != ' ' && *msg != ')') { msg++; } /* advance past goalie */ } } return result; } Parser::ObjType Parser::ParseBall(char *msg) { (void)msg; ObjType result; result.type = OBJ_Ball; return result; } Parser::ObjProperty Parser::ParseObjProperty(char *msg) { ObjProperty result; /* 'high' quality only */ result.dist = parser::get_double(&msg); /* 'high' quality */ result.dir = parser::get_double(&msg); if (*msg != ')') { if (*msg == ' ') { ++msg; } if (*msg == 't') { result.tackling = true; ++msg; } else if (*msg == 'k') { result.kicked = true; ++msg; } else if (*msg == 'f') { result.lying = true; ++msg; } } if (*msg != ')') { result.dist_chg = parser::get_double(&msg); // 也可能是pointdir if (*msg == ' ') { // 后面还有 msg++; // 跳过空格 if (*msg == 't' || *msg == 'k' || *msg == 'f') { if (*msg == 't') { result.tackling = true; } else if (*msg == 'k') { result.kicked = true; } else result.lying = true; msg++; result.point_dir = result.dist_chg; result.pointing = true; result.dist_chg = INVALID_VALUE; } else { result.dir_chg = parser::get_double(&msg); } } else if (*msg == ')') { result.pointing = true; result.point_dir = result.dist_chg; result.dist_chg = INVALID_VALUE; } } if (*msg != ')') { result.body_dir = parser::get_double(&msg); result.head_dir = parser::get_double(&msg); if (*msg == ' ') { // 后面还有 pointdir and/or tackling/kicked flag msg++; if (*msg == 't' || *msg == 'k' || *msg == 'f') { // 只有tackling/kicked flag if (*msg == 't') { result.tackling = true; } else if (*msg == 'k') { result.kicked = true; } else result.lying = true; msg++; } else { // 是数字 result.pointing = true; result.point_dir = parser::get_double(&msg); if (*msg == ' ') { while (*msg == ' ') ++msg; if (*msg == 't' || *msg == 'k' || *msg == 'f') { if (*msg == 't') { result.tackling = true; ++msg; } else if (*msg == 'k') { result.kicked = true; ++msg; } else { result.lying = true; ++msg; } while (*msg == ' ') ++msg; } if (*msg == 'y') { result.card_type = CR_Yellow; ++msg; } else if (*msg == 'r') { result.card_type = CR_Red; ++msg; } else if (*msg != ')') { PARSE_ERROR("why come to this place"); } } } } } if (*msg != ')') { PARSE_ERROR("Should be done with object info here"); } Assert(result.card_type == CR_None); // TODO: server 不会发card_type和foul_charged Assert(result.lying == false); return result; } Parser::ObjProperty_Coach Parser::ParseObjProperty_Coach(char *msg) { ObjProperty_Coach result; // goal or ball or player result.x = parser::get_double(&msg); result.y = parser::get_double(&msg); if (*msg != ')') { // ball or player result.vx = parser::get_double(&msg); result.vy = parser::get_double(&msg); if (*msg != ')') { // player result.body_dir = parser::get_double(&msg); result.head_dir = parser::get_double(&msg); while (*msg == ' ') ++msg; if (*msg != ')') { switch (*msg) { case 't': result.tackling = true; ++msg; break; case 'f': result.lying = true; ++msg; break; case 'y': result.card_type = CR_Yellow; ++msg; break; case 'r': result.card_type = CR_Red; ++msg; break; case 'k': // kicking ++msg; break; default: result.pointing = true; result.point_dir = parser::get_double(&msg); break; } while (*msg == ' ') ++msg; if (*msg != ')') { if (*msg == 't') { result.tackling = true; } else if (*msg == 'f') { result.lying = true; } else if (*msg == 'k') { } else if (*msg == 'y') { result.card_type = CR_Yellow; } else if (*msg == 'r') { result.card_type = CR_Red; } while (*msg == ' ') ++msg; if (*msg != ')') { ++msg; if (*msg == 'y') { result.card_type = CR_Yellow; } else if (*msg == 'r') { result.card_type = CR_Red; } // else { // PARSE_ERROR("why come to this //place"); // } } /*else { PARSE_ERROR("why come to this place"); }*/ } } } } return result; } Parser::ObjProperty_Fullstate Parser::ParseObjProperty_Fullstate(char *msg) { //((p r 11 14) 0.385 -7.01275e-12 -1.15337e-23 -8.33192e-24 46.129 0 (stamina //8000 0.933173 1 124249))) //((p {l|r} <unum> [g] <player_type_id>) // <pos.x> <pos.y> <vel.x> <vel.y> <body_angle> <neck_angle> // [ <point_dist> <point_dir>] // (<stamina> <effort> <recovery> <capacity>) // [t|k|f] [y|r]) ObjProperty_Fullstate result; // ball or player result.x = parser::get_double(&msg); result.y = parser::get_double(&msg); result.vx = parser::get_double(&msg); result.vy = parser::get_double(&msg); if (*msg != ')') { // player result.body_dir = parser::get_double(&msg); result.head_dir = parser::get_double(&msg); while (*msg == ' ') ++msg; if (*msg != '(') { // pointing result.pointing = true; result.point_dist = parser::get_double(&msg); result.point_dir = parser::get_double(&msg); } result.stamina = parser::get_double(&msg); result.effort = parser::get_double(&msg); result.recovery = parser::get_double(&msg); result.capacity = parser::get_double(&msg); msg++; if (*msg != ')') { while (*msg == ' ') ++msg; switch (*msg) { case 't': result.tackling = true; ++msg; break; case 'f': result.lying = true; ++msg; break; case 'y': result.card_type = CR_Yellow; ++msg; break; case 'r': result.card_type = CR_Red; ++msg; break; case 'k': // kicking ++msg; break; default: Assert(0); break; } while (*msg == ' ') ++msg; if (*msg != ')') { if (*msg == 't') { result.tackling = true; } else if (*msg == 'f') { result.lying = true; } else if (*msg == 'k') { } else if (*msg == 'y') { result.card_type = CR_Yellow; } else if (*msg == 'r') { result.card_type = CR_Red; } while (*msg == ' ') ++msg; if (*msg != ')') { ++msg; if (*msg == 'y') { result.card_type = CR_Yellow; } else if (*msg == 'r') { result.card_type = CR_Red; } } } } } return result; } void Parser::ParseSense(char *msg) { if (!PlayerParam::instance().isCoach() || !PlayerParam::instance().isTrainer()) { TimeTest::instance().Update( mpObserver->CurrentTime()); // player每周期都有sense } NetworkTest::instance().Update(mpObserver->CurrentTime()); NetworkTest::instance().Begin("Sense"); parser::get_word(&msg); parser::get_next_word(&msg); // skip 'view' parser::get_next_word(&msg); // skip 'mode' parser::get_next_word(&msg); // skip not used view quality ViewWidth view_width = VW_None; switch (msg[1]) { case 'o': view_width = VW_Normal; break; /* normal */ case 'a': view_width = VW_Narrow; break; /* narrow */ case 'i': view_width = VW_Wide; break; /* wide */ default: PARSE_ERROR("Unknown view quality"); break; } double stamina = parser::get_double(&msg); double effort = parser::get_double(&msg); double capacity = parser::get_double(&msg); double speed = parser::get_double(&msg); double speed_dir = parser::get_double(&msg); double neck_dir = parser::get_double(&msg); int kicks = parser::get_int(&msg); int dashes = parser::get_int(&msg); int turns = parser::get_int(&msg); int says = parser::get_int(&msg); int turn_necks = parser::get_int(&msg); int catchs = parser::get_int(&msg); int moves = parser::get_int(&msg); int change_views = parser::get_int(&msg); int arm_movable_ban = parser::get_int(&msg); // 直到下次手臂能动的剩余周期数 int arm_expires = parser::get_int(&msg); // 直到手臂动作失效剩余的周期数 double arm_target_dist = parser::get_double(&msg); // 指向的目标的距离 AngleDeg arm_target_dir = parser::get_double(&msg); // 指向的目标的方向 int points = parser::get_int(&msg); // point count parser::get_next_word(&msg); // focus parser::get_next_word(&msg); // target parser::get_next_word(&msg); // side char focus_side = msg[0]; Unum focus_unum = 0; if (focus_side != 'l' && focus_side != 'r') { // 没有特别注意的队员 focus_side = '?'; } else { // 特别注意的队员号码 focus_unum = parser::get_int(&msg); } int focuses = parser::get_int(&msg); int tackle_expires = parser::get_int(&msg); int tackles = parser::get_int(&msg); //以下是碰撞和犯规信息 mpObserver->ClearCollisionState(); parser::get_word(&msg); // (collision {none|[(ball)][(player)][(post)]}) parser::get_next_word(&msg); // skip 'collision' if (msg[0] != 'n') { do { switch (msg[1]) { case 'a': mpObserver->SetCollideWithBall(); break; case 'l': mpObserver->SetCollideWithPlayer(); break; case 'o': mpObserver->SetCollideWithPost(); break; } parser::get_next_word(&msg); } while (msg[0] != 'f' && msg[0]); } int foul_charged_cycle = 0; CardType card_type = CR_None; if (msg[0]) { // v14 foul_charged_cycle = parser::get_int( &msg); // (foul (charged CYCLE) (card {none|yellow|red}))) parser::get_word(&msg); parser::get_next_word(&msg); // skip 'card' switch (msg[0]) { case 'n': break; case 'y': card_type = CR_Yellow; break; case 'r': card_type = CR_Red; break; } } mpObserver->SetSenseBody( view_width, stamina, effort, capacity, speed, speed_dir, neck_dir, kicks, dashes, turns, says, turn_necks, catchs, moves, change_views, arm_movable_ban, arm_expires, arm_target_dist, arm_target_dir, points, focus_side, focus_unum, focuses, tackle_expires, tackles, foul_charged_cycle, card_type, mpObserver->CurrentTime()); NetworkTest::instance().SetCommandExecuteCount( dashes, kicks, turns, says, turn_necks, catchs, moves, change_views, points, tackles, focuses); } void Parser::ParseRefereeMsg(char *msg) { if (msg[0] == 'y' || msg[0] == 'r') ParseCard(msg); else ParsePlayMode(msg); } void Parser::ParseSound(char *msg) { char *end; int n; static char buffer[MAX_MESSAGE]; msg++; if (msg[0] == 'r') // referee { parser::get_next_word(&msg); end = msg; while (*end != ')') end++; n = end - msg; strncpy(buffer, msg, n * sizeof(char)); buffer[n] = '\0'; ParseRefereeMsg(buffer); } else if (msg[0] == 's') // self { // self say } else if (msg[0] == 'o') // coach say { msg += 13; /** online_coach_ */ if (msg[0] == mpObserver->OurInitSide()) { while (*msg != ' ') ++msg; ++msg; end = msg; // while (*end != ')' || *(end + 1) != ')') end++; // // 对手阵型信息中有可能包含右括号 n = strlen(msg); strncpy(buffer, msg, n * sizeof(char)); buffer[n] = '\0'; mpObserver->HearOurCoachSay(std::string(buffer)); } else { // opponent coach say } } else // player say { // dir our|opp unum AngleDeg dir = parser::get_double(&msg); if (msg[2] == 'u') { // our Unum unum = parser::get_int(&msg); while (*msg != '\"') msg++; msg++; end = msg; while (*end != '\"') end++; n = end - msg; strncpy(buffer, msg, n * sizeof(char)); buffer[n] = '\0'; mpObserver->HearTeammateSay(dir, unum, std::string(buffer)); } else { // opponent player say } } } void Parser::ParseOkMsg(char *msg) { bool is_ok_say = false; msg++; parser::get_next_word(&msg); switch (msg[0]) { case 'c': switch (msg[1]) { case 'l': mOkMutex.Lock(); mClangOk = true; mOkMutex.UnLock(); break; case 'h': /* mOkMutex.Lock(); mChangePlayerTypeOk[parser::get_int(msg)] = true; mOkMutex.UnLock(); break; */ mOkMutex.Lock(); if ((!(mpObserver->SelfUnum() == TRAINER_UNUM)) || std::strncmp(parser::get_next_word(&msg), PlayerParam::instance().teamName().c_str(), 3) == 0) // Trainer接收到的信息包括己方和敌方,现在只处理己方 mChangePlayerTypeOk[parser::get_int(msg)] = true; mOkMutex.UnLock(); break; default: PRINT_ERROR("unknow ok message " << msg); break; } break; case 's': switch (msg[1]) { case 'y': mOkMutex.Lock(); mSynchOk = true; mOkMutex.UnLock(); break; case 'a': is_ok_say = true; break; /** (ok say) */ default: PRINT_ERROR("unknow ok message " << msg); break; } break; // case 'e': mOkMutex.Lock(); mEyeOnOk = true; mOkMutex.UnLock(); //break; case 'e': switch (msg[1]) { case 'y': mOkMutex.Lock(); mEyeOnOk = true; mOkMutex.UnLock(); break; case 'a': mOkMutex.Lock(); mEarOnOk = true; mOkMutex.UnLock(); break; default: PRINT_ERROR("unknow ok message " << msg); break; } break; case 'm': case 'r': /*std::cout << "#" << PlayerParam::instance().teamName() << " Trainer: (" << msg << std::endl;*/ break; default: PRINT_ERROR("unknow ok message " << msg); break; } if (is_ok_say && (PlayerParam::instance().isCoach() || PlayerParam::instance().isTrainer())) { mpObserver->SetCoachSayCount(mpObserver->GetCoachSayCount() + 1); } else { if (mpObserver->SelfUnum() == 0) { std::cout << "#" << PlayerParam::instance().teamName() << " Coach: (" << msg << std::endl; } else if (mpObserver->SelfUnum() == TRAINER_UNUM) { /*std::cout << "#" << PlayerParam::instance().teamName() << " Trainer: (" * << msg << std::endl;*/ } else { std::cout << "#" << PlayerParam::instance().teamName() << " " << mpObserver->SelfUnum() << ": (" << msg << std::endl; } } } void Parser::ParsePlayMode(char *msg) { ServerPlayMode spm = ServerPlayModeMap::instance().GetServerPlayMode(msg); if (spm == SPM_Null) { PRINT_ERROR("unknown server play mode: " << msg << " @ " << mpObserver->CurrentTime()); return; } PlayMode pm = PM_No_Mode; mpObserver->SetServerPlayMode(spm); switch (spm) { case SPM_PlayOn: pm = PM_Play_On; break; /* play_on */ case SPM_KickIn_Left: /* kick_in */ pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Kick_In : PM_Opp_Kick_In; break; case SPM_KickIn_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Kick_In : PM_Opp_Kick_In; break; case SPM_KickOff_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Kick_Off : PM_Opp_Kick_Off; break; case SPM_KickOff_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Kick_Off : PM_Opp_Kick_Off; break; case SPM_GoalKick_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Goal_Kick : PM_Opp_Goal_Kick; break; case SPM_GoalKick_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Goal_Kick : PM_Opp_Goal_Kick; break; case SPM_AfterGoal_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Goal_Ours : PM_Goal_Opps; break; case SPM_AfterGoal_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Goal_Ours : PM_Goal_Opps; break; case SPM_CornerKick_Left: /* corner_kick */ pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Corner_Kick : PM_Opp_Corner_Kick; break; case SPM_CornerKick_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Corner_Kick : PM_Opp_Corner_Kick; break; case SPM_Drop_Ball: pm = PM_Drop_Ball; break; /* drop_ball */ case SPM_OffSide_Left: /* offside */ pm = (mpObserver->OurInitSide() == 'l') ? PM_Opp_Offside_Kick : PM_Our_Offside_Kick; break; case SPM_OffSide_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Opp_Offside_Kick : PM_Our_Offside_Kick; break; case SPM_CatchFault_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Opp_CatchFault_Kick : PM_Our_CatchFault_Kick; break; case SPM_CatchFault_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Opp_CatchFault_Kick : PM_Our_CatchFault_Kick; break; case SPM_FreeKick_Left: if (mLastServerPlayMode == SPM_GoalieCatchBall_Left) pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Goalie_Free_Kick : PM_Opp_Goalie_Free_Kick; else pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Free_Kick : PM_Opp_Free_Kick; break; case SPM_FreeKick_Right: if (mLastServerPlayMode == SPM_GoalieCatchBall_Right) pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Goalie_Free_Kick : PM_Opp_Goalie_Free_Kick; else pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Free_Kick : PM_Opp_Free_Kick; break; case SPM_Free_Kick_Fault_Left: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Free_Kick_Fault_Kick : PM_Opp_Free_Kick_Fault_Kick; break; case SPM_Free_Kick_Fault_Right: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Free_Kick_Fault_Kick : PM_Opp_Free_Kick_Fault_Kick; break; case SPM_FirstHalfOver: /* half_time */ pm = PM_Half_Time; /* play_mode to before_kick_off */ break; case SPM_BeforeKickOff: pm = PM_Before_Kick_Off; break; /* before_kick_off */ break; case SPM_Back_Pass_Left: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Back_Pass_Kick : PM_Opp_Back_Pass_Kick; break; case SPM_Back_Pass_Right: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Back_Pass_Kick : PM_Opp_Back_Pass_Kick; break; case SPM_TimeOver: pm = PM_Time_Over; break; case SPM_TimeUp: pm = PM_Time_Up; break; case SPM_IndFreeKick_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Indirect_Free_Kick : PM_Opp_Indirect_Free_Kick; break; case SPM_IndFreeKick_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Indirect_Free_Kick : PM_Opp_Indirect_Free_Kick; break; case SPM_PenaltySetup_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Penalty_Setup : PM_Opp_Penalty_Setup; break; case SPM_PenaltySetup_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Penalty_Setup : PM_Opp_Penalty_Setup; break; case SPM_PenaltyReady_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Penalty_Ready : PM_Opp_Penalty_Ready; break; case SPM_PenaltyReady_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Penalty_Ready : PM_Opp_Penalty_Ready; break; case SPM_PenaltyTaken_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Penalty_Taken : PM_Opp_Penalty_Taken; break; case SPM_PenaltyTaken_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Penalty_Taken : PM_Opp_Penalty_Taken; break; case SPM_PenaltyScore_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Penalty_Score : PM_Opp_Penalty_Score; break; case SPM_PenaltyScore_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Penalty_Score : PM_Opp_Penalty_Score; break; case SPM_PenaltyMiss_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Penalty_Miss : PM_Opp_Penalty_Miss; break; case SPM_PenaltyMiss_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Penalty_Miss : PM_Opp_Penalty_Miss; break; case SPM_GoalieCatchBall_Left: pm = mpObserver->GetPlayMode(); break; case SPM_GoalieCatchBall_Right: pm = mpObserver->GetPlayMode(); break; case SPM_HalfTime: pm = PM_Half_Time; break; case SPM_PenaltyOnfield_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Penalty_On_Our_Field : PM_Penalty_On_Opp_Field; break; case SPM_PenaltyOnfield_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Penalty_On_Our_Field : PM_Penalty_On_Opp_Field; break; case SPM_PenaltyFoul_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Penalty_Foul : PM_Opp_Penalty_Foul; break; case SPM_PenaltyFoul_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Penalty_Foul : PM_Opp_Penalty_Foul; break; case SPM_PenaltyWinner_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Penalty_Winner : PM_Opp_Penalty_Winner; break; case SPM_PenaltyWinner_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Penalty_Winner : PM_Opp_Penalty_Winner; break; case SPM_Foul_Left: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Foul : PM_Opp_Foul; break; case SPM_Foul_Right: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Foul : PM_Opp_Foul; break; case SPM_TimeExtended: pm = PM_Extended_Time; break; case SPM_Foul_Charge_Left: pm = (mpObserver->OurInitSide() == 'r') ? PM_Our_Foul_Charge_Kick : PM_Opp_Foul_Charge_Kick; break; case SPM_Foul_Charge_Right: pm = (mpObserver->OurInitSide() == 'l') ? PM_Our_Foul_Charge_Kick : PM_Opp_Foul_Charge_Kick; break; default: PRINT_ERROR("unknown server play mode: " << msg << " @ " << mpObserver->CurrentTime()); break; } mLastServerPlayMode = spm; if (pm == PM_Penalty_On_Our_Field) { if (mpObserver->SelfUnum() != PlayerParam::instance().ourGoalieUnum()) { mpObserver->SetOurSide((mpObserver->OurInitSide() == 'l') ? 'r' : 'l'); mpObserver->Initialize(); } } else if (pm == PM_Penalty_On_Opp_Field) { if (mpObserver->SelfUnum() == PlayerParam::instance().ourGoalieUnum()) { mpObserver->SetOurSide((mpObserver->OurInitSide() == 'l') ? 'r' : 'l'); mpObserver->Initialize(); } } if (pm != PM_No_Mode) { switch (pm) { case PM_Goal_Ours: mpObserver->OurScoreInc(); mpObserver->SetKickOffMode(KO_Opps); pm = PM_Before_Kick_Off; break; case PM_Goal_Opps: mpObserver->OppScoreInc(); mpObserver->SetKickOffMode(KO_Ours); pm = PM_Before_Kick_Off; break; case PM_Our_Penalty_Score: mpObserver->OurScoreInc(); break; case PM_Opp_Penalty_Score: mpObserver->OppScoreInc(); break; case PM_Half_Time: case PM_Extended_Time: ++mHalfTime; if (mHalfTime % 2 == 1) { mpObserver->SetKickOffMode( (mpObserver->OurInitSide() == 'l') ? KO_Ours : KO_Opps); } else { mpObserver->SetKickOffMode( (mpObserver->OurInitSide() == 'r') ? KO_Ours : KO_Opps); } break; case PM_Drop_Ball: mpObserver->DropBall(); break; default: break; } mpObserver->SetPlayMode(pm); } else { PRINT_ERROR("Unkonow playmode : " << msg << " @ " << mpObserver->CurrentTime()); } } void Parser::ParseCard(char *msg) { CardType card_type; switch (msg[0]) { case 'y': card_type = CR_Yellow; break; case 'r': card_type = CR_Red; break; default: card_type = CR_None; break; } Unum player; if (msg[7] == 'd') { if (msg[9] == mpObserver->OurInitSide()) { player = parser::get_int(&msg); mpObserver->SetTeammateCardType(player, card_type); } else { player = parser::get_int(&msg); mpObserver->SetOpponentCardType(player, card_type); } } else { if (msg[12] == mpObserver->OurInitSide()) { player = parser::get_int(&msg); mpObserver->SetTeammateCardType(player, card_type); } else { player = parser::get_int(&msg); mpObserver->SetOpponentCardType(player, card_type); } } } void Parser::ParseSight_Coach(char *msg) { if (PlayerParam::instance().isCoach() || PlayerParam::instance().isTrainer()) { TimeTest::instance().Update( mpObserver->CurrentTime()); // coach每周期都有sight } for (int i = 1; i <= TEAMSIZE; ++i) { mpObserver->Teammate_Fullstate(i).SetIsAlive(false); mpObserver->Opponent_Fullstate(i).SetIsAlive(false); } msg = strstr(msg, "(("); while (msg != 0) { // 直到没有object为止 msg += 2; // 跳过 (( ObjType obj = ParseObjType(msg); // 获得object的类型 msg = strchr(msg, ')'); ObjProperty_Coach prop = ParseObjProperty_Coach(msg + 1); // 获得object的属性 switch (obj.type) { case OBJ_Ball: mpObserver->Ball_Fullstate().UpdatePos(Vector(prop.x, prop.y), 0, 1.0); mpObserver->Ball_Fullstate().UpdateVel(Vector(prop.vx, prop.vy), 0, 1.0); break; case OBJ_Player: if (obj.side == mpObserver->OurSide()) { mpObserver->Teammate_Fullstate(obj.num).SetIsAlive(true); mpObserver->Teammate_Fullstate(obj.num).UpdatePos( Vector(prop.x, prop.y), 0, 1.0); mpObserver->Teammate_Fullstate(obj.num).UpdateVel( Vector(prop.vx, prop.vy), 0, 1.0); mpObserver->Teammate_Fullstate(obj.num).UpdateBodyDir(prop.body_dir, 0, 1.0); mpObserver->Teammate_Fullstate(obj.num).UpdateNeckDir(prop.head_dir, 0, 1.0); mpObserver->Teammate_Fullstate(obj.num).UpdateCardType(prop.card_type); if (prop.pointing) { mpObserver->Teammate_Fullstate(obj.num).UpdateArmPoint( prop.point_dir, 0, 1.0, 0.0, 0, 0); // TODO: // 这个接口不好,因为是看不到dist,ban等信息的,这些要自己算然后维护 } if (prop.tackling) { if (mpObserver->Teammate_Fullstate(obj.num).GetTackleBan() == 0) { mpObserver->Teammate_Fullstate(obj.num).UpdateTackleBan( ServerParam::instance().tackleCycles() - 1); } } else { mpObserver->Teammate_Fullstate(obj.num).UpdateTackleBan(0); } if (prop.lying) { if (mpObserver->Teammate_Fullstate(obj.num).GetFoulChargedCycle() == 0) { mpObserver->Teammate_Fullstate(obj.num).UpdateFoulChargedCycle( ServerParam::instance().foulCycles() - 1); } } else { mpObserver->Teammate_Fullstate(obj.num).UpdateFoulChargedCycle(0); } } else { mpObserver->Opponent_Fullstate(obj.num).SetIsAlive(true); mpObserver->Opponent_Fullstate(obj.num).UpdatePos( Vector(prop.x, prop.y), 0, 1.0); mpObserver->Opponent_Fullstate(obj.num).UpdateVel( Vector(prop.vx, prop.vy), 0, 1.0); mpObserver->Opponent_Fullstate(obj.num).UpdateBodyDir(prop.body_dir, 0, 1.0); mpObserver->Opponent_Fullstate(obj.num).UpdateNeckDir(prop.head_dir, 0, 1.0); mpObserver->Opponent_Fullstate(obj.num).UpdateCardType(prop.card_type); if (prop.pointing) { mpObserver->Opponent_Fullstate(obj.num).UpdateArmPoint( prop.point_dir, 0, 1.0, 0.0, 0, 0); // TODO: // 这个接口不好,因为是看不到dist,ban等信息的,这些要自己算然后维护 } if (prop.tackling) { if (mpObserver->Opponent_Fullstate(obj.num).GetTackleBan() == 0) { mpObserver->Opponent_Fullstate(obj.num).UpdateTackleBan( ServerParam::instance().tackleCycles() - 1); } } else { mpObserver->Opponent_Fullstate(obj.num).UpdateTackleBan(0); } if (prop.lying) { if (mpObserver->Opponent_Fullstate(obj.num).GetFoulChargedCycle() == 0) { mpObserver->Opponent_Fullstate(obj.num).UpdateFoulChargedCycle( ServerParam::instance().foulCycles() - 1); } } else { mpObserver->Opponent_Fullstate(obj.num).UpdateFoulChargedCycle(0); } } break; default: break; } msg = strstr(msg, "(("); // 下一个object } } bool Parser::ParseForTrainer(char *msg) { char *end; int n; static char buffer[MAX_MESSAGE]; if (msg[6] == 'r') // 跳过括号和hear,referee { ParseTime(msg, &msg, true); parser::get_word(&msg); end = msg; while (*end != ')') end++; n = end - msg; strncpy(buffer, msg, n * sizeof(char)); buffer[n] = '\0'; ParseRefereeMsg(buffer); return true; } else return false; }
54d3b0a6ba3a1a86979448ddf98037215ae77135
e94559835dec204537927865800f95b81a191b7f
/Tympan/geometric_methods/AcousticRaytracer/Acoustic/Source.h
24f0a5afc385b8f63b4176596a803c914dfc2110
[]
no_license
FDiot/code_tympan3
64530a3fc8a392cdbe26f478a9ea9ce03abab051
cf4383c4a162962b68df470e2bf757ad534880b9
refs/heads/master
2022-04-07T10:54:05.711913
2019-10-24T13:27:42
2019-10-24T13:27:42
239,812,326
1
1
null
null
null
null
UTF-8
C++
false
false
5,792
h
Source.h
/* * Copyright (C) <2012> <EDF-R&D> <FRANCE> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef SOURCE_H #define SOURCE_H #include <string> #include <iostream> #include "Geometry/Sampler.h" #include "Base.h" #ifdef _ALLOW_TARGETING_ #include "Tools/TargetManager.h" #endif //_ALLOW_TARGETING_ #include "Spectre.h" /** * \brief Acoustic source class */ class Source : public Base { public: #ifdef _ALLOW_TARGETING_ Source(std::string _name = "unknown source") : Base(), sampler(NULL), targetManager(NULL) { name = _name;} Source(const Source& other) : Base(other) { name = std::string(other.name); pos = vec3(other.pos); spectrePuissance = Spectre(other.spectrePuissance); if (other.sampler) { sampler = other.sampler->Clone(); } else { sampler = NULL; } nbRayLeft = other.nbRayLeft; initialRayCount = other.initialRayCount; targetManager = other.targetManager; for (unsigned int i = 0; i < other.directions.size(); i++) { directions.push_back(other.directions.at(i)); } } #else /// Base constructor Source(std::string _name = "unknown source") : Base(), sampler(NULL) { name = _name; nbRayLeft=0 ;initialRayCount=0;id=-1; indice=-1; } /// Copy constructor Source(const Source& other) : Base(other) { name = std::string(other.name); pos = vec3(other.pos); spectrePuissance = Spectre(other.spectrePuissance); if (other.sampler) { sampler = other.sampler->Clone(); } else { sampler = NULL; } nbRayLeft = other.nbRayLeft; initialRayCount = other.initialRayCount; id = other.id; indice =other.indice; } #endif /// Destructor virtual ~Source() { } /// Get the name of the Source std::string getName() { return name; } /// Set the name of the Source void setName(const std::string& _name) { name = std::string(_name); } /// Get the position of the Source vec3 getPosition() { return vec3(pos); } /// Set the position of the Source void setPosition(const vec3 _pos) { pos = vec3(_pos); } /// Get the spectrum Spectre getSpectre() { return spectrePuissance; } /// Set the spectrum void setSpectre(const Spectre& spectre) { spectrePuissance = Spectre(spectre); } /// Get the number of remaining rays to generate int getNbRayLeft() { return nbRayLeft; } /// Set the number of remaining rays to generate void setNbRayLeft(int nb) { nbRayLeft = nb; if (nbRayLeft > initialRayCount) { initialRayCount = nbRayLeft; } } /// Get the initial rays counter int getInitialRayCount() { return initialRayCount; } /// Set the initial rays counter void setInitialRayCount(int nb) { initialRayCount = nb; nbRayLeft = nb;} /// Get the Sampler of this Source Sampler* getSampler() { return sampler; } /// Set the Sampler for this Source void setSampler(Sampler* _sampler) { sampler = _sampler; } /// Get the Source id unsigned int getId() { return id; } /// Set the Source id void setId(unsigned int _id) { id = _id; } /// Get a direction (return false if all rays has been launched) bool getDirection(vec3& r) { #ifdef _ALLOW_TARGETING_ if (nbRayLeft <= 0) { return false; } nbRayLeft--; if (!directions.empty()) { r = vec3(directions.back()); directions.pop_back(); } //else if(targetCount != 0){ // targetCount--; // std::vector<vec3>& targets = targetManager->getTargets(); // unsigned int indexTarget = rand() % targets.size(); // r = vec3(targets.at(indexTarget) - pos); // r.normalize(); //} else { r = vec3(sampler->getSample()); } #else if (nbRayLeft <= 0) { return false; } nbRayLeft--; r = vec3(sampler->getSample()); #endif // _ALLOW_TARGETING_ //std::cout<<"Renvoie d'une nouvelle direction."<<std::endl; return true; } protected: std::string name; //!< Name vec3 pos; //!< Position Spectre spectrePuissance; //!< Spectrum Sampler* sampler; //!< A pointer to a Sampler int nbRayLeft; //!< Number of remaining rays to generate int initialRayCount; //!< Initial rays counter unsigned int id; //!< Source identification int indice; //!< Index to know which ray we are working on. #ifdef _ALLOW_TARGETING_ public: void setTargetManager(TargetManager* _targetManager) { targetManager = _targetManager; } void setInitialTargetCount(unsigned int nb) { initialTargetCount = nb; targetCount = nb;} unsigned int getInitialTargetCount() { return initialTargetCount; } void addDirection(vec3 dir) { directions.push_back(dir); } std::vector<vec3>& getPrecomputedDirections() { return directions; } protected: unsigned int initialTargetCount; unsigned int targetCount; std::vector<vec3> directions; TargetManager* targetManager; #endif //_ALLOW_TARGETING_ }; #endif
d57701aa3fcedaaf66bb69ffe77662ed581d14da
40c276887b62c128248883246839687f20f23cb4
/src/main/native/src/org_broadinstitute_hellbender_tools_spark_bwa_NativeSplitFastqSparkEngine.cpp
ae5b4097b82b5f9abd0263ab2d0122b0e9891c7d
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
falcon-computing/gatk
08ebbda56920beaa430be20cce04e55c22786432
384de223ac1c788ed7a2be3ab7837adedacfbb11
refs/heads/master
2021-06-27T09:12:39.992898
2017-09-11T21:56:44
2017-09-11T21:56:44
95,244,579
0
0
null
2017-06-23T18:08:19
2017-06-23T18:08:18
null
UTF-8
C++
false
false
2,655
cpp
org_broadinstitute_hellbender_tools_spark_bwa_NativeSplitFastqSparkEngine.cpp
#include<string> #include<jni.h> #include"org_broadinstitute_hellbender_tools_spark_bwa_NativeSplitFastqSparkEngine.h" using namespace std; int SplitFASTQ(const int kVerboseFlag, const size_t kBatchSize, int* seq_length, const string& kInputFastq1, const string& kOutputFastq1, const string& kInputFastq2, const string& kOutputFastq2, const int kHDFSBufferSize = 0, const short kHDFSReplication = 0, const size_t kHDFSBlockSize = 0, const int8_t kCompressionLevel = 1); /* * Class: org_broadinstitute_hellbender_tools_spark_bwa_NativeSplitFastqSparkEngine * Method: doNativeSplit * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JJJ)[I */ JNIEXPORT jintArray JNICALL Java_org_broadinstitute_hellbender_tools_spark_bwa_NativeSplitFastqSparkEngine_doNativeSplit (JNIEnv* env, jclass obj, jstring input_fastq1, jstring input_splitted_fastq1, jstring input_fastq2, jstring input_splitted_fastq2, jlong fastq_split_size, jlong fastq_split_replication, jlong fastq_split_compression_level) { const char* input_fastq1_chars = env->GetStringUTFChars(input_fastq1, nullptr); const char* input_splitted_fastq1_chars = env->GetStringUTFChars(input_splitted_fastq1, nullptr); const string kInputFastq1(input_fastq1_chars); const string kInputSplittedFastq1(input_splitted_fastq1_chars); env->ReleaseStringUTFChars(input_fastq1, input_fastq1_chars); env->ReleaseStringUTFChars(input_splitted_fastq1, input_splitted_fastq1_chars); const char* input_fastq2_chars = input_fastq2==nullptr ? nullptr : env->GetStringUTFChars(input_fastq2, nullptr); const char* input_splitted_fastq2_chars = input_fastq2==nullptr ? nullptr : env->GetStringUTFChars(input_splitted_fastq2, nullptr); const string kInputFastq2(input_fastq2!=nullptr ? input_fastq2_chars : ""); const string kInputSplittedFastq2(input_fastq2!=nullptr ? input_splitted_fastq2_chars : ""); if(input_fastq2!=nullptr) { env->ReleaseStringUTFChars(input_fastq2, input_fastq2_chars); env->ReleaseStringUTFChars(input_splitted_fastq2, input_splitted_fastq2_chars); } const int kHDFSReplication = int(fastq_split_replication); const size_t kBatchSize = size_t(fastq_split_size); const int8_t kCompressionLevel = int8_t(fastq_split_compression_level); jintArray result = env->NewIntArray(2); int result_array[2]; result_array[0] = SplitFASTQ(true, kBatchSize, result_array+1, kInputFastq1, kInputSplittedFastq1, kInputFastq2, kInputSplittedFastq2, 0, kHDFSReplication, 0, kCompressionLevel); env->SetIntArrayRegion(result, 0, 2, result_array); return result; }
5fa638d7bb7a13a0f04698f8b2a200820c693448
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/services/network/public/cpp/devtools_observer_util.h
5090e66eae7430cfe6a0fb6892e3fdd0f897a73d
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
803
h
devtools_observer_util.h
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_NETWORK_PUBLIC_CPP_DEVTOOLS_OBSERVER_UTIL_H_ #define SERVICES_NETWORK_PUBLIC_CPP_DEVTOOLS_OBSERVER_UTIL_H_ #include "base/component_export.h" #include "services/network/public/mojom/devtools_observer.mojom.h" namespace network { struct ResourceRequest; namespace mojom { class URLResponseHead; } COMPONENT_EXPORT(NETWORK_CPP) mojom::URLResponseHeadDevToolsInfoPtr ExtractDevToolsInfo( const mojom::URLResponseHead& head); COMPONENT_EXPORT(NETWORK_CPP) mojom::URLRequestDevToolsInfoPtr ExtractDevToolsInfo( const ResourceRequest& request); } // namespace network #endif // SERVICES_NETWORK_PUBLIC_CPP_DEVTOOLS_OBSERVER_UTIL_H_
7029f89e864986f18687110ff87e2841c106a111
ae29d4dab4f10c7ccd5b106544e00fb1a11de82b
/Embedded and Real Time Systems/110/Complete Code/src/GpioOutAct/GpioOut/GpioPattern.h
d279896e7c6f3f6ec48c15874bd62dcdec0e941f
[]
no_license
djgordon-maker/Portfolio
9ab2d4c8b8eaf72f27c8aae20e3a900209f4360d
9d336a29a2349b1c2f89fec93bafd4e27b20a8d9
refs/heads/main
2023-04-22T05:59:35.022742
2021-05-16T23:08:49
2021-05-16T23:08:49
367,220,031
0
0
null
null
null
null
UTF-8
C++
false
false
1,621
h
GpioPattern.h
#ifndef GPIO_PATTERN_H #define GPIO_PATTERN_H #include "bsp.h" #include <stdint.h> #include "fw_log.h" #include "qassert.h" #define GPIO_PATTERN_ASSERT(t_) ((t_)? (void)0: Q_onAssert("GpioPattern.h", (int32_t)__LINE__)) namespace APP { class GpioInterval { public: uint16_t m_levelPermil; // Brightness level 0-1000. uint16_t m_durationMs; // Duration in millisecond. uint16_t GetLevelPermil() const { return m_levelPermil; } uint16_t GetDurationMs() const { return m_durationMs; } }; class GpioPattern { public: enum { COUNT = 256 }; uint32_t m_count; // Number of intervals in use. GpioInterval m_interval[COUNT]; // Array of intervals. Used ones start from index 0. // Must perform range check. Assert if invalid. uint32_t GetCount() const { return m_count; } GpioInterval const &GetInterval(uint32_t index) const { GPIO_PATTERN_ASSERT(index < m_count); return m_interval[index]; } }; class GpioPatternSet { public: enum { COUNT = 4 }; uint32_t m_count; // Number of patterns in use. GpioPattern m_pattern[COUNT]; // Array of patterns. Used ones start from index 0. // Must perform range check. Assert if invalid. uint32_t GetCount() const { return m_count; } GpioPattern const *GetPattern(uint32_t index) const { if (index < m_count) { return &m_pattern[index]; } return NULL; } }; extern GpioPatternSet const TEST_GPIO_PATTERN_SET; } // namespace APP #endif // GPIO_PATTERN_H
f02e3b10b06871b288ebbc6ce6861932bc93fbdd
568b312985afec4e83112020f4683bd8141fdabf
/FineMesh.cpp
7c2805e9a6197a8aa2bb528d273ec326417318ae
[]
no_license
pkestene/carmen
8b9040f3edf972ad4875ec0e0dfac9aff6532093
280d8d0048f20c8663ddfb471d16ab66841a7186
refs/heads/master
2020-12-25T23:56:58.828202
2016-08-23T08:25:08
2016-08-23T08:25:08
66,345,593
1
0
null
2016-08-23T07:48:39
2016-08-23T07:48:37
null
UTF-8
C++
false
false
51,516
cpp
FineMesh.cpp
/*************************************************************************** FineMesh.cpp - description ------------------- begin : Wed Jun 13 2001 last correction : Thu Jan 10 2012 by Margarete Domingues copyright : (C) 2001 by Olivier Roussel & Alexei Tsigulin email : roussel@ict.uni-karlsruhe.de, lpsoft@mail.ru ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "Carmen.h" /* ______________________________________________________________________________________________ Constructor ______________________________________________________________________________________________ */ FineMesh::FineMesh() { // --- Local variables --- int n=0, i=0, j=0, k=0; // position numbers real x=0., y=0., z=0.; // positions real dx=0., dy=0., dz=0.; // space steps // --- Create an array of 2^(ScaleNb*Dimension) cells --- MeshCell = new Cell[(1<<(ScaleNb*Dimension))]; //Parallel #if defined PARMPI Neighbour_iL = new Cell**[NeighbourNb]; Neighbour_iU = new Cell**[NeighbourNb]; Neighbour_jL = new Cell**[NeighbourNb]; Neighbour_jU = new Cell**[NeighbourNb]; Neighbour_kL = new Cell**[NeighbourNb]; Neighbour_kU = new Cell**[NeighbourNb]; for (i=0;i<NeighbourNb;i++) { Neighbour_iL[i] = new Cell*[one_D]; Neighbour_iU[i] = new Cell*[one_D]; Neighbour_jL[i] = new Cell*[one_D]; Neighbour_jU[i] = new Cell*[one_D]; Neighbour_kL[i] = new Cell*[one_D]; Neighbour_kU[i] = new Cell*[one_D]; } for (i=0;i<NeighbourNb;i++) for (j=0;j<one_D;j++) { Neighbour_iL[i][j] = new Cell[two_D]; Neighbour_iU[i][j] = new Cell[two_D]; Neighbour_jL[i][j] = new Cell[two_D]; Neighbour_jU[i][j] = new Cell[two_D]; Neighbour_kL[i][j] = new Cell[two_D]; Neighbour_kU[i][j] = new Cell[two_D]; } #endif // --- Create a time-average grid --- if (TimeAveraging) MyTimeAverageGrid = new TimeAverageGrid(ScaleNb); // --- Compute dx, dy, dz --- dx = (XMax[1]-XMin[1])/(1<<ScaleNb); if (Dimension > 1) dy = (XMax[2]-XMin[2])/(1<<ScaleNb); if (Dimension > 2) dz = (XMax[3]-XMin[3])/(1<<ScaleNb); // --- Loop on all cells --- for (n = 0; n < 1<<(ScaleNb*Dimension); n++) { // -- Compute i, j, k -- i = n%(1<<ScaleNb); if (Dimension > 1) j = (n%(1<<(2*ScaleNb)))/(1<<ScaleNb); if (Dimension > 2) k = n/(1<<(2*ScaleNb)); // -- Compute x, y, z -- x = XMin[1] + (i+.5)*dx; if (Dimension > 1) y = XMin[2] + (j+.5)*dy; if (Dimension > 2) z = XMin[3] + (k+.5)*dz; // -- Set position -- cell(n)->setCenter(1,x); if (Dimension > 1) cell(n)->setCenter(2,y); if (Dimension > 2) cell(n)->setCenter(3,z); // -- Set size -- cell(n)->setSize(1,dx); if (Dimension > 1) cell(n)->setSize(2,dy); if (Dimension > 2) cell(n)->setSize(3,dz); } // --- End loop on all cells --- //Parallel #if defined PARMPI for (i=0;i<one_D;i++) for (j=0;j<two_D;j++) for (k=0;k<NeighbourNb;k++) { Neighbour_iL[k][i][j].setSize(1,dx); Neighbour_iU[k][i][j].setSize(1,dx); Neighbour_jL[k][i][j].setSize(1,dx); Neighbour_jU[k][i][j].setSize(1,dx); Neighbour_kL[k][i][j].setSize(1,dx); Neighbour_kU[k][i][j].setSize(1,dx); if (Dimension > 1) { Neighbour_iL[k][i][j].setSize(2,dy); Neighbour_iU[k][i][j].setSize(2,dy); Neighbour_jL[k][i][j].setSize(2,dy); Neighbour_jU[k][i][j].setSize(2,dy); Neighbour_kL[k][i][j].setSize(2,dy); Neighbour_kU[k][i][j].setSize(2,dy); } if (Dimension > 2) { Neighbour_iL[k][i][j].setSize(3,dz); Neighbour_iU[k][i][j].setSize(3,dz); Neighbour_jL[k][i][j].setSize(3,dz); Neighbour_jU[k][i][j].setSize(3,dz); Neighbour_kL[k][i][j].setSize(3,dz); Neighbour_kU[k][i][j].setSize(3,dz); } } #endif // -- Set initial cell-average value -- /* //!!!DEBUG printf("\nRecovery: %d",Recovery); printf("\nUseBackup: %d",UseBackup); printf("\nComputeCPUTimeRef: %d\n",ComputeCPUTimeRef); */ if (Recovery && UseBackup && !ComputeCPUTimeRef) { // printf("\nRestore!\n"); restore(); } else { for (n = 0; n < 1<<(ScaleNb*Dimension); n++) { cell(n)->setAverageZero(); if (UseBoundaryRegions && BoundaryRegion(cell(n)->center()) != 0) { x = cell(n)->center(1); y = (Dimension > 1)? cell(n)->center(2): 0.; z = (Dimension > 2)? cell(n)->center(3): 0.; cell(n)->setAverage(InitAverage(x,y,z)); } else { if(centredIC){ switch (Dimension) { case 1: for (i=0;i<=1;i++) cell(n)->setAverage( cell(n)->average()+.5* InitAverage( cell(n)->center(1)+(i-0.5)*cell(n)->size(1)) ); break; case 2: for (i=0;i<=1;i++) for (j=0;j<=1;j++) cell(n)->setAverage( cell(n)->average()+.25* InitAverage( cell(n)->center(1)+(i-0.5)*cell(n)->size(1), cell(n)->center(2)+(j-0.5)*cell(n)->size(2) ) ); break; case 3: for (i=0;i<=1;i++) for (j=0;j<=1;j++) for (k=0;k<=1;k++) cell(n)->setAverage( cell(n)->average()+.125* InitAverage( cell(n)->center(1)+(i-0.5)*cell(n)->size(1), cell(n)->center(2)+(j-0.5)*cell(n)->size(2), cell(n)->center(3)+(k-0.5)*cell(n)->size(3) ) ); break; }; } else{ switch (Dimension) { case 1: cell(n)->setAverage(InitAverage( cell(n)->center(1)) ); break; case 2: cell(n)->setAverage( InitAverage( cell(n)->center(1), cell(n)->center(2) ) ); break; case 3: cell(n)->setAverage( InitAverage( cell(n)->center(1), cell(n)->center(2), cell(n)->center(3) ) ); break; }; } } } } #if defined PARMPI //Important moment: Exchange boundary (neighbour) cells before start computation (1st iteration) CPUExchange(this, SendQ); if (MPIRecvType == 1) MPI_Waitall(4*Dimension,req,st); //Send quantity number one (code name "Q") if (EquationType==6) { CPUExchange(this, SendGrad); if (MPIRecvType == 1) MPI_Waitall(4*Dimension,req,st); //Send gradient } #endif } /* ______________________________________________________________________________________________ Distructor ______________________________________________________________________________________________ */ FineMesh::~FineMesh() { // --- Delete pointers to cells --- delete[] MeshCell; #if defined PARMPI int i,j; for (i=0;i<NeighbourNb;i++) for (j=0;j<one_D;j++) { delete[] Neighbour_iL[i][j]; delete[] Neighbour_iU[i][j]; delete[] Neighbour_jL[i][j]; delete[] Neighbour_jU[i][j]; delete[] Neighbour_kL[i][j]; delete[] Neighbour_kU[i][j]; } for (i=0;i<NeighbourNb;i++) { delete[] Neighbour_iL[i]; delete[] Neighbour_iU[i]; delete[] Neighbour_jL[i]; delete[] Neighbour_jU[i]; delete[] Neighbour_kL[i]; delete[] Neighbour_kU[i]; } delete[] Neighbour_iL; delete[] Neighbour_iU; delete[] Neighbour_jL; delete[] Neighbour_jU; delete[] Neighbour_kL; delete[] Neighbour_kU; #endif if (TimeAveraging) delete MyTimeAverageGrid; } /* ______________________________________________________________________________________________ Get procedures ______________________________________________________________________________________________ */ Cell* FineMesh::cell(const int i, const int j, const int k) const { int n = (1<<ScaleNb); #if defined PARMPI int BCi,BCj,BCk; Cell *C; BCi=BC(i,1,n); BCj=BC(j,2,n); BCk=BC(k,3,n); if (BCi>=n && BCj>=n) printf("\nDiagonal neighbours not implemented!"); if (BCi<0 && BCj<0) printf("\nDiagonal neighbours not implemented!"); if (BCi<0 && BCj>=n) printf("\nDiagonal neighbours not implemented!"); if (BCi>=n && BCj<0) printf("\nDiagonal neighbours not implemented!"); if (BCi<0) C=&Neighbour_iL[NeighbourNb+BCi][j][k]; else if (BCi>=n) C=&Neighbour_iU[BCi-n][j][k]; else if (BCj<0) C=&Neighbour_jL[NeighbourNb+BCj][i][k]; else if (BCj>=n) C=&Neighbour_jU[BCj-n][i][k]; else if (BCk<0) C=&Neighbour_kL[NeighbourNb+BCk][i][j]; else if (BCk>=n) C=&Neighbour_kU[BCk-n][i][j]; else C=MeshCell + BCi + n*(BCj + n*BCk); return C; #else return ( MeshCell + BC(i,1,n) + n*(BC(j,2,n) + n*BC(k,3,n)) ); #endif } void FineMesh::computeDivergence_cell(int n) { // --- Local variables --- int i=0, j=0, k=0; // position numbers Vector FluxIn, FluxOut; // ingoing and outgoing fluxes real XIn=0., XOut=0.; // Limits of the cell (only when using 1D spherical coordinates) // --- Loop on all cells --- // --- Only in fluid region --- if (!UseBoundaryRegions || BoundaryRegion(cell(n)->center())==0) { // --- Compute source term -- cell(n)->setDivergence(Source(*cell(n))); // -- Compute i, j, k -- i = n%(1<<ScaleNb); if (Dimension > 1) j = (n%(1<<(2*ScaleNb)))/(1<<ScaleNb); if (Dimension > 2) k = n/(1<<(2*ScaleNb)); // Add flux in x-direction FluxIn = Flux( *cell(i-2, j, k), *cell(i-1, j, k), *cell(i, j, k), *cell(i+1, j, k), 1 ); FluxOut = Flux( *cell(i-1, j, k), *cell(i , j, k), *cell(i+1, j, k), *cell(i+2, j, k), 1 ); if (Dimension == 1 && Coordinate == 2) { XIn = cell(n)->center(1) - 0.5*cell(n)->size(1); XOut = XIn + cell(n)->size(1); cell(n)->setDivergence( cell(n)->divergence() + 3.*(FluxIn*XIn*XIn - FluxOut*XOut*XOut)/(XOut*XOut*XOut - XIn*XIn*XIn) ); } else cell(n)->setDivergence( cell(n)->divergence() + (FluxIn - FluxOut)/(cell(n)->size(1)) ); // Add flux in y-direction if (Dimension > 1) { FluxIn = Flux( *cell(i, j-2, k), *cell(i, j-1, k), *cell(i, j , k), *cell(i, j+1, k), 2 ); FluxOut = Flux( *cell(i, j-1, k), *cell(i, j , k), *cell(i, j+1, k), *cell(i, j+2, k), 2 ); cell(n)->setDivergence( cell(n)->divergence() + (FluxIn - FluxOut)/(cell(n)->size(2)) ); } // Add flux in z-direction if (Dimension > 2) { FluxIn = Flux( *cell(i, j, k-2), *cell(i, j, k-1), *cell(i, j, k ), *cell(i, j, k+1), 3 ); FluxOut = Flux( *cell(i, j, k+1), *cell(i, j, k ), *cell(i, j, k+1), *cell(i, j, k+2), 3 ); cell(n)->setDivergence( cell(n)->divergence() + (FluxIn - FluxOut)/(cell(n)->size(3)) ); } } // --- End loop on all cells --- } void FineMesh::computeDivergence(int mode) { int i,j,k,d; // --- Loops for internal cells if (mode==0) { if (Dimension==1) for (i=2*NeighbourNb;i<(1<<ScaleNb)-2*NeighbourNb;i++) { j=0; k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeDivergence_cell(d); } if (Dimension==2) for (i=2*NeighbourNb;i<(1<<ScaleNb)-2*NeighbourNb;i++) for (j=2*NeighbourNb;j<(1<<ScaleNb)-2*NeighbourNb;j++) { k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeDivergence_cell(d); } if (Dimension==3) for (i=2*NeighbourNb;i<(1<<ScaleNb)-2*NeighbourNb;i++) for (j=2*NeighbourNb;j<(1<<ScaleNb)-2*NeighbourNb;j++) for (k=2*NeighbourNb;k<(1<<ScaleNb)-2*NeighbourNb;k++) { d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeDivergence_cell(d); } } // --- loop for neighbour cells if (mode==1) { if (Dimension==1) for (i=0;i<(1<<ScaleNb);i++) if (i<2*NeighbourNb || i>=(1<<ScaleNb)-2*NeighbourNb) { j=0; k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeDivergence_cell(d); } if (Dimension==2) for (i=0;i<(1<<ScaleNb);i++) for (j=0;j<one_D;j++) if (i<2*NeighbourNb || j<2*NeighbourNb || i>=(1<<ScaleNb)-2*NeighbourNb || j>=(1<<ScaleNb)-2*NeighbourNb) { k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeDivergence_cell(d); } if (Dimension==3) for (i=0;i<(1<<ScaleNb);i++) for (j=0;j<one_D;j++) for (k=0;k<two_D;k++) if (i<2*NeighbourNb || j<2*NeighbourNb || k<2*NeighbourNb || i>=(1<<ScaleNb)-2*NeighbourNb || j>=(1<<ScaleNb)-2*NeighbourNb || k>=(1<<ScaleNb)-2*NeighbourNb) { d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeDivergence_cell(d); } } /* int n; for (n = 0; n < 1<<(ScaleNb*Dimension); n++) computeDivergence_cell(n);*/ } /* ______________________________________________________________________________________________ Compute quantity gradient (Navier-Stokes only) ______________________________________________________________________________________________ */ void FineMesh::computeGradient_cell(int n) { // --- Local variables --- int i=0, j=0, k=0; // Counter on children real V1=0., V2=0.; // Velocities real dx=0.; // Distance between the centers of the neighbour cells real dxV=0.; // Correction of dx for the computation of GradV close to solid walls // Cell size real rho1=0., rho2=0.; // Densities real rhoE1=0., rhoE2=0.; // Energies int p=0, q=0; // Counters on dimension (between 0 and Dimension) int ei=0, ej=0, ek=0; // 1 if this direction is chosen, 0 elsewhere real result = 0.; // --- Recursion --- if (EquationType != 6) { cout << "FineMesh.cpp: In method `void FineMesh::computeGradient()':\n"; cout << "FineMesh.cpp: EquationType not equal to 6 \n"; cout << "carmen: *** [FineMesh.o] Execution error\n"; cout << "carmen: abort execution.\n"; exit(1); } // --- Loop on all cells --- // Only in the fluid if (BoundaryRegion(cell(n)->center()) == 0) { i = n%(1<<ScaleNb); if (Dimension > 1) j = (n%(1<<(2*ScaleNb)))/(1<<ScaleNb); if (Dimension > 2) k = n/(1<<(2*ScaleNb)); for (p=1; p <= Dimension; p++) { ei = (p==1)? 1:0; ej = (p==2)? 1:0; ek = (p==3)? 1:0; dx = cell(i,j,k)->size(p); dx *= 2.; // dxV = correction on dx for the computation of GradV close to solid walls if (BoundaryRegion(cell(i+ei,j+ej,k+ek)->center()) > 3 || BoundaryRegion(cell(i-ei,j-ej,k-ek)->center()) > 3 ) dxV = 0.75*dx; else dxV = dx; rho1 = cell(i+ei,j+ej,k+ek)->density(); rho2 = cell(i-ei,j-ej,k-ek)->density(); cell(n)->setGradient(p, 1, (rho1-rho2)/dx); for (q=1; q <= Dimension; q++) { V1=cell(i+ei,j+ej,k+ek)->velocity(q); V2=cell(i-ei,j-ej,k-ek)->velocity(q); result = (V1-V2)/dx; cell(n)->setGradient(p, q+1, (V1-V2)/dxV); } rhoE1 = cell(i+ei,j+ej,k+ek)->energy(); rhoE2 = cell(i-ei,j-ej,k-ek)->energy(); cell(n)->setGradient(p, Dimension+2, (rhoE1-rhoE2)/dx); } } } void FineMesh::computeGradient(int mode) { int i,j,k,d; // --- Loops for internal cells if (mode==0) { if (Dimension==1) for (i=NeighbourNb;i<(1<<ScaleNb)-NeighbourNb;i++) { j=0; k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeGradient_cell(d); } if (Dimension==2) for (i=NeighbourNb;i<(1<<ScaleNb)-NeighbourNb;i++) for (j=NeighbourNb;j<(1<<ScaleNb)-NeighbourNb;j++) { k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeGradient_cell(d); } if (Dimension==3) for (i=NeighbourNb;i<(1<<ScaleNb)-NeighbourNb;i++) for (j=NeighbourNb;j<(1<<ScaleNb)-NeighbourNb;j++) for (k=NeighbourNb;k<(1<<ScaleNb)-NeighbourNb;k++) { d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeGradient_cell(d); } } // --- loop for neighbour cells if (mode==1) { if (Dimension==1) for (i=0;i<(1<<ScaleNb);i++) if (i<NeighbourNb || i>=(1<<ScaleNb)-NeighbourNb) { j=0; k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeGradient_cell(d); } if (Dimension==2) for (i=0;i<(1<<ScaleNb);i++) for (j=0;j<one_D;j++) if (i<NeighbourNb || j<NeighbourNb || i>=(1<<ScaleNb)-NeighbourNb || j>=(1<<ScaleNb)-NeighbourNb) { k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeGradient_cell(d); } if (Dimension==3) for (i=0;i<(1<<ScaleNb);i++) for (j=0;j<one_D;j++) for (k=0;k<two_D;k++) if (i<NeighbourNb || j<NeighbourNb || k<NeighbourNb || i>=(1<<ScaleNb)-NeighbourNb || j>=(1<<ScaleNb)-NeighbourNb || k>=(1<<ScaleNb)-NeighbourNb) { d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); computeGradient_cell(d); } } /* int n; for (n = 0; n < 1<<(ScaleNb*Dimension); n++) computeDivergence_cell(n);*/ } /* ______________________________________________________________________________________________ Runge-Kutta step ______________________________________________________________________________________________ */ void FineMesh::RungeKutta_cell(int n) { // --- Local variables --- real c1=0., c2=0., c3=0.; // Runge-Kutta coefficients Vector Q(QuantityNb), Qs(QuantityNb), D(QuantityNb); // Cell-average, temporary cell-average and divergence // --- Loop on all cells --- if (!UseBoundaryRegions || BoundaryRegion(cell(n)->center()) == 0) { switch(StepNo) { case 1: c1 = 1.; c2 = 0.; c3 = 1.; break; case 2: if (StepNb == 2) {c1 = .5; c2 = .5; c3 = .5; } if (StepNb == 3) {c1 = .75; c2 = .25; c3 = .25; } break; case 3: if (StepNb == 3) {c1 = 1./3.; c2 = 2.*c1; c3 = c2;} break; }; // --- Runge-Kutta step --- Q = cell(n)->average(); Qs = cell(n)->tempAverage(); D = cell(n)->divergence(); cell(n)->setAverage( c1*Qs + c2*Q + (c3 * TimeStep)*D ); // For the Runge-Kutta-Fehlberg 2(3) method, store second-stage with the RK2 coefficients if (!ConstantTimeStep && StepNo == 2 && StepNb == 3) cell(n)->setLowAverage(0.5*(Qs + Q + TimeStep*D)); // Correction on concentration: if Y < 0, then Y = 0 if (EquationType >= 3 && EquationType <= 5) { if (cell(n)->average(2) < 0) cell(n)->setAverage(2, 0.); } // Correction on scalar if Y > 1 => Y = 1, if Y < 0 => Y = 0 if (EquationType == 6 && ScalarEqNb == 1) { if (cell(n)->average(Dimension+3) < 0) cell(n)->setAverage(Dimension+3, 0); if (cell(n)->average(Dimension+3) > cell(n)->average(1)) cell(n)->setAverage(Dimension+3, cell(n)->average(1)); } } } /* ______________________________________________________________________________________________ Runge-Kutta step (parallel version) ______________________________________________________________________________________________ */ void FineMesh::RungeKutta(int mode) { int i,j,k,d; // --- Loops for internal cells if (mode==0) { if (Dimension==1) for (i=NeighbourNb;i<(1<<ScaleNb)-NeighbourNb;i++) { j=0; k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); RungeKutta_cell(d); } if (Dimension==2) for (i=NeighbourNb;i<(1<<ScaleNb)-NeighbourNb;i++) for (j=NeighbourNb;j<(1<<ScaleNb)-NeighbourNb;j++) { k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); RungeKutta_cell(d); } if (Dimension==3) for (i=NeighbourNb;i<(1<<ScaleNb)-NeighbourNb;i++) for (j=NeighbourNb;j<(1<<ScaleNb)-NeighbourNb;j++) for (k=NeighbourNb;k<(1<<ScaleNb)-NeighbourNb;k++) { d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); RungeKutta_cell(d); } } // --- loop for neighbour cells if (mode==1) { if (Dimension==1) for (i=0;i<(1<<ScaleNb);i++) if (i<NeighbourNb || i>=(1<<ScaleNb)-NeighbourNb) { j=0; k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); RungeKutta_cell(d); } if (Dimension==2) for (i=0;i<(1<<ScaleNb);i++) for (j=0;j<one_D;j++) if (i<NeighbourNb || j<NeighbourNb || i>=(1<<ScaleNb)-NeighbourNb || j>=(1<<ScaleNb)-NeighbourNb) { k=0; d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); RungeKutta_cell(d); } if (Dimension==3) for (i=0;i<(1<<ScaleNb);i++) for (j=0;j<one_D;j++) for (k=0;k<two_D;k++) if (i<NeighbourNb || j<NeighbourNb || k<NeighbourNb || i>=(1<<ScaleNb)-NeighbourNb || j>=(1<<ScaleNb)-NeighbourNb || k>=(1<<ScaleNb)-NeighbourNb) { d=i + (1<<ScaleNb)*(j + (1<<ScaleNb)*k); RungeKutta_cell(d); } } // int n; // for (n = 0; n < 1<<(ScaleNb*Dimension); n++) RungeKutta_cell(n); } /* ______________________________________________________________________________________________ Store cell-average values into temporary ones ______________________________________________________________________________________________ */ void FineMesh::store() { // --- Local variables --- int n=0; // cell number for (n = 0; n < 1<<(ScaleNb*Dimension); n++) { if (UseBoundaryRegions) { if (IterationNo == 1) cell(n)->setOldAverage(cell(n)->average()); else cell(n)->setOldAverage(cell(n)->tempAverage()); } cell(n)->setTempAverage(cell(n)->average()); } } /* ______________________________________________________________________________________________ Store gradient values into temporary ones ______________________________________________________________________________________________ */ void FineMesh::storeGrad() { // --- Local variables --- int n=0; // cell number for (n = 0; n < 1<<(ScaleNb*Dimension); n++) cell(n)->setTempGradient(cell(n)->gradient()); } /* ______________________________________________________________________________________________ Check stability ______________________________________________________________________________________________ */ void FineMesh::checkStability() const { // --- Local variables --- int n=0, iaux; // cell number real x=0., y=0., z=0.; // Real position // --- Loop on all cells --- for (n = 0; n < 1<<(ScaleNb*Dimension); n++) { // --- Compute x, y, z --- x = cell(n)->center(1); if (Dimension > 1) y = cell(n)->center(2); if (Dimension > 2) z = cell(n)->center(3); // --- Test if one cell is overflow --- if (cell(n)->isOverflow()) { iaux=system("echo Unstable computation.>> carmen.prf"); if (Cluster == 0) iaux=system("echo carmen: unstable computation. >> OUTPUT"); cout << "carmen: instability detected at iteration no. "<< IterationNo <<"\n"; cout << "carmen: position ("<< x <<", "<<y<<", "<<z<<")\n"; cout << "carmen: abort execution.\n"; exit(1); } } // --- End loop on all cells --- } /* ______________________________________________________________________________________________ Compute integral values ______________________________________________________________________________________________ */ void FineMesh::computeIntegral() { // --- Local variables --- int n=0; // cell number int AxisNo; // Counter on dimension int QuantityNo; // Quantity number real T, Y; // Temperature and concentration real dx=0., dy=0., dz=0.; // Cell size real x, y, z, t; // position, time real Omega, Radius; // local reaction rate Vector Center(Dimension); // local center of the flame ball real VelocityMax=0.; // local maximum of the velocity Vector GradDensity(Dimension); // gradient of density Vector GradPressure(Dimension);// gradient of pressure real Density=0.; // density real X1=0., X2=0.; // Positions of the center for the computation of GradPressure real P1=0., P2=0.; // Pressures for the computations of GradPressure int ei=0, ej=0, ek=0; // 1 if this direction is chosen, 0 elsewhere int i=0, j=0, k=0; // Counter on children // --- Init --- // Init integral values FlameVelocity = 0.; GlobalMomentum = 0.; GlobalEnergy = 0.; GlobalEnstrophy = 0.; ExactMomentum = 0.; ExactEnergy = 0.; GlobalReactionRate = 0.; AverageRadius = 0.; ReactionRateMax = 0.; for (AxisNo=1; AxisNo <= Dimension; AxisNo++) Center.setValue(AxisNo,XCenter[AxisNo]); ErrorMax = 0.; ErrorMid = 0.; ErrorL2 = 0.; ErrorNb = 0; RKFError = 0.; EigenvalueMax = 0.; QuantityMax.setZero(); IntVorticity=0.; IntDensity=0.; IntMomentum.setZero(); BaroclinicEffect=0.; // --- Loop on all cells --- for (n = 0; n < 1<<(ScaleNb*Dimension); n++) { i = n%(1<<ScaleNb); if (Dimension > 1) j = (n%(1<<(2*ScaleNb)))/(1<<ScaleNb); if (Dimension > 2) k = n/(1<<(2*ScaleNb)); // Whatever the equation, if ConstantTimeStep is false, compute RKFError if (!ConstantTimeStep && StepNb == 3) { for (QuantityNo = 1; QuantityNo <= QuantityNb; QuantityNo++) { if (Abs(cell(n)->average(QuantityNo)) > RKFAccuracyFactor) RKFError = Max(RKFError, Abs(1.-cell(n)->lowAverage(QuantityNo)/cell(n)->average(QuantityNo))); } } switch (EquationType) { // LINEAR ADVECTION, BURGERS case 1: case 2: if (Dimension == 1) { x = cell(n)->center(1); dx = cell(n)->size(1); t = IterationNo*TimeStep; ErrorNb++; ErrorGlobalNb++; ErrorMax = Max( ErrorMax, Abs(cell(n)->average(1)-AnalyticAverage(x, dx, t) )); ErrorGlobalMax = Max( ErrorGlobalMax, ErrorMax ); ErrorMid = ( (ErrorNb-1)*ErrorMid + Abs( cell(n)->average(1)-AnalyticAverage(x, dx, t) )) / ErrorNb; ErrorGlobalMid = ( (ErrorGlobalNb-1)*ErrorGlobalMid + Abs( cell(n)->average(1)-AnalyticAverage(x, dx, t) )) / ErrorGlobalNb; ErrorL2 = sqrt(( (ErrorNb-1)*power2(ErrorL2) + power2( cell(n)->average(1)-AnalyticAverage(x, dx, t) )) / ErrorNb); ErrorGlobalL2 = sqrt(( (ErrorGlobalNb-1)*power2(ErrorGlobalL2) + power2( cell(n)->average(1)-AnalyticAverage(x, dx, t) )) / ErrorGlobalNb); // Compute global momentum and energy for MR and exact solutions GlobalMomentum += Abs(cell(n)->average(1))*dx; ExactMomentum += Abs(AnalyticAverage(x,dx,t))*dx; GlobalEnergy += power2(cell(n)->average(1))*dx; ExactEnergy += power2(AnalyticAverage(x,dx,t))*dx; } else if (Dimension == 2 && EquationType == 1) { x = cell(n)->center(1); dx = cell(n)->size(1); y = cell(n)->center(2); dy = cell(n)->size(2); t = IterationNo*TimeStep; QuantityNo = (EquationType == 1) ? 1:2; ErrorNb++; ErrorGlobalNb++; ErrorMax = Max( ErrorMax, Abs(cell(n)->average(QuantityNo)-AnalyticAverage(x, dx, y, dy, t) )); ErrorGlobalMax = Max( ErrorGlobalMax, ErrorMax ); ErrorMid = ( (ErrorNb-1)*ErrorMid + Abs( cell(n)->average(QuantityNo)-AnalyticAverage(x, dx, y, dy, t) )) / ErrorNb; ErrorGlobalMid = ( (ErrorGlobalNb-1)*ErrorGlobalMid + Abs( cell(n)->average(QuantityNo)-AnalyticAverage(x, dx, y, dy, t) )) / ErrorGlobalNb; ErrorL2 = sqrt(( (ErrorNb-1)*power2(ErrorL2) + power2( cell(n)->average(QuantityNo)-AnalyticAverage(x, dx, y, dy, t) )) / ErrorNb); ErrorGlobalL2 = sqrt(( (ErrorGlobalNb-1)*power2(ErrorGlobalL2) + power2( cell(n)->average(QuantityNo)-AnalyticAverage(x, dx, y, dy, t) )) / ErrorGlobalNb); } else if (Dimension == 3 && EquationType == 1) { x = cell(n)->center(1); dx = cell(n)->size(1); y = cell(n)->center(2); dy = cell(n)->size(2); z = cell(n)->center(3); dz = cell(n)->size(3); t = IterationNo*TimeStep; QuantityNo = (EquationType == 1) ? 1:2; ErrorNb++; ErrorGlobalNb++; ErrorMax = Max( ErrorMax, Abs(cell(n)->average(QuantityNo)-AnalyticAverage(x, dx, y, dy, z, dz, t) )); ErrorGlobalMax = Max( ErrorGlobalMax, ErrorMax ); ErrorMid = ( (ErrorNb-1)*ErrorMid + Abs( cell(n)->average(QuantityNo)-AnalyticAverage(x, dx, y, dy, z, dz, t) )) / ErrorNb; ErrorGlobalMid = ( (ErrorGlobalNb-1)*ErrorGlobalMid + Abs( cell(n)->average(QuantityNo)-AnalyticAverage(x, dx, y, dy, z, dz, t) )) / ErrorGlobalNb; ErrorL2 = sqrt(( (ErrorNb-1)*power2(ErrorL2) + power2( cell(n)->average(QuantityNo)-AnalyticAverage(x, dx, y, dy, z, dz, t) )) / ErrorNb); ErrorGlobalL2 = sqrt(( (ErrorGlobalNb-1)*power2(ErrorGlobalL2) + power2( cell(n)->average(QuantityNo)-AnalyticAverage(x, dx, y, dy, z, dz, t) )) / ErrorGlobalNb); } break; // FLAME FRONT AND FLAME-VORTEX case 3: case 5: T = cell(n)->average(1); Y = cell(n)->average(2); dx = cell(n)->size(1); if (Dimension > 1) dy = cell(n)->size(2); if (Dimension > 2) dz = cell(n)->size(3); switch (Dimension) { case 1: FlameVelocity += ReactionRate(T,Y)*dx; break; case 2: if (EquationType==3) FlameVelocity += ReactionRate(T,Y)*dx*dy/(XMax[2]-XMin[2]); else FlameVelocity += ReactionRate(T,Y)*dx*dy; break; case 3: if (EquationType==3) FlameVelocity += ReactionRate(T,Y)*dx*dy*dz/((XMax[2]-XMin[2])*(XMax[3]-XMin[3])); else FlameVelocity += ReactionRate(T,Y)*dx*dy*dz; break; }; break; // FLAME BALL case 4: T = cell(n)->average(1); Y = cell(n)->average(2); dx = cell(n)->size(1); dy = (Dimension > 1)? cell(n)->size(2) : 1.; dz = (Dimension > 2)? cell(n)->size(3) : 1.; // Compute flame ball average radius Omega = ReactionRate(T,Y); ReactionRateMax += Omega; if (ReactionRateMax != 0.) { Radius = N2( cell(n)->center() - Center ); AverageRadius = ((ReactionRateMax-Omega)*AverageRadius+Omega*Radius)/ReactionRateMax; } // Compute global reaction rate GlobalReactionRate+= Omega*dx*dy*dz; break; // NAVIER-STOKES case 6: dx = cell(n)->size(1); dy = (Dimension > 1) ? cell(n)->size(2) : 1.; dz = (Dimension > 2) ? cell(n)->size(3) : 1.; // --- Compute the global momentum, the global energy, and the global enstrophy --- GlobalMomentum += cell(n)->average(2)*dx*dy*dz; GlobalEnergy += .5*cell(n)->density()*(cell(n)->velocity()*cell(n)->velocity())*dx*dy*dz; if (Dimension > 1) GlobalEnstrophy += .5*power2(N2(cell(n)->vorticity()))*dx*dy*dz; // --- Compute Maximum of the conservative quantities --- for (QuantityNo=1; QuantityNo <=QuantityNb; QuantityNo++) { if ( QuantityMax.value(QuantityNo) < Abs(cell(n)->average(QuantityNo)) ) QuantityMax.setValue(QuantityNo, Abs(cell(n)->average(QuantityNo)) ); } // --- Compute the Maximal eigenvalue --- VelocityMax = 0.; for (AxisNo=1; AxisNo <= Dimension; AxisNo ++) { if (VelocityMax < Abs(cell(n)->velocity(AxisNo))) VelocityMax = Abs(cell(n)->velocity(AxisNo)); } VelocityMax += cell(n)->speedOfSound(); if (EigenvalueMax < VelocityMax) EigenvalueMax = VelocityMax; // --- Compute integral of modulus of vorticity --- IntVorticity += N2(cell(n)->vorticity())*dx*dy*dz; IntDensity += Abs(cell(n)->density())*dx*dy*dz; IntEnergy += Abs(cell(n)->energy())*dx*dy*dz; for (AxisNo = 1; AxisNo <= Dimension; AxisNo++) IntMomentum.setValue(AxisNo, Abs(cell(n)->average(AxisNo+1))*dx*dy*dz); // --- Compute integral of modulus of baroclinic torque --- Density = cell(n)->density(); for (AxisNo = 1; AxisNo <= Dimension; AxisNo ++) { GradDensity.setValue(AxisNo, cell(n)->gradient(AxisNo,1)); ei = (AxisNo == 1)? 1:0; ej = (AxisNo == 2)? 1:0; ek = (AxisNo == 3)? 1:0; X1 = cell(i+ei,j+ej,k+ek)->center(AxisNo); X2 = cell(i-ei,j-ej,k-ek)->center(AxisNo); P1 = cell(i+ei,j+ej,k+ek)->pressure(); P2 = cell(i-ei,j-ej,k-ek)->pressure(); GradPressure.setValue(AxisNo, (P1-P2)/(X1-X2) ); } BaroclinicEffect += N2(GradDensity^GradPressure)/(Density*Density)*dx*dy*dz; break; }; } // --- End loop on all cells --- ReduceIntegralValues(); } /* ______________________________________________________________________________________________ Print header for Data Explorer visualization ______________________________________________________________________________________________ */ void FineMesh::writeHeader(const char* FileName) const { // --- Local variables --- real dx, dy, dz; // deltas in x, y, and z FILE *output; // Pointer to output file int GridPoints; // Grid points char DependencyType[12]; // positions or connections // --- For the final data, use positions instead of connections --- if (WriteAsPoints) { GridPoints = (1<<(ScaleNb+PrintMoreScales)); sprintf(DependencyType,"positions"); } else { GridPoints = (1<<(ScaleNb+PrintMoreScales))+1; sprintf(DependencyType,"connections"); } // --- Open file --- if ((output = fopen(FileName,"w")) != NULL) { // --- Header --- // GNUPLOT switch(PostProcessing) { // GNUPLOT case 1: fprintf(output,"#"); fprintf(output, TXTFORMAT, " x"); switch(EquationType) { // LINEAR ADVECTION AND BURGERS case 1: case 2: fprintf(output, TXTFORMAT, "u"); fprintf(output, "\n"); break; // FLAME BALL, FLAME FRONT, INTERACTION FLAME-CURL case 3: case 4: case 5: fprintf(output, TXTFORMAT, "Temperature"); fprintf(output, TXTFORMAT, "Concentration"); fprintf(output, TXTFORMAT, "Reaction rate"); break; // NAVIER-STOKES case 6: fprintf(output, TXTFORMAT, "Density"); fprintf(output, TXTFORMAT, "Pressure"); fprintf(output, TXTFORMAT, "Temperature"); fprintf(output, TXTFORMAT, "Energy"); fprintf(output, TXTFORMAT, "Vorticity"); fprintf(output, TXTFORMAT, "Velocity"); break; }; fprintf(output, "\n"); break; // DATA EXPLORER case 2: fprintf(output, "# Data Explorer file\n# generated by Carmen\n"); switch(Dimension) { case 2: dx = (XMax[1]-XMin[1])/(1<<(ScaleNb+PrintMoreScales)); dy = (XMax[2]-XMin[2])/(1<<(ScaleNb+PrintMoreScales)); fprintf(output, "grid = %d x %d\n", GridPoints, GridPoints); fprintf(output, "positions = %f, %f, %f, %f\n#\n",XMin[1],dx,XMin[2],dy ); break; case 3: dx = (XMax[1]-XMin[1])/(1<<(ScaleNb+PrintMoreScales)); dy = (XMax[2]-XMin[2])/(1<<(ScaleNb+PrintMoreScales)); dz = (XMax[3]-XMin[3])/(1<<(ScaleNb+PrintMoreScales)); fprintf(output, "grid = %d x %d x %d\n", GridPoints, GridPoints, GridPoints); fprintf(output, "positions = %f, %f, %f, %f, %f, %f\n#\n",XMin[1],dx,XMin[2],dy,XMin[3],dz); break; }; if (DataIsBinary) fprintf(output, "format = binary\n"); else fprintf(output, "format = ascii\n"); fprintf(output, "interleaving = field\n"); switch(EquationType) { // LINEAR ADVECTION AND BURGERS case 1: case 2: fprintf(output, "field = velocity\n"); fprintf(output, "structure = scalar\n"); fprintf(output, "type = %s\n", REAL); fprintf(output, "dependency = %s\n", DependencyType); break; // FLAME FRONT AND FLAME BALL case 3: case 4: fprintf(output, "field = temperature, concentration, reaction\n"); fprintf(output, "structure = scalar, scalar, scalar\n"); fprintf(output, "type = %s, %s, %s\n", REAL, REAL, REAL); fprintf(output, "dependency = %s, %s, %s\n", DependencyType, DependencyType, DependencyType); break; // INTERACTION FLAME - CURL case 5: fprintf(output, "field = temperature, concentration, reaction, velocity\n"); fprintf(output, "structure = scalar, scalar, scalar, 2-vector\n"); fprintf(output, "type = %s, %s, %s, %s\n", REAL, REAL, REAL, REAL); fprintf(output, "dependency = %s, %s, %s, %s\n", DependencyType, DependencyType, DependencyType, DependencyType); break; // NAVIER-STOKES case 6: fprintf(output, "field = density, pressure, temperature, energy, velocity\n"); fprintf(output, "structure = scalar, scalar, scalar, scalar, %d-vector\n",Dimension); fprintf(output, "type = %s, %s, %s, %s, %s\n", REAL, REAL, REAL, REAL, REAL); fprintf(output, "dependency = %s, %s, %s, %s, %s\n", DependencyType, DependencyType, DependencyType, DependencyType, DependencyType); break; }; fprintf(output, "header = marker \"START_DATA\\n\" \n"); fprintf(output, "end\n"); fprintf(output, "START_DATA\n"); break; // TECPLOT case 3: fprintf(output, "VARIABLES = \"x\"\n"); if (Dimension > 1) fprintf(output,"\"y\"\n"); if (Dimension > 2) fprintf(output,"\"z\"\n"); switch(EquationType) { // LINEAR ADVECTION AND BURGERS case 1: case 2: fprintf(output,"\"U\"\n "); break; // FLAME FRONT AND FLAME BALL case 3: case 4: fprintf(output,"\"T\"\n\"C\"\n\"OMEGA\"\n"); break; // INTERACTION FLAME - CURL case 5: fprintf(output,"\"T\"\n\"C\"\n\"OMEGA\"\n\"U\"\n\"V\""); break; // NAVIER-STOKES case 6: fprintf(output,"\"RHO\"\n\"P\"\n\"T\"\n\"E\"\n\"U\"\n"); if (Dimension > 1) fprintf(output,"\"V\"\n"); if (Dimension > 2) fprintf(output,"\"W\"\n"); break; }; fprintf(output,"ZONE T=\"Carmen %3.1f\"\n", CarmenVersion); fprintf(output,"I=%i, ",GridPoints-1); if (Dimension > 1) fprintf(output,"J=%i, ",GridPoints-1); if (Dimension > 2) fprintf(output,"K=%i, ",GridPoints-1); fprintf(output,"F=POINT\n"); break; }; fclose(output); return; } else { cout << "FineMesh.cpp: In method `void FineMesh::writeHeader()':\n"; cout << "FineMesh.cpp: cannot open file " << FileName << '\n'; cout << "carmen: *** [FineMesh.o] Execution error\n"; cout << "carmen: abort execution.\n"; exit(1); } } /* ______________________________________________________________________________________________ Print cell-average values for graphic visualization ______________________________________________________________________________________________ */ void FineMesh::writeAverage(const char* FileName) { // --- Local variables --- int i=0,j=0,k=0, n=0; // Coordinates FILE *output; // pointer to output file real x=0., y=0., z=0., t=0.; // --- Open file --- if ((output = fopen(FileName,"a")) != NULL) { // --- Eventually coarsen grid if (PrintMoreScales == -1) { coarsen(); ScaleNb--; } // --- Loop on all cells --- for (n=0; n < (1<<(Dimension*ScaleNb)); n++) { // -- Compute i, j, k -- // For Gnuplot and DX, loop order: for i... {for j... {for k...} } if (PostProcessing != 3) { switch(Dimension) { case 1: i = n; break; case 2: j = n%(1<<ScaleNb); i = n/(1<<ScaleNb); break; case 3: k = n%(1<<ScaleNb); j = (n%(1<<(2*ScaleNb)))/(1<<ScaleNb); i = n/(1<<(2*ScaleNb)); break; }; } else { // For Tecplot, loop order: for k... {for j... {for i...} } i = n%(1<<ScaleNb); if (Dimension > 1) j = (n%(1<<(2*ScaleNb)))/(1<<ScaleNb); if (Dimension > 2) k = n/(1<<(2*ScaleNb)); } // Compute x,y,z,t if (PrintMoreScales == 0) { x = cell(i,j,k)->center(1); if (Dimension > 1) y = cell(i,j,k)->center(2); if (Dimension > 2) z = cell(i,j,k)->center(3); } else if (PrintMoreScales == -1) { x = XMin[1] + (0.5+i)*(XMax[1]-XMin[1])/(1<<ScaleNb); if (Dimension > 1) y = XMin[2] + (0.5+j)*(XMax[2]-XMin[2])/(1<<ScaleNb); if (Dimension > 2) z = XMin[3] + (0.5+k)*(XMax[3]-XMin[3])/(1<<ScaleNb); } t = IterationNo*TimeStep; // Write cell-center coordinates (only for Gnuplot and Tecplot) if (PostProcessing != 2) { fprintf(output, FORMAT, x); if (Dimension > 1) fprintf(output, FORMAT, y); if (Dimension > 2) fprintf(output, FORMAT, z); } switch(EquationType) { case 1: case 2: // LINEAR ADVECTION AND BURGERS FileWrite(output, FORMAT, cell(i,j,k)->average(1)); break; case 3: case 4: case 5: // FLAME BALL, FLAME FRONT, INTERACTION FLAME BALL-CURL FileWrite(output, FORMAT, cell(i,j,k)->temperature()); FileWrite(output, FORMAT, cell(i,j,k)->concentration()); FileWrite(output, FORMAT, ReactionRate(cell(i,j,k)->temperature(),cell(i,j,k)->concentration())); if (EquationType == 5) { FileWrite(output, FORMAT, CurlVelocity(x, y, t, 1)); FileWrite(output, FORMAT, CurlVelocity(x, y, t, 2)); } break; case 6: // NAVIER-STOKES if (ScalarEqNb == 1) FileWrite(output, FORMAT, cell(i,j,k)->average(Dimension+3)/cell(i,j,k)->density()); else FileWrite(output, FORMAT, cell(i,j,k)->density()); FileWrite(output, FORMAT, cell(i,j,k)->pressure()*Gamma*Ma*Ma); // Dimensionless pressure FileWrite(output, FORMAT, cell(i,j,k)->temperature()); FileWrite(output, FORMAT, cell(i,j,k)->energy()); if (PostProcessing == 1) FileWrite(output, FORMAT, 0.); for (int AxisNo = 1; AxisNo <= Dimension; AxisNo++) FileWrite(output, FORMAT, cell(i,j,k)->velocity(AxisNo)); break; }; if (!DataIsBinary) fprintf(output,"\n"); if (PostProcessing == 1) { if (j==(1<<ScaleNb)-1) fprintf(output,"\n"); if (k==(1<<ScaleNb)-1) fprintf(output,"\n"); } } fclose(output); // --- Eventually refine grid if (PrintMoreScales == -1) { ScaleNb++; refine(); } } else { cout << "FineMesh.cpp: In method `void FineMesh::writeAverage()':\n"; cout << "FineMesh.cpp: cannot open file " << FileName << '\n'; cout << "carmen: *** [FineMesh.o] Execution error\n"; cout << "carmen: abort execution.\n"; exit(1); } } /* ______________________________________________________________________________________________ Write coarse ______________________________________________________________________________________________ */ /* ______________________________________________________________________________________________ Back up data ______________________________________________________________________________________________ */ void FineMesh::backup() { int n=0; // Cell number FILE* output; // Output file int QuantityNo; // Counter on quantities // --- Init --- output = fopen(BackupName,"w"); // --- Backup data on cells --- fprintf(output, "Backup at iteration %i, physical time %e\n", IterationNo, ElapsedTime); for (n = 0; n < 1<<(ScaleNb*Dimension); n++) for (QuantityNo=1; QuantityNo <= QuantityNb; QuantityNo++) fprintf(output, FORMAT, cell(n)->average(QuantityNo)); fclose(output); } /* ______________________________________________________________________________________________ Restore data ______________________________________________________________________________________________ */ void FineMesh::restore() { int n,iaux; // Cell number int QuantityNo; // Counter on quantities FILE* input; // Input file real buf; // Buffer // char line[1024]; // --- Init --- input = fopen(BackupName,"r"); // When there is no back-up file, return if (!input) return; // --- Restore data on cells --- //fgets(line, 1024, input); for (n = 0; n < 1<<(ScaleNb*Dimension); n++) for (QuantityNo=1; QuantityNo <= QuantityNb; QuantityNo++) { iaux=fscanf(input, BACKUP_FILE_FORMAT, &buf); cell(n)->setAverage(QuantityNo, buf); } fclose(input); return; } /* ______________________________________________________________________________________________ Compute time-average values ______________________________________________________________________________________________ */ void FineMesh::computeTimeAverage() { // Local variables int i=0, j=0, k=0, n=0; // Counters on directions // Start this procedure when the physical time is larger than StartTimeAveraging if (TimeStep*IterationNo <= StartTimeAveraging) return; // Update time-average values with values in FineMesh for (n = 0; n < 1<<(ScaleNb*Dimension); n++) { i = n%(1<<ScaleNb); if (Dimension > 1) j = (n%(1<<(2*ScaleNb)))/(1<<ScaleNb); if (Dimension > 2) k = n/(1<<(2*ScaleNb)); MyTimeAverageGrid->updateValue(i,j,k,cell(i,j,k)->average()); } // Update the number of samples (Warning: currently only for constant time step !!) MyTimeAverageGrid->updateSample(); } /* ______________________________________________________________________________________________ Print cell-average values for graphic visualization ______________________________________________________________________________________________ */ void FineMesh::writeTimeAverage(const char* FileName) const { // --- Local variables --- int n=0, i=0, j=0, k=0; real dx, dy, dz; // deltas in x, y, and z real x=0, y=0, z=0; // positions FILE *output; // Pointer to output file int GridPoints = (1<<ScaleNb)+1;// Grid points // --- Open file --- if ((output = fopen(FileName,"w")) != NULL) { // --- Header --- switch(PostProcessing) { // GNUPLOT case 1: fprintf(output,"# x Velocity Stress\n"); break; // DATA EXPLORER case 2: fprintf(output, "# Data Explorer file\n# generated by Carmen\n"); switch(Dimension) { case 2: dx = (XMax[1]-XMin[1])/(1<<ScaleNb); dy = (XMax[2]-XMin[2])/(1<<ScaleNb); fprintf(output, "grid = %d x %d\n", GridPoints, GridPoints); fprintf(output, "positions = %f, %f, %f, %f\n#\n",XMin[1],dx,XMin[2],dy ); break; case 3: dx = (XMax[1]-XMin[1])/(1<<ScaleNb); dy = (XMax[2]-XMin[2])/(1<<ScaleNb); dz = (XMax[3]-XMin[3])/(1<<ScaleNb); fprintf(output, "grid = %d x %d x %d\n", GridPoints, GridPoints, GridPoints); fprintf(output, "positions = %f, %f, %f, %f, %f, %f\n#\n",XMin[1],dx,XMin[2],dy,XMin[3],dz); break; }; if (DataIsBinary) fprintf(output, "format = binary\n"); else fprintf(output, "format = ascii\n"); fprintf(output, "interleaving = field\n"); fprintf(output, "field = U, V"); if (Dimension >2) fprintf(output, ", W"); fprintf(output, ", U\'U\', U\'V\', V\'V\'"); if (Dimension >2) fprintf(output, ", U\'W\', V\'W\', W\'W\'"); fprintf(output, "\n"); fprintf(output, "structure = scalar"); for (n=1; n < (Dimension*(Dimension+3))/2 ; n++) fprintf(output, ", scalar"); fprintf(output, "\n"); fprintf(output, "type = %s", REAL); for (n=1; n < (Dimension*(Dimension+3))/2 ; n++) fprintf(output, ", %s", REAL); fprintf(output, "\n"); fprintf(output, "dependency = connections"); for (n=1; n < (Dimension*(Dimension+3))/2 ; n++) fprintf(output, ", connections"); fprintf(output, "\n"); fprintf(output, "header = marker \"START_DATA\\n\" \n"); fprintf(output, "end\n"); fprintf(output, "START_DATA\n"); break; // TECPLOT case 3: // --- Write axes (x,y,z) --- fprintf(output, "VARIABLES = \"x\"\n"); if (Dimension > 1) fprintf(output,"\"y\"\n"); if (Dimension > 2) fprintf(output,"\"z\"\n"); // --- Write averages U, V, W --- fprintf(output,"\"U\"\n"); if (Dimension > 1) fprintf(output,"\"V\"\n"); if (Dimension > 2) fprintf(output,"\"W\"\n"); // --- Write stress tensor U'U', U'V', V'V', U'W', V'W', W'W' --- fprintf(output,"\"U\'U\'\"\n"); if (Dimension > 1) { fprintf(output,"\"U\'V\'\"\n"); fprintf(output,"\"V\'V\'\"\n"); } if (Dimension > 2) { fprintf(output,"\"U\'W\'\"\n"); fprintf(output,"\"V\'W\'\"\n"); fprintf(output,"\"W\'W\'\"\n"); } fprintf(output,"ZONE T=\"Carmen %3.1f\"\n",CarmenVersion); fprintf(output,"I=%i, ",(1<<ScaleNb)); if (Dimension > 1) fprintf(output,"J=%i, ",(1<<ScaleNb)); if (Dimension > 2) fprintf(output,"K=%i, ",(1<<ScaleNb)); fprintf(output,"F=POINT\n"); break; }; // --- Loop on all cells --- for (n=0; n < (1<<(Dimension*ScaleNb)); n++) { // -- Compute i, j, k -- // For Gnuplot and DX, loop order: for i... {for j... {for k...} } if (PostProcessing != 3) { switch(Dimension) { case 1: i = n; break; case 2: j = n%(1<<ScaleNb); i = n/(1<<ScaleNb); break; case 3: k = n%(1<<ScaleNb); j = (n%(1<<(2*ScaleNb)))/(1<<ScaleNb); i = n/(1<<(2*ScaleNb)); break; }; } else { // For Tecplot, loop order: for k... {for j... {for i...} } i = n%(1<<ScaleNb); if (Dimension > 1) j = (n%(1<<(2*ScaleNb)))/(1<<ScaleNb); if (Dimension > 2) k = n/(1<<(2*ScaleNb)); } // Compute x,y,z x = cell(i,j,k)->center(1); if (Dimension > 1) y = cell(i,j,k)->center(2); if (Dimension > 2) z = cell(i,j,k)->center(3); // Write cell-center coordinates (only for Gnuplot and Tecplot) if (PostProcessing != 2) { fprintf(output, FORMAT, x); if (Dimension > 1) fprintf(output, FORMAT, y); if (Dimension > 2) fprintf(output, FORMAT, z); } for (int AxisNo = 1; AxisNo <= Dimension; AxisNo++) FileWrite(output, FORMAT,MyTimeAverageGrid->velocity(i,j,k,AxisNo)); for (int AxisNo = 1; AxisNo <= (Dimension*(Dimension+1))/2; AxisNo++) FileWrite(output, FORMAT,MyTimeAverageGrid->stress(i,j,k,AxisNo)); if (!DataIsBinary) fprintf(output,"\n"); if (PostProcessing == 1) { if (j==(1<<ScaleNb)-1) fprintf(output,"\n"); if (k==(1<<ScaleNb)-1) fprintf(output,"\n"); } } fclose(output); } else { cout << "FineMesh.cpp: In method `void FineMesh::writeTimeAverage()':\n"; cout << "FineMesh.cpp: cannot open file " << FileName << '\n'; cout << "carmen: *** [FineMesh.o] Execution error\n"; cout << "carmen: abort execution.\n"; exit(1); } } /* ______________________________________________________________________________________________ Make coarse grid data and store fine grid data into temporary ______________________________________________________________________________________________ */ void FineMesh::coarsen() { int n=0; int i=0,j=0,k=0; int li=0, lj=0, lk=0; int ei = 1; int ej = (Dimension > 1) ? 1:0; int ek = (Dimension > 2) ? 1:0; // --- Store data into temporary and reset it --- for (n=0; n < (1<<(Dimension*ScaleNb)); n++) { cell(n)->setTempAverage(cell(n)->average()); cell(n)->setAverageZero(); } // -- Reset data --- n = 0; for (k = 0; k <= ek*((1<<(ScaleNb-1))-1); k++) for (j = 0; j <= ej*((1<<(ScaleNb-1))-1); j++) for (i = 0; i <= ei*((1<<(ScaleNb-1))-1); i++) { for (lk = 0; lk <= ek; lk++) for (lj = 0; lj <= ej; lj++) for (li = 0; li <= ei; li++) cell(n)->setAverage(cell(n)->average()+ cell(2*i+li, 2*j+lj, 2*k+lk)->tempAverage()); cell(n)->setAverage( (1./(1<<Dimension)) * cell(n)->average() ); n++; } } /* ______________________________________________________________________________________________ Restore fine grid data from temporary. Inverse of 'coarsen()' ______________________________________________________________________________________________ */ void FineMesh::refine() { int n; // --- Restore data from temporary --- for (n=0; n < (1<<(Dimension*ScaleNb)); n++) { cell(n)->setAverage(cell(n)->tempAverage()); } }
54b1a5cd2a35daee6e5c4d4f1acf85e8c9dd72a6
142763726959c21bb1dc75baff1e3a227534604a
/libraries/chain/get_config.cpp
8028a199fc73330e6b52cd15f79af63f3cca9086
[ "MIT" ]
permissive
xeroc/graphene
5df3120d4b18122436f494177fb84e2f48821f5a
a3e609d331e196679ba48a0a346eb5c25eda3b4f
refs/heads/master
2020-04-05T04:41:45.963467
2016-02-09T12:59:22
2016-02-09T12:59:22
51,822,072
2
0
null
2016-02-16T09:02:37
2016-02-16T09:02:35
null
UTF-8
C++
false
false
8,267
cpp
get_config.cpp
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * 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. Any modified source or binaries are used only with the BitShares network. * * 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <graphene/chain/get_config.hpp> #include <graphene/chain/config.hpp> #include <graphene/chain/protocol/types.hpp> namespace graphene { namespace chain { fc::variant_object get_config() { fc::mutable_variant_object result; result[ "GRAPHENE_SYMBOL" ] = GRAPHENE_SYMBOL; result[ "GRAPHENE_ADDRESS_PREFIX" ] = GRAPHENE_ADDRESS_PREFIX; result[ "GRAPHENE_MIN_ACCOUNT_NAME_LENGTH" ] = GRAPHENE_MIN_ACCOUNT_NAME_LENGTH; result[ "GRAPHENE_MAX_ACCOUNT_NAME_LENGTH" ] = GRAPHENE_MAX_ACCOUNT_NAME_LENGTH; result[ "GRAPHENE_MIN_ASSET_SYMBOL_LENGTH" ] = GRAPHENE_MIN_ASSET_SYMBOL_LENGTH; result[ "GRAPHENE_MAX_ASSET_SYMBOL_LENGTH" ] = GRAPHENE_MAX_ASSET_SYMBOL_LENGTH; result[ "GRAPHENE_MAX_SHARE_SUPPLY" ] = GRAPHENE_MAX_SHARE_SUPPLY; result[ "GRAPHENE_MAX_PAY_RATE" ] = GRAPHENE_MAX_PAY_RATE; result[ "GRAPHENE_MAX_SIG_CHECK_DEPTH" ] = GRAPHENE_MAX_SIG_CHECK_DEPTH; result[ "GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT" ] = GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT; result[ "GRAPHENE_MIN_BLOCK_INTERVAL" ] = GRAPHENE_MIN_BLOCK_INTERVAL; result[ "GRAPHENE_MAX_BLOCK_INTERVAL" ] = GRAPHENE_MAX_BLOCK_INTERVAL; result[ "GRAPHENE_DEFAULT_BLOCK_INTERVAL" ] = GRAPHENE_DEFAULT_BLOCK_INTERVAL; result[ "GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE" ] = GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE; result[ "GRAPHENE_DEFAULT_MAX_BLOCK_SIZE" ] = GRAPHENE_DEFAULT_MAX_BLOCK_SIZE; result[ "GRAPHENE_DEFAULT_MAX_TIME_UNTIL_EXPIRATION" ] = GRAPHENE_DEFAULT_MAX_TIME_UNTIL_EXPIRATION; result[ "GRAPHENE_DEFAULT_MAINTENANCE_INTERVAL" ] = GRAPHENE_DEFAULT_MAINTENANCE_INTERVAL; result[ "GRAPHENE_DEFAULT_MAINTENANCE_SKIP_SLOTS" ] = GRAPHENE_DEFAULT_MAINTENANCE_SKIP_SLOTS; result[ "GRAPHENE_MIN_UNDO_HISTORY" ] = GRAPHENE_MIN_UNDO_HISTORY; result[ "GRAPHENE_MAX_UNDO_HISTORY" ] = GRAPHENE_MAX_UNDO_HISTORY; result[ "GRAPHENE_MIN_BLOCK_SIZE_LIMIT" ] = GRAPHENE_MIN_BLOCK_SIZE_LIMIT; result[ "GRAPHENE_MIN_TRANSACTION_EXPIRATION_LIMIT" ] = GRAPHENE_MIN_TRANSACTION_EXPIRATION_LIMIT; result[ "GRAPHENE_BLOCKCHAIN_PRECISION" ] = GRAPHENE_BLOCKCHAIN_PRECISION; result[ "GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS" ] = GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS; result[ "GRAPHENE_DEFAULT_TRANSFER_FEE" ] = GRAPHENE_DEFAULT_TRANSFER_FEE; result[ "GRAPHENE_MAX_INSTANCE_ID" ] = GRAPHENE_MAX_INSTANCE_ID; result[ "GRAPHENE_100_PERCENT" ] = GRAPHENE_100_PERCENT; result[ "GRAPHENE_1_PERCENT" ] = GRAPHENE_1_PERCENT; result[ "GRAPHENE_MAX_MARKET_FEE_PERCENT" ] = GRAPHENE_MAX_MARKET_FEE_PERCENT; result[ "GRAPHENE_DEFAULT_FORCE_SETTLEMENT_DELAY" ] = GRAPHENE_DEFAULT_FORCE_SETTLEMENT_DELAY; result[ "GRAPHENE_DEFAULT_FORCE_SETTLEMENT_OFFSET" ] = GRAPHENE_DEFAULT_FORCE_SETTLEMENT_OFFSET; result[ "GRAPHENE_DEFAULT_FORCE_SETTLEMENT_MAX_VOLUME" ] = GRAPHENE_DEFAULT_FORCE_SETTLEMENT_MAX_VOLUME; result[ "GRAPHENE_DEFAULT_PRICE_FEED_LIFETIME" ] = GRAPHENE_DEFAULT_PRICE_FEED_LIFETIME; result[ "GRAPHENE_MAX_FEED_PRODUCERS" ] = GRAPHENE_MAX_FEED_PRODUCERS; result[ "GRAPHENE_DEFAULT_MAX_AUTHORITY_MEMBERSHIP" ] = GRAPHENE_DEFAULT_MAX_AUTHORITY_MEMBERSHIP; result[ "GRAPHENE_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES" ] = GRAPHENE_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES; result[ "GRAPHENE_DEFAULT_MAX_ASSET_FEED_PUBLISHERS" ] = GRAPHENE_DEFAULT_MAX_ASSET_FEED_PUBLISHERS; result[ "GRAPHENE_COLLATERAL_RATIO_DENOM" ] = GRAPHENE_COLLATERAL_RATIO_DENOM; result[ "GRAPHENE_MIN_COLLATERAL_RATIO" ] = GRAPHENE_MIN_COLLATERAL_RATIO; result[ "GRAPHENE_MAX_COLLATERAL_RATIO" ] = GRAPHENE_MAX_COLLATERAL_RATIO; result[ "GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO" ] = GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO; result[ "GRAPHENE_DEFAULT_MAX_SHORT_SQUEEZE_RATIO" ] = GRAPHENE_DEFAULT_MAX_SHORT_SQUEEZE_RATIO; result[ "GRAPHENE_DEFAULT_MARGIN_PERIOD_SEC" ] = GRAPHENE_DEFAULT_MARGIN_PERIOD_SEC; result[ "GRAPHENE_DEFAULT_MAX_WITNESSES" ] = GRAPHENE_DEFAULT_MAX_WITNESSES; result[ "GRAPHENE_DEFAULT_MAX_COMMITTEE" ] = GRAPHENE_DEFAULT_MAX_COMMITTEE; result[ "GRAPHENE_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC" ] = GRAPHENE_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC; result[ "GRAPHENE_DEFAULT_COMMITTEE_PROPOSAL_REVIEW_PERIOD_SEC" ] = GRAPHENE_DEFAULT_COMMITTEE_PROPOSAL_REVIEW_PERIOD_SEC; result[ "GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE" ] = GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE; result[ "GRAPHENE_DEFAULT_LIFETIME_REFERRER_PERCENT_OF_FEE" ] = GRAPHENE_DEFAULT_LIFETIME_REFERRER_PERCENT_OF_FEE; result[ "GRAPHENE_DEFAULT_MAX_BULK_DISCOUNT_PERCENT" ] = GRAPHENE_DEFAULT_MAX_BULK_DISCOUNT_PERCENT; result[ "GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MIN" ] = GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MIN; result[ "GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MAX" ] = GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MAX; result[ "GRAPHENE_DEFAULT_CASHBACK_VESTING_PERIOD_SEC" ] = GRAPHENE_DEFAULT_CASHBACK_VESTING_PERIOD_SEC; result[ "GRAPHENE_DEFAULT_CASHBACK_VESTING_THRESHOLD" ] = GRAPHENE_DEFAULT_CASHBACK_VESTING_THRESHOLD; result[ "GRAPHENE_DEFAULT_BURN_PERCENT_OF_FEE" ] = GRAPHENE_DEFAULT_BURN_PERCENT_OF_FEE; result[ "GRAPHENE_WITNESS_PAY_PERCENT_PRECISION" ] = GRAPHENE_WITNESS_PAY_PERCENT_PRECISION; result[ "GRAPHENE_DEFAULT_MAX_ASSERT_OPCODE" ] = GRAPHENE_DEFAULT_MAX_ASSERT_OPCODE; result[ "GRAPHENE_DEFAULT_FEE_LIQUIDATION_THRESHOLD" ] = GRAPHENE_DEFAULT_FEE_LIQUIDATION_THRESHOLD; result[ "GRAPHENE_DEFAULT_ACCOUNTS_PER_FEE_SCALE" ] = GRAPHENE_DEFAULT_ACCOUNTS_PER_FEE_SCALE; result[ "GRAPHENE_DEFAULT_ACCOUNT_FEE_SCALE_BITSHIFTS" ] = GRAPHENE_DEFAULT_ACCOUNT_FEE_SCALE_BITSHIFTS; result[ "GRAPHENE_MAX_WORKER_NAME_LENGTH" ] = GRAPHENE_MAX_WORKER_NAME_LENGTH; result[ "GRAPHENE_MAX_URL_LENGTH" ] = GRAPHENE_MAX_URL_LENGTH; result[ "GRAPHENE_NEAR_SCHEDULE_CTR_IV" ] = GRAPHENE_NEAR_SCHEDULE_CTR_IV; result[ "GRAPHENE_FAR_SCHEDULE_CTR_IV" ] = GRAPHENE_FAR_SCHEDULE_CTR_IV; result[ "GRAPHENE_CORE_ASSET_CYCLE_RATE" ] = GRAPHENE_CORE_ASSET_CYCLE_RATE; result[ "GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS" ] = GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS; result[ "GRAPHENE_DEFAULT_WITNESS_PAY_PER_BLOCK" ] = GRAPHENE_DEFAULT_WITNESS_PAY_PER_BLOCK; result[ "GRAPHENE_DEFAULT_WITNESS_PAY_VESTING_SECONDS" ] = GRAPHENE_DEFAULT_WITNESS_PAY_VESTING_SECONDS; result[ "GRAPHENE_DEFAULT_WORKER_BUDGET_PER_DAY" ] = GRAPHENE_DEFAULT_WORKER_BUDGET_PER_DAY; result[ "GRAPHENE_MAX_INTEREST_APR" ] = GRAPHENE_MAX_INTEREST_APR; result[ "GRAPHENE_COMMITTEE_ACCOUNT" ] = GRAPHENE_COMMITTEE_ACCOUNT; result[ "GRAPHENE_WITNESS_ACCOUNT" ] = GRAPHENE_WITNESS_ACCOUNT; result[ "GRAPHENE_RELAXED_COMMITTEE_ACCOUNT" ] = GRAPHENE_RELAXED_COMMITTEE_ACCOUNT; result[ "GRAPHENE_NULL_ACCOUNT" ] = GRAPHENE_NULL_ACCOUNT; result[ "GRAPHENE_TEMP_ACCOUNT" ] = GRAPHENE_TEMP_ACCOUNT; return result; } } } // graphene::chain
8f4e7163a49de5688403d78423e12e38f5ed54c6
0c22d527c18df1f4edb90523f01e4a56cdf58606
/NaoTH2011-light/NaoTHSoccer/Source/Core/Cognition/Modules/Modeling/GoalLocator/ActiveGoalLocator/AGLSample.h
675e6164c11b252a1264eca8f07d4f2ee2de1776
[]
no_license
IntelligentRoboticsLab/DNT2013
3d9fdb1677858fe73006132cc47dda54b47ef165
ddc47ce982fe9f9cfaf924902208df1d5e53a802
refs/heads/master
2020-04-09T06:04:30.577673
2013-12-11T13:39:12
2013-12-11T13:39:12
9,521,743
3
1
null
null
null
null
UTF-8
C++
false
false
619
h
AGLSample.h
/** * @file Sample.h * * @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a> * Declaration of class Sample */ #ifndef __AGLSample_h_ #define __AGLSample_h_ #include "Cognition/Modules/Modeling/SelfLocator/MonteCarloSelfLocator/Sample.h" #include "Tools/ColorClasses.h" class AGLSample: public Sample2D { public: AGLSample() : likelihood(0.0){} ~AGLSample() {} double likelihood; Vector2<double> translation; ColorClasses::Color color; virtual const Vector2<double>& getPos() const { return translation; } }; #endif //__AGLSample_h_
17a5029d9f6cbe5f5f9f423d990531352399bc13
f9b2a0ad56047a42823d3d9bec67b78752d4c8a2
/src/demosaic.cpp
47f9dea244309f817563b1fce1b13cc125640198
[]
no_license
KailunL/418
7bec5bf5c1527b4fe64c1b618988a06721f608e2
a0ab87c75909bc7c6ce9fcb2904209413529d3dc
refs/heads/master
2020-04-17T05:18:18.049400
2019-01-17T18:09:27
2019-01-17T18:09:27
166,272,669
0
0
null
null
null
null
UTF-8
C++
false
false
5,512
cpp
demosaic.cpp
#include "demosaic.h" void demosaic( const std::vector<unsigned char> & bayer, const int & width, const int & height, std::vector<unsigned char> & rgb) { rgb.resize(width * height * 3); //////////////////////////////////////////////////////////////////////////// // Add your code here //////////////////////////////////////////////////////////////////////////// int color1 = 0; int color2 = 0; int org_channel = 0; int up = 1; int left = 1; for (int i = 0; i < height; i++) { int left = 1; for (int j = 0; j < width; j++) { color1 = width * i + j; color2 = width * i * 3 + 3 * j; int directions = 8; int red = 0; int blue = 0; int green = 0; int Cred = 0; int Cblue = 0; int Cgreen = 0; // std::vector<int> red; // std::vector<int> green; // std::vector<int> blue; if (left == up) {//green org_channel = 1; if (i != 1) {//has top Cred++; red += (int) bayer[(i - 1) * width + j]; } if (i != height - 1) { //has but Cred++; red += (int) bayer[(i + 1) * width + j]; } if (j != 1) {//left Cblue++; blue += (int) bayer[i * width + j - 1]; } if (j != width - 1) {//right Cblue++; blue += (int) bayer[i * width + j + 1]; } } else if (left == 1 && up == 0) { //red org_channel = 0; if (i != 1) {//has top Cgreen++; green += (int) bayer[(i - 1) * width + j]; if (j != 1) {//top left Cblue++; blue += (int) bayer[(i - 1) * width + j - 1]; } if (j != width - 1) {//top right Cblue++; blue += (int) bayer[(i - 1) * width + j + 1]; } } if (i != height - 1) { //has but Cgreen++; green += (int) bayer[(i + 1) * width + j]; if (j != 1) {//but left Cblue++; blue += (int) bayer[(i + 1) * width + j - 1]; } if (j != width - 1) {//but right Cblue++; blue += (int) bayer[(i + 1) * width + j + 1]; } } if (j != 1) {//left Cgreen++; green += (int) bayer[i * width + j - 1]; } if (j != width - 1) {//right Cgreen++; green += (int) bayer[i * width + j + 1]; } } else { //blue org_channel = 2; if (i != 1) {//has top Cgreen++; green += (int) bayer[(i - 1) * width + j]; if (j != 1) {//top left Cred++; red += (int) bayer[(i - 1) * width + j - 1]; } if (j != width - 1) {//top right Cred++; red += (int) bayer[(i - 1) * width + j + 1]; } } if (i != height - 1) { //has but Cgreen++; green += (int) bayer[(i + 1) * width + j]; if (j != 1) {//but left Cred++; red += (int) bayer[(i + 1) * width + j - 1]; } if (j != width - 1) {//but right Cred++; red += (int) bayer[(i + 1) * width + j + 1]; } } if (j != 1) {//left Cgreen++; green += (int) bayer[i * width + j - 1]; } if (j != width - 1) {//right Cgreen++; green += (int) bayer[i * width + j + 1]; } } if (Cred != 0) red = red / Cred; if (Cgreen != 0) green = green / Cgreen; if (Cblue != 0) blue = blue / Cblue; //reflected[color2+channel] = input[color2+channel]; if (org_channel == 0) { rgb [color2] = bayer[color1]; rgb [color2+1] = green; rgb [color2+2] = blue; }//red else if (org_channel == 1) { rgb [color2] = red; rgb [color2+1] = bayer[color1]; rgb [color2+2] = blue; }//green else { rgb [color2] = red; rgb [color2+1] = green; rgb [color2+2] = bayer[color1]; }//blue //reflected[color2+channel] = input[color2+channel]; if (left == 0) left++; else left--; } if (up == 0) up++; else up--; } }
2e98c8dd51d9c001b6c0bafedfe671fcb382d528
71ce9666e1b0f78c2deb08e5550483ce57c5b9e6
/(mini)/winapi(labs)/pentamollis/pentamollis/source.cpp
f61a9eddeccbd529c8a098415bbd3e1f7c71918b
[]
no_license
RV8V/code-cpp
c49f2bd2fd8fe20c8a916590e99ceea9dc552a86
16076bdb9318f0aad15bbc6a78f3c72d40958d79
refs/heads/master
2023-02-15T04:13:08.147451
2021-01-10T12:20:15
2021-01-10T12:20:15
290,825,039
1
0
null
null
null
null
UTF-8
C++
false
false
6,845
cpp
source.cpp
#include <Windows.h> #include <stdlib.h> #define FILE_MENU_NEW 1 #define FILE_MENU_OPEN 2 #define FILE_MENU_EXIT 3 #define CHANGE_TITLE 4 #define CHANGE_TITLE_VIA_BUTTON 5 #define GENERATE_BUTTON 6 #define ID_DIALOGBOX 7 #define INPUT_TEXT_SIZE 100 #define NAME_SIZE 30 #define AGE_SIZE 10 #define OUT_SIZE 50 LRESULT CALLBACK windowProcedure(HWND, UINT, WPARAM, LPARAM); VOID addMenus(HWND); VOID addControls(HWND); VOID addControls_app(HWND); VOID loadImages(); VOID registerDialogClass(HINSTANCE); VOID displayDialog(HWND); HMENU handle_menu; HWND handle_edit, handle_main_window; HBITMAP handle_image_load, handle_image_load_generate; HWND handle_name, handle_age, handle_out, handle_image_logo; LRESULT CALLBACK dialogProcedure(HWND, UINT, WPARAM, LPARAM); INT CALLBACK wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, INT) { WNDCLASSW wc = { 0 }; wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hInstance = hInstance; wc.lpszClassName = L"myclassname"; wc.lpfnWndProc = windowProcedure; if (!RegisterClassW(&wc)) return -1; registerDialogClass(hInstance); handle_main_window = CreateWindowW(L"myclassname", L"windowname", WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 100, 500, 500, NULL, NULL, NULL, NULL); //MessageBoxW(NULL, L"HELLO", L"HI", MB_OK); MSG msg = { 0 }; while (GetMessage(&msg, NULL, NULL, NULL)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; } LRESULT CALLBACK windowProcedure(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp) { INT value; switch (msg) { case WM_CREATE: loadImages(); addMenus(hWnd); addControls_app(hWnd); return 0; case WM_COMMAND: switch (wp) { case FILE_MENU_NEW: displayDialog(hWnd); MessageBeep(MB_ICONINFORMATION); return 0; case CHANGE_TITLE: wchar_t text[INPUT_TEXT_SIZE]; GetWindowTextW(handle_edit, text, INPUT_TEXT_SIZE); SetWindowTextW(hWnd, text); return 0; case CHANGE_TITLE_VIA_BUTTON: wchar_t input_text[INPUT_TEXT_SIZE]; GetWindowTextW(handle_edit, input_text, INPUT_TEXT_SIZE); SetWindowTextW(hWnd, input_text); return 0; case GENERATE_BUTTON: char name[NAME_SIZE], age[AGE_SIZE], out[OUT_SIZE]; GetWindowTextA(handle_name, name, NAME_SIZE); GetWindowTextA(handle_age, age, AGE_SIZE); if (strcmp(name, "") == 0 || strcmp(age, "") == 0) { value = MessageBoxW(hWnd, L"You did not enter name or age", NULL, MB_ABORTRETRYIGNORE); switch (value) { case IDABORT: DestroyWindow(hWnd); return 0; case IDRETRY: return 0; case IDIGNORE: break; } } strcpy_s(out, name); strcat_s(out, " is "); strcat_s(out, age); strcat_s(out, " years old"); SetWindowTextA(handle_out, out); return 0; case FILE_MENU_EXIT: value = MessageBoxW(hWnd, L"Are you sure?", L"Wait!", MB_YESNO | MB_ICONEXCLAMATION | MB_ICONERROR); if (value == IDYES) DestroyWindow(hWnd); else if (value == IDNO) { } return 0; } return 0; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wp, lp); } VOID addMenus(HWND hWnd) { handle_menu = CreateMenu(); HMENU handle_file_menu = CreateMenu(); HMENU handle_submenu = CreateMenu(); AppendMenu(handle_submenu, MF_STRING, CHANGE_TITLE, "change title"); AppendMenu(handle_file_menu, MF_STRING, FILE_MENU_NEW, "new"); AppendMenu(handle_file_menu, MF_POPUP, (UINT)handle_submenu, "open submenu"); AppendMenu(handle_file_menu, MF_SEPARATOR, NULL, NULL); AppendMenu(handle_file_menu, MF_STRING, FILE_MENU_EXIT, "exit"); AppendMenu(handle_menu, MF_POPUP, (UINT_PTR)handle_file_menu, "File"); AppendMenu(handle_menu, MF_STRING, NULL, "Help"); SetMenu(hWnd, handle_menu); } VOID addControls(HWND hWnd) { CreateWindowW(L"static", L"Enter text here:", WS_VISIBLE | WS_CHILD | WS_BORDER | SS_CENTER, 200, 100, 100, 50, hWnd, NULL, NULL, NULL); handle_edit = CreateWindowW(L"edit", L"...", WS_VISIBLE | WS_CHILD | WS_BORDER | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL, 200, 152, 100, 50, hWnd, NULL, NULL, NULL); CreateWindowW(L"button", L"change title via button click", WS_VISIBLE | WS_CHILD, 200, 204, 100, 50, hWnd, (HMENU)CHANGE_TITLE_VIA_BUTTON, NULL, NULL); } VOID addControls_app(HWND hWnd) { CreateWindowW(L"static", L"name: ", WS_VISIBLE | WS_CHILD, 100, 50, 98, 38, hWnd, NULL, NULL, NULL); handle_name = CreateWindowW(L"edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER, 200, 50, 98, 38, hWnd, NULL, NULL, NULL); CreateWindowW(L"static", L"age: ", WS_VISIBLE | WS_CHILD, 100, 90, 98, 38, hWnd, NULL, NULL, NULL); handle_age = CreateWindowW(L"edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER, 200, 90, 98, 38, hWnd, NULL, NULL, NULL); HWND handle_button = CreateWindowW(L"button", L"generate", WS_VISIBLE | WS_CHILD | BS_BITMAP, 150, 140, 98, 38, hWnd, (HMENU)GENERATE_BUTTON, NULL, NULL); SendMessageW(handle_button, BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)handle_image_load_generate); handle_out = CreateWindowW(L"edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER, 100, 200, 300, 200, hWnd, NULL, NULL, NULL); handle_image_logo = CreateWindowW(L"static", NULL, WS_VISIBLE | WS_CHILD | SS_BITMAP, 350, 60, 100, 100, hWnd, NULL, NULL, NULL); SendMessageW(handle_image_logo, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)handle_image_load); } VOID loadImages() { handle_image_load = (HBITMAP)LoadImageW(NULL, L" C:\\Users\\Administrator\\source\\repos\\pentamollis\\pentamollis\\IMAGE_LAND2.BMP", IMAGE_BITMAP, 100, 100, LR_LOADFROMFILE); handle_image_load_generate = (HBITMAP)LoadImageW(NULL, L" C:\\Users\\Administrator\\source\\repos\\pentamollis\\pentamollis\\GENERATE_LAND2.BMP", IMAGE_BITMAP, 100, 100, LR_LOADFROMFILE); } LRESULT CALLBACK dialogProcedure(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp) { switch (msg) { case WM_COMMAND: switch (wp) { case ID_DIALOGBOX: EnableWindow(handle_main_window, TRUE); DestroyWindow(hWnd); return 0; } return 0; case WM_CLOSE: EnableWindow(handle_main_window, TRUE); DestroyWindow(hWnd); return 0; } return DefWindowProc(hWnd, msg, wp, lp); } VOID registerDialogClass(HINSTANCE hInstance) { WNDCLASSW dialog = { 0 }; dialog.hbrBackground = (HBRUSH)COLOR_WINDOW; dialog.hCursor = LoadCursor(NULL, IDC_CROSS); dialog.hInstance = hInstance; dialog.lpszClassName = L"mydialogclassname"; dialog.lpfnWndProc = dialogProcedure; RegisterClassW(&dialog); } VOID displayDialog(HWND hWnd) { HWND handle_dialog = CreateWindowW(L"mydialogclassname", L"dialog", WS_VISIBLE | WS_OVERLAPPEDWINDOW, 400, 400, 200, 200, hWnd, NULL, NULL, NULL); CreateWindowW(L"button", L"close", WS_VISIBLE | WS_CHILD, 20, 20, 100, 40, handle_dialog, (HMENU)ID_DIALOGBOX, NULL, NULL); EnableWindow(hWnd, FALSE); }
82c0dbe9078a64597e3f52853538e04f881acbcc
14967a93424babfb3d8e80c6c0aa5fc54f857b9a
/FluxSol-Solver/Tmp/TmpI-.h
e58ca4a0caf40fe691895297b93edfd3f9616cfe
[]
no_license
luchete80/fluxsol
aec0cdf118e0726d559916aba3f8d6e32d3cc609
a29af77858597d3fe77d3715d7c0fb65dba07736
refs/heads/master
2020-03-22T09:26:40.640514
2018-07-18T16:25:00
2018-07-18T16:25:00
42,241,640
1
0
null
null
null
null
UTF-8
C++
false
false
4,793
h
TmpI-.h
//#include "error.H" // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // template<class T> inline FluxSol::tmp<T>::tmp(T* tPtr) : isTmp_(true), ptr_(tPtr), ref_(*tPtr) {} template<class T> inline FluxSol::tmp<T>::tmp(const T& tRef) : isTmp_(false), ptr_(0), ref_(tRef) {} template<class T> inline FluxSol::tmp<T>::tmp(const tmp<T>& t) : isTmp_(t.isTmp_), ptr_(t.ptr_), ref_(t.ref_) { if (isTmp_) { if (ptr_) { ptr_->operator++(); } else { // FatalErrorIn("FluxSol::tmp<T>::tmp(const tmp<T>&)") // << "attempted copy of a deallocated temporary" // << abort(FatalError); } } } template<class T> inline FluxSol::tmp<T>::~tmp() { // if (isTmp_ && ptr_) // { // if (ptr_->okToDelete()) // { // delete ptr_; // ptr_ = 0; // } // else // { // ptr_->operator--(); // } // } } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class T> inline bool FluxSol::tmp<T>::isTmp() const { return isTmp_; } template<class T> inline bool FluxSol::tmp<T>::empty() const { return (isTmp_ && !ptr_); } template<class T> inline bool FluxSol::tmp<T>::valid() const { return (!isTmp_ || (isTmp_ && ptr_)); } template<class T> inline T* FluxSol::tmp<T>::ptr() const { if (isTmp_) { if (!ptr_) { // FatalErrorIn("FluxSol::tmp<T>::ptr() const") // << "temporary deallocated" // << abort(FatalError); } T* ptr = ptr_; ptr_ = 0; ptr->resetRefCount(); return ptr; } else { return new T(ref_); } } template<class T> inline void FluxSol::tmp<T>::clear() const { if (isTmp_ && ptr_) // skip this bit: && ptr_->okToDelete()) { delete ptr_; ptr_ = 0; } } // * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * // template<class T> inline T& FluxSol::tmp<T>::operator()() { if (isTmp_) { if (!ptr_) { // FatalErrorIn("T& FluxSol::tmp<T>::operator()()") // << "temporary deallocated" // << abort(FatalError); } return *ptr_; } else { // Note: const is cast away! // Perhaps there should be two refs, one for const and one for non const // and if the ref is actually const then you cannot return it here. // // Another possibility would be to store a const ref and a flag to say // whether the tmp was constructed with a const or a non-const argument. // // eg, enum refType { POINTER = 0, REF = 1, CONSTREF = 2 }; return const_cast<T&>(ref_); } } template<class T> inline const T& FluxSol::tmp<T>::operator()() const { if (isTmp_) { if (!ptr_) { // FatalErrorIn("const T& FluxSol::tmp<T>::operator()() const") // << "temporary deallocated" // << abort(FatalError); } return *ptr_; } else { return ref_; } } template<class T> inline FluxSol::tmp<T>::operator const T&() const { return operator()(); } template<class T> inline T* FluxSol::tmp<T>::operator->() { if (isTmp_) { if (!ptr_) { // FatalErrorIn("FluxSol::tmp<T>::operator->()") // << "temporary deallocated" // << abort(FatalError); } return ptr_; } else { return &const_cast<T&>(ref_); } } template<class T> inline const T* FluxSol::tmp<T>::operator->() const { return const_cast<tmp<T>&>(*this).operator->(); } template<class T> inline void FluxSol::tmp<T>::operator=(const tmp<T>& t) { if (isTmp_ && ptr_) { if (ptr_->okToDelete()) { delete ptr_; ptr_ = 0; } else { ptr_->operator--(); } } if (t.isTmp_) { isTmp_ = true; ptr_ = t.ptr_; if (ptr_) { ptr_->operator++(); } else { // FatalErrorIn("FluxSol::tmp<T>::operator=(const tmp<T>&)") // << "attempted copy of a deallocated temporary" // << abort(FatalError); } } else { // FatalErrorIn("FluxSol::tmp<T>::operator=(const tmp<T>&)") // << "attempted to assign to a const reference to constant object" // << abort(FatalError); } } // ************************************************************************* //
b9be5b7ea080af16c378ebc4601095fac08b6fe4
0ce14ede0093afa61f977723f718c5f326226601
/nopsn/natives.h
9f58705f424cd31783e84377f50c441df83da92c
[]
no_license
esc0rtd3w/nopsn-sprx
faff4de8cf6a559de5baf543d60195a28f332d99
797f1fc4eaf4f1a5ea88b91534bc4710cb5b88d9
refs/heads/master
2021-01-19T09:08:04.988970
2017-04-22T23:42:45
2017-04-22T23:42:45
87,726,010
7
2
null
null
null
null
UTF-8
C++
false
false
259
h
natives.h
#pragma once #include "core.h" namespace YouTube { // Unknown Text 1 opd_s _UNK_TEXT_1 = {UNK_TEXT_1, TOC}; void(*UNK_TEXT_1)(char* unk1, int* unk2, int* unk3, int* unk4, int* unk5) = (void(*)(char*, int*, int*, int*, int*))&_UNK_TEXT_1; };
f3f87364b5c775ed5a56de5dc880f0f63607099f
aad28fa1140e713c8591db5a383ac5f6605f743b
/343 Поиски минимума/Поиски минимума.cpp
5566ddad21fe254474e363a8bc3e517004137b6b
[]
no_license
DaniilMuntyan/Solutions_e-olymp
d7ad45357d4f999c853efefcd47c39bc17e33664
7a318572e13f2e6103a2ade49c8ce9c5210caad9
refs/heads/master
2021-02-28T15:22:58.506994
2020-03-07T21:42:50
2020-03-07T21:42:50
245,708,666
3
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
Поиски минимума.cpp
#include <bits/stdc++.h> using namespace std; int main() { long long n,i,mi; cin >> n; vector <long long> d(n); cin >> d[0]; mi = d[0]; for(i=1;i<n;i++){ cin >> d[i]; if(mi > d[i]) mi = d[i]; } cout << mi << endl; }
395b89c0194c4f2512a6715d2641d2f79a04ad4e
25f96fbbf57000b1c4dbe3f48fa15d1dc9032245
/Soluciones/SPOJ/LUCKY/LUCKY.cpp
91bbbf37ba5f137e68fb2b243af3848aaa2dba6a
[]
no_license
joacru/Programacion-Competitiva
2a16655403b9c057b79e102a17e3beaec37a2b84
b0d58b1690214556e27ef626aae2a54eec4062dc
refs/heads/master
2023-07-19T21:28:07.369044
2023-07-09T00:14:51
2023-07-09T00:14:51
207,465,986
4
0
null
null
null
null
UTF-8
C++
false
false
1,772
cpp
LUCKY.cpp
#include<bits/stdc++.h> #define forn(i, n) for(int i = 0; i < n; i++) using namespace std; const int MAXN = 1E5 + 5; struct edge{ int u, v, comp; bool lucky; int getTo(int x){ return (u ^ v) ^ x; } }; int dfsN[MAXN], dfsM[MAXN], bicC = 0; vector<int> adj[MAXN]; vector<bool> lucky(MAXN); edge edges[MAXN]; stack<int> forBic; void dfs(int u, int l, int p){ dfsN[u] = dfsM[u] = l; for(int x : adj[u]){ int v = edges[x].getTo(u); if(dfsN[v] == 0){ forBic.push(x); dfs(v, l + 1, u); dfsM[u] = min(dfsM[u], dfsM[v]); if(dfsN[u] <= dfsM[v]){ bicC++; while(forBic.size()){ int i = forBic.top(); forBic.pop(); edges[i].comp = bicC; if((edges[i].u == u || edges[i].v == u) && !edges[i].lucky) break; } } } else if(v != p && dfsN[u] > dfsN[v]){ dfsM[u] = min(dfsM[u], dfsN[v]); if((dfsN[u] - dfsN[v]) % 2 == 0){ forBic.push(x); edges[x].lucky = 1; } } } } int main(){ int tc; cin>>tc; while(tc--){ int n, m; bicC = 0; while(forBic.size()) forBic.pop(); cin>>n>>m; forn(i, MAXN) lucky[i] = 0; forn(i, n){ dfsN[i] = 0; adj[i].clear(); } forn(i, m){ int a, b; cin>>a>>b; a--; b--; edges[i] = {a, b, 0, 0}; adj[a].push_back(i); adj[b].push_back(i); lucky[i + 1] = 0; } forn(i, n){ if(dfsN[i]) continue; dfs(i, 1, -1); } forn(i, m){ if(!edges[i].lucky) continue; lucky[edges[i].comp] = 1; } int res = 0; forn(i, n){ bool valid = 0; for(int x : adj[i]){ if(lucky[edges[x].comp]) valid = 1; } res += valid; } cout<<res<<"\n"; } return 0; }
fd732487c711dd45cf8cee988ac7400ad6198e7a
0cf74b1be006bff40e929c37a8cd721e6c2d970e
/src/Timsort.h
1d00c13da13ab3c33f2cd7beb3637e7380439e7c
[ "MIT" ]
permissive
mmwind/timsort-cpp
422e5b05703b0ce85bbd4f0254b4cdf0e94dba30
d10829ed5746cb63214b9f6b6e390ffcd9f2865b
refs/heads/master
2021-01-10T06:47:04.158722
2015-11-03T15:01:10
2015-11-03T15:01:10
44,866,338
0
0
null
null
null
null
UTF-8
C++
false
false
1,691
h
Timsort.h
/* * Timsort.h * * Created on: 24 окт. 2015 г. * Author: mmwind */ #ifndef TIMSORT_H_ #define TIMSORT_H_ #include <cstdlib> #include <vector> class Timsort { public: Timsort(){ }; virtual ~Timsort(){ }; void sort(){ if(Array == NULL) { throw (std::bad_array_length()); } minrun = getMinrun(); std::vector<int>::iterator it = Array->begin(); while(it != Array->end()){ std::pair< std::vector<int>::iterator, bool> eit = getRunEnd(it); unsigned int len = eit.first - it; if(len < minrun){ eit.first = eit.first + (minrun - len); } } } std::vector<int>* getArray() { return Array; } void setArray(std::vector<int>* array) { Array = array; } protected: std::vector<int> * Array; int minrun; int getMinrun() { int n = Array->size(); int r = 0; while (n >= 64) { r |= n & 1; n >>= 1; } return n + r; } /** * * @param first * @return конец подмассива и то, как он упорядочен (true - по убыванию, дальнейшая сортировка нужна) */ std::pair< std::vector<int>::iterator, bool> getRunEnd(std::vector<int>::iterator first){ std::pair< std::vector<int>::iterator, bool> res; std::vector<int>::iterator it = first + 1; if(*(it - 1) > *it && it != Array->end()) res.second = true; else res.second = false; while(*(it - 1) > *it && it != Array->end() ){ it++; } while(*(it - 1) <= *it && it != Array->end() ){ it++; } res.first = it - 1; return(res); } }; #endif /* TIMSORT_H_ */
3fa51fc7dd8516d0685cefc8afcf48f298d00bb3
f20e965e19b749e84281cb35baea6787f815f777
/Hlt/Hlt/HltLuminosity/src/LumiCountVertices.h
d5745903ba1d5ccc0d6d14c2d24fc88a1d81794d
[]
no_license
marromlam/lhcb-software
f677abc9c6a27aa82a9b68c062eab587e6883906
f3a80ecab090d9ec1b33e12b987d3d743884dc24
refs/heads/master
2020-12-23T15:26:01.606128
2016-04-08T15:48:59
2016-04-08T15:48:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
901
h
LumiCountVertices.h
// $Id: LumiCountVertices.h,v 1.2 2008-08-25 10:59:04 panmanj Exp $ #ifndef LUMICOUNTVERTICES_H #define LUMICOUNTVERTICES_H 1 // Include files // from Gaudi #include "GaudiAlg/GaudiAlgorithm.h" // from LHCB #include "Event/Vertex.h" #include "Event/RecVertex.h" /** @class LumiCountVertices LumiCountVertices.h * * * @author Jaap Panman * @date 2008-07-21 */ class LumiCountVertices : public GaudiAlgorithm { public: /// Standard constructor LumiCountVertices( const std::string& name, ISvcLocator* pSvcLocator ); ~LumiCountVertices() override = default; ///< Destructor StatusCode initialize() override; ///< Algorithm initialization StatusCode execute() override; ///< Algorithm execution private: std::string m_InputSelectionName; std::string m_CounterName; std::string m_OutputContainerName; int m_Counter; }; #endif // LUMICOUNTVERTICES_H
e191a0b50af154c78cb534c29040de1ab07a14a3
8072f4d2c4d7416c1ffd975b059f79573cbbceec
/exceptionhandler.hpp
022cf5c2ccb84282e494a8d5f98d05ac2fc8f415
[]
no_license
jjzhang166/angle
1857719a9d813cb7f862e953376190cd6cbc98ff
041766ae941a81b5b8dcaa5d06126a593fb9815e
refs/heads/master
2021-01-01T19:36:37.169393
2017-03-07T19:06:18
2017-03-07T19:06:18
98,623,816
0
0
null
null
null
null
UTF-8
C++
false
false
812
hpp
exceptionhandler.hpp
//@ { //@ "targets":[{"name":"exceptionhandler.hpp","type":"include"}] //@ ,"dependencies_extra":[{"ref":"exceptionhandler.o","rel":"implementation"}] //@} #ifndef ANGLE_EXCEPTIONHANDLER_HPP #define ANGLE_EXCEPTIONHANDLER_HPP #include "error.hpp" namespace Angle { class ExceptionHandler { virtual void raise(const Error& err) {throw err;} friend void exceptionRaise(const Error& err); }; ExceptionHandler& exceptionHandlerSet(ExceptionHandler* eh) noexcept; void exceptionRaise(const Error& err); class ExceptionContext { public: explicit ExceptionContext(ExceptionHandler* eh) noexcept: r_handler_old(exceptionHandlerSet(eh)) {} ~ExceptionContext() noexcept {exceptionHandlerSet(&r_handler_old);} private: ExceptionHandler& r_handler_old; }; } #endif
e0c33eced98866b4e11b4ae9cd731e2e8d18d0ce
16f6c597e76e65bf77400c28a12cc6bb2a51f3ff
/Project/LEDA/test/core/misc/qsort_isort.cpp
d514cd1ea473a8e9395c02de686bf0afcd03329c
[]
no_license
raghukul01/Randomized_Algorithms
347e82d7518e693c2d2adada28b0f7faaeecd3c2
36488f45b4ee2d3f4415ddacaedee61c2b94921a
refs/heads/master
2020-03-27T06:07:48.920465
2018-11-15T13:01:05
2018-11-15T13:01:05
146,081,033
10
4
null
null
null
null
UTF-8
C++
false
false
1,771
cpp
qsort_isort.cpp
#include <LEDA/system/basic.h> #include <LEDA/core/array.h> #include <LEDA/core/basic_alg.h> #include <LEDA/core/quicksort.h> #include <assert.h> using namespace leda; #if defined(LEDA_STD_IO_HEADERS) using std::cout; using std::endl; using std::flush; #endif int main () { int N = read_int("N = "); array<int> A(N); array<int> B(N); for (int i = 0; i < N; i++) A[i] = B[i] = rand_int(1,1000000); leda_smaller<int> smaller; float T = used_time(); cout << "quicksort " << flush; quicksort(B.first_item(),B.last_item(),smaller); cout << string("%5.3f sec",used_time(T)) << endl; /* for (int i = 0; i < N; i++) B[i] = A[i]; T = used_time(); cout << "mergesort " << flush; mergesort(B.first_item(),B.last_item(),smaller); cout << string("%5.3f sec",used_time(T)) << endl; cout << endl; */ for (int i = 0; i < N; i++) B[i] = A[i]; T = used_time(); cout << "int_sort " << flush; INTSORT(B.first_item(),N); cout << string("%5.3f sec",used_time(T)) << endl; cout << endl; for(int d=1; d<256;d*=2) { for (int i = 0; i < N; i++) B[i] = A[i]; cout << string("quicksort d = %3d ",d) << flush; float t1 = used_time(); quicksort_d(B.first_item(),B.last_item(),smaller,d); float t2 = used_time(); insertion_sort(B.first_item(),B.last_item(),smaller); float t3 = used_time(); cout << string("%5.3f + %5.3f = %5.2f sec",t2-t1,t3-t2,t3-t1) << flush; for (int i = 1; i < N; i++) assert(B[i-1] <= B[i]); for (int i = 0; i < N; i++) B[i] = A[i]; t1 = used_time(); quicksort_i(B.first_item(),B.last_item(),smaller,d); cout << string(" %5.2f sec",used_time(t1)) << endl; for (int i = 1; i < N; i++) assert(B[i-1] <= B[i]); } return 0; }
037fb90acf58c41af5e28c8605a6d4ca45b81f0f
96de4fc452fc9d1a6473ec8ad68c1d6cf0cf60bf
/les1_knipperlampje.ino
6a9ee05748eb6d1264b45701f9244c79a201e12f
[]
no_license
shoebby/arduino_experiments
7d81e26f38556596d21cabfa768c16ea13f9e769
7f448ddc2c2a2c4dddc6127354607ff8289845bf
refs/heads/master
2020-12-09T21:38:34.182097
2020-01-12T16:36:04
2020-01-12T16:36:04
233,423,203
0
0
null
null
null
null
UTF-8
C++
false
false
595
ino
les1_knipperlampje.ino
void setup() { pinMode(3,OUTPUT); pinMode(5,OUTPUT); pinMode(6,OUTPUT); pinMode(9,OUTPUT); } void loop() { for (int i=0;i<255;i++) { analogWrite(3, i); delay(5); } for (int i=0;i<255;i++) { analogWrite(5, i); delay(5); } for (int i=0;i<255;i++) { analogWrite(6, i); delay(5); } for (int i=0;i<255;i++) { analogWrite(9, i); delay(5); } for (int i=255;i>0;i--) { analogWrite(3, i); analogWrite(5, i); analogWrite(6, i); analogWrite(9, i); delay(5); } delay(200); }
b6e6e02b089bfbeb275a727313e2653eb05f5be3
56ba2984d5f47c13ebb3ded8a041d43f9522e27f
/inexlib/ourex/SOPHYA/src/SkyMap/spherehealpix.cc
d6b2b225a64db7ced4bd7f5e8ae9c6158eb54185
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
gbarrand/TouchSky
2ad7ec6eef209a8319698829877c20469857dbe1
a6216fb20fbcf9e38ac62a81cef8c4f053a07b8c
refs/heads/master
2021-09-11T07:25:41.523286
2021-08-31T09:29:39
2021-08-31T09:29:39
133,839,247
0
0
null
null
null
null
UTF-8
C++
false
false
19,543
cc
spherehealpix.cc
/* ------------------------------------------------------------------------------------ SOPHYA class library - (C) UPS+LAL IN2P3/CNRS , (C) CEA-Irfu-SPP Spherical map in HEALPix pixelisation G. Le Meur, F. Touze 2000 Updated: R. Ansari 2015 ------------------------------------------------------------------------------------ */ #include "machdefs.h" #include <math.h> #include <complex> #include "pexceptions.h" #include "fiondblock.h" #include "strutil.h" #define SPHEREHEALPIX_CC_BFILE // avoid extern template declarations #include "spherehealpix.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> using namespace std; namespace SOPHYA { /*! \class SphereHEALPix \ingroup SkyMap \brief Spherical maps in HEALPix pixelisation scheme. Class implementing spherical maps, in the HEALPix pixelisation scheme, with template data types (double, float, complex, ...) \verbatim Adapted from : ----------------------------------------------------------------------- version 0.8.2 Aug97 TAC Eric Hivon, Kris Gorski ----------------------------------------------------------------------- by G. Le Meur , F. Touze (01/2000) the sphere is split in 12 diamond-faces containing nside**2 pixels each the numbering of the pixels (in the nested scheme) is similar to quad-cube In each face the first pixel is in the lowest corner of the diamond the faces are (x,y) coordinate on each face . . . . <--- North Pole / \ / \ / \ / \ ^ ^ . 0 . 1 . 2 . 3 . <--- z = 2/3 \ / \ / \ / \ / \ / y \ / x 4 . 5 . 6 . 7 . 4 <--- equator \ / / \ / \ / \ / \ \/ . 8 . 9 .10 .11 . <--- z = -2/3 (0,0) : lowest corner \ / \ / \ / \ / . . . . <--- South Pole \endverbatim phi:0 2Pi in the ring scheme pixels are numbered along the parallels the first parallel is the one closest to the north pole and so on on each parallel, pixels are numbered starting from the one closest to phi = 0 nside MUST be a power of 2 (<= 8192) This class can be instanciated for the following data types: \verbatim Integer data types: uint_1 uint_2 int_1 int_2 int_4 int_8 float and complex data types r_4 r_8 complex<r_4> complex<r_8> and if support for long double (SO_LDBLE128) enabled r_16 complex<r_16> \endverbatim */ /* --Methode-- */ /*! \brief Constructor with optional parameter specifying the pixelisation scheme RING (default) or NESTED The default constructor creates a 0 size map in RING pixelisation \param fgring : true -> RING scheme , false -> NESTED */ template<class T> SphereHEALPix<T>::SphereHEALPix(bool fgring) : HEALPixBase(fgring), pixels_(), sliceBeginIndex_(), sliceLenght_() { } /*! \brief Constructor with specification of nside and optional pixelisation scheme \param <m> : "nside" of the Healpix algorithm \param <fgring> : if true -> RING pixelisation (default), if not NESTED The total number of pixels will be Npix = 12*nside**2 nside MUST be a power of 2 (<= 8192) */ template<class T> SphereHEALPix<T>::SphereHEALPix(int_4 m, bool fgring) : HEALPixBase(fgring) { setNSide(m); } /*! \brief Copy constructor, sharing or copying map data \param share : true -> shares the map data, false -> copies the data */ template<class T> SphereHEALPix<T>::SphereHEALPix(const SphereHEALPix<T>& s, bool share) : pixels_(s.pixels_, share), sliceBeginIndex_(s.sliceBeginIndex_, share), sliceLenght_(s.sliceLenght_, share) { copyFrom(s); if(s.mInfo_) this->mInfo_= new DVList(*s.mInfo_); } template<class T> SphereHEALPix<T>::SphereHEALPix(const SphereHEALPix<T>& s) : pixels_(s.pixels_), sliceBeginIndex_(s.sliceBeginIndex_), sliceLenght_(s.sliceLenght_) { copyFrom(s); if(s.mInfo_) this->mInfo_= new DVList(*s.mInfo_); // CloneOrShare(s); } //! Clone if \b a is not temporary, share if temporary /*! \sa NDataBlock::CloneOrShare(const NDataBlock<T>&) */ template<class T> void SphereHEALPix<T>::CloneOrShare(const SphereHEALPix<T>& a) { copyFrom(a); pixels_.CloneOrShare(a.pixels_); sliceBeginIndex_.CloneOrShare(a.sliceBeginIndex_); sliceLenght_.CloneOrShare(a.sliceLenght_); if (this->mInfo_) {delete this->mInfo_; this->mInfo_ = NULL;} if (a.mInfo_) this->mInfo_ = new DVList(*(a.mInfo_)); } //! Share data with a template<class T> void SphereHEALPix<T>::Share(const SphereHEALPix<T>& a) { copyFrom(a); pixels_.Share(a.pixels_); sliceBeginIndex_.Share(a.sliceBeginIndex_); sliceLenght_.Share(a.sliceLenght_); if (this->mInfo_) {delete this->mInfo_; this->mInfo_ = NULL;} if (a.mInfo_) this->mInfo_ = new DVList(*(a.mInfo_)); } ////////////////////////// methodes de copie/share template<class T> SphereHEALPix<T>& SphereHEALPix<T>::Set(const SphereHEALPix<T>& a) { if (this != &a) { if (a.NbPixels() < 1) throw RangeCheckError("SphereHEALPix<T>::Set(a ) - SphereHEALPix a not allocated ! "); if (NbPixels() < 1) CloneOrShare(a); else CopyElt(a); if (this->mInfo_) delete this->mInfo_; this->mInfo_ = NULL; if (a.mInfo_) this->mInfo_ = new DVList(*(a.mInfo_)); } return(*this); } template<class T> SphereHEALPix<T>& SphereHEALPix<T>::CopyElt(const SphereHEALPix<T>& a) { if (NbPixels() < 1) throw RangeCheckError("SphereHEALPix<T>::CopyElt(a) - Not Allocated SphereHEALPix ! "); if (NbPixels() != a.NbPixels()) throw(SzMismatchError("SphereHEALPix<T>::CopyElt(a) SizeMismatch")) ; if (fgring_ == a.fgring_) pixels_ = a.pixels_; else { if (fgring_) for (int_4 k=0; k< nPix_; k++) pixels_(k) = a.pixels_(HEALPixUtils::ring2nest(nSide_, k)); else for (int_4 k=0; k< nPix_; k++) pixels_(k) = a.pixels_(HEALPixUtils::nest2ring(nSide_, k)); } return(*this); } template<class T> SphereHEALPix<T>::~SphereHEALPix() { } /*! \brief Set or changes the pixelisation resolution by defining the HEALPix \b nside parameter redefinition of the base clase SOPHYA::HEALPixBase::setNSide() method can throw ParmError exception if \b m is invalid \param nside : nside should be a power of 2 ( nside = 2^p ) and 1 <= nside <= 8192 */ template<class T> void SphereHEALPix<T>::setNSide(int_4 nside, bool fgring) { HEALPixBase::setNSide(nside, fgring); pixels_.ReSize(nPix_, true); SetThetaSlices(); } /*! \fn void SOPHYA::SphereHEALPix::Resize(int_4 m) \param <m> "nside" of the HEALPix algorithm The total number of pixels will be Npix = 12*nside**2 nside MUST be a power of 2 (<= 8192) */ template<class T> void SphereHEALPix<T>::Resize(int_4 m) { if ((m <= 0 && nSide_ > 0)) { if (SphericalMap_GetGlobalPrintLevel()>0) cout << "SphereHEALPix<T>::Resize(m) with m<=0, NOT resized" << endl; return; } setNSide(m); } //! return type of the map pixelisation : RING or NESTED template<class T> string SphereHEALPix<T>::TypeOfMap() const { if (fgring_) return string("RING"); else return string("NESTED"); } template<class T> int_4 SphereHEALPix<T>::NbPixels() const { return(nPix_); } /*! \fn uint_4 SOPHYA::SphereHEALPix::NbThetaSlices() const \return number of slices in theta direction on the sphere */ template<class T> uint_4 SphereHEALPix<T>::NbThetaSlices() const { if (nSide_<=0) return 0; uint_4 nbslices = uint_4(4*nSide_-1); return nbslices; } //! Return the theta angle for slice defined by \b index template<class T> r_8 SphereHEALPix<T>::ThetaOfSlice(int_4 index) const { uint_4 nbslices = uint_4(4*nSide_-1); if (nSide_<=0) nbslices = 0; if (index<0 || index >= (int_4)nbslices) throw RangeCheckError(" SphereHEALPix::ThetaOfSlice() index out of range"); r_8 theta, phi0; PixThetaPhi(sliceBeginIndex_(index), theta, phi0); return theta; } //! Return true : All theta slices have a symmetric slice at Pi-Theta in SphereHEALPix template <class T> bool SphereHEALPix<T>::HasSymThetaSlice() const { return true; } //! Return the slice index for the symmetric slice at theta=Pi-ThetaOfSlice(idx) template <class T> int_4 SphereHEALPix<T>::GetSymThetaSliceIndex(int_4 idx) const { if(idx < 0 || idx >= (int_4)NbThetaSlices()) throw RangeCheckError("SphereHEALPix::GetSymThetaSliceIndex index out of range"); return (NbThetaSlices()-1-idx); } /*! \fn void SOPHYA::SphereHEALPix::GetThetaSlice(int_4 index,r_8& theta,TVector<r_8>& phi,TVector<T>& value) const For a theta-slice with index 'index', return : the corresponding "theta" a vector containing the phi's of the pixels of the slice a vector containing the corresponding values of pixels */ template<class T> void SphereHEALPix<T>::GetThetaSlice(int_4 index,r_8& theta,TVector<r_8>& phi,TVector<T>& value) const { if (index<0 || index >= (int_4)NbThetaSlices()) throw RangeCheckError(" SphereHEALPix::GetThetaSlice() index out of range"); int_4 iring= sliceBeginIndex_(index); int_4 lring = sliceLenght_(index); phi.ReSize(lring); value.ReSize(lring); double TH= 0.; double FI= 0.; if (fgring_) { // RING pixelisation scheme for(int_4 kk = 0; kk < lring;kk++) { PixThetaPhi(kk+iring,TH,FI); phi(kk)= FI; value(kk)= pixels_(kk+iring); } PixThetaPhi(iring, theta, FI); } else { // NESTED pixelisation scheme for(int_4 kk = 0; kk < lring;kk++) { int kkn = HEALPixUtils::ring2nest(nSide_, kk+iring); PixThetaPhi(kkn,TH,FI); phi(kk)= FI; value(kk)= pixels_(kkn); } PixThetaPhi(HEALPixUtils::ring2nest(nSide_,iring), theta, FI); } // theta= TH; } /*! \fn void SOPHYA::SphereHEALPix::GetThetaSlice(int_4 sliceIndex,r_8& theta, r_8& phi0, TVector<int_4>& pixelIndices,TVector<T>& value) const For a theta-slice with index 'index', return : the corresponding "theta" the corresponding "phi" for first pixel of the slice a vector containing indices of the pixels of the slice (equally distributed in phi) a vector containing the corresponding values of pixels */ template<class T> void SphereHEALPix<T>::GetThetaSlice(int_4 sliceIndex,r_8& theta, r_8& phi0, TVector<int_4>& pixelIndices,TVector<T>& value) const { if (sliceIndex<0 || sliceIndex >= (int_4)NbThetaSlices()) throw RangeCheckError(" SphereHEALPix::GetThetaSlice() index out of range"); int_4 iring= sliceBeginIndex_(sliceIndex); int_4 lring = sliceLenght_(sliceIndex); pixelIndices.ReSize(lring); value.ReSize(lring); if (fgring_) { // RING pixelisation scheme for(int_4 kk = 0; kk < lring;kk++) { pixelIndices(kk)= kk+iring; value(kk)= pixels_(kk+iring); } PixThetaPhi(iring, theta, phi0); } else { // NESTED pixelisation scheme for(int_4 kk = 0; kk < lring;kk++) { int_4 kkn = HEALPixUtils::ring2nest(nSide_, kk+iring); pixelIndices(kk)= kkn; value(kk)= pixels_(kkn); } PixThetaPhi(HEALPixUtils::ring2nest(nSide_,iring), theta, phi0); } } //! return a pointer to the specified slice pixel data in RING ordering, NULL in NESTED template<class T> T* SphereHEALPix<T>::GetThetaSliceDataPtr(int_4 sliceIndex) { if (sliceIndex<0 || sliceIndex >= (int_4)NbThetaSlices()) throw RangeCheckError(" SphereHEALPix::GetThetaSliceDataPtr(): index out of range"); if (fgring_) return pixels_.Begin()+sliceBeginIndex_(sliceIndex); else return NULL; } template<class T> void SphereHEALPix<T>::SetThetaSlices() { sliceBeginIndex_.ReSize(4*nSide_-1); sliceLenght_.ReSize(4*nSide_-1); int_4 sliceIndex; int_4 offp = 0; for (sliceIndex=0; sliceIndex< nSide_-1; sliceIndex++) { // sliceBeginIndex_(sliceIndex) = 2*sliceIndex*(sliceIndex+1); sliceBeginIndex_(sliceIndex) = offp; sliceLenght_(sliceIndex) = 4*(sliceIndex+1); offp += sliceLenght_(sliceIndex); } for (sliceIndex= nSide_-1; sliceIndex< 3*nSide_; sliceIndex++) { // sliceBeginIndex_(sliceIndex) = 2*nSide_*(2*sliceIndex-nSide_+1); sliceBeginIndex_(sliceIndex) = offp; sliceLenght_(sliceIndex) = 4*nSide_; offp += sliceLenght_(sliceIndex); } for (sliceIndex= 3*nSide_; sliceIndex< 4*nSide_-1; sliceIndex++) { int_4 nc= 4*nSide_-1-sliceIndex; // sliceBeginIndex_(sliceIndex) = nPix_-2*nc*(nc+1); sliceBeginIndex_(sliceIndex) = offp; sliceLenght_(sliceIndex) = 4*nc; offp += sliceLenght_(sliceIndex); } } /*! \return value of the \b k th pixel */ template<class T> T& SphereHEALPix<T>::PixVal(int_4 k) { if((k < 0) || (k >= nPix_)) throw RangeCheckError("SphereHEALPix::PixVal() index out of range"); return pixels_(k); } /*! \return value of the \b k th pixel */ template<class T> T SphereHEALPix<T>::PixVal(int_4 k) const { if((k < 0) || (k >= nPix_)) throw RangeCheckError("SphereHEALPix::PIxVal() const index out of range"); return *(pixels_.Data()+k); } /*! \fn bool SOPHYA::SphereHEALPix::ContainsSph(double theta, double phi) const \return true if teta,phi in map */ template<class T> bool SphereHEALPix<T>::ContainsSph(double theta, double phi) const { return(true); } /*! \fn int_4 SOPHYA::SphereHEALPix::PixIndexSph(double theta,double phi) const \return "RING" index of the pixel corresponding to direction (theta, phi). */ template<class T> int_4 SphereHEALPix<T>::PixIndexSph(double theta,double phi) const { if (fgring_) return HEALPixUtils::ang2pix_ring(nSide_,theta,phi); else return HEALPixUtils::ang2pix_nest(nSide_,theta,phi); } //! \return (theta,phi) coordinates of middle of pixel with "RING" index k template<class T> void SphereHEALPix<T>::PixThetaPhi(int_4 k,double& theta,double& phi) const { if (fgring_) HEALPixUtils::pix2ang_ring(nSide_,k,theta,phi); else HEALPixUtils::pix2ang_nest(nSide_,k,theta,phi); } // ...... Operations de calcul ...... //! Fill a SphereHEALPix with a constant value \b a template <class T> T SphereHEALPix<T>::SetPixels(T a) { if (NbPixels() < 1) throw NotAllocatedError("SphereHEALPix<T>::SetPixels(T a) - not allocated map ! "); pixels_ = a; return (a); } /*! Add a constant value \b x to a SphereHEALPix */ template <class T> SphereHEALPix<T>& SphereHEALPix<T>::AddCst(T a) { if (NbPixels() < 1) throw RangeCheckError("SphereHEALPix<T>::AddCst(T ) - SphereHEALPix not dimensionned ! "); // pixels_ += a; pixels_.AddCst(a); return (*this); } // /*! Substract a constant value \b from the SphereHEALPix object pixel values \param fginv : if false (default), perform the operation in normal order map.pixel[k] -= a if true, the operands order is exchanged: map.pixel[k] = a-map.pixel[k] */ template <class T> SphereHEALPix<T>& SphereHEALPix<T>::SubCst(T a,bool fginv) { if (NbPixels() < 1) throw RangeCheckError("SphereHEALPix<T>::SubCst(T ) - SphereHEALPix not dimensionned ! "); pixels_.SubCst(a,fginv); return (*this); } /*! multiply a SphereHEALPix by a constant value \b a */ template <class T> SphereHEALPix<T>& SphereHEALPix<T>::MulCst(T a) { if (NbPixels() < 1) throw RangeCheckError("SphereHEALPix<T>::MulCst(T ) - SphereHEALPix not dimensionned ! "); pixels_.MulCst(a); return (*this); } /*! divide a SphereHEALPix by a constant value \b a \param fginv : if false (default), perform the operation in normal order map.pixel[k] /= a if true, the operands order is exchanged: map.pixel[k] = a / map.pixel[k] */ template <class T> SphereHEALPix<T>& SphereHEALPix<T>::DivCst(T a, bool fginv) { if (NbPixels() < 1) throw RangeCheckError("SphereHEALPix<T>::DivCst(T ) - SphereHEALPix not dimensionned ! "); pixels_.DivCst(a, fginv); return (*this); } // >>>> Operations avec 2nd membre de type SphereHEALPix /*! Add two SphereHEALPix pixel wise */ template <class T> SphereHEALPix<T>& SphereHEALPix<T>::AddElt(const SphereHEALPix<T>& a) { if (NbPixels() != a.NbPixels() ) throw(SzMismatchError("SphereHEALPix<T>::AddElt(a) SizeMismatch")) ; if (fgring_ != a.fgring_) throw(ParmError("SphereHEALPix<T>::AddElt(a) different pixelisation RING<>NESTED")) ; pixels_.AddElt(a.pixels_); return (*this); } /*! Substract two SphereHEALPix pixel wise \param fginv : if false (default), perform the operation in normal order map.pixel[k] -= a if true, the operands order is exchanged: map.pixel[k] = a-map.pixel[k] */ template <class T> SphereHEALPix<T>& SphereHEALPix<T>::SubElt(const SphereHEALPix<T>& a, bool fginv) { if (NbPixels() != a.NbPixels() ) throw(SzMismatchError("SphereHEALPix<T>::SubElt(a) SizeMismatch")) ; if (fgring_ != a.fgring_) throw(ParmError("SphereHEALPix<T>::SubElt(a) different pixelisation RING<>NESTED")) ; pixels_.SubElt(a.pixels_, fginv); return (*this); } /*! Multiply two SphereHEALPix pixel wise */ template <class T> SphereHEALPix<T>& SphereHEALPix<T>::MulElt(const SphereHEALPix<T>& a) { if (NbPixels() != a.NbPixels() ) throw(SzMismatchError("SphereHEALPix<T>::MulElt(a) SizeMismatch")) ; if (fgring_ != a.fgring_) throw(ParmError("SphereHEALPix<T>::MulElt(a) different pixelisation RING<>NESTED")) ; pixels_.MulElt(a.pixels_); return (*this); } /*! Divide two SphereHEALPix pixel wise - No protection for divide by 0 \param fginv : if false (default), perform the operation in normal order map.pixel[k] /= a if true, the operands order is exchanged: map.pixel[k] = a / map.pixel[k] */ template <class T> SphereHEALPix<T>& SphereHEALPix<T>::DivElt(const SphereHEALPix<T>& a, bool fginv) { if (NbPixels() != a.NbPixels() ) throw(SzMismatchError("SphereHEALPix<T>::DivElt(a) SizeMismatch")) ; if (fgring_ != a.fgring_) throw(ParmError("SphereHEALPix<T>::DivElt(a) different pixelisation RING<>NESTED")) ; pixels_.DivElt(a.pixels_,fginv); return (*this); } template <class T> void SphereHEALPix<T>::print(ostream& os) const { this->Show(os); os << "SphereHEALPix<T>(" << TypeOfMap() << ") NSide= " << nSide_ << " nPix_ = " << nPix_ << " omeg_ = " << omeg_ << endl; if(this->mInfo_) os << " DVList Info= " << *(this->mInfo_) << endl; os << "... Pixel values : "; for(int i=0; i < nPix_; i++) { if(i%5 == 0) os << endl; os << pixels_(i) <<", "; } os << endl; } //******************************************************************* #ifdef __CXX_PRAGMA_TEMPLATES__ #pragma define_template SphereHEALPix<uint_2> #pragma define_template SphereHEALPix<int_4> #pragma define_template SphereHEALPix<r_8> #pragma define_template SphereHEALPix<r_4> #pragma define_template SphereHEALPix< complex<r_4> > #pragma define_template SphereHEALPix< complex<r_8> > #endif #if defined(ANSI_TEMPLATES) || defined(GNU_TEMPLATES) template class SphereHEALPix<uint_1>; template class SphereHEALPix<uint_2>; template class SphereHEALPix<int_1>; template class SphereHEALPix<int_2>; template class SphereHEALPix<int_4>; template class SphereHEALPix<int_8>; template class SphereHEALPix<r_4>; template class SphereHEALPix<r_8>; template class SphereHEALPix< complex<r_4> >; template class SphereHEALPix< complex<r_8> >; #ifdef SO_LDBLE128 template class SphereHEALPix<r_16>; template class SphereHEALPix< complex<r_16> >; #endif #endif } // FIN namespace SOPHYA
ba58e68b5adfb547f8feaaecc1888f5388d2a077
539aff4c4469b2cc74fa08a3f574377b4c76c484
/COJ/2185.cpp
84bd29f7868168350d12691b59b7e1c366401449
[]
no_license
jorgenunezsiri/competitive-programming-solutions
ddf837547ec7cdb5360b50d46e1b536421faf91f
e0193020d0a0dbadec6bbee21eb1d3e0ce76e849
refs/heads/master
2020-06-22T07:51:22.414944
2019-07-20T03:26:26
2019-07-20T03:26:26
197,675,552
0
0
null
null
null
null
UTF-8
C++
false
false
362
cpp
2185.cpp
// Copyright (c) Jorge Nunez Siri. All rights reserved. // Problem URL: https://coj.uci.cu/24h/problem.xhtml?pid=2185 #include <iostream> using namespace std; int main() { int A, B; cin >> A >> B; cout << (A+B) << "\n"; cout << (A-B) << "\n"; cout << (A*B) << "\n"; cout << (A/B) << "\n"; cout << (A%B) << "\n"; return 0; }
6afb3df86d4b413dcf2077cda5bb4d5824366640
45bebb1cf4e951d673755e5700a9e30b27b1c3ae
/VME/mafVMEGenericAbstract.h
be405ff568d7dd90fdd20e626f7fda2a638d5d61
[]
no_license
besoft/MAF2
1a26bfbb4bedb036741941a43b135162448bbf33
b576955f4f6b954467021f12baedfebcaf79a382
refs/heads/master
2020-04-13T13:58:44.609511
2019-07-31T13:56:54
2019-07-31T13:56:54
31,658,947
1
3
null
2015-03-04T13:41:48
2015-03-04T13:41:48
null
UTF-8
C++
false
false
5,612
h
mafVMEGenericAbstract.h
/*========================================================================= Program: MAF2 Module: mafVMEGenericAbstract Authors: Marco Petrone Copyright (c) B3C All rights reserved. See Copyright.txt or http://www.scsitaly.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef __mafVMEGenericAbstract_h #define __mafVMEGenericAbstract_h //---------------------------------------------------------------------------- // Include: //---------------------------------------------------------------------------- #include "mafVME.h" //---------------------------------------------------------------------------- // forward declarations : //---------------------------------------------------------------------------- class mafDataVector; class mafMatrixVector; class mafNode; class mafGUI; /** mafVMEGenericAbstract - a VME featuring an internal array for matrices and data. mafVMEGenericAbstract is a node featuring a standard way for managing 4D data, featuring an array for pose matrixes (MatrixVector) and an array for internally stored data (DataSetVector). @sa mafVME mafMatrixVector mafDataVector @todo - */ class MAF_EXPORT mafVMEGenericAbstract : public mafVME { public: mafTypeMacro(mafVMEGenericAbstract,mafVME); enum VME_GUI_ID { ID_VME_CRYPTING = Superclass::ID_LAST, ID_LAST }; /** print a dump of this object */ virtual void Print(std::ostream& os, const int tabs=0);// const; /** Copy the contents of another VME into this one. Notice that subtrees are not copied, i.e. copy is not recursive! Concrete class should reimplement this function to verify admitted conversion. */ virtual int DeepCopy(mafNode *a); /** Allow to perform a DeepCopy with data very large. Release memory of the input mafNode. */ virtual int DeepCopyVmeLarge(mafNode *a); /** perform a copy by simply referencing the copied VME's data array. Beware: This can allow to save memory when doing special tasks, but can be very dangerous making one of the VME inconsistent. Some VMEs do not support such a function! */ virtual int ShallowCopy(mafVME *a); /** Compare two VME. Two VME are considered equivalent if they have equivalent items, TagArrays, MatrixVectors, Name and Type. */ virtual bool Equals(mafVME *vme); /** Reparent this VME into a different place of the same tree or into a different tree. If the tree is not the same, the data of all items of all sub vme is read into memory and Id is reset to -1, to allow the VMEStorage to write new data as new files on file. In case of error during operation return NULL, otherwise return this node pointer: this is to be compatible with nodes that during reparenting make copy of the VME (mafVMEGenericAbstractRoot)*/ virtual int ReparentTo(mafNode *parent); /** Return the matrix vector associated with this VME. Matrix vector is an array of time stamped 4x4 matrices, used to generate the output VME pose matrix. The matrix vector is made persistent by saving it in the MSF-XML file (or other kind of storage for metadata). This array can be NULL for VMEs generating the output matrix procedurally starting from from different sources. */ mafMatrixVector *GetMatrixVector() {return m_MatrixVector;} /** Set the Pose matrix of the VME. This function modifies the MatrixVector. You can set or get the Pose for a specified time. When setting, if the time does not exist the MatrixVector creates a new KeyMatrix on the fly. When getting, the matrix vector interpolates on the fly according to the matrix interpolator.*/ void SetMatrix(const mafMatrix &mat); /** Get the pointer to the array of VMEItem's*/ mafDataVector *GetDataVector() {return m_DataVector;} /** Return the list of time stamps of the VMEItemArray stored in this VME. */ virtual void GetDataTimeStamps(std::vector<mafTimeStamp> &kframes); /** Return the list of time stamps of the MatrixVector stored in this VME. */ void GetMatrixTimeStamps(std::vector<mafTimeStamp> &kframes); /** Return the list of timestamps for this VME. Timestamps list is obtained merging timestamps for matrices and VME items*/ virtual void GetLocalTimeStamps(std::vector<mafTimeStamp> &kframes); /** Set the time bounds for the time varying VME based on data and matrix vector.*/ void GetLocalTimeBounds(mafTimeStamp tbounds[2]); /** return true is this VME has more than one time stamp, either for data or matrices */ virtual bool IsAnimated(); /** Return true if the data associated with the VME is present and updated at the current time.*/ virtual bool IsDataAvailable(); /** return an xpm-icon that can be used to represent this node */ static char ** GetIcon(); //SIL. 11-4-2005: void OnEvent(mafEventBase *maf_event); protected: mafVMEGenericAbstract(); virtual ~mafVMEGenericAbstract(); virtual int InternalStore(mafStorageElement *parent); virtual int InternalRestore(mafStorageElement *node); /** Create GUI for the VME */ virtual mafGUI *CreateGui(); mafMatrixVector *m_MatrixVector; mafDataVector *m_DataVector; private: mafVMEGenericAbstract(const mafVMEGenericAbstract&); // Not implemented void operator=(const mafVMEGenericAbstract&); // Not implemented }; #endif
70cf8e3b609a184b37803329d58af797c8ee3f5c
0f7da6410704d3682de7e4e2968355911ba0bd80
/AVR/AVR/Trampoline.cpp
7890723e2082b17879e0ee7e6652824486e3cf55
[]
no_license
modulolabs/firmware
21c95b2995dfd1e8a8a2662ed287bced5c65495e
1f5bf96faac5b894de3654d3c7c86894703cc52b
refs/heads/master
2020-04-09T10:11:23.956729
2015-12-06T23:38:31
2015-12-06T23:38:31
21,027,607
0
0
null
null
null
null
UTF-8
C++
false
false
225
cpp
Trampoline.cpp
/* * Trampoline.cpp * * Created: 11/2/2015 12:08:58 PM * Author: ekt */ void startApplication() __attribute__((section (".trampoline"))) __attribute__((naked)); void startApplication() { asm("rjmp __ctors_start"); }
a187f74999e81b7838648452fc1ff8b26cb22629
7e45ea36e7919ab7335ee4079b6d102cfd91c69d
/Bomberman/createpartymultigamer.cpp
bf456578c95d0227ec1a4f0adc320498164b8687
[ "MIT" ]
permissive
CPI4Admin/BomberMan
aadf9e7cc99fa0eb81d53b17b58b9ad1ff5a1982
9f9aae50e71e458c55671952216ea85fa13dc5f4
refs/heads/master
2021-01-10T18:58:32.573642
2014-06-23T08:57:23
2014-06-23T08:57:23
16,377,048
0
0
null
2014-06-23T08:57:23
2014-01-30T12:45:27
C++
UTF-8
C++
false
false
840
cpp
createpartymultigamer.cpp
#include "createpartymultigamer.h" #include "ui_createpartymultigamer.h" #include "bmnetworktcpserver.h" #include "bmnetworktcpclient.h" createpartymultigamer::createpartymultigamer(QWidget *parent) : QDialog(parent), ui(new Ui::createpartymultigamer) { server = new BmNetworkTCPServer(); ui->setupUi(this); connect(ui->btStartServer,SIGNAL(clicked()),this, SLOT(StartServer())); connect(ui->btStopServer,SIGNAL(clicked()),this, SLOT(StopServer())); connect(ui->btQuitterServer,SIGNAL(clicked()),this,SLOT(QuitServer())); } createpartymultigamer::~createpartymultigamer() { delete ui; } void createpartymultigamer::StartServer() { server->start(); } void createpartymultigamer::StopServer() { server->close(); } void createpartymultigamer::QuitServer() { server->close(); close(); }
3a69459502b6e5e3ac92b3360a93993194514aab
21556e8fdf12bee1a9d6990c3c84b8eba2843900
/src/Emulator/mappers/uxrom.cc
225ebe183bf62775e2f2416f938fd761930b4824
[ "MIT" ]
permissive
DalePutnam/D-NES
60989b24d3d49d90646245f22d93fa37e47bf61b
a169ed69edf2d895ae26f412d068433254d7c39b
refs/heads/master
2021-04-03T02:09:00.290213
2020-05-28T02:36:24
2020-05-28T02:37:49
17,896,013
0
0
null
null
null
null
UTF-8
C++
false
false
1,458
cc
uxrom.cc
#include "uxrom.h" UXROM::UXROM(iNesFile& file) : MapperBase(file) , _register(0) { } void UXROM::SaveState(StateSave::Ptr& state) { MapperBase::SaveState(state); state->StoreValue(_register); } void UXROM::LoadState(const StateSave::Ptr& state) { MapperBase::LoadState(state); state->StoreValue(_register); } uint8_t UXROM::CpuRead(uint16_t address) { if (address >= 0x6000 && address < 0x8000) { return _prgRam[address - 0x6000]; } else if (address >= 0x8000) { if (address < 0xC000) { return _prgRom[(address - 0x8000) + (0x4000 * _register)]; } else { return _prgRom[(address - 0xC000) + (_prgRomSize - 0x4000)]; } } else { return 0x00; } } void UXROM::CpuWrite(uint8_t M, uint16_t address) { if (address >= 0x6000 && address < 0x8000) { _prgRam[address - 0x6000] = M; } else if (address >= 0x8000) { _register = M; } } uint8_t UXROM::PpuRead() { return UXROM::PpuPeek(_ppuAddress); } void UXROM::PpuWrite(uint8_t M) { if (_ppuAddress < 0x2000) { _chrRam[_ppuAddress] = M; } else { DefaultNameTableWrite(M, _ppuAddress); } } uint8_t UXROM::PpuPeek(uint16_t address) { if (address < 0x2000) { return _chrRam[address]; } else { return DefaultNameTableRead(address); } }
a22cd82003a02ad9cace57f83f8ff03513f4a78c
3f4aefcdf695627adb590e8d7a87487772d548f1
/ecoin/build/ui_savingsdialog.h
72d934247839697e0f112feb332697b352e8261f
[ "MIT" ]
permissive
aleph1888/ecoin
a502d7ce993440e3f5cb551ca0b8539487f0f05c
862358161037c863018d2b801892adfcb8d4cd27
refs/heads/master
2020-12-11T01:50:34.888901
2015-04-11T23:15:20
2015-04-11T23:15:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,881
h
ui_savingsdialog.h
/******************************************************************************** ** Form generated from reading UI file 'savingsdialog.ui' ** ** Created by: Qt User Interface Compiler version 4.8.6 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_SAVINGSDIALOG_H #define UI_SAVINGSDIALOG_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QFrame> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QLineEdit> #include <QtGui/QPushButton> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_AutoSavingsDialog { public: QLineEdit *savingsPercentEdit; QLineEdit *savingsAddressEdit; QLabel *label_2; QLineEdit *savingsMinEdit; QLineEdit *savingsMaxEdit; QLabel *message; QPushButton *enableButton; QPushButton *disableButton; QPushButton *addressBookButton; QLineEdit *savingsChangeAddressEdit; QPushButton *changeAddressBookButton; QLabel *label; QLabel *label_3; QLabel *label_4; QLabel *label_6; QLineEdit *freeAddressEdit; QPushButton *freeAddressBookButton; QLabel *freelabel; QPushButton *freeRequestButton; QFrame *line; QLabel *freeMessage; QLabel *label_7; QPushButton *pushButton_copy; QPushButton *freeDisableButton; QPushButton *freeReferButton; void setupUi(QWidget *AutoSavingsDialog) { if (AutoSavingsDialog->objectName().isEmpty()) AutoSavingsDialog->setObjectName(QString::fromUtf8("AutoSavingsDialog")); AutoSavingsDialog->setWindowModality(Qt::NonModal); AutoSavingsDialog->resize(850, 400); savingsPercentEdit = new QLineEdit(AutoSavingsDialog); savingsPercentEdit->setObjectName(QString::fromUtf8("savingsPercentEdit")); savingsPercentEdit->setGeometry(QRect(20, 130, 131, 21)); savingsAddressEdit = new QLineEdit(AutoSavingsDialog); savingsAddressEdit->setObjectName(QString::fromUtf8("savingsAddressEdit")); savingsAddressEdit->setGeometry(QRect(20, 180, 301, 21)); label_2 = new QLabel(AutoSavingsDialog); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setGeometry(QRect(20, 20, 611, 41)); label_2->setLineWidth(1); label_2->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop); label_2->setWordWrap(true); savingsMinEdit = new QLineEdit(AutoSavingsDialog); savingsMinEdit->setObjectName(QString::fromUtf8("savingsMinEdit")); savingsMinEdit->setGeometry(QRect(160, 130, 131, 21)); savingsMaxEdit = new QLineEdit(AutoSavingsDialog); savingsMaxEdit->setObjectName(QString::fromUtf8("savingsMaxEdit")); savingsMaxEdit->setGeometry(QRect(300, 130, 131, 21)); message = new QLabel(AutoSavingsDialog); message->setObjectName(QString::fromUtf8("message")); message->setGeometry(QRect(20, 210, 611, 21)); enableButton = new QPushButton(AutoSavingsDialog); enableButton->setObjectName(QString::fromUtf8("enableButton")); enableButton->setGeometry(QRect(350, 180, 75, 21)); disableButton = new QPushButton(AutoSavingsDialog); disableButton->setObjectName(QString::fromUtf8("disableButton")); disableButton->setGeometry(QRect(430, 180, 75, 21)); addressBookButton = new QPushButton(AutoSavingsDialog); addressBookButton->setObjectName(QString::fromUtf8("addressBookButton")); addressBookButton->setGeometry(QRect(320, 180, 28, 21)); QIcon icon; icon.addFile(QString::fromUtf8(":/icons/address-book"), QSize(), QIcon::Normal, QIcon::Off); addressBookButton->setIcon(icon); addressBookButton->setAutoDefault(false); savingsChangeAddressEdit = new QLineEdit(AutoSavingsDialog); savingsChangeAddressEdit->setObjectName(QString::fromUtf8("savingsChangeAddressEdit")); savingsChangeAddressEdit->setGeometry(QRect(20, 260, 301, 21)); changeAddressBookButton = new QPushButton(AutoSavingsDialog); changeAddressBookButton->setObjectName(QString::fromUtf8("changeAddressBookButton")); changeAddressBookButton->setGeometry(QRect(320, 260, 28, 21)); changeAddressBookButton->setIcon(icon); changeAddressBookButton->setAutoDefault(false); label = new QLabel(AutoSavingsDialog); label->setObjectName(QString::fromUtf8("label")); label->setGeometry(QRect(20, 110, 121, 16)); label_3 = new QLabel(AutoSavingsDialog); label_3->setObjectName(QString::fromUtf8("label_3")); label_3->setGeometry(QRect(180, 110, 101, 16)); label_4 = new QLabel(AutoSavingsDialog); label_4->setObjectName(QString::fromUtf8("label_4")); label_4->setGeometry(QRect(320, 110, 101, 16)); label_6 = new QLabel(AutoSavingsDialog); label_6->setObjectName(QString::fromUtf8("label_6")); label_6->setGeometry(QRect(20, 160, 121, 16)); freeAddressEdit = new QLineEdit(AutoSavingsDialog); freeAddressEdit->setObjectName(QString::fromUtf8("freeAddressEdit")); freeAddressEdit->setGeometry(QRect(20, 330, 301, 21)); freeAddressBookButton = new QPushButton(AutoSavingsDialog); freeAddressBookButton->setObjectName(QString::fromUtf8("freeAddressBookButton")); freeAddressBookButton->setGeometry(QRect(320, 330, 28, 21)); freeAddressBookButton->setIcon(icon); freeAddressBookButton->setAutoDefault(false); freelabel = new QLabel(AutoSavingsDialog); freelabel->setObjectName(QString::fromUtf8("freelabel")); freelabel->setGeometry(QRect(20, 310, 331, 16)); freeRequestButton = new QPushButton(AutoSavingsDialog); freeRequestButton->setObjectName(QString::fromUtf8("freeRequestButton")); freeRequestButton->setGeometry(QRect(350, 330, 75, 21)); line = new QFrame(AutoSavingsDialog); line->setObjectName(QString::fromUtf8("line")); line->setGeometry(QRect(20, 290, 611, 16)); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); freeMessage = new QLabel(AutoSavingsDialog); freeMessage->setObjectName(QString::fromUtf8("freeMessage")); freeMessage->setGeometry(QRect(20, 360, 611, 21)); label_7 = new QLabel(AutoSavingsDialog); label_7->setObjectName(QString::fromUtf8("label_7")); label_7->setGeometry(QRect(110, 70, 481, 21)); pushButton_copy = new QPushButton(AutoSavingsDialog); pushButton_copy->setObjectName(QString::fromUtf8("pushButton_copy")); pushButton_copy->setGeometry(QRect(20, 70, 85, 21)); freeDisableButton = new QPushButton(AutoSavingsDialog); freeDisableButton->setObjectName(QString::fromUtf8("freeDisableButton")); freeDisableButton->setGeometry(QRect(430, 330, 75, 21)); freeReferButton = new QPushButton(AutoSavingsDialog); freeReferButton->setObjectName(QString::fromUtf8("freeReferButton")); freeReferButton->setGeometry(QRect(510, 330, 75, 21)); QIcon icon1; icon1.addFile(QString::fromUtf8(":/icons/add"), QSize(), QIcon::Normal, QIcon::Off); freeReferButton->setIcon(icon1); retranslateUi(AutoSavingsDialog); QMetaObject::connectSlotsByName(AutoSavingsDialog); } // setupUi void retranslateUi(QWidget *AutoSavingsDialog) { AutoSavingsDialog->setWindowTitle(QApplication::translate("AutoSavingsDialog", "EcoinShare", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP savingsPercentEdit->setToolTip(QApplication::translate("AutoSavingsDialog", "Enter the percent to share (whole numbers)", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP savingsPercentEdit->setText(QString()); savingsPercentEdit->setPlaceholderText(QApplication::translate("AutoSavingsDialog", "Enter % to share", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP savingsAddressEdit->setToolTip(QApplication::translate("AutoSavingsDialog", "Enter Ecoin address", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP savingsAddressEdit->setText(QString()); savingsAddressEdit->setPlaceholderText(QApplication::translate("AutoSavingsDialog", "EgAiyRYKKsQEDsbkYuML9d48WUm5DMTdAw", 0, QApplication::UnicodeUTF8)); label_2->setText(QApplication::translate("AutoSavingsDialog", "EcoinShare allows you to automatically send up to 50% of your stake to another Ecoin address after it matures.", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP savingsMinEdit->setToolTip(QApplication::translate("AutoSavingsDialog", "Do not send less than this (whole numbers)", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP savingsMinEdit->setPlaceholderText(QApplication::translate("AutoSavingsDialog", "Enter Min Amount", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP savingsMaxEdit->setToolTip(QApplication::translate("AutoSavingsDialog", "Do not send more than this (whole numbers)", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP savingsMaxEdit->setText(QString()); savingsMaxEdit->setPlaceholderText(QApplication::translate("AutoSavingsDialog", "Enter Max Amount", 0, QApplication::UnicodeUTF8)); message->setText(QString()); #ifndef QT_NO_STATUSTIP enableButton->setStatusTip(QApplication::translate("AutoSavingsDialog", "Check and turn on EcoinShare", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_STATUSTIP enableButton->setText(QApplication::translate("AutoSavingsDialog", "Enable", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_STATUSTIP disableButton->setStatusTip(QApplication::translate("AutoSavingsDialog", "Turn off EcoinShare", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_STATUSTIP disableButton->setText(QApplication::translate("AutoSavingsDialog", "Disable", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP addressBookButton->setToolTip(QApplication::translate("AutoSavingsDialog", "Choose an address from the address book", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP addressBookButton->setText(QString()); addressBookButton->setShortcut(QApplication::translate("AutoSavingsDialog", "Alt+A", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP savingsChangeAddressEdit->setToolTip(QApplication::translate("AutoSavingsDialog", "Change address must be owned by you", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP savingsChangeAddressEdit->setPlaceholderText(QApplication::translate("AutoSavingsDialog", "Enter Change Address (optional)", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP changeAddressBookButton->setToolTip(QApplication::translate("AutoSavingsDialog", "Choose an address from the address book", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP changeAddressBookButton->setText(QString()); changeAddressBookButton->setShortcut(QApplication::translate("AutoSavingsDialog", "Alt+A", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("AutoSavingsDialog", "Donation Percent", 0, QApplication::UnicodeUTF8)); label_3->setText(QApplication::translate("AutoSavingsDialog", "Min(optional)", 0, QApplication::UnicodeUTF8)); label_4->setText(QApplication::translate("AutoSavingsDialog", "Max(optional)", 0, QApplication::UnicodeUTF8)); label_6->setText(QApplication::translate("AutoSavingsDialog", "Donation Address", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP freeAddressEdit->setToolTip(QApplication::translate("AutoSavingsDialog", "Enter Ecoin address", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP freeAddressEdit->setText(QString()); freeAddressEdit->setPlaceholderText(QApplication::translate("AutoSavingsDialog", "EgAiyRYKKsQEDsbkYuML9d48WUm5DMTdAw", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP freeAddressBookButton->setToolTip(QApplication::translate("AutoSavingsDialog", "Choose an address from the address book", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP freeAddressBookButton->setText(QString()); freeAddressBookButton->setShortcut(QApplication::translate("AutoSavingsDialog", "Alt+A", 0, QApplication::UnicodeUTF8)); freelabel->setText(QApplication::translate("AutoSavingsDialog", "Free Ecoins for running the app each day!", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_STATUSTIP freeRequestButton->setStatusTip(QApplication::translate("AutoSavingsDialog", "Get Free Ecoins", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_STATUSTIP freeRequestButton->setText(QApplication::translate("AutoSavingsDialog", "Enable", 0, QApplication::UnicodeUTF8)); freeMessage->setText(QString()); label_7->setText(QApplication::translate("AutoSavingsDialog", "EgAiyRYKKsQEDsbkYuML9d48WUm5DMTdAw - Ecoin Bounty Fund", 0, QApplication::UnicodeUTF8)); pushButton_copy->setText(QApplication::translate("AutoSavingsDialog", "Copy", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_STATUSTIP freeDisableButton->setStatusTip(QApplication::translate("AutoSavingsDialog", "Get Free Ecoins", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_STATUSTIP freeDisableButton->setText(QApplication::translate("AutoSavingsDialog", "Disable", 0, QApplication::UnicodeUTF8)); freeReferButton->setText(QApplication::translate("AutoSavingsDialog", "Friend", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class AutoSavingsDialog: public Ui_AutoSavingsDialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_SAVINGSDIALOG_H